context
stringlengths
2.52k
185k
gt
stringclasses
1 value
#define UseDictionary using System; using System.Linq; using System.Drawing; using System.Collections.Generic; using Rimss.GraphicsProcessing.Palette.ColorCaches; using Rimss.GraphicsProcessing.Palette.ColorCaches.Octree; using Rimss.GraphicsProcessing.Palette.Extensions; using Rimss.GraphicsProcessing.Palette.Helpers; #if (UseDictionary) using System.Collections.Concurrent; #endif namespace Rimss.GraphicsProcessing.Palette.Quantizers.DistinctSelection { /// <summary> /// This is my baby. Read more in the article on the Code Project: /// http://www.codeproject.com/KB/recipes/SimplePaletteQuantizer.aspx /// </summary> public class DistinctSelectionQuantizer : BaseColorCacheQuantizer { #region | Fields | private List<Color> palette; private Int32 foundColorCount; #if (UseDictionary) private ConcurrentDictionary<Int32, DistinctColorInfo> colorMap; #else private DistinctBucket rootBucket; #endif #endregion #region | Methods | private static Boolean ProcessList(Int32 colorCount, List<DistinctColorInfo> list, ICollection<IEqualityComparer<DistinctColorInfo>> comparers, out List<DistinctColorInfo> outputList) { IEqualityComparer<DistinctColorInfo> bestComparer = null; Int32 maximalCount = 0; outputList = list; foreach (IEqualityComparer<DistinctColorInfo> comparer in comparers) { List<DistinctColorInfo> filteredList = list. Distinct(comparer). ToList(); Int32 filteredListCount = filteredList.Count; if (filteredListCount > colorCount && filteredListCount > maximalCount) { maximalCount = filteredListCount; bestComparer = comparer; outputList = filteredList; if (maximalCount <= colorCount) break; } } comparers.Remove(bestComparer); return comparers.Count > 0 && maximalCount > colorCount; } #endregion #region << BaseColorCacheQuantizer >> /// <summary> /// See <see cref="IColorQuantizer.Prepare"/> for more details. /// </summary> protected override void OnPrepare(ImageBuffer image) { base.OnPrepare(image); OnFinish(); } /// <summary> /// See <see cref="BaseColorCacheQuantizer.OnCreateDefaultCache"/> for more details. /// </summary> protected override IColorCache OnCreateDefaultCache() { // use OctreeColorCache best performance/quality return new OctreeColorCache(); } /// <summary> /// See <see cref="BaseColorQuantizer.OnAddColor"/> for more details. /// </summary> protected override void OnAddColor(Color color, Int32 key, Int32 x, Int32 y) { #if (UseDictionary) colorMap.AddOrUpdate(key, colorKey => new DistinctColorInfo(color), (colorKey, colorInfo) => colorInfo.IncreaseCount()); #else color = QuantizationHelper.ConvertAlpha(color); rootBucket.StoreColor(color); #endif } /// <summary> /// See <see cref="BaseColorCacheQuantizer.OnGetPaletteToCache"/> for more details. /// </summary> protected override List<Color> OnGetPaletteToCache(Int32 colorCount) { // otherwise calculate one palette.Clear(); // lucky seed :) FastRandom random = new FastRandom(13); #if (UseDictionary) List<DistinctColorInfo> colorInfoList = colorMap.Values.ToList(); #else List<DistinctColorInfo> colorInfoList = rootBucket.GetValues().ToList(); #endif foundColorCount = colorInfoList.Count; if (foundColorCount >= colorCount) { // shuffles the colormap colorInfoList = colorInfoList. OrderBy(entry => random.Next(foundColorCount)). ToList(); // workaround for backgrounds, the most prevalent color DistinctColorInfo background = colorInfoList.MaxBy(info => info.Count); colorInfoList.Remove(background); colorCount--; ColorHueComparer hueComparer = new ColorHueComparer(); ColorSaturationComparer saturationComparer = new ColorSaturationComparer(); ColorBrightnessComparer brightnessComparer = new ColorBrightnessComparer(); // generates catalogue List<IEqualityComparer<DistinctColorInfo>> comparers = new List<IEqualityComparer<DistinctColorInfo>> { hueComparer, saturationComparer, brightnessComparer }; // take adequate number from each slot while (ProcessList(colorCount, colorInfoList, comparers, out colorInfoList)) { } Int32 listColorCount = colorInfoList.Count(); if (listColorCount > 0) { Int32 allowedTake = Math.Min(colorCount, listColorCount); colorInfoList = colorInfoList.Take(allowedTake).ToList(); } // adds background color first palette.Add(Color.FromArgb(background.Color)); } // adds the selected colors to a final palette palette.AddRange(colorInfoList.Select(colorInfo => Color.FromArgb(colorInfo.Color))); // returns our new palette return palette; } /// <summary> /// See <see cref="BaseColorQuantizer.GetColorCount"/> for more details. /// </summary> protected override Int32 OnGetColorCount() { return foundColorCount; } /// <summary> /// See <see cref="BaseColorQuantizer.OnFinish"/> for more details. /// </summary> protected override void OnFinish() { base.OnFinish(); palette = new List<Color>(); #if (UseDictionary) colorMap = new ConcurrentDictionary<Int32, DistinctColorInfo>(); #else rootBucket = new DistinctBucket(); #endif } #endregion #region << IColorQuantizer >> /// <summary> /// See <see cref="IColorQuantizer.AllowParallel"/> for more details. /// </summary> public override Boolean AllowParallel { get { return true; } } #endregion #region | Helper classes (comparers) | /// <summary> /// Compares a hue components of a color info. /// </summary> private class ColorHueComparer : IEqualityComparer<DistinctColorInfo> { public Boolean Equals(DistinctColorInfo x, DistinctColorInfo y) { return x.Hue == y.Hue; } public Int32 GetHashCode(DistinctColorInfo colorInfo) { return colorInfo.Hue.GetHashCode(); } } /// <summary> /// Compares a saturation components of a color info. /// </summary> private class ColorSaturationComparer : IEqualityComparer<DistinctColorInfo> { public Boolean Equals(DistinctColorInfo x, DistinctColorInfo y) { return x.Saturation == y.Saturation; } public Int32 GetHashCode(DistinctColorInfo colorInfo) { return colorInfo.Saturation.GetHashCode(); } } /// <summary> /// Compares a brightness components of a color info. /// </summary> private class ColorBrightnessComparer : IEqualityComparer<DistinctColorInfo> { public Boolean Equals(DistinctColorInfo x, DistinctColorInfo y) { return x.Brightness == y.Brightness; } public Int32 GetHashCode(DistinctColorInfo colorInfo) { return colorInfo.Brightness.GetHashCode(); } } #endregion } }
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // ----------------------------------------------------------------------------- // The following code is a port of XNA StockEffects http://xbox.create.msdn.com/en-US/education/catalog/sample/stock_effects // ----------------------------------------------------------------------------- // Microsoft Public License (Ms-PL) // // 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. //----------------------------------------------------------------------------- // BasicEffect.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- using SharpDX.Mathematics; namespace SharpDX.Toolkit.Graphics { /// <summary> /// Built-in effect that supports optional texturing, vertex coloring, fog, and lighting. /// </summary> public partial class BasicEffect : Effect, IEffectMatrices, IEffectLights, IEffectFog { #region Effect Parameters EffectParameter textureParam; EffectParameter samplerParam; EffectParameter diffuseColorParam; EffectParameter emissiveColorParam; EffectParameter specularColorParam; EffectParameter specularPowerParam; EffectParameter eyePositionParam; EffectParameter fogColorParam; EffectParameter fogVectorParam; EffectParameter worldParam; EffectParameter worldInverseTransposeParam; EffectParameter worldViewProjParam; EffectPass shaderPass; #endregion #region Fields bool lightingEnabled; bool preferPerPixelLighting; bool oneLight; bool fogEnabled; bool textureEnabled; bool vertexColorEnabled; Matrix world = Matrix.Identity; Matrix view = Matrix.Identity; Matrix projection = Matrix.Identity; Matrix worldView; Vector4 diffuseColor = Vector4.One; Vector3 emissiveColor = Vector3.Zero; Vector3 ambientLightColor = Vector3.Zero; float alpha = 1; DirectionalLight light0; DirectionalLight light1; DirectionalLight light2; float fogStart = 0; float fogEnd = 1; EffectDirtyFlags dirtyFlags = EffectDirtyFlags.All; #endregion #region Public Properties /// <summary> /// Gets or sets the world matrix. /// </summary> public Matrix World { get { return world; } set { world = value; dirtyFlags |= EffectDirtyFlags.World | EffectDirtyFlags.WorldViewProj | EffectDirtyFlags.Fog; } } /// <summary> /// Gets or sets the view matrix. /// </summary> public Matrix View { get { return view; } set { view = value; dirtyFlags |= EffectDirtyFlags.WorldViewProj | EffectDirtyFlags.EyePosition | EffectDirtyFlags.Fog; } } /// <summary> /// Gets or sets the projection matrix. /// </summary> public Matrix Projection { get { return projection; } set { projection = value; dirtyFlags |= EffectDirtyFlags.WorldViewProj; } } /// <summary> /// Gets or sets the material diffuse color (range 0 to 1). /// </summary> public Vector4 DiffuseColor { get { return diffuseColor; } set { diffuseColor = value; dirtyFlags |= EffectDirtyFlags.MaterialColor; } } /// <summary> /// Gets or sets the material emissive color (range 0 to 1). /// </summary> public Vector3 EmissiveColor { get { return emissiveColor; } set { emissiveColor = value; dirtyFlags |= EffectDirtyFlags.MaterialColor; } } /// <summary> /// Gets or sets the material specular color (range 0 to 1). /// </summary> public Vector3 SpecularColor { get { return specularColorParam.GetValue<Vector3>(); } set { specularColorParam.SetValue(value); } } /// <summary> /// Gets or sets the material specular power. /// </summary> public float SpecularPower { get { return specularPowerParam.GetValue<float>(); } set { specularPowerParam.SetValue(value); } } /// <summary> /// Gets or sets the material alpha. /// </summary> public float Alpha { get { return alpha; } set { alpha = value; dirtyFlags |= EffectDirtyFlags.MaterialColor; } } /// <summary> /// Gets or sets the lighting enable flag. /// </summary> public bool LightingEnabled { get { return lightingEnabled; } set { if (lightingEnabled != value) { lightingEnabled = value; dirtyFlags |= EffectDirtyFlags.ShaderIndex | EffectDirtyFlags.MaterialColor; } } } /// <summary> /// Gets or sets the per-pixel lighting prefer flag. /// </summary> public bool PreferPerPixelLighting { get { return preferPerPixelLighting; } set { if (preferPerPixelLighting != value) { preferPerPixelLighting = value; dirtyFlags |= EffectDirtyFlags.ShaderIndex; } } } /// <summary> /// Gets or sets the ambient light color (range 0 to 1). /// </summary> public Vector3 AmbientLightColor { get { return ambientLightColor; } set { ambientLightColor = value; dirtyFlags |= EffectDirtyFlags.MaterialColor; } } /// <summary> /// Gets the first directional light. /// </summary> public DirectionalLight DirectionalLight0 { get { return light0; } } /// <summary> /// Gets the second directional light. /// </summary> public DirectionalLight DirectionalLight1 { get { return light1; } } /// <summary> /// Gets the third directional light. /// </summary> public DirectionalLight DirectionalLight2 { get { return light2; } } /// <summary> /// Gets or sets the fog enable flag. /// </summary> public bool FogEnabled { get { return fogEnabled; } set { if (fogEnabled != value) { fogEnabled = value; dirtyFlags |= EffectDirtyFlags.ShaderIndex | EffectDirtyFlags.FogEnable; } } } /// <summary> /// Gets or sets the fog start distance. /// </summary> public float FogStart { get { return fogStart; } set { fogStart = value; dirtyFlags |= EffectDirtyFlags.Fog; } } /// <summary> /// Gets or sets the fog end distance. /// </summary> public float FogEnd { get { return fogEnd; } set { fogEnd = value; dirtyFlags |= EffectDirtyFlags.Fog; } } /// <summary> /// Gets or sets the fog color. /// </summary> public Vector3 FogColor { get { return fogColorParam.GetValue<Vector3>(); } set { fogColorParam.SetValue(value); } } /// <summary> /// Gets or sets whether texturing is enabled. /// </summary> public bool TextureEnabled { get { return textureEnabled; } set { if (textureEnabled != value) { textureEnabled = value; dirtyFlags |= EffectDirtyFlags.ShaderIndex; } } } /// <summary> /// Gets or sets the current texture. Either use this property or <see cref="TextureView"/> but not both at the same time. /// </summary> public Texture2DBase Texture { get { return textureParam.GetResource<Texture2DBase>(); } set { textureParam.SetResource(value); } } /// <summary> /// Gets or sets the current texture sampler. Default is <see cref="SamplerStateCollection.Default"/>. /// </summary> public SamplerState Sampler { get { return samplerParam.GetResource<SamplerState>(); } set { samplerParam.SetResource(value); } } /// <summary> /// Gets or sets the current texture view. Either use this property or <see cref="Texture"/> but not both at the same time. /// </summary> public Direct3D11.ShaderResourceView TextureView { get { return textureParam.GetResource<Direct3D11.ShaderResourceView>(); } set { textureParam.SetResource(value); } } /// <summary> /// Gets or sets whether vertex color is enabled. /// </summary> public bool VertexColorEnabled { get { return vertexColorEnabled; } set { if (vertexColorEnabled != value) { vertexColorEnabled = value; dirtyFlags |= EffectDirtyFlags.ShaderIndex; } } } #endregion #region Methods /// <summary> /// Initializes a new instance of the <see cref="BasicEffect" /> class. /// </summary> /// <param name="device">The device.</param> public BasicEffect(GraphicsDevice device) : this(device, device.DefaultEffectPool) { } /// <summary> /// Initializes a new instance of the <see cref="BasicEffect" /> class from a specified <see cref="EffectPool"/>. /// </summary> /// <param name="device">The device.</param> /// <param name="pool">The pool.</param> public BasicEffect(GraphicsDevice device, EffectPool pool) : base(device, effectBytecode, pool) { DirectionalLight0.Enabled = true; SpecularColor = Vector3.One; SpecularPower = 16; } protected override void Initialize() { textureParam = Parameters["Texture"]; samplerParam = Parameters["TextureSampler"]; diffuseColorParam = Parameters["DiffuseColor"]; emissiveColorParam = Parameters["EmissiveColor"]; specularColorParam = Parameters["SpecularColor"]; specularPowerParam = Parameters["SpecularPower"]; eyePositionParam = Parameters["EyePosition"]; fogColorParam = Parameters["FogColor"]; fogVectorParam = Parameters["FogVector"]; worldParam = Parameters["World"]; worldInverseTransposeParam = Parameters["WorldInverseTranspose"]; worldViewProjParam = Parameters["WorldViewProj"]; light0 = new DirectionalLight(Parameters["DirLight0Direction"], Parameters["DirLight0DiffuseColor"], Parameters["DirLight0SpecularColor"], null); light1 = new DirectionalLight(Parameters["DirLight1Direction"], Parameters["DirLight1DiffuseColor"], Parameters["DirLight1SpecularColor"], null); light2 = new DirectionalLight(Parameters["DirLight2Direction"], Parameters["DirLight2DiffuseColor"], Parameters["DirLight2SpecularColor"], null); samplerParam.SetResource(GraphicsDevice.SamplerStates.Default); } ///// <summary> ///// Creates a new BasicEffect by cloning parameter settings from an existing instance. ///// </summary> //protected BasicEffect(BasicEffect cloneSource) // : base(cloneSource) //{ // CacheEffectParameters(cloneSource); // lightingEnabled = cloneSource.lightingEnabled; // preferPerPixelLighting = cloneSource.preferPerPixelLighting; // fogEnabled = cloneSource.fogEnabled; // textureEnabled = cloneSource.textureEnabled; // vertexColorEnabled = cloneSource.vertexColorEnabled; // world = cloneSource.world; // view = cloneSource.view; // projection = cloneSource.projection; // diffuseColor = cloneSource.diffuseColor; // emissiveColor = cloneSource.emissiveColor; // ambientLightColor = cloneSource.ambientLightColor; // alpha = cloneSource.alpha; // fogStart = cloneSource.fogStart; // fogEnd = cloneSource.fogEnd; //} /// <summary> /// Creates a clone of the current BasicEffect instance. /// </summary> //public override Effect Clone() //{ // return new BasicEffect(this); //} /// <summary> /// Sets up the standard key/fill/back lighting rig. /// </summary> public void EnableDefaultLighting() { LightingEnabled = true; AmbientLightColor = EffectHelpers.EnableDefaultLighting(light0, light1, light2); } /// <summary> /// Lazily computes derived parameter values immediately before applying the effect. /// </summary> protected internal override EffectPass OnApply(EffectPass pass) { // Make sure that domain, hull and geometry shaders are disable. GraphicsDevice.DomainShaderStage.Set(null); GraphicsDevice.HullShaderStage.Set(null); GraphicsDevice.GeometryShaderStage.Set(null); // Recompute the world+view+projection matrix or fog vector? dirtyFlags = EffectHelpers.SetWorldViewProjAndFog(dirtyFlags, ref world, ref view, ref projection, ref worldView, fogEnabled, fogStart, fogEnd, worldViewProjParam, fogVectorParam); // Recompute the diffuse/emissive/alpha material color parameters? if ((dirtyFlags & EffectDirtyFlags.MaterialColor) != 0) { EffectHelpers.SetMaterialColor(lightingEnabled, alpha, ref diffuseColor, ref emissiveColor, ref ambientLightColor, diffuseColorParam, emissiveColorParam); dirtyFlags &= ~EffectDirtyFlags.MaterialColor; } if (lightingEnabled) { // Recompute the world inverse transpose and eye position? dirtyFlags = EffectHelpers.SetLightingMatrices(dirtyFlags, ref world, ref view, worldParam, worldInverseTransposeParam, eyePositionParam); // Check if we can use the only-bother-with-the-first-light shader optimization. bool newOneLight = !light1.Enabled && !light2.Enabled; if (oneLight != newOneLight) { oneLight = newOneLight; dirtyFlags |= EffectDirtyFlags.ShaderIndex; } } // Recompute the shader index? if ((dirtyFlags & EffectDirtyFlags.ShaderIndex) != 0) { int shaderIndex = 0; if (!fogEnabled) shaderIndex += 1; if (vertexColorEnabled) shaderIndex += 2; if (textureEnabled) shaderIndex += 4; if (lightingEnabled) { if (preferPerPixelLighting) shaderIndex += 24; else if (oneLight) shaderIndex += 16; else shaderIndex += 8; } shaderPass = pass.SubPasses[shaderIndex]; dirtyFlags &= ~EffectDirtyFlags.ShaderIndex; } // Call the base class to process callbacks pass = base.OnApply(shaderPass); return pass; } #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 System; using System.Collections.Generic; using System.Xml; using System.Xml.Serialization; using OpenMetaverse; namespace OpenSim.Framework { /// <summary> /// Details of a Parcel of land /// </summary> public class LandData { // use only one serializer to give the runtime a chance to // optimize it (it won't do that if you use a new instance // every time) private static XmlSerializer serializer = new XmlSerializer(typeof (LandData)); private Vector3 _AABBMax = new Vector3(); private Vector3 _AABBMin = new Vector3(); private int _area = 0; private uint _auctionID = 0; //Unemplemented. If set to 0, not being auctioned private UUID _authBuyerID = UUID.Zero; //Unemplemented. Authorized Buyer's UUID private ParcelCategory _category = ParcelCategory.None; //Unemplemented. Parcel's chosen category private int _claimDate = 0; private int _claimPrice = 0; //Unemplemented private UUID _globalID = UUID.Zero; private UUID _groupID = UUID.Zero; private int _groupPrims = 0; private bool _isGroupOwned = false; private byte[] _bitmap = new byte[512]; private string _description = String.Empty; private uint _flags = (uint) ParcelFlags.AllowFly | (uint) ParcelFlags.AllowLandmark | (uint) ParcelFlags.AllowAPrimitiveEntry | (uint) ParcelFlags.AllowDeedToGroup | (uint) ParcelFlags.AllowTerraform | (uint) ParcelFlags.CreateObjects | (uint) ParcelFlags.AllowOtherScripts | (uint) ParcelFlags.SoundLocal; private byte _landingType = 0; private string _name = "Your Parcel"; private ParcelStatus _status = ParcelStatus.Leased; private int _localID = 0; private byte _mediaAutoScale = 0; private UUID _mediaID = UUID.Zero; private string _mediaURL = String.Empty; private string _musicURL = String.Empty; private int _otherPrims = 0; private UUID _ownerID = UUID.Zero; private int _ownerPrims = 0; private List<ParcelManager.ParcelAccessEntry> _parcelAccessList = new List<ParcelManager.ParcelAccessEntry>(); private float _passHours = 0; private int _passPrice = 0; private int _salePrice = 0; //Unemeplemented. Parcels price. private int _selectedPrims = 0; private int _simwideArea = 0; private int _simwidePrims = 0; private UUID _snapshotID = UUID.Zero; private Vector3 _userLocation = new Vector3(); private Vector3 _userLookAt = new Vector3(); private int _dwell = 0; private int _otherCleanTime = 0; /// <summary> /// Upper corner of the AABB for the parcel /// </summary> [XmlIgnore] public Vector3 AABBMax { get { return _AABBMax; } set { _AABBMax = value; } } /// <summary> /// Lower corner of the AABB for the parcel /// </summary> [XmlIgnore] public Vector3 AABBMin { get { return _AABBMin; } set { _AABBMin = value; } } /// <summary> /// Area in meters^2 the parcel contains /// </summary> public int Area { get { return _area; } set { _area = value; } } /// <summary> /// ID of auction (3rd Party Integration) when parcel is being auctioned /// </summary> public uint AuctionID { get { return _auctionID; } set { _auctionID = value; } } /// <summary> /// UUID of authorized buyer of parcel. This is UUID.Zero if anyone can buy it. /// </summary> public UUID AuthBuyerID { get { return _authBuyerID; } set { _authBuyerID = value; } } /// <summary> /// Category of parcel. Used for classifying the parcel in classified listings /// </summary> public ParcelCategory Category { get { return _category; } set { _category = value; } } /// <summary> /// Date that the current owner purchased or claimed the parcel /// </summary> public int ClaimDate { get { return _claimDate; } set { _claimDate = value; } } /// <summary> /// The last price that the parcel was sold at /// </summary> public int ClaimPrice { get { return _claimPrice; } set { _claimPrice = value; } } /// <summary> /// Global ID for the parcel. (3rd Party Integration) /// </summary> public UUID GlobalID { get { return _globalID; } set { _globalID = value; } } /// <summary> /// Unique ID of the Group that owns /// </summary> public UUID GroupID { get { return _groupID; } set { _groupID = value; } } /// <summary> /// Number of SceneObjectPart that are owned by a Group /// </summary> [XmlIgnore] public int GroupPrims { get { return _groupPrims; } set { _groupPrims = value; } } /// <summary> /// Returns true if the Land Parcel is owned by a group /// </summary> public bool IsGroupOwned { get { return _isGroupOwned; } set { _isGroupOwned = value; } } /// <summary> /// jp2 data for the image representative of the parcel in the parcel dialog /// </summary> public byte[] Bitmap { get { return _bitmap; } set { _bitmap = value; } } /// <summary> /// Parcel Description /// </summary> public string Description { get { return _description; } set { _description = value; } } /// <summary> /// Parcel settings. Access flags, Fly, NoPush, Voice, Scripts allowed, etc. ParcelFlags /// </summary> public uint Flags { get { return _flags; } set { _flags = value; } } /// <summary> /// Determines if people are able to teleport where they please on the parcel or if they /// get constrainted to a specific point on teleport within the parcel /// </summary> public byte LandingType { get { return _landingType; } set { _landingType = value; } } /// <summary> /// Parcel Name /// </summary> public string Name { get { return _name; } set { _name = value; } } /// <summary> /// Status of Parcel, Leased, Abandoned, For Sale /// </summary> public ParcelStatus Status { get { return _status; } set { _status = value; } } /// <summary> /// Internal ID of the parcel. Sometimes the client will try to use this value /// </summary> public int LocalID { get { return _localID; } set { _localID = value; } } /// <summary> /// Determines if we scale the media based on the surface it's on /// </summary> public byte MediaAutoScale { get { return _mediaAutoScale; } set { _mediaAutoScale = value; } } /// <summary> /// Texture Guid to replace with the output of the media stream /// </summary> public UUID MediaID { get { return _mediaID; } set { _mediaID = value; } } /// <summary> /// URL to the media file to display /// </summary> public string MediaURL { get { return _mediaURL; } set { _mediaURL = value; } } private int[] _mediaSize = new int[2]; public int[] MediaSize { get { return _mediaSize; } set { _mediaSize = value; } } private string _mediaType = ""; public string MediaType { get { return _mediaType; } set { _mediaType = value; } } /// <summary> /// URL to the shoutcast music stream to play on the parcel /// </summary> public string MusicURL { get { return _musicURL; } set { _musicURL = value; } } /// <summary> /// Number of SceneObjectPart that are owned by users who do not own the parcel /// and don't have the 'group. These are elegable for AutoReturn collection /// </summary> [XmlIgnore] public int OtherPrims { get { return _otherPrims; } set { _otherPrims = value; } } /// <summary> /// Owner Avatar or Group of the parcel. Naturally, all land masses must be /// owned by someone /// </summary> public UUID OwnerID { get { return _ownerID; } set { _ownerID = value; } } /// <summary> /// Number of SceneObjectPart that are owned by the owner of the parcel /// </summary> [XmlIgnore] public int OwnerPrims { get { return _ownerPrims; } set { _ownerPrims = value; } } /// <summary> /// List of access data for the parcel. User data, some bitflags, and a time /// </summary> public List<ParcelManager.ParcelAccessEntry> ParcelAccessList { get { return _parcelAccessList; } set { _parcelAccessList = value; } } /// <summary> /// How long in hours a Pass to the parcel is given /// </summary> public float PassHours { get { return _passHours; } set { _passHours = value; } } /// <summary> /// Price to purchase a Pass to a restricted parcel /// </summary> public int PassPrice { get { return _passPrice; } set { _passPrice = value; } } /// <summary> /// When the parcel is being sold, this is the price to purchase the parcel /// </summary> public int SalePrice { get { return _salePrice; } set { _salePrice = value; } } /// <summary> /// Number of SceneObjectPart that are currently selected by avatar /// </summary> [XmlIgnore] public int SelectedPrims { get { return _selectedPrims; } set { _selectedPrims = value; } } /// <summary> /// Number of meters^2 in the Simulator /// </summary> [XmlIgnore] public int SimwideArea { get { return _simwideArea; } set { _simwideArea = value; } } /// <summary> /// Number of SceneObjectPart in the Simulator /// </summary> [XmlIgnore] public int SimwidePrims { get { return _simwidePrims; } set { _simwidePrims = value; } } /// <summary> /// ID of the snapshot used in the client parcel dialog of the parcel /// </summary> public UUID SnapshotID { get { return _snapshotID; } set { _snapshotID = value; } } /// <summary> /// When teleporting is restricted to a certain point, this is the location /// that the user will be redirected to /// </summary> public Vector3 UserLocation { get { return _userLocation; } set { _userLocation = value; } } /// <summary> /// When teleporting is restricted to a certain point, this is the rotation /// that the user will be positioned /// </summary> public Vector3 UserLookAt { get { return _userLookAt; } set { _userLookAt = value; } } /// <summary> /// Deprecated idea. Number of visitors ~= free money /// </summary> public int Dwell { get { return _dwell; } set { _dwell = value; } } /// <summary> /// Number of minutes to return SceneObjectGroup that are owned by someone who doesn't own /// the parcel and isn't set to the same 'group' as the parcel. /// </summary> public int OtherCleanTime { get { return _otherCleanTime; } set { _otherCleanTime = value; } } public LandData() { _globalID = UUID.Random(); } /// <summary> /// Make a new copy of the land data /// </summary> /// <returns></returns> public LandData Copy() { LandData landData = new LandData(); landData._AABBMax = _AABBMax; landData._AABBMin = _AABBMin; landData._area = _area; landData._auctionID = _auctionID; landData._authBuyerID = _authBuyerID; landData._category = _category; landData._claimDate = _claimDate; landData._claimPrice = _claimPrice; landData._globalID = _globalID; landData._groupID = _groupID; landData._groupPrims = _groupPrims; landData._otherPrims = _otherPrims; landData._ownerPrims = _ownerPrims; landData._selectedPrims = _selectedPrims; landData._isGroupOwned = _isGroupOwned; landData._localID = _localID; landData._landingType = _landingType; landData._mediaAutoScale = _mediaAutoScale; landData._mediaID = _mediaID; landData._mediaURL = _mediaURL; landData._musicURL = _musicURL; landData._ownerID = _ownerID; landData._bitmap = (byte[]) _bitmap.Clone(); landData._description = _description; landData._flags = _flags; landData._name = _name; landData._status = _status; landData._passHours = _passHours; landData._passPrice = _passPrice; landData._salePrice = _salePrice; landData._snapshotID = _snapshotID; landData._userLocation = _userLocation; landData._userLookAt = _userLookAt; landData._otherCleanTime = _otherCleanTime; landData._dwell = _dwell; landData._parcelAccessList.Clear(); foreach (ParcelManager.ParcelAccessEntry entry in _parcelAccessList) { ParcelManager.ParcelAccessEntry newEntry = new ParcelManager.ParcelAccessEntry(); newEntry.AgentID = entry.AgentID; newEntry.Flags = entry.Flags; newEntry.Time = entry.Time; landData._parcelAccessList.Add(newEntry); } return landData; } public void ToXml(XmlWriter xmlWriter) { serializer.Serialize(xmlWriter, this); } /// <summary> /// Restore a LandData object from the serialized xml representation. /// </summary> /// <param name="xmlReader"></param> /// <returns></returns> public static LandData FromXml(XmlReader xmlReader) { LandData land = (LandData)serializer.Deserialize(xmlReader); return land; } } }
using System; using System.Globalization; using System.Linq; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.CompilerServices; namespace Aardvark.Base { #region Rot2f /// <summary> /// Represents a 2D rotation counterclockwise around the origin. /// </summary> [DataContract] [StructLayout(LayoutKind.Sequential)] public struct Rot2f { [DataMember] public float Angle; #region Constructors /// <summary> /// Constructs a <see cref="Rot2f"/> transformation given a rotation angle in radians. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Rot2f(float angleInRadians) { Angle = angleInRadians; } /// <summary> /// Constructs a copy of a <see cref="Rot2f"/> transformation. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Rot2f(Rot2f r) { Angle = r.Angle; } #endregion #region Constants /// <summary> /// Gets the identity <see cref="Rot2f"/> transformation. /// </summary> public static Rot2f Identity { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => new Rot2f(0); } #endregion #region Properties /// <summary> /// Gets the inverse of this <see cref="Rot2f"/> tranformation. /// </summary> public Rot2f Inverse { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => new Rot2f(-Angle); } #endregion #region Arithmetic operators /// <summary> /// Multiplies two <see cref="Rot2f"/> transformations. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Rot2f operator *(Rot2f r0, Rot2f r1) { return new Rot2f(r0.Angle + r1.Angle); } #region Rot / Vector Multiplication /// <summary> /// Multiplies a <see cref="Rot2f"/> transformation with a <see cref="V2f"/>. /// Attention: Multiplication is NOT commutative! /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static V2f operator *(Rot2f rot, V2f vec) { float a = Fun.Cos(rot.Angle); float b = Fun.Sin(rot.Angle); return new V2f(a * vec.X + -b * vec.Y, b * vec.X + a * vec.Y); } #endregion #region Rot / Matrix Multiplication /// <summary> /// Multiplies a <see cref="Rot2f"/> transformation (as a 2x2 matrix) with a <see cref="M22f"/>. /// Attention: Multiplication is NOT commutative! /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static M22f operator *(Rot2f r, M22f m) { float a = Fun.Cos(r.Angle); float b = Fun.Sin(r.Angle); return new M22f( a * m.M00 + -b * m.M10, a * m.M01 + -b * m.M11, b * m.M00 + a * m.M10, b * m.M01 + a * m.M11); } /// <summary> /// Multiplies a <see cref="M22f"/> with a <see cref="Rot2f"/> transformation (as a 2x2 matrix). /// Attention: Multiplication is NOT commutative! /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static M22f operator *(M22f m, Rot2f r) { float a = Fun.Cos(r.Angle); float b = Fun.Sin(r.Angle); return new M22f( m.M00 * a + m.M01 * b, m.M00 * -b + m.M01 * a, m.M10 * a + m.M11 * b, m.M10 * -b + m.M11 * a); } /// <summary> /// Multiplies a <see cref="Rot2f"/> transformation (as a 2x2 matrix) with a <see cref="M23f"/>. /// Attention: Multiplication is NOT commutative! /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static M23f operator *(Rot2f r, M23f m) { float a = Fun.Cos(r.Angle); float b = Fun.Sin(r.Angle); return new M23f( a * m.M00 + -b * m.M10, a * m.M01 + -b * m.M11, a * m.M02 + -b * m.M12, b * m.M00 + a * m.M10, b * m.M01 + a * m.M11, b * m.M02 + a * m.M12); } /// <summary> /// Multiplies a <see cref="M23f"/> with a <see cref="Rot2f"/> transformation (as a 3x3 matrix). /// Attention: Multiplication is NOT commutative! /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static M23f operator *(M23f m, Rot2f r) { float a = Fun.Cos(r.Angle); float b = Fun.Sin(r.Angle); return new M23f( m.M00 * a + m.M01 * b, m.M00 * -b + m.M01 * a, m.M02, m.M10 * a + m.M11 * b, m.M10 * -b + m.M11 * a, m.M12); } /// <summary> /// Multiplies a <see cref="Rot2f"/> transformation (as a 3x3 matrix) with a <see cref="M33f"/>. /// Attention: Multiplication is NOT commutative! /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static M33f operator *(Rot2f r, M33f m) { float a = Fun.Cos(r.Angle); float b = Fun.Sin(r.Angle); return new M33f( a * m.M00 + -b * m.M10, a * m.M01 + -b * m.M11, a * m.M02 + -b * m.M12, b * m.M00 + a * m.M10, b * m.M01 + a * m.M11, b * m.M02 + a * m.M12, m.M20, m.M21, m.M22); } /// <summary> /// Multiplies a <see cref="M33f"/> with a <see cref="Rot2f"/> transformation (as a 3x3 matrix). /// Attention: Multiplication is NOT commutative! /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static M33f operator *(M33f m, Rot2f r) { float a = Fun.Cos(r.Angle); float b = Fun.Sin(r.Angle); return new M33f( m.M00 * a + m.M01 * b, m.M00 * -b + m.M01 * a, m.M02, m.M10 * a + m.M11 * b, m.M10 * -b + m.M11 * a, m.M12, m.M20 * a + m.M21 * b, m.M20 * -b + m.M21 * a, m.M22); } #endregion #region Rot / Shift, Scale Multiplication /// <summary> /// Multiplies a <see cref="Rot2f"/> transformation with a <see cref="Shift2f"/> transformation. /// Attention: Multiplication is NOT commutative! /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Euclidean2f operator *(Rot2f a, Shift2f b) => new Euclidean2f(a, a * b.V); /// <summary> /// Multiplies a <see cref="Rot2f"/> transformation with a <see cref="Scale2f"/> transformation. /// Attention: Multiplication is NOT commutative! /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Affine2f operator *(Rot2f a, Scale2f b) => new Affine2f((M22f)a * (M22f)b); #endregion #endregion #region Comparison Operators /// <summary> /// Checks if 2 rotations are equal. /// </summary> /// <returns>Result of comparison.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Rot2f rotation1, Rot2f rotation2) => Rot.Distance(rotation1, rotation2) == 0; /// <summary> /// Checks if 2 rotations are not equal. /// </summary> /// <returns>Result of comparison.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Rot2f rotation1, Rot2f rotation2) => Rot.Distance(rotation1, rotation2) != 0; #endregion #region Static Creators /// <summary> /// Creates a <see cref="Rot2f"/> transformation from a <see cref="M22f"/> matrix. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Rot2f FromM22f(M22f m) { return new Rot2f(m.GetRotation()); } /// <summary> /// Creates a <see cref="Rot2f"/> transformation from a <see cref="M33f"/> matrix. /// The matrix has to be homogeneous and must not contain perspective components. /// </summary> /// <exception cref="ArgumentException"></exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Rot2f FromM33f(M33f m, float epsilon = 1e-5f) { if (!(m.M20.IsTiny(epsilon) && m.M21.IsTiny(epsilon))) throw new ArgumentException("Matrix contains perspective components."); if (!m.C2.XY.ApproximateEquals(V2f.Zero, epsilon)) throw new ArgumentException("Matrix contains translational component."); if (m.M22.IsTiny(epsilon)) throw new ArgumentException("Matrix is not homogeneous."); return FromM22f(((M22f)m) / m.M22); } /// <summary> /// Creates a <see cref="Rot2f"/> transformation from a <see cref="Euclidean2f"/>. /// The transformation <paramref name="euclidean"/> must only consist of a rotation. /// </summary> /// <exception cref="ArgumentException"></exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Rot2f FromEuclidean2f(Euclidean2f euclidean, float epsilon = 1e-5f) { if (!euclidean.Trans.ApproximateEquals(V2f.Zero, epsilon)) throw new ArgumentException("Euclidean transformation contains translational component"); return euclidean.Rot; } /// <summary> /// Creates a <see cref="Rot2f"/> transformation from a <see cref="Similarity2f"/>. /// The transformation <paramref name="similarity"/> must only consist of a rotation. /// </summary> /// <exception cref="ArgumentException"></exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Rot2f FromSimilarity2f(Similarity2f similarity, float epsilon = 1e-5f) { if (!similarity.Scale.ApproximateEquals(1, epsilon)) throw new ArgumentException("Similarity transformation contains scaling component"); if (!similarity.Trans.ApproximateEquals(V2f.Zero, epsilon)) throw new ArgumentException("Similarity transformation contains translational component"); return similarity.Rot; } /// <summary> /// Creates a <see cref="Rot2f"/> transformation from an <see cref="Affine2f"/>. /// The transformation <paramref name="affine"/> must only consist of a rotation. /// </summary> /// <exception cref="ArgumentException"></exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Rot2f FromAffine2f(Affine2f affine, float epsilon = 1e-5f) => FromM33f((M33f)affine, epsilon); /// <summary> /// Creates a <see cref="Rot2f"/> transformation from a <see cref="Trafo2f"/>. /// The transformation <paramref name="trafo"/> must only consist of a rotation. /// </summary> /// <exception cref="ArgumentException"></exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Rot2f FromTrafo2f(Trafo2f trafo, float epsilon = 1e-5f) => FromM33f(trafo.Forward, epsilon); /// <summary> /// Creates a <see cref="Rot2f"/> transformation with the specified angle in radians. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Rot2f FromRadians(float angleInRadians) => new Rot2f(angleInRadians); /// <summary> /// Creates a <see cref="Rot2f"/> transformation with the specified angle in degrees. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Rot2f FromDegrees(float angleInDegrees) => new Rot2f(angleInDegrees.RadiansFromDegrees()); #endregion #region Conversion Operators [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator M22f(Rot2f r) { float a = Fun.Cos(r.Angle); float b = Fun.Sin(r.Angle); return new M22f( a, -b, b, a); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator M23f(Rot2f r) { float a = Fun.Cos(r.Angle); float b = Fun.Sin(r.Angle); return new M23f( a, -b, 0, b, a, 0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator M33f(Rot2f r) { float a = Fun.Cos(r.Angle); float b = Fun.Sin(r.Angle); return new M33f( a, -b, 0, b, a, 0, 0, 0, 1); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator M34f(Rot2f r) { float a = Fun.Cos(r.Angle); float b = Fun.Sin(r.Angle); return new M34f( a, -b, 0, 0, b, a, 0, 0, 0, 0, 1, 0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator M44f(Rot2f r) { float a = Fun.Cos(r.Angle); float b = Fun.Sin(r.Angle); return new M44f( a, -b, 0, 0, b, a, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator Euclidean2f(Rot2f r) => new Euclidean2f(r, V2f.Zero); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator Similarity2f(Rot2f r) => new Similarity2f(1, r, V2f.Zero); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator Affine2f(Rot2f r) => new Affine2f((M22f)r); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator Trafo2f(Rot2f r) => new Trafo2f((M33f)r, (M33f)r.Inverse); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator Rot2d(Rot2f r) => new Rot2d((double)r.Angle); #endregion #region Overrides public override int GetHashCode() { return Angle.GetHashCode(); } public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "[{0}]", Angle); } public static Rot2f Parse(string s) { var x = s.NestedBracketSplitLevelOne().ToArray(); return new Rot2f( float.Parse(x[0], CultureInfo.InvariantCulture) ); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(Rot2f other) => Rot.Distance(this, other) == 0; public override bool Equals(object other) => (other is Rot2f o) ? Equals(o) : false; #endregion } public static partial class Rot { #region Invert /// <summary> /// Returns the inverse of a <see cref="Rot2f"/> transformation. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Rot2f Inverse(Rot2f rot) => rot.Inverse; /// <summary> /// Inverts a <see cref="Rot2f"/>. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Invert(this ref Rot2f rot) { rot.Angle = -rot.Angle; } #endregion #region Distance /// <summary> /// Returns the absolute difference in radians between two <see cref="Rot2f"/> rotations. /// The result is within the range of [0, Pi]. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Distance(this Rot2f r1, Rot2f r2) { var phi = Fun.Abs(r2.Angle - r1.Angle) % (float)Constant.PiTimesTwo; return (phi > (float)Constant.Pi) ? (float)Constant.PiTimesTwo - phi : phi; } #endregion #region Transform /// <summary> /// Transforms a <see cref="V2f"/> vector by a <see cref="Rot2f"/> transformation. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static V2f Transform(this Rot2f rot, V2f v) { return rot * v; } /// <summary> /// Transforms a <see cref="V3f"/> vector by a <see cref="Rot2f"/> transformation. /// The z coordinate of the vector is unaffected. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static V3f Transform(this Rot2f rot, V3f v) { float a = Fun.Cos(rot.Angle); float b = Fun.Sin(rot.Angle); return new V3f(a * v.X + -b * v.Y, b * v.X + a * v.Y, v.Z); } /// <summary> /// Transforms a <see cref="V4f"/> vector by a <see cref="Rot2f"/> transformation. /// The z and w coordinates of the vector are unaffected. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static V4f Transform(this Rot2f rot, V4f v) { float a = Fun.Cos(rot.Angle); float b = Fun.Sin(rot.Angle); return new V4f(a * v.X + -b * v.Y, b * v.X + a * v.Y, v.Z, v.W); } /// <summary> /// Transforms a <see cref="V2f"/> vector by the inverse of a <see cref="Rot2f"/> transformation. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static V2f InvTransform(this Rot2f rot, V2f v) { float a = Fun.Cos(-rot.Angle); float b = Fun.Sin(-rot.Angle); return new V2f(a * v.X + -b * v.Y, b * v.X + a * v.Y); } /// <summary> /// Transforms a <see cref="V3f"/> vector by the inverse of a <see cref="Rot2f"/> transformation. /// The z coordinate of the vector is unaffected. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static V3f InvTransform(this Rot2f rot, V3f v) => Transform(rot.Inverse, v); /// <summary> /// Transforms a <see cref="V4f"/> vector by the inverse of a <see cref="Rot2f"/> transformation. /// The z and w coordinates of the vector are unaffected. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static V4f InvTransform(this Rot2f rot, V4f v) => Transform(rot.Inverse, v); #endregion } public static partial class Fun { #region ApproximateEquals [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool ApproximateEquals(this Rot2f r0, Rot2f r1) { return ApproximateEquals(r0, r1, Constant<float>.PositiveTinyValue); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool ApproximateEquals(this Rot2f r0, Rot2f r1, float tolerance) { return Rot.Distance(r0, r1) <= tolerance; } #endregion } #endregion #region Rot2d /// <summary> /// Represents a 2D rotation counterclockwise around the origin. /// </summary> [DataContract] [StructLayout(LayoutKind.Sequential)] public struct Rot2d { [DataMember] public double Angle; #region Constructors /// <summary> /// Constructs a <see cref="Rot2d"/> transformation given a rotation angle in radians. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Rot2d(double angleInRadians) { Angle = angleInRadians; } /// <summary> /// Constructs a copy of a <see cref="Rot2d"/> transformation. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Rot2d(Rot2d r) { Angle = r.Angle; } #endregion #region Constants /// <summary> /// Gets the identity <see cref="Rot2d"/> transformation. /// </summary> public static Rot2d Identity { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => new Rot2d(0); } #endregion #region Properties /// <summary> /// Gets the inverse of this <see cref="Rot2d"/> tranformation. /// </summary> public Rot2d Inverse { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => new Rot2d(-Angle); } #endregion #region Arithmetic operators /// <summary> /// Multiplies two <see cref="Rot2d"/> transformations. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Rot2d operator *(Rot2d r0, Rot2d r1) { return new Rot2d(r0.Angle + r1.Angle); } #region Rot / Vector Multiplication /// <summary> /// Multiplies a <see cref="Rot2d"/> transformation with a <see cref="V2d"/>. /// Attention: Multiplication is NOT commutative! /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static V2d operator *(Rot2d rot, V2d vec) { double a = Fun.Cos(rot.Angle); double b = Fun.Sin(rot.Angle); return new V2d(a * vec.X + -b * vec.Y, b * vec.X + a * vec.Y); } #endregion #region Rot / Matrix Multiplication /// <summary> /// Multiplies a <see cref="Rot2d"/> transformation (as a 2x2 matrix) with a <see cref="M22d"/>. /// Attention: Multiplication is NOT commutative! /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static M22d operator *(Rot2d r, M22d m) { double a = Fun.Cos(r.Angle); double b = Fun.Sin(r.Angle); return new M22d( a * m.M00 + -b * m.M10, a * m.M01 + -b * m.M11, b * m.M00 + a * m.M10, b * m.M01 + a * m.M11); } /// <summary> /// Multiplies a <see cref="M22d"/> with a <see cref="Rot2d"/> transformation (as a 2x2 matrix). /// Attention: Multiplication is NOT commutative! /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static M22d operator *(M22d m, Rot2d r) { double a = Fun.Cos(r.Angle); double b = Fun.Sin(r.Angle); return new M22d( m.M00 * a + m.M01 * b, m.M00 * -b + m.M01 * a, m.M10 * a + m.M11 * b, m.M10 * -b + m.M11 * a); } /// <summary> /// Multiplies a <see cref="Rot2d"/> transformation (as a 2x2 matrix) with a <see cref="M23d"/>. /// Attention: Multiplication is NOT commutative! /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static M23d operator *(Rot2d r, M23d m) { double a = Fun.Cos(r.Angle); double b = Fun.Sin(r.Angle); return new M23d( a * m.M00 + -b * m.M10, a * m.M01 + -b * m.M11, a * m.M02 + -b * m.M12, b * m.M00 + a * m.M10, b * m.M01 + a * m.M11, b * m.M02 + a * m.M12); } /// <summary> /// Multiplies a <see cref="M23d"/> with a <see cref="Rot2d"/> transformation (as a 3x3 matrix). /// Attention: Multiplication is NOT commutative! /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static M23d operator *(M23d m, Rot2d r) { double a = Fun.Cos(r.Angle); double b = Fun.Sin(r.Angle); return new M23d( m.M00 * a + m.M01 * b, m.M00 * -b + m.M01 * a, m.M02, m.M10 * a + m.M11 * b, m.M10 * -b + m.M11 * a, m.M12); } /// <summary> /// Multiplies a <see cref="Rot2d"/> transformation (as a 3x3 matrix) with a <see cref="M33d"/>. /// Attention: Multiplication is NOT commutative! /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static M33d operator *(Rot2d r, M33d m) { double a = Fun.Cos(r.Angle); double b = Fun.Sin(r.Angle); return new M33d( a * m.M00 + -b * m.M10, a * m.M01 + -b * m.M11, a * m.M02 + -b * m.M12, b * m.M00 + a * m.M10, b * m.M01 + a * m.M11, b * m.M02 + a * m.M12, m.M20, m.M21, m.M22); } /// <summary> /// Multiplies a <see cref="M33d"/> with a <see cref="Rot2d"/> transformation (as a 3x3 matrix). /// Attention: Multiplication is NOT commutative! /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static M33d operator *(M33d m, Rot2d r) { double a = Fun.Cos(r.Angle); double b = Fun.Sin(r.Angle); return new M33d( m.M00 * a + m.M01 * b, m.M00 * -b + m.M01 * a, m.M02, m.M10 * a + m.M11 * b, m.M10 * -b + m.M11 * a, m.M12, m.M20 * a + m.M21 * b, m.M20 * -b + m.M21 * a, m.M22); } #endregion #region Rot / Shift, Scale Multiplication /// <summary> /// Multiplies a <see cref="Rot2d"/> transformation with a <see cref="Shift2d"/> transformation. /// Attention: Multiplication is NOT commutative! /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Euclidean2d operator *(Rot2d a, Shift2d b) => new Euclidean2d(a, a * b.V); /// <summary> /// Multiplies a <see cref="Rot2d"/> transformation with a <see cref="Scale2d"/> transformation. /// Attention: Multiplication is NOT commutative! /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Affine2d operator *(Rot2d a, Scale2d b) => new Affine2d((M22d)a * (M22d)b); #endregion #endregion #region Comparison Operators /// <summary> /// Checks if 2 rotations are equal. /// </summary> /// <returns>Result of comparison.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Rot2d rotation1, Rot2d rotation2) => Rot.Distance(rotation1, rotation2) == 0; /// <summary> /// Checks if 2 rotations are not equal. /// </summary> /// <returns>Result of comparison.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Rot2d rotation1, Rot2d rotation2) => Rot.Distance(rotation1, rotation2) != 0; #endregion #region Static Creators /// <summary> /// Creates a <see cref="Rot2d"/> transformation from a <see cref="M22d"/> matrix. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Rot2d FromM22d(M22d m) { return new Rot2d(m.GetRotation()); } /// <summary> /// Creates a <see cref="Rot2d"/> transformation from a <see cref="M33d"/> matrix. /// The matrix has to be homogeneous and must not contain perspective components. /// </summary> /// <exception cref="ArgumentException"></exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Rot2d FromM33d(M33d m, double epsilon = 1e-12) { if (!(m.M20.IsTiny(epsilon) && m.M21.IsTiny(epsilon))) throw new ArgumentException("Matrix contains perspective components."); if (!m.C2.XY.ApproximateEquals(V2d.Zero, epsilon)) throw new ArgumentException("Matrix contains translational component."); if (m.M22.IsTiny(epsilon)) throw new ArgumentException("Matrix is not homogeneous."); return FromM22d(((M22d)m) / m.M22); } /// <summary> /// Creates a <see cref="Rot2d"/> transformation from a <see cref="Euclidean2d"/>. /// The transformation <paramref name="euclidean"/> must only consist of a rotation. /// </summary> /// <exception cref="ArgumentException"></exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Rot2d FromEuclidean2d(Euclidean2d euclidean, double epsilon = 1e-12) { if (!euclidean.Trans.ApproximateEquals(V2d.Zero, epsilon)) throw new ArgumentException("Euclidean transformation contains translational component"); return euclidean.Rot; } /// <summary> /// Creates a <see cref="Rot2d"/> transformation from a <see cref="Similarity2d"/>. /// The transformation <paramref name="similarity"/> must only consist of a rotation. /// </summary> /// <exception cref="ArgumentException"></exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Rot2d FromSimilarity2d(Similarity2d similarity, double epsilon = 1e-12) { if (!similarity.Scale.ApproximateEquals(1, epsilon)) throw new ArgumentException("Similarity transformation contains scaling component"); if (!similarity.Trans.ApproximateEquals(V2d.Zero, epsilon)) throw new ArgumentException("Similarity transformation contains translational component"); return similarity.Rot; } /// <summary> /// Creates a <see cref="Rot2d"/> transformation from an <see cref="Affine2d"/>. /// The transformation <paramref name="affine"/> must only consist of a rotation. /// </summary> /// <exception cref="ArgumentException"></exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Rot2d FromAffine2d(Affine2d affine, double epsilon = 1e-12) => FromM33d((M33d)affine, epsilon); /// <summary> /// Creates a <see cref="Rot2d"/> transformation from a <see cref="Trafo2d"/>. /// The transformation <paramref name="trafo"/> must only consist of a rotation. /// </summary> /// <exception cref="ArgumentException"></exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Rot2d FromTrafo2d(Trafo2d trafo, double epsilon = 1e-12) => FromM33d(trafo.Forward, epsilon); /// <summary> /// Creates a <see cref="Rot2d"/> transformation with the specified angle in radians. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Rot2d FromRadians(double angleInRadians) => new Rot2d(angleInRadians); /// <summary> /// Creates a <see cref="Rot2d"/> transformation with the specified angle in degrees. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Rot2d FromDegrees(double angleInDegrees) => new Rot2d(angleInDegrees.RadiansFromDegrees()); #endregion #region Conversion Operators [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator M22d(Rot2d r) { double a = Fun.Cos(r.Angle); double b = Fun.Sin(r.Angle); return new M22d( a, -b, b, a); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator M23d(Rot2d r) { double a = Fun.Cos(r.Angle); double b = Fun.Sin(r.Angle); return new M23d( a, -b, 0, b, a, 0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator M33d(Rot2d r) { double a = Fun.Cos(r.Angle); double b = Fun.Sin(r.Angle); return new M33d( a, -b, 0, b, a, 0, 0, 0, 1); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator M34d(Rot2d r) { double a = Fun.Cos(r.Angle); double b = Fun.Sin(r.Angle); return new M34d( a, -b, 0, 0, b, a, 0, 0, 0, 0, 1, 0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator M44d(Rot2d r) { double a = Fun.Cos(r.Angle); double b = Fun.Sin(r.Angle); return new M44d( a, -b, 0, 0, b, a, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator Euclidean2d(Rot2d r) => new Euclidean2d(r, V2d.Zero); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator Similarity2d(Rot2d r) => new Similarity2d(1, r, V2d.Zero); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator Affine2d(Rot2d r) => new Affine2d((M22d)r); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator Trafo2d(Rot2d r) => new Trafo2d((M33d)r, (M33d)r.Inverse); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator Rot2f(Rot2d r) => new Rot2f((float)r.Angle); #endregion #region Overrides public override int GetHashCode() { return Angle.GetHashCode(); } public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "[{0}]", Angle); } public static Rot2d Parse(string s) { var x = s.NestedBracketSplitLevelOne().ToArray(); return new Rot2d( double.Parse(x[0], CultureInfo.InvariantCulture) ); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(Rot2d other) => Rot.Distance(this, other) == 0; public override bool Equals(object other) => (other is Rot2d o) ? Equals(o) : false; #endregion } public static partial class Rot { #region Invert /// <summary> /// Returns the inverse of a <see cref="Rot2d"/> transformation. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Rot2d Inverse(Rot2d rot) => rot.Inverse; /// <summary> /// Inverts a <see cref="Rot2d"/>. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Invert(this ref Rot2d rot) { rot.Angle = -rot.Angle; } #endregion #region Distance /// <summary> /// Returns the absolute difference in radians between two <see cref="Rot2d"/> rotations. /// The result is within the range of [0, Pi]. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double Distance(this Rot2d r1, Rot2d r2) { var phi = Fun.Abs(r2.Angle - r1.Angle) % Constant.PiTimesTwo; return (phi > Constant.Pi) ? Constant.PiTimesTwo - phi : phi; } #endregion #region Transform /// <summary> /// Transforms a <see cref="V2d"/> vector by a <see cref="Rot2d"/> transformation. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static V2d Transform(this Rot2d rot, V2d v) { return rot * v; } /// <summary> /// Transforms a <see cref="V3d"/> vector by a <see cref="Rot2d"/> transformation. /// The z coordinate of the vector is unaffected. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static V3d Transform(this Rot2d rot, V3d v) { double a = Fun.Cos(rot.Angle); double b = Fun.Sin(rot.Angle); return new V3d(a * v.X + -b * v.Y, b * v.X + a * v.Y, v.Z); } /// <summary> /// Transforms a <see cref="V4d"/> vector by a <see cref="Rot2d"/> transformation. /// The z and w coordinates of the vector are unaffected. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static V4d Transform(this Rot2d rot, V4d v) { double a = Fun.Cos(rot.Angle); double b = Fun.Sin(rot.Angle); return new V4d(a * v.X + -b * v.Y, b * v.X + a * v.Y, v.Z, v.W); } /// <summary> /// Transforms a <see cref="V2d"/> vector by the inverse of a <see cref="Rot2d"/> transformation. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static V2d InvTransform(this Rot2d rot, V2d v) { double a = Fun.Cos(-rot.Angle); double b = Fun.Sin(-rot.Angle); return new V2d(a * v.X + -b * v.Y, b * v.X + a * v.Y); } /// <summary> /// Transforms a <see cref="V3d"/> vector by the inverse of a <see cref="Rot2d"/> transformation. /// The z coordinate of the vector is unaffected. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static V3d InvTransform(this Rot2d rot, V3d v) => Transform(rot.Inverse, v); /// <summary> /// Transforms a <see cref="V4d"/> vector by the inverse of a <see cref="Rot2d"/> transformation. /// The z and w coordinates of the vector are unaffected. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static V4d InvTransform(this Rot2d rot, V4d v) => Transform(rot.Inverse, v); #endregion } public static partial class Fun { #region ApproximateEquals [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool ApproximateEquals(this Rot2d r0, Rot2d r1) { return ApproximateEquals(r0, r1, Constant<double>.PositiveTinyValue); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool ApproximateEquals(this Rot2d r0, Rot2d r1, double tolerance) { return Rot.Distance(r0, r1) <= tolerance; } #endregion } #endregion }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Text; using Microsoft.Build.BuildEngine.Shared; using System.Xml; namespace Microsoft.Build.BuildEngine { /// <summary> /// This class represents a collection of all Import elements in a given project file /// </summary> /// <owner>LukaszG</owner> public class ImportCollection : IEnumerable, ICollection { #region Fields private Hashtable imports; private Project parentProject; #endregion #region Constructors /// <summary> /// Constructor exposed to the outside world /// </summary> /// <owner>LukaszG</owner> internal ImportCollection(Project parentProject) { // Make sure we have a valid parent Project ErrorUtilities.VerifyThrow(parentProject != null, "Need a parent Project object to instantiate an ImportCollection."); this.parentProject = parentProject; this.imports = new Hashtable(StringComparer.OrdinalIgnoreCase); } #endregion #region IEnumerable Members /// <summary> /// IEnumerable member method for returning the enumerator /// </summary> /// <returns></returns> /// <owner>LukaszG</owner> public IEnumerator GetEnumerator() { ErrorUtilities.VerifyThrow(this.imports != null, "ImportCollection's Hashtable not initialized!"); return this.imports.Values.GetEnumerator(); } #endregion #region ICollection Members /// <summary> /// ICollection member method for copying the contents of this collection into an array /// </summary> /// <param name="array"></param> /// <param name="index"></param> /// <owner>LukaszG</owner> public void CopyTo(Array array, int index) { ErrorUtilities.VerifyThrow(this.imports != null, "ImportCollection's Dictionary not initialized!"); this.imports.Values.CopyTo(array, index); } /// <summary> /// ICollection member property for returning the number of items in this collection /// </summary> /// <owner>LukaszG</owner> public int Count { get { ErrorUtilities.VerifyThrow(this.imports != null, "ImportCollection's Dictionary not initialized!"); return this.imports.Count; } } /// <summary> /// ICollection member property for determining whether this collection is thread-safe /// </summary> /// <owner>LukaszG</owner> public bool IsSynchronized { get { ErrorUtilities.VerifyThrow(this.imports != null, "ImportCollection's Dictionary not initialized!"); return this.imports.IsSynchronized; } } /// <summary> /// ICollection member property for returning this collection's synchronization object /// </summary> /// <owner>LukaszG</owner> public object SyncRoot { get { ErrorUtilities.VerifyThrow(this.imports != null, "ImportCollection's Dictionary not initialized!"); return this.imports.SyncRoot; } } #endregion #region Members /// <summary> /// Read-only accessor for the Project instance that this ImportCollection belongs to. /// </summary> internal Project ParentProject { get { return parentProject; } } /// <summary> /// Removes all Imports from this collection. Does not alter the parent project's XML. /// </summary> /// <owner>LukaszG</owner> internal void Clear() { ErrorUtilities.VerifyThrow(this.imports != null, "ImportCollection's Hashtable not initialized!"); this.imports.Clear(); } /// <summary> /// Gets the Import object with the given index /// </summary> /// <param name="index"></param> /// <returns></returns> /// <owner>LukaszG</owner> internal Import this[string index] { get { ErrorUtilities.VerifyThrow(this.imports != null, "ImportCollection's Hashtable not initialized!"); return (Import)this.imports[index]; } set { this.imports[index] = value; } } /// <summary> /// Copy the contents of this collection into a strongly typed array /// </summary> /// <param name="array"></param> /// <param name="index"></param> /// <owner>LukaszG</owner> public void CopyTo(Import[] array, int index) { ErrorUtilities.VerifyThrow(this.imports != null, "ImportCollection's Hashtable not initialized!"); this.imports.Values.CopyTo(array, index); } /// <summary> /// Adds a new import to the project ,and adds a corresponding &lt;Import&gt; element to the end of the project. /// </summary> /// <param name="projectFile">Project file to add the import to</param> /// <param name="condition">Condition. If null, no condition is added.</param> public void AddNewImport(string projectFile, string condition) { ErrorUtilities.VerifyThrowArgumentLength(projectFile, "projectFile"); XmlElement projectElement = this.parentProject.ProjectElement; XmlElement newImportElement = projectElement.OwnerDocument.CreateElement(XMakeElements.import, XMakeAttributes.defaultXmlNamespace); if (condition != null) { newImportElement.SetAttribute(XMakeAttributes.condition, condition); } newImportElement.SetAttribute(XMakeAttributes.project, projectFile); projectElement.AppendChild(newImportElement); this.parentProject.MarkProjectAsDirtyForReprocessXml(); } /// <summary> /// Removes an import from the project, and removes the corresponding &lt;Import&gt; element /// from the project's XML. /// </summary> /// <param name="importToRemove"></param> /// <owner>JeffCal</owner> public void RemoveImport ( Import importToRemove ) { ErrorUtilities.VerifyThrowArgumentNull(importToRemove, "importToRemove"); // Confirm that it's not an imported import. ErrorUtilities.VerifyThrowInvalidOperation(!importToRemove.IsImported, "CannotModifyImportedProjects"); // Confirm that the import belongs to this project. ErrorUtilities.VerifyThrowInvalidOperation(importToRemove.ParentProject == this.parentProject, "IncorrectObjectAssociation", "Import", "Project"); // Remove the Xml for the <Import> from the <Project>. this.parentProject.ProjectElement.RemoveChild(importToRemove.ImportElement); // Remove the import from our hashtable. this.imports.Remove(importToRemove.EvaluatedProjectPath); // Dissociate the import from the parent project. importToRemove.ParentProject = null; // The project file has been modified and needs to be saved and re-evaluated. this.parentProject.MarkProjectAsDirtyForReprocessXml(); } #endregion } }
using System; using System.Data; using Csla; using Csla.Data; using SelfLoadSoftDelete.DataAccess; using SelfLoadSoftDelete.DataAccess.ERCLevel; namespace SelfLoadSoftDelete.Business.ERCLevel { /// <summary> /// H03_SubContinentColl (editable child list).<br/> /// This is a generated base class of <see cref="H03_SubContinentColl"/> business object. /// </summary> /// <remarks> /// This class is child of <see cref="H02_Continent"/> editable child object.<br/> /// The items of the collection are <see cref="H04_SubContinent"/> objects. /// </remarks> [Serializable] public partial class H03_SubContinentColl : BusinessListBase<H03_SubContinentColl, H04_SubContinent> { #region Collection Business Methods /// <summary> /// Removes a <see cref="H04_SubContinent"/> item from the collection. /// </summary> /// <param name="subContinent_ID">The SubContinent_ID of the item to be removed.</param> public void Remove(int subContinent_ID) { foreach (var h04_SubContinent in this) { if (h04_SubContinent.SubContinent_ID == subContinent_ID) { Remove(h04_SubContinent); break; } } } /// <summary> /// Determines whether a <see cref="H04_SubContinent"/> item is in the collection. /// </summary> /// <param name="subContinent_ID">The SubContinent_ID of the item to search for.</param> /// <returns><c>true</c> if the H04_SubContinent is a collection item; otherwise, <c>false</c>.</returns> public bool Contains(int subContinent_ID) { foreach (var h04_SubContinent in this) { if (h04_SubContinent.SubContinent_ID == subContinent_ID) { return true; } } return false; } /// <summary> /// Determines whether a <see cref="H04_SubContinent"/> item is in the collection's DeletedList. /// </summary> /// <param name="subContinent_ID">The SubContinent_ID of the item to search for.</param> /// <returns><c>true</c> if the H04_SubContinent is a deleted collection item; otherwise, <c>false</c>.</returns> public bool ContainsDeleted(int subContinent_ID) { foreach (var h04_SubContinent in DeletedList) { if (h04_SubContinent.SubContinent_ID == subContinent_ID) { return true; } } return false; } #endregion #region Find Methods /// <summary> /// Finds a <see cref="H04_SubContinent"/> item of the <see cref="H03_SubContinentColl"/> collection, based on a given SubContinent_ID. /// </summary> /// <param name="subContinent_ID">The SubContinent_ID.</param> /// <returns>A <see cref="H04_SubContinent"/> object.</returns> public H04_SubContinent FindH04_SubContinentBySubContinent_ID(int subContinent_ID) { for (var i = 0; i < this.Count; i++) { if (this[i].SubContinent_ID.Equals(subContinent_ID)) { return this[i]; } } return null; } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="H03_SubContinentColl"/> collection. /// </summary> /// <returns>A reference to the created <see cref="H03_SubContinentColl"/> collection.</returns> internal static H03_SubContinentColl NewH03_SubContinentColl() { return DataPortal.CreateChild<H03_SubContinentColl>(); } /// <summary> /// Factory method. Loads a <see cref="H03_SubContinentColl"/> collection, based on given parameters. /// </summary> /// <param name="parent_Continent_ID">The Parent_Continent_ID parameter of the H03_SubContinentColl to fetch.</param> /// <returns>A reference to the fetched <see cref="H03_SubContinentColl"/> collection.</returns> internal static H03_SubContinentColl GetH03_SubContinentColl(int parent_Continent_ID) { return DataPortal.FetchChild<H03_SubContinentColl>(parent_Continent_ID); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="H03_SubContinentColl"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public H03_SubContinentColl() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; AllowNew = true; AllowEdit = true; AllowRemove = true; RaiseListChangedEvents = rlce; } #endregion #region Data Access /// <summary> /// Loads a <see cref="H03_SubContinentColl"/> collection from the database, based on given criteria. /// </summary> /// <param name="parent_Continent_ID">The Parent Continent ID.</param> protected void Child_Fetch(int parent_Continent_ID) { var args = new DataPortalHookArgs(parent_Continent_ID); OnFetchPre(args); using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var dal = dalManager.GetProvider<IH03_SubContinentCollDal>(); var data = dal.Fetch(parent_Continent_ID); LoadCollection(data); } OnFetchPost(args); foreach (var item in this) { item.FetchChildren(); } } private void LoadCollection(IDataReader data) { using (var dr = new SafeDataReader(data)) { Fetch(dr); } } /// <summary> /// Loads all <see cref="H03_SubContinentColl"/> 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(H04_SubContinent.GetH04_SubContinent(dr)); } RaiseListChangedEvents = rlce; } #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 } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Management.Automation; using System.Management.Automation.Internal; using System.Management.Automation.Runspaces; using System.Reflection; using System.Text; namespace Microsoft.PowerShell.Commands.Internal.Format { /// <summary> /// Class containing miscellaneous helpers to deal with /// PSObject manipulation. /// </summary> internal static class PSObjectHelper { #region tracer [TraceSource("PSObjectHelper", "PSObjectHelper")] private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("PSObjectHelper", "PSObjectHelper"); #endregion tracer internal const char Ellipsis = '\u2026'; internal static string PSObjectIsOfExactType(Collection<string> typeNames) { if (typeNames.Count != 0) return typeNames[0]; return null; } internal static bool PSObjectIsEnum(Collection<string> typeNames) { if (typeNames.Count < 2 || string.IsNullOrEmpty(typeNames[1])) return false; return string.Equals(typeNames[1], "System.Enum", StringComparison.Ordinal); } /// <summary> /// Retrieve the display name. It looks for a well known property and, /// if not found, it uses some heuristics to get a "close" match. /// </summary> /// <param name="target">Shell object to process.</param> /// <param name="expressionFactory">Expression factory to create PSPropertyExpression.</param> /// <returns>Resolved PSPropertyExpression; null if no match was found.</returns> internal static PSPropertyExpression GetDisplayNameExpression(PSObject target, PSPropertyExpressionFactory expressionFactory) { // first try to get the expression from the object (types.ps1xml data) PSPropertyExpression expressionFromObject = GetDefaultNameExpression(target); if (expressionFromObject != null) { return expressionFromObject; } // we failed the default display name, let's try some well known names // trying to get something potentially useful string[] knownPatterns = new string[] { "name", "id", "key", "*key", "*name", "*id", }; // go over the patterns, looking for the first match foreach (string pattern in knownPatterns) { PSPropertyExpression ex = new PSPropertyExpression(pattern); List<PSPropertyExpression> exprList = ex.ResolveNames(target); while ((exprList.Count > 0) && ( exprList[0].ToString().Equals(RemotingConstants.ComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase) || exprList[0].ToString().Equals(RemotingConstants.ShowComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase) || exprList[0].ToString().Equals(RemotingConstants.RunspaceIdNoteProperty, StringComparison.OrdinalIgnoreCase) || exprList[0].ToString().Equals(RemotingConstants.SourceJobInstanceId, StringComparison.OrdinalIgnoreCase))) { exprList.RemoveAt(0); } if (exprList.Count == 0) continue; // if more than one match, just return the first one return exprList[0]; } // we did not find anything return null; } /// <summary> /// It gets the display name value. /// </summary> /// <param name="target">Shell object to process.</param> /// <param name="expressionFactory">Expression factory to create PSPropertyExpression.</param> /// <returns>PSPropertyExpressionResult if successful; null otherwise.</returns> internal static PSPropertyExpressionResult GetDisplayName(PSObject target, PSPropertyExpressionFactory expressionFactory) { // get the expression to evaluate PSPropertyExpression ex = GetDisplayNameExpression(target, expressionFactory); if (ex == null) return null; // evaluate the expression List<PSPropertyExpressionResult> resList = ex.GetValues(target); if (resList.Count == 0 || resList[0].Exception != null) { // no results or the retrieval on the first one failed return null; } // return something only if the first match was successful return resList[0]; } /// <summary> /// This is necessary only to consider IDictionaries as IEnumerables, since LanguagePrimitives.GetEnumerable does not. /// </summary> /// <param name="obj">Object to extract the IEnumerable from.</param> internal static IEnumerable GetEnumerable(object obj) { PSObject mshObj = obj as PSObject; if (mshObj != null) { obj = mshObj.BaseObject; } if (obj is IDictionary) { return (IEnumerable)obj; } return LanguagePrimitives.GetEnumerable(obj); } private static string GetSmartToStringDisplayName(object x, PSPropertyExpressionFactory expressionFactory) { PSPropertyExpressionResult r = PSObjectHelper.GetDisplayName(PSObjectHelper.AsPSObject(x), expressionFactory); if ((r != null) && (r.Exception == null)) { return PSObjectHelper.AsPSObject(r.Result).ToString(); } else { return PSObjectHelper.AsPSObject(x).ToString(); } } private static string GetObjectName(object x, PSPropertyExpressionFactory expressionFactory) { string objName; // check if the underlying object is of primitive type // if so just return its value if (x is PSObject && (LanguagePrimitives.IsBoolOrSwitchParameterType((((PSObject)x).BaseObject).GetType()) || LanguagePrimitives.IsNumeric(((((PSObject)x).BaseObject).GetType()).GetTypeCode()) || LanguagePrimitives.IsNull(x))) { objName = x.ToString(); } else if (x == null) { // use PowerShell's $null variable to indicate that the value is null... objName = "$null"; } else { MethodInfo toStringMethod = x.GetType().GetMethod("ToString", Type.EmptyTypes); // TODO:CORECLR double check with CORE CLR that x.GetType() == toStringMethod.ReflectedType // Check if the given object "x" implements "toString" method. Do that by comparing "DeclaringType" which 'Gets the class that declares this member' and the object type if (toStringMethod.DeclaringType == x.GetType()) { objName = PSObjectHelper.AsPSObject(x).ToString(); } else { PSPropertyExpressionResult r = PSObjectHelper.GetDisplayName(PSObjectHelper.AsPSObject(x), expressionFactory); if ((r != null) && (r.Exception == null)) { objName = PSObjectHelper.AsPSObject(r.Result).ToString(); } else { objName = PSObjectHelper.AsPSObject(x).ToString(); if (objName == string.Empty) { var baseObj = PSObject.Base(x); if (baseObj != null) { objName = baseObj.ToString(); } } } } } return objName; } /// <summary> /// Helper to convert an PSObject into a string /// It takes into account enumerations (use display name) /// </summary> /// <param name="so">Shell object to process.</param> /// <param name="expressionFactory">Expression factory to create PSPropertyExpression.</param> /// <param name="enumerationLimit">Limit on IEnumerable enumeration.</param> /// <param name="formatErrorObject">Stores errors during string conversion.</param> /// <returns>String representation.</returns> internal static string SmartToString(PSObject so, PSPropertyExpressionFactory expressionFactory, int enumerationLimit, StringFormatError formatErrorObject) { if (so == null) return string.Empty; try { IEnumerable e = PSObjectHelper.GetEnumerable(so); if (e != null) { StringBuilder sb = new StringBuilder(); sb.Append('{'); bool first = true; int enumCount = 0; IEnumerator enumerator = e.GetEnumerator(); if (enumerator != null) { IBlockingEnumerator<object> be = enumerator as IBlockingEnumerator<object>; if (be != null) { while (be.MoveNext(false)) { if (LocalPipeline.GetExecutionContextFromTLS().CurrentPipelineStopping) { throw new PipelineStoppedException(); } if (enumerationLimit >= 0) { if (enumCount == enumerationLimit) { sb.Append(Ellipsis); break; } enumCount++; } if (!first) { sb.Append(", "); } sb.Append(GetObjectName(be.Current, expressionFactory)); if (first) first = false; } } else { foreach (object x in e) { if (LocalPipeline.GetExecutionContextFromTLS().CurrentPipelineStopping) { throw new PipelineStoppedException(); } if (enumerationLimit >= 0) { if (enumCount == enumerationLimit) { sb.Append(Ellipsis); break; } enumCount++; } if (!first) { sb.Append(", "); } sb.Append(GetObjectName(x, expressionFactory)); if (first) first = false; } } } sb.Append('}'); return sb.ToString(); } // take care of the case there is no base object return so.ToString(); } catch (Exception e) when (e is ExtendedTypeSystemException || e is InvalidOperationException) { // These exceptions are being caught and handled by returning an empty string when // the object cannot be stringified due to ETS or an instance in the collection has been modified s_tracer.TraceWarning($"SmartToString method: Exception during conversion to string, emitting empty string: {e.Message}"); if (formatErrorObject != null) { formatErrorObject.sourceObject = so; formatErrorObject.exception = e; } return string.Empty; } } private static readonly PSObject s_emptyPSObject = new PSObject(string.Empty); internal static PSObject AsPSObject(object obj) { return (obj == null) ? s_emptyPSObject : PSObject.AsPSObject(obj); } /// <summary> /// Format an object using a provided format string directive. /// </summary> /// <param name="directive">Format directive object to use.</param> /// <param name="val">Object to format.</param> /// <param name="enumerationLimit">Limit on IEnumerable enumeration.</param> /// <param name="formatErrorObject">Formatting error object, if present.</param> /// <param name="expressionFactory">Expression factory to create PSPropertyExpression.</param> /// <returns>String representation.</returns> internal static string FormatField(FieldFormattingDirective directive, object val, int enumerationLimit, StringFormatError formatErrorObject, PSPropertyExpressionFactory expressionFactory) { PSObject so = PSObjectHelper.AsPSObject(val); if (directive != null && !string.IsNullOrEmpty(directive.formatString)) { // we have a formatting directive, apply it // NOTE: with a format directive, we do not make any attempt // to deal with IEnumerable try { // use some heuristics to determine if we have "composite formatting" // 2004/11/16-JonN This is heuristic but should be safe enough if (directive.formatString.Contains("{0") || directive.formatString.Contains('}')) { // we do have it, just use it return string.Format(CultureInfo.CurrentCulture, directive.formatString, so); } // we fall back to the PSObject's IFormattable.ToString() // pass a null IFormatProvider return so.ToString(directive.formatString, null); } catch (Exception e) // 2004/11/17-JonN This covers exceptions thrown in // string.Format and PSObject.ToString(). // I think we can swallow these. { // NOTE: we catch all the exceptions, since we do not know // what the underlying object access would throw if (formatErrorObject != null) { formatErrorObject.sourceObject = so; formatErrorObject.exception = e; formatErrorObject.formatString = directive.formatString; return string.Empty; } } } // we do not have a formatting directive or we failed the formatting (fallback) // but we did not report as an error; // this call would deal with IEnumerable if the object implements it return PSObjectHelper.SmartToString(so, expressionFactory, enumerationLimit, formatErrorObject); } private static PSMemberSet MaskDeserializedAndGetStandardMembers(PSObject so) { Diagnostics.Assert(so != null, "Shell object to process cannot be null"); var typeNames = so.InternalTypeNames; Collection<string> typeNamesWithoutDeserializedPrefix = Deserializer.MaskDeserializationPrefix(typeNames); if (typeNamesWithoutDeserializedPrefix == null) { return null; } TypeTable typeTable = so.GetTypeTable(); if (typeTable == null) { return null; } PSMemberInfoInternalCollection<PSMemberInfo> members = typeTable.GetMembers<PSMemberInfo>(new ConsolidatedString(typeNamesWithoutDeserializedPrefix)); return members[TypeTable.PSStandardMembers] as PSMemberSet; } private static List<PSPropertyExpression> GetDefaultPropertySet(PSMemberSet standardMembersSet) { if (standardMembersSet != null) { PSPropertySet defaultDisplayPropertySet = standardMembersSet.Members[TypeTable.DefaultDisplayPropertySet] as PSPropertySet; if (defaultDisplayPropertySet != null) { List<PSPropertyExpression> retVal = new List<PSPropertyExpression>(); foreach (string prop in defaultDisplayPropertySet.ReferencedPropertyNames) { if (!string.IsNullOrEmpty(prop)) { retVal.Add(new PSPropertyExpression(prop)); } } return retVal; } } return new List<PSPropertyExpression>(); } /// <summary> /// Helper to retrieve the default property set of a shell object. /// </summary> /// <param name="so">Shell object to process.</param> /// <returns>Resolved expression; empty list if not found.</returns> internal static List<PSPropertyExpression> GetDefaultPropertySet(PSObject so) { List<PSPropertyExpression> retVal = GetDefaultPropertySet(so.PSStandardMembers); if (retVal.Count == 0) { retVal = GetDefaultPropertySet(MaskDeserializedAndGetStandardMembers(so)); } return retVal; } private static PSPropertyExpression GetDefaultNameExpression(PSMemberSet standardMembersSet) { if (standardMembersSet != null) { PSNoteProperty defaultDisplayProperty = standardMembersSet.Members[TypeTable.DefaultDisplayProperty] as PSNoteProperty; if (defaultDisplayProperty != null) { string expressionString = defaultDisplayProperty.Value.ToString(); if (string.IsNullOrEmpty(expressionString)) { // invalid data, the PSObject is empty return null; } else { return new PSPropertyExpression(expressionString); } } } return null; } private static PSPropertyExpression GetDefaultNameExpression(PSObject so) { PSPropertyExpression retVal = GetDefaultNameExpression(so.PSStandardMembers) ?? GetDefaultNameExpression(MaskDeserializedAndGetStandardMembers(so)); return retVal; } /// <summary> /// Helper to retrieve the value of an PSPropertyExpression and to format it. /// </summary> /// <param name="so">Shell object to process.</param> /// <param name="enumerationLimit">Limit on IEnumerable enumeration.</param> /// <param name="ex">Expression to use for retrieval.</param> /// <param name="directive">Format directive to use for formatting.</param> /// <param name="formatErrorObject"></param> /// <param name="expressionFactory">Expression factory to create PSPropertyExpression.</param> /// <param name="result">Not null if an error condition arose.</param> /// <returns>Formatted string.</returns> internal static string GetExpressionDisplayValue( PSObject so, int enumerationLimit, PSPropertyExpression ex, FieldFormattingDirective directive, StringFormatError formatErrorObject, PSPropertyExpressionFactory expressionFactory, out PSPropertyExpressionResult result) { result = null; List<PSPropertyExpressionResult> resList = ex.GetValues(so); if (resList.Count == 0) { return string.Empty; } result = resList[0]; if (result.Exception != null) { return string.Empty; } return PSObjectHelper.FormatField(directive, result.Result, enumerationLimit, formatErrorObject, expressionFactory); } /// <summary> /// Queries PSObject and determines if ComputerName property should be shown. /// </summary> /// <param name="so"></param> /// <returns></returns> internal static bool ShouldShowComputerNameProperty(PSObject so) { bool result = false; if (so != null) { try { PSPropertyInfo computerNameProperty = so.Properties[RemotingConstants.ComputerNameNoteProperty]; PSPropertyInfo showComputerNameProperty = so.Properties[RemotingConstants.ShowComputerNameNoteProperty]; // if computer name property exists then this must be a remote object. see // if it can be displayed. if ((computerNameProperty != null) && (showComputerNameProperty != null)) { LanguagePrimitives.TryConvertTo<bool>(showComputerNameProperty.Value, out result); } } catch (ArgumentException) { // ignore any exceptions thrown retrieving the *ComputerName properties // from the object } catch (ExtendedTypeSystemException) { // ignore any exceptions thrown retrieving the *ComputerName properties // from the object } } return result; } } internal abstract class FormattingError { internal object sourceObject; } internal sealed class PSPropertyExpressionError : FormattingError { internal PSPropertyExpressionResult result; } internal sealed class StringFormatError : FormattingError { internal string formatString; internal Exception exception; } internal delegate ScriptBlock CreateScriptBlockFromString(string scriptBlockString); /// <summary> /// Helper class to create PSPropertyExpression's from format.ps1xml data structures. /// </summary> internal sealed class PSPropertyExpressionFactory { /// <exception cref="ParseException"></exception> internal void VerifyScriptBlockText(string scriptText) { ScriptBlock.Create(scriptText); } /// <summary> /// Create an expression from an expression token. /// </summary> /// <param name="et">Expression token to use.</param> /// <returns>Constructed expression.</returns> /// <exception cref="ParseException"></exception> internal PSPropertyExpression CreateFromExpressionToken(ExpressionToken et) { return CreateFromExpressionToken(et, null); } /// <summary> /// Create an expression from an expression token. /// </summary> /// <param name="et">Expression token to use.</param> /// <param name="loadingInfo">The context from which the file was loaded.</param> /// <returns>Constructed expression.</returns> /// <exception cref="ParseException"></exception> internal PSPropertyExpression CreateFromExpressionToken(ExpressionToken et, DatabaseLoadingInfo loadingInfo) { if (et.isScriptBlock) { // we cache script blocks from expression tokens if (_expressionCache != null) { PSPropertyExpression value; if (_expressionCache.TryGetValue(et, out value)) { // got a hit on the cache, just return return value; } } else { _expressionCache = new Dictionary<ExpressionToken, PSPropertyExpression>(); } bool isFullyTrusted = false; bool isProductCode = false; if (loadingInfo != null) { isFullyTrusted = loadingInfo.isFullyTrusted; isProductCode = loadingInfo.isProductCode; } // no hit, we build one and we cache ScriptBlock sb = ScriptBlock.CreateDelayParsedScriptBlock(et.expressionValue, isProductCode: isProductCode); sb.DebuggerStepThrough = true; if (isFullyTrusted) { sb.LanguageMode = PSLanguageMode.FullLanguage; } PSPropertyExpression ex = new PSPropertyExpression(sb); _expressionCache.Add(et, ex); return ex; } // we do not cache if it is just a property name return new PSPropertyExpression(et.expressionValue); } private Dictionary<ExpressionToken, PSPropertyExpression> _expressionCache; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Dynamic.Utils; using System.Reflection; using System.Runtime.CompilerServices; namespace System.Linq.Expressions.Interpreter { internal abstract class OffsetInstruction : Instruction { internal const int Unknown = int.MinValue; internal const int CacheSize = 32; // the offset to jump to (relative to this instruction): protected int _offset = Unknown; public abstract Instruction[] Cache { get; } public Instruction Fixup(int offset) { Debug.Assert(_offset == Unknown && offset != Unknown); _offset = offset; Instruction[] cache = Cache; if (cache != null && offset >= 0 && offset < cache.Length) { return cache[offset] ?? (cache[offset] = this); } return this; } public override string ToDebugString(int instructionIndex, object cookie, Func<int, int> labelIndexer, IReadOnlyList<object> objects) { return ToString() + (_offset != Unknown ? " -> " + (instructionIndex + _offset) : ""); } public override string ToString() { return InstructionName + (_offset == Unknown ? "(?)" : "(" + _offset + ")"); } } internal sealed class BranchFalseInstruction : OffsetInstruction { private static Instruction[] s_cache; public override Instruction[] Cache { get { if (s_cache == null) { s_cache = new Instruction[CacheSize]; } return s_cache; } } internal BranchFalseInstruction() { } public override string InstructionName => "BranchFalse"; public override int ConsumedStack => 1; public override int Run(InterpretedFrame frame) { Debug.Assert(_offset != Unknown); if (!(bool)frame.Pop()) { return _offset; } return 1; } } internal sealed class BranchTrueInstruction : OffsetInstruction { private static Instruction[] s_cache; public override Instruction[] Cache { get { if (s_cache == null) { s_cache = new Instruction[CacheSize]; } return s_cache; } } internal BranchTrueInstruction() { } public override string InstructionName => "BranchTrue"; public override int ConsumedStack => 1; public override int Run(InterpretedFrame frame) { Debug.Assert(_offset != Unknown); if ((bool)frame.Pop()) { return _offset; } return 1; } } internal sealed class CoalescingBranchInstruction : OffsetInstruction { private static Instruction[] s_cache; public override Instruction[] Cache { get { if (s_cache == null) { s_cache = new Instruction[CacheSize]; } return s_cache; } } internal CoalescingBranchInstruction() { } public override string InstructionName => "CoalescingBranch"; public override int ConsumedStack => 1; public override int ProducedStack => 1; public override int Run(InterpretedFrame frame) { Debug.Assert(_offset != Unknown); if (frame.Peek() != null) { return _offset; } return 1; } } internal class BranchInstruction : OffsetInstruction { private static Instruction[][][] s_caches; public override Instruction[] Cache { get { if (s_caches == null) { s_caches = new Instruction[2][][] { new Instruction[2][], new Instruction[2][] }; } return s_caches[ConsumedStack][ProducedStack] ?? (s_caches[ConsumedStack][ProducedStack] = new Instruction[CacheSize]); } } internal readonly bool _hasResult; internal readonly bool _hasValue; internal BranchInstruction() : this(false, false) { } public BranchInstruction(bool hasResult, bool hasValue) { _hasResult = hasResult; _hasValue = hasValue; } public override string InstructionName => "Branch"; public override int ConsumedStack => _hasValue ? 1 : 0; public override int ProducedStack => _hasResult ? 1 : 0; public override int Run(InterpretedFrame frame) { Debug.Assert(_offset != Unknown); return _offset; } } internal abstract class IndexedBranchInstruction : Instruction { protected const int CacheSize = 32; internal readonly int _labelIndex; public IndexedBranchInstruction(int labelIndex) { _labelIndex = labelIndex; } public RuntimeLabel GetLabel(InterpretedFrame frame) { Debug.Assert(_labelIndex != UnknownInstrIndex); return frame.Interpreter._labels[_labelIndex]; } public override string ToDebugString(int instructionIndex, object cookie, Func<int, int> labelIndexer, IReadOnlyList<object> objects) { Debug.Assert(_labelIndex != UnknownInstrIndex); int targetIndex = labelIndexer(_labelIndex); return ToString() + (targetIndex != BranchLabel.UnknownIndex ? " -> " + targetIndex : ""); } public override string ToString() { Debug.Assert(_labelIndex != UnknownInstrIndex); return InstructionName + "[" + _labelIndex + "]"; } } /// <summary> /// This instruction implements a goto expression that can jump out of any expression. /// It pops values (arguments) from the evaluation stack that the expression tree nodes in between /// the goto expression and the target label node pushed and not consumed yet. /// A goto expression can jump into a node that evaluates arguments only if it carries /// a value and jumps right after the first argument (the carried value will be used as the first argument). /// Goto can jump into an arbitrary child of a BlockExpression since the block doesn't accumulate values /// on evaluation stack as its child expressions are being evaluated. /// /// Goto needs to execute any finally blocks on the way to the target label. /// <example> /// { /// f(1, 2, try { g(3, 4, try { goto L } finally { ... }, 6) } finally { ... }, 7, 8) /// L: ... /// } /// </example> /// The goto expression here jumps to label L while having 4 items on evaluation stack (1, 2, 3 and 4). /// The jump needs to execute both finally blocks, the first one on stack level 4 the /// second one on stack level 2. So, it needs to jump the first finally block, pop 2 items from the stack, /// run second finally block and pop another 2 items from the stack and set instruction pointer to label L. /// /// Goto also needs to rethrow ThreadAbortException iff it jumps out of a catch handler and /// the current thread is in "abort requested" state. /// </summary> internal sealed class GotoInstruction : IndexedBranchInstruction { private const int Variants = 8; private static readonly GotoInstruction[] s_cache = new GotoInstruction[Variants * CacheSize]; public override string InstructionName => "Goto"; private readonly bool _hasResult; private readonly bool _hasValue; private readonly bool _labelTargetGetsValue; // The values should technically be Consumed = 1, Produced = 1 for gotos that target a label whose continuation depth // is different from the current continuation depth. This is because we will consume one continuation from the _continuations // and at meantime produce a new _pendingContinuation. However, in case of forward gotos, we don't not know that is the // case until the label is emitted. By then the consumed and produced stack information is useless. // The important thing here is that the stack balance is 0. public override int ConsumedContinuations => 0; public override int ProducedContinuations => 0; public override int ConsumedStack => _hasValue ? 1 : 0; public override int ProducedStack => _hasResult ? 1 : 0; private GotoInstruction(int targetIndex, bool hasResult, bool hasValue, bool labelTargetGetsValue) : base(targetIndex) { _hasResult = hasResult; _hasValue = hasValue; _labelTargetGetsValue = labelTargetGetsValue; } internal static GotoInstruction Create(int labelIndex, bool hasResult, bool hasValue, bool labelTargetGetsValue) { if (labelIndex < CacheSize) { int index = Variants * labelIndex | (labelTargetGetsValue ? 4 : 0) | (hasResult ? 2 : 0) | (hasValue ? 1 : 0); return s_cache[index] ?? (s_cache[index] = new GotoInstruction(labelIndex, hasResult, hasValue, labelTargetGetsValue)); } return new GotoInstruction(labelIndex, hasResult, hasValue, labelTargetGetsValue); } public override int Run(InterpretedFrame frame) { // Are we jumping out of catch/finally while aborting the current thread? #if FEATURE_THREAD_ABORT Interpreter.AbortThreadIfRequested(frame, _labelIndex); #endif // goto the target label or the current finally continuation: object value = _hasValue ? frame.Pop() : Interpreter.NoValue; return frame.Goto(_labelIndex, _labelTargetGetsValue ? value : Interpreter.NoValue, gotoExceptionHandler: false); } } internal sealed class EnterTryCatchFinallyInstruction : IndexedBranchInstruction { private readonly bool _hasFinally = false; private TryCatchFinallyHandler _tryHandler; internal void SetTryHandler(TryCatchFinallyHandler tryHandler) { Debug.Assert(_tryHandler == null && tryHandler != null, "the tryHandler can be set only once"); _tryHandler = tryHandler; } internal TryCatchFinallyHandler Handler => _tryHandler; public override int ProducedContinuations => _hasFinally ? 1 : 0; private EnterTryCatchFinallyInstruction(int targetIndex, bool hasFinally) : base(targetIndex) { _hasFinally = hasFinally; } internal static EnterTryCatchFinallyInstruction CreateTryFinally(int labelIndex) { return new EnterTryCatchFinallyInstruction(labelIndex, true); } internal static EnterTryCatchFinallyInstruction CreateTryCatch() { return new EnterTryCatchFinallyInstruction(UnknownInstrIndex, false); } public override int Run(InterpretedFrame frame) { Debug.Assert(_tryHandler != null, "the tryHandler must be set already"); if (_hasFinally) { // Push finally. frame.PushContinuation(_labelIndex); } int prevInstrIndex = frame.InstructionIndex; frame.InstructionIndex++; // Start to run the try/catch/finally blocks Instruction[] instructions = frame.Interpreter.Instructions.Instructions; ExceptionHandler exHandler; object unwrappedException; try { // run the try block int index = frame.InstructionIndex; while (index >= _tryHandler.TryStartIndex && index < _tryHandler.TryEndIndex) { index += instructions[index].Run(frame); frame.InstructionIndex = index; } // we finish the try block and is about to jump out of the try/catch blocks if (index == _tryHandler.GotoEndTargetIndex) { // run the 'Goto' that jumps out of the try/catch/finally blocks Debug.Assert(instructions[index] is GotoInstruction, "should be the 'Goto' instruction that jumps out the try/catch/finally"); frame.InstructionIndex += instructions[index].Run(frame); } } catch (Exception exception) when (_tryHandler.HasHandler(frame, exception, out exHandler, out unwrappedException)) { Debug.Assert(!(unwrappedException is RethrowException)); frame.InstructionIndex += frame.Goto(exHandler.LabelIndex, unwrappedException, gotoExceptionHandler: true); #if FEATURE_THREAD_ABORT // stay in the current catch so that ThreadAbortException is not rethrown by CLR: var abort = exception as ThreadAbortException; if (abort != null) { Interpreter.AnyAbortException = abort; frame.CurrentAbortHandler = exHandler; } #endif bool rethrow = false; try { // run the catch block int index = frame.InstructionIndex; while (index >= exHandler.HandlerStartIndex && index < exHandler.HandlerEndIndex) { index += instructions[index].Run(frame); frame.InstructionIndex = index; } // we finish the catch block and is about to jump out of the try/catch blocks if (index == _tryHandler.GotoEndTargetIndex) { // run the 'Goto' that jumps out of the try/catch/finally blocks Debug.Assert(instructions[index] is GotoInstruction, "should be the 'Goto' instruction that jumps out the try/catch/finally"); frame.InstructionIndex += instructions[index].Run(frame); } } catch (RethrowException) { // a rethrow instruction in a catch block gets to run rethrow = true; } if (rethrow) { throw; } } finally { if (_tryHandler.IsFinallyBlockExist) { // We get to the finally block in two paths: // 1. Jump from the try/catch blocks. This includes two sub-routes: // a. 'Goto' instruction in the middle of try/catch block // b. try/catch block runs to its end. Then the 'Goto(end)' will be trigger to jump out of the try/catch block // 2. Exception thrown from the try/catch blocks // In the first path, the continuation mechanism works and frame.InstructionIndex will be updated to point to the first instruction of the finally block // In the second path, the continuation mechanism is not involved and frame.InstructionIndex is not updated #if DEBUG bool isFromJump = frame.IsJumpHappened(); Debug.Assert(!isFromJump || (isFromJump && _tryHandler.FinallyStartIndex == frame.InstructionIndex), "we should already jump to the first instruction of the finally"); #endif // run the finally block // we cannot jump out of the finally block, and we cannot have an immediate rethrow in it int index = frame.InstructionIndex = _tryHandler.FinallyStartIndex; while (index >= _tryHandler.FinallyStartIndex && index < _tryHandler.FinallyEndIndex) { index += instructions[index].Run(frame); frame.InstructionIndex = index; } } } return frame.InstructionIndex - prevInstrIndex; } public override string InstructionName => _hasFinally ? "EnterTryFinally" : "EnterTryCatch"; public override string ToString() => _hasFinally ? "EnterTryFinally[" + _labelIndex + "]" : "EnterTryCatch"; } internal sealed class EnterTryFaultInstruction : IndexedBranchInstruction { private TryFaultHandler _tryHandler; internal EnterTryFaultInstruction(int targetIndex) : base(targetIndex) { } public override string InstructionName => "EnterTryFault"; public override int ProducedContinuations => 1; internal TryFaultHandler Handler => _tryHandler; internal void SetTryHandler(TryFaultHandler tryHandler) { Debug.Assert(tryHandler != null); Debug.Assert(_tryHandler == null, "the tryHandler can be set only once"); _tryHandler = tryHandler; } public override int Run(InterpretedFrame frame) { Debug.Assert(_tryHandler != null, "the tryHandler must be set already"); // Push fault. frame.PushContinuation(_labelIndex); int prevInstrIndex = frame.InstructionIndex; frame.InstructionIndex++; // Start to run the try/fault blocks Instruction[] instructions = frame.Interpreter.Instructions.Instructions; // C# 6 has no direct support for fault blocks, but they can be faked or coerced out of the compiler // in several ways. Catch-and-rethrow can work in specific cases, but not generally as the double-pass // will not work correctly with filters higher up the call stack. Iterators can be used to produce real // fault blocks, but it depends on an implementation detail rather than a guarantee, and is rather // indirect. This leaves using a finally block and not doing anything in it if the body ran to // completion, which is the approach used here. bool ranWithoutFault = false; try { // run the try block int index = frame.InstructionIndex; while (index >= _tryHandler.TryStartIndex && index < _tryHandler.TryEndIndex) { index += instructions[index].Run(frame); frame.InstructionIndex = index; } // run the 'Goto' that jumps out of the try/fault blocks Debug.Assert(instructions[index] is GotoInstruction, "should be the 'Goto' instruction that jumps out the try/fault"); // if we've arrived here there was no exception thrown. As the fault block won't run, we need to // pop the continuation for it here, before Gotoing the end of the try/fault. ranWithoutFault = true; frame.RemoveContinuation(); frame.InstructionIndex += instructions[index].Run(frame); } finally { if (!ranWithoutFault) { // run the fault block // we cannot jump out of the finally block, and we cannot have an immediate rethrow in it int index = frame.InstructionIndex = _tryHandler.FinallyStartIndex; while (index >= _tryHandler.FinallyStartIndex && index < _tryHandler.FinallyEndIndex) { index += instructions[index].Run(frame); frame.InstructionIndex = index; } } } return frame.InstructionIndex - prevInstrIndex; } } /// <summary> /// The first instruction of finally block. /// </summary> internal sealed class EnterFinallyInstruction : IndexedBranchInstruction { private static readonly EnterFinallyInstruction[] s_cache = new EnterFinallyInstruction[CacheSize]; private EnterFinallyInstruction(int labelIndex) : base(labelIndex) { } public override string InstructionName => "EnterFinally"; public override int ProducedStack => 2; public override int ConsumedContinuations => 1; internal static EnterFinallyInstruction Create(int labelIndex) { if (labelIndex < CacheSize) { return s_cache[labelIndex] ?? (s_cache[labelIndex] = new EnterFinallyInstruction(labelIndex)); } return new EnterFinallyInstruction(labelIndex); } public override int Run(InterpretedFrame frame) { // If _pendingContinuation == -1 then we were getting into the finally block because an exception was thrown // in this case we need to set the stack depth // Else we were getting into this finally block from a 'Goto' jump, and the stack depth is already set properly if (!frame.IsJumpHappened()) { frame.SetStackDepth(GetLabel(frame).StackDepth); } frame.PushPendingContinuation(); frame.RemoveContinuation(); return 1; } } /// <summary> /// The last instruction of finally block. /// </summary> internal sealed class LeaveFinallyInstruction : Instruction { internal static readonly Instruction Instance = new LeaveFinallyInstruction(); private LeaveFinallyInstruction() { } public override int ConsumedStack => 2; public override string InstructionName => "LeaveFinally"; public override int Run(InterpretedFrame frame) { frame.PopPendingContinuation(); // If _pendingContinuation == -1 then we were getting into the finally block because an exception was thrown // In this case we just return 1, and the real instruction index will be calculated by GotoHandler later if (!frame.IsJumpHappened()) { return 1; } // jump to goto target or to the next finally: return frame.YieldToPendingContinuation(); } } internal sealed class EnterFaultInstruction : IndexedBranchInstruction { private static readonly EnterFaultInstruction[] s_cache = new EnterFaultInstruction[CacheSize]; private EnterFaultInstruction(int labelIndex) : base(labelIndex) { } public override string InstructionName => "EnterFault"; public override int ProducedStack => 2; internal static EnterFaultInstruction Create(int labelIndex) { if (labelIndex < CacheSize) { return s_cache[labelIndex] ?? (s_cache[labelIndex] = new EnterFaultInstruction(labelIndex)); } return new EnterFaultInstruction(labelIndex); } public override int Run(InterpretedFrame frame) { Debug.Assert(!frame.IsJumpHappened()); frame.SetStackDepth(GetLabel(frame).StackDepth); frame.PushPendingContinuation(); frame.RemoveContinuation(); return 1; } } internal sealed class LeaveFaultInstruction : Instruction { internal static readonly Instruction Instance = new LeaveFaultInstruction(); private LeaveFaultInstruction() { } public override int ConsumedStack => 2; public override int ConsumedContinuations => 1; public override string InstructionName => "LeaveFault"; public override int Run(InterpretedFrame frame) { frame.PopPendingContinuation(); Debug.Assert(!frame.IsJumpHappened()); // Just return 1, and the real instruction index will be calculated by GotoHandler later return 1; } } // no-op: we need this just to balance the stack depth and aid debugging of the instruction list. internal sealed class EnterExceptionFilterInstruction : Instruction { internal static readonly EnterExceptionFilterInstruction Instance = new EnterExceptionFilterInstruction(); private EnterExceptionFilterInstruction() { } public override string InstructionName => "EnterExceptionFilter"; public override int ConsumedStack => 0; // The exception is pushed onto the stack in the filter runner. public override int ProducedStack => 1; [ExcludeFromCodeCoverage] // Known to be a no-op, this instruction is skipped on execution. public override int Run(InterpretedFrame frame) => 1; } // no-op: we need this just to balance the stack depth and aid debugging of the instruction list. internal sealed class LeaveExceptionFilterInstruction : Instruction { internal static readonly LeaveExceptionFilterInstruction Instance = new LeaveExceptionFilterInstruction(); private LeaveExceptionFilterInstruction() { } public override string InstructionName => "LeaveExceptionFilter"; // The boolean result is popped from the stack in the filter runner. public override int ConsumedStack => 1; public override int ProducedStack => 0; [ExcludeFromCodeCoverage] // Known to be a no-op, this instruction is skipped on execution. public override int Run(InterpretedFrame frame) => 1; } // no-op: we need this just to balance the stack depth. internal sealed class EnterExceptionHandlerInstruction : Instruction { internal static readonly EnterExceptionHandlerInstruction Void = new EnterExceptionHandlerInstruction(false); internal static readonly EnterExceptionHandlerInstruction NonVoid = new EnterExceptionHandlerInstruction(true); // True if try-expression is non-void. private readonly bool _hasValue; private EnterExceptionHandlerInstruction(bool hasValue) { _hasValue = hasValue; } public override string InstructionName => "EnterExceptionHandler"; // If an exception is throws in try-body the expression result of try-body is not evaluated and loaded to the stack. // So the stack doesn't contain the try-body's value when we start executing the handler. // However, while emitting instructions try block falls thru the catch block with a value on stack. // We need to declare it consumed so that the stack state upon entry to the handler corresponds to the real // stack depth after throw jumped to this catch block. public override int ConsumedStack => _hasValue ? 1 : 0; // A variable storing the current exception is pushed to the stack by exception handling. // Catch handlers: The value is immediately popped and stored into a local. public override int ProducedStack => 1; [ExcludeFromCodeCoverage] // Known to be a no-op, this instruction is skipped on execution. public override int Run(InterpretedFrame frame) { // nop (the exception value is pushed by the interpreter in HandleCatch) return 1; } } /// <summary> /// The last instruction of a catch exception handler. /// </summary> internal sealed class LeaveExceptionHandlerInstruction : IndexedBranchInstruction { private static readonly LeaveExceptionHandlerInstruction[] s_cache = new LeaveExceptionHandlerInstruction[2 * CacheSize]; private readonly bool _hasValue; private LeaveExceptionHandlerInstruction(int labelIndex, bool hasValue) : base(labelIndex) { _hasValue = hasValue; } public override string InstructionName => "LeaveExceptionHandler"; // The catch block yields a value if the body is non-void. This value is left on the stack. public override int ConsumedStack => _hasValue ? 1 : 0; public override int ProducedStack => _hasValue ? 1 : 0; internal static LeaveExceptionHandlerInstruction Create(int labelIndex, bool hasValue) { if (labelIndex < CacheSize) { int index = (2 * labelIndex) | (hasValue ? 1 : 0); return s_cache[index] ?? (s_cache[index] = new LeaveExceptionHandlerInstruction(labelIndex, hasValue)); } return new LeaveExceptionHandlerInstruction(labelIndex, hasValue); } public override int Run(InterpretedFrame frame) { // CLR rethrows ThreadAbortException when leaving catch handler if abort is requested on the current thread. #if FEATURE_THREAD_ABORT Interpreter.AbortThreadIfRequested(frame, _labelIndex); #endif return GetLabel(frame).Index - frame.InstructionIndex; } } internal sealed class ThrowInstruction : Instruction { internal static readonly ThrowInstruction Throw = new ThrowInstruction(true, false); internal static readonly ThrowInstruction VoidThrow = new ThrowInstruction(false, false); internal static readonly ThrowInstruction Rethrow = new ThrowInstruction(true, true); internal static readonly ThrowInstruction VoidRethrow = new ThrowInstruction(false, true); private static ConstructorInfo _runtimeWrappedExceptionCtor; private readonly bool _hasResult, _rethrow; private ThrowInstruction(bool hasResult, bool isRethrow) { _hasResult = hasResult; _rethrow = isRethrow; } public override string InstructionName => "Throw"; public override int ProducedStack => _hasResult ? 1 : 0; public override int ConsumedStack => 1; public override int Run(InterpretedFrame frame) { Exception ex = WrapThrownObject(frame.Pop()); if (_rethrow) { throw new RethrowException(); } throw ex; } private static Exception WrapThrownObject(object thrown) => thrown == null ? null : (thrown as Exception ?? RuntimeWrap(thrown)); private static RuntimeWrappedException RuntimeWrap(object thrown) { ConstructorInfo ctor = _runtimeWrappedExceptionCtor ?? (_runtimeWrappedExceptionCtor = typeof(RuntimeWrappedException) .GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic) .First(c => c.GetParametersCached().Length == 1)); return (RuntimeWrappedException)ctor.Invoke(new [] {thrown}); } } internal sealed class IntSwitchInstruction<T> : Instruction { private readonly Dictionary<T, int> _cases; internal IntSwitchInstruction(Dictionary<T, int> cases) { Assert.NotNull(cases); _cases = cases; } public override string InstructionName => "IntSwitch"; public override int ConsumedStack => 1; public override int ProducedStack => 0; public override int Run(InterpretedFrame frame) { int target; return _cases.TryGetValue((T)frame.Pop(), out target) ? target : 1; } } internal sealed class StringSwitchInstruction : Instruction { private readonly Dictionary<string, int> _cases; private readonly StrongBox<int> _nullCase; internal StringSwitchInstruction(Dictionary<string, int> cases, StrongBox<int> nullCase) { Assert.NotNull(cases); Assert.NotNull(nullCase); _cases = cases; _nullCase = nullCase; } public override string InstructionName => "StringSwitch"; public override int ConsumedStack => 1; public override int ProducedStack => 0; public override int Run(InterpretedFrame frame) { object value = frame.Pop(); if (value == null) { return _nullCase.Value; } int target; return _cases.TryGetValue((string)value, out target) ? target : 1; } } }
using AnnuaireCertifies.Data.Context; using AnnuaireCertifies.Domaine; using AnnuaireCertifies.Business.Depots; using System.Linq; using System.Collections.Generic; using System.Data.SqlClient; using System.Data; using System; using AnnuaireCertifies.Domaine.Results; namespace AnnuaireCertifies.Data.Depots { public partial class DepotContenu : IDepotContenu { private readonly IDepotBlocContenu _blocContenu; private readonly IDepotRelationContenu _relationContenu; public DepotContenu(IAnnuaireCertifiesDbContext dataContext, IDepotBlocContenu blocContenu, IDepotRelationContenu relationContenu) : this(dataContext) { _blocContenu = blocContenu; _relationContenu = relationContenu; } public IEnumerable<ChampResult> ContenuGetChamps(long? typeContenu) { List<SqlParameter> parameters = new List<SqlParameter>(); parameters.Add(new SqlParameter("@TypeContenuID", SqlDbType.BigInt) { Value = typeContenu}); return DbContext.ExecuteStoredProcedure<ChampResult>("sp_GestionContenusContenuLireChamps", parameters); } public ContenuDto LireContenu(long idFonctionnel, long utilisateurID) { List<SqlParameter> parameters = new List<SqlParameter>(); parameters.Add(new SqlParameter("@IdFonctionnel", SqlDbType.BigInt) { Value = idFonctionnel }); parameters.Add(new SqlParameter("@UtilisateurID", SqlDbType.BigInt) { Value = utilisateurID }); return DbContext.ExecuteStoredProcedure<ContenuDto>("sp_ContenusLireInfosGenerales", parameters).FirstOrDefault(); } public IEnumerable<RelationContenuResult> GetSousContenus(long contenuID, long utilisateurID) { List<SqlParameter> parameters = new List<SqlParameter>(); parameters.Add(new SqlParameter("@ContenuID", SqlDbType.BigInt) { Value = contenuID }); parameters.Add(new SqlParameter("@UtilisateurID", SqlDbType.BigInt) { Value = utilisateurID }); return DbContext.ExecuteStoredProcedure<RelationContenuResult>("sp_GetSousContenus", parameters); } public IEnumerable<DbErrorMsg> DeleteContenus(long contenuID) { List<DbErrorMsg> res = new List<DbErrorMsg>(); var children = _relationContenu.Find(x => x.SourceContenuID == contenuID); if (!children.Any()) { return DeleteContenu(contenuID); } else { foreach (var c in children) { res.AddRange(DeleteContenus(c.FilsContenuID)); if (res.Any()) { break; } } } return res; } private IEnumerable<DbErrorMsg> DeleteContenu(long contenuID) { List<SqlParameter> parameters = new List<SqlParameter>(); parameters.Add(new SqlParameter("@ContenuID", SqlDbType.BigInt) { Value = contenuID }); return DbContext.ExecuteStoredProcedure<DbErrorMsg>("sp_deleteContenu", parameters); } private bool CheckProperty(IEnumerable<ChampResult> champs, string property) { var p = champs.Where(x => property.Equals(x.Code)).FirstOrDefault(); return p != null; } public long SaveContenusInfosGenerales(ContenusInfosGeneralesComposite composite) { Contenu _contenu; if (composite.Data.ID > 0) { _contenu = this.GetById(composite.Data.ID); } else { _contenu = new Contenu(); _contenu.TypeContenu = composite.Data.TypeContenuID; } if (CheckProperty(composite.Champs, "Indicateur1")) { _contenu.Indicateur1 = composite.Data.Indicateur1; } if (CheckProperty(composite.Champs, "Indicateur2")) { _contenu.Indicateur2 = composite.Data.Indicateur2; } if (CheckProperty(composite.Champs, "Titre")) { _contenu.Titre = composite.Data.Titre; } if (CheckProperty(composite.Champs, "Ordre")) { _contenu.Ordre = composite.Data.Ordre; } if (CheckProperty(composite.Champs, "Option")) { _contenu.Option = composite.Data.Option; } if (CheckProperty(composite.Champs, "Accroche")) { _contenu.Accroche = composite.Data.Accroche; } if (CheckProperty(composite.Champs, "Texte")) { _contenu.Texte = composite.Data.Texte; } if (CheckProperty(composite.Champs, "AffichagePopup")) { _contenu.AffichagePopup = composite.Data.AffichagePopup; } if (CheckProperty(composite.Champs, "UrlDestination")) { _contenu.UrlDestination = composite.Data.UrlDestination; } if (CheckProperty(composite.Champs, "CodeFonctionnel")) { _contenu.CodeFonctionnel = composite.Data.CodeFonctionnel; } if (CheckProperty(composite.Champs, "CleModificationLot")) { _contenu.CleModificationLot = composite.Data.CleModificationLot; } if (CheckProperty(composite.Champs, "OptionSupplementaire")) { _contenu.OptionSupplementaire = composite.Data.OptionSupplementaire; } if (CheckProperty(composite.Champs, "ContenuIDDup")) { _contenu.ContenuIDDup = composite.Data.ContenuIDDup; } if (CheckProperty(composite.Champs, "BlocIdDup")) { _contenu.BlocIdDup = composite.Data.BlocIdDup; } if (composite.Data.ID > 0) { this.Update(); } else { this.Add(_contenu); if (composite.IsSousContenu) { RelationContenu relationContenu = new RelationContenu {FilsContenuID = _contenu.ID, SourceContenuID = composite.ParentID}; _relationContenu.Add(relationContenu); } else { BlocContenu blocContenu = new BlocContenu { BlocID = composite.ParentID, ContenuID = _contenu.ID, Date = DateTime.Today }; _blocContenu.Add(blocContenu); } } return _contenu.ID; } public IEnumerable<DictionaryResult> GetAscendantCatalogue(long articleId) { List<SqlParameter> parameters = new List<SqlParameter>(); parameters.Add(new SqlParameter("@ArticleID", SqlDbType.BigInt) { Value = articleId }); return DbContext.ExecuteStoredProcedure<DictionaryResult>("sp_GetAscendantCatalogue", parameters); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Collections.Generic; using System.Text; using OLEDB.Test.ModuleCore; /// <summary> /// This class is used to write out XML tokens. This tool can write /// well-formed as well as non well-formed file. This writer does not /// guarantee well-formedness. It does not implement XmlWriter. /// The class can write tokens by explicit API calls as well as parse /// a pattern string to generate these tokens. /// </summary> namespace XmlCoreTest.Common { public class ManagedNodeWriter { public static bool DEBUG = false; private const string XML_DECL = "<?xml version='1.0' ?>\n"; private const string S_ROOT = "<root>"; private const string E_ROOT = "</root>"; private const string E_NAME = "ELEMENT_"; private const string A_NAME = "ATTRIB_"; private const string A_VALUE = "VALUE_"; private const string CDATA = "CDATA_"; private const string TEXT = "TEXT_"; private const string PI = "PI_"; private const string COMMENT = "COMMENT_"; private long _eCount = 0; //element indexer private long _aCount = 0; //attribute indexer private long _cCount = 0; //Cdata indexer private long _tCount = 0; //Text indexer private long _pCount = 0; //PI Indexer private long _mCount = 0; //Comment Indexer private StreamWriter _textWriter = null; //Obviously performance is not a major requirement so //making use of out-of-box data structures to keep //state of the writer. //Managing the Element Stack. private Stack<string> _stack = null; //Managing the Node Queue. private StringBuilder _q = null; private const string LT = "<"; private const string GT = ">"; private const string MT = "/>"; private const string ET = "</"; private const string SPACE = " "; private const string S_QUOTE = "'"; private const string D_QUOTE = "\""; private const string EQ = "="; private const string LF = "\n"; private void Init() { _q = new StringBuilder(); _stack = new Stack<string>(); } private void Destroy() { _q = null; _stack = null; } /// <summary> /// Default Constructor. /// </summary> public ManagedNodeWriter() { Init(); } /// /// Overloaded Constructor with FileName to Write /// public ManagedNodeWriter(string filename) { Init(); _textWriter = new StreamWriter(FilePathUtil.getStream(filename)); } public ManagedNodeWriter(Stream myStream, Encoding enc) { Init(); _textWriter = new StreamWriter(myStream, enc); } /// <summary> /// Similar to the XmlWriter WriteDocType /// </summary> /// <param name="name">Doctype name</param> /// <param name="sysid">System ID</param> /// <param name="pubid">Public ID</param> /// <param name="subset">Content Model</param> public void WriteDocType(string name, string sysid, string pubid, string subset) { StringBuilder dt = new StringBuilder(); dt.Append("<!DOCTYPE "); dt.Append(name); if (pubid == null) { if (sysid != null) dt.Append(" SYSTEM " + sysid); } else { dt.Append(" PUBLIC " + pubid); if (sysid != null) { dt.Append(" " + sysid); } } dt.Append("["); if (subset != null) dt.Append(subset); dt.Append("]>"); if (DEBUG) CError.WriteLine(dt.ToString()); _q.Append(dt.ToString()); } /// <summary> /// GetNodes returns the existing XML string thats been written so far. /// </summary> /// <returns>String of XML</returns> public string GetNodes() { return _q.ToString(); } /// Closing the NodeWriter public void Close() { if (_textWriter != null) { _textWriter.Write(_q.ToString()); //textWriter.Close(); _textWriter.Dispose(); _textWriter = null; } Destroy(); } /// Writing XML Decl public void PutDecl() { _q.Append(XML_DECL); } /// Writing a Root Element. public void PutRoot() { _q.Append(S_ROOT); } /// Writing End Root Element. public void PutEndRoot() { _q.Append(E_ROOT); } /// Writing a start of open element. public void OpenElement() { string elem = LT + E_NAME + _eCount + SPACE; _q.Append(elem); _stack.Push(E_NAME + _eCount); ++_eCount; } /// Writing a start of open element with user supplied name. public void OpenElement(string myName) { string elem = LT + myName + SPACE; _stack.Push(myName); _q.Append(elem); } /// Closing the open element. public void CloseElement() { _q.Append(GT); } // Closing the open element as empty element public void CloseEmptyElement() { _q.Append(MT); } /// Writing an attribute. public void PutAttribute() { string attr = A_NAME + _aCount + EQ + S_QUOTE + A_VALUE + _aCount + S_QUOTE + SPACE; _q.Append(attr); ++_aCount; } /// Overloaded PutAttribute which takes user values. public void PutAttribute(string myAttrName, string myAttrValue) { string attr = SPACE + myAttrName + EQ + S_QUOTE + myAttrValue + S_QUOTE; _q.Append(attr); } /// Writing empty element. public void PutEmptyElement() { string elem = LT + E_NAME + _eCount + MT; _q.Append(elem); ++_eCount; } /// Writing an end element from the stack. public void PutEndElement() { string elem = (string)_stack.Pop(); _q.Append(ET + elem + GT); } /// Writing an end element for a given name. public void PutEndElement(string myName) { if (DEBUG) CError.WriteLine("Popping : " + (string)_stack.Pop()); _q.Append(ET + myName + GT); } /// <summary> /// Finish allows user to complete xml file with the end element tags that were so far open. /// </summary> public void Finish() { while (_stack.Count > 0) { string elem = (string)_stack.Pop(); _q.Append(ET + elem + GT); } } /// Writing text. /// Note : This is basically equivalent to WriteRaw and the string may contain any number of embedded tags. /// No checking is performed on them either. public void PutText(string myStr) { _q.Append(myStr); } /// <summary> /// AutoGenerated Text /// </summary> public void PutText() { _q.Append(TEXT + _tCount++); } /// <summary> /// Writing a Byte Array. /// </summary> /// <param name="bArr"></param> public void PutBytes(byte[] bArr) { foreach (byte b in bArr) { _q.Append(b); } } public void PutByte() { _q.Append(Convert.ToByte("a")); } /// <summary> /// Writes out CDATA Node. /// </summary> public void PutCData() { _q.Append("<![CDATA[" + CDATA + _cCount++ + "]]>"); } /// <summary> /// Writes out a PI Node. /// </summary> public void PutPI() { _q.Append("<?" + PI + _pCount++ + "?>"); } /// <summary> /// Writes out a Comment Node. /// </summary> public void PutComment() { _q.Append("<!--" + COMMENT + _mCount++ + " -->"); } /// <summary> /// Writes out a single whitespace /// </summary> public void PutWhiteSpace() { _q.Append(" "); } /// <summary> /// This method is a convenience method and a shortcut to create an XML string. Each character in the pattern /// maps to a particular Put/Open function and calls it for you. For e.g. XEAA/ will call PutDecl, OpenElement, /// PutAttribute, PutAttribute and CloseElement for you. /// The following is the list of all allowed characters and their function mappings : /// ///'X' : PutDecl() ///'E' : OpenElement() ///'M' : CloseEmptyElement() ///'/' : CloseElement() ///'e' : PutEndElement() ///'A' : PutAttribute() ///'P' : PutPI() ///'T' : PutText() ///'C' : PutComment() ///'R' : PutRoot() ///'r' : PutEndRoot() ///'B' : PutEndRoot() ///'W' : PutWhiteSpace() /// /// </summary> /// <param name="pattern">String containing the pattern which you want to use to create /// the XML string. Refer to table above for supported chars.</param> public void PutPattern(string pattern) { char[] patternArr = pattern.ToCharArray(); foreach (char ch in patternArr) { switch (ch) { case 'X': PutDecl(); break; case 'E': OpenElement(); break; case 'M': CloseEmptyElement(); break; case '/': CloseElement(); break; case 'e': PutEndElement(); break; case 'A': PutAttribute(); break; case 'P': PutPI(); break; case 'T': PutText(); break; case 'C': PutComment(); break; case 'R': PutRoot(); break; case 'r': PutEndRoot(); break; case 'B': PutEndRoot(); break; case 'W': PutWhiteSpace(); break; default: CError.WriteLine("Skipping Character : " + ch); break; } } } // Entry point. public static void Main(string[] args) { string filename = "temp.xml"; ManagedNodeWriter mw = new ManagedNodeWriter(filename); ManagedNodeWriter mnw = new ManagedNodeWriter(); mnw.PutPattern("X"); int count = 0; do { mnw.PutPattern("E/"); count++; } while (count < 65536); mnw.PutText("<a/>"); mnw.Finish(); StreamWriter sw = new StreamWriter(FilePathUtil.getStream("deep.xml")); sw.Write(mnw.GetNodes()); sw.Dispose(); } } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.ElasticBeanstalk.Model { /// <summary> /// Container for the parameters to the UpdateConfigurationTemplate operation. /// <para> Updates the specified configuration template to have the specified properties or configuration option values. </para> /// <para><b>NOTE:</b> If a property (for example, ApplicationName) is not provided, its value remains unchanged. To clear such properties, /// specify an empty string. </para> <para>Related Topics</para> /// <ul> /// <li> DescribeConfigurationOptions </li> /// /// </ul> /// </summary> /// <seealso cref="Amazon.ElasticBeanstalk.AmazonElasticBeanstalk.UpdateConfigurationTemplate"/> public class UpdateConfigurationTemplateRequest : AmazonWebServiceRequest { private string applicationName; private string templateName; private string description; private List<ConfigurationOptionSetting> optionSettings = new List<ConfigurationOptionSetting>(); private List<OptionSpecification> optionsToRemove = new List<OptionSpecification>(); /// <summary> /// The name of the application associated with the configuration template to update. If no application is found with this name, /// <c>UpdateConfigurationTemplate</c> returns an <c>InvalidParameterValue</c> error. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 100</description> /// </item> /// </list> /// </para> /// </summary> public string ApplicationName { get { return this.applicationName; } set { this.applicationName = value; } } /// <summary> /// Sets the ApplicationName property /// </summary> /// <param name="applicationName">The value to set for the ApplicationName property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public UpdateConfigurationTemplateRequest WithApplicationName(string applicationName) { this.applicationName = applicationName; return this; } // Check to see if ApplicationName property is set internal bool IsSetApplicationName() { return this.applicationName != null; } /// <summary> /// The name of the configuration template to update. If no configuration template is found with this name, <c>UpdateConfigurationTemplate</c> /// returns an <c>InvalidParameterValue</c> error. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 100</description> /// </item> /// </list> /// </para> /// </summary> public string TemplateName { get { return this.templateName; } set { this.templateName = value; } } /// <summary> /// Sets the TemplateName property /// </summary> /// <param name="templateName">The value to set for the TemplateName property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public UpdateConfigurationTemplateRequest WithTemplateName(string templateName) { this.templateName = templateName; return this; } // Check to see if TemplateName property is set internal bool IsSetTemplateName() { return this.templateName != null; } /// <summary> /// A new description for the configuration. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>0 - 200</description> /// </item> /// </list> /// </para> /// </summary> public string Description { get { return this.description; } set { this.description = value; } } /// <summary> /// Sets the Description property /// </summary> /// <param name="description">The value to set for the Description property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public UpdateConfigurationTemplateRequest WithDescription(string description) { this.description = description; return this; } // Check to see if Description property is set internal bool IsSetDescription() { return this.description != null; } /// <summary> /// A list of configuration option settings to update with the new specified option value. /// /// </summary> public List<ConfigurationOptionSetting> OptionSettings { get { return this.optionSettings; } set { this.optionSettings = value; } } /// <summary> /// Adds elements to the OptionSettings collection /// </summary> /// <param name="optionSettings">The values to add to the OptionSettings collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public UpdateConfigurationTemplateRequest WithOptionSettings(params ConfigurationOptionSetting[] optionSettings) { foreach (ConfigurationOptionSetting element in optionSettings) { this.optionSettings.Add(element); } return this; } /// <summary> /// Adds elements to the OptionSettings collection /// </summary> /// <param name="optionSettings">The values to add to the OptionSettings collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public UpdateConfigurationTemplateRequest WithOptionSettings(IEnumerable<ConfigurationOptionSetting> optionSettings) { foreach (ConfigurationOptionSetting element in optionSettings) { this.optionSettings.Add(element); } return this; } // Check to see if OptionSettings property is set internal bool IsSetOptionSettings() { return this.optionSettings.Count > 0; } /// <summary> /// A list of configuration options to remove from the configuration set. Constraint: You can remove only <c>UserDefined</c> configuration /// options. /// /// </summary> public List<OptionSpecification> OptionsToRemove { get { return this.optionsToRemove; } set { this.optionsToRemove = value; } } /// <summary> /// Adds elements to the OptionsToRemove collection /// </summary> /// <param name="optionsToRemove">The values to add to the OptionsToRemove collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public UpdateConfigurationTemplateRequest WithOptionsToRemove(params OptionSpecification[] optionsToRemove) { foreach (OptionSpecification element in optionsToRemove) { this.optionsToRemove.Add(element); } return this; } /// <summary> /// Adds elements to the OptionsToRemove collection /// </summary> /// <param name="optionsToRemove">The values to add to the OptionsToRemove collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public UpdateConfigurationTemplateRequest WithOptionsToRemove(IEnumerable<OptionSpecification> optionsToRemove) { foreach (OptionSpecification element in optionsToRemove) { this.optionsToRemove.Add(element); } return this; } // Check to see if OptionsToRemove property is set internal bool IsSetOptionsToRemove() { return this.optionsToRemove.Count > 0; } } }
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: blah@cliffano.com * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; namespace Org.OpenAPITools.Model { /// <summary> /// PipelineFolderImpl /// </summary> [DataContract] public partial class PipelineFolderImpl : IEquatable<PipelineFolderImpl>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="PipelineFolderImpl" /> class. /// </summary> /// <param name="_class">_class.</param> /// <param name="displayName">displayName.</param> /// <param name="fullName">fullName.</param> /// <param name="name">name.</param> /// <param name="organization">organization.</param> /// <param name="numberOfFolders">numberOfFolders.</param> /// <param name="numberOfPipelines">numberOfPipelines.</param> public PipelineFolderImpl(string _class = default(string), string displayName = default(string), string fullName = default(string), string name = default(string), string organization = default(string), int numberOfFolders = default(int), int numberOfPipelines = default(int)) { this.Class = _class; this.DisplayName = displayName; this.FullName = fullName; this.Name = name; this.Organization = organization; this.NumberOfFolders = numberOfFolders; this.NumberOfPipelines = numberOfPipelines; } /// <summary> /// Gets or Sets Class /// </summary> [DataMember(Name="_class", EmitDefaultValue=false)] public string Class { get; set; } /// <summary> /// Gets or Sets DisplayName /// </summary> [DataMember(Name="displayName", EmitDefaultValue=false)] public string DisplayName { get; set; } /// <summary> /// Gets or Sets FullName /// </summary> [DataMember(Name="fullName", EmitDefaultValue=false)] public string FullName { get; set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Gets or Sets Organization /// </summary> [DataMember(Name="organization", EmitDefaultValue=false)] public string Organization { get; set; } /// <summary> /// Gets or Sets NumberOfFolders /// </summary> [DataMember(Name="numberOfFolders", EmitDefaultValue=false)] public int NumberOfFolders { get; set; } /// <summary> /// Gets or Sets NumberOfPipelines /// </summary> [DataMember(Name="numberOfPipelines", EmitDefaultValue=false)] public int NumberOfPipelines { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class PipelineFolderImpl {\n"); sb.Append(" Class: ").Append(Class).Append("\n"); sb.Append(" DisplayName: ").Append(DisplayName).Append("\n"); sb.Append(" FullName: ").Append(FullName).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Organization: ").Append(Organization).Append("\n"); sb.Append(" NumberOfFolders: ").Append(NumberOfFolders).Append("\n"); sb.Append(" NumberOfPipelines: ").Append(NumberOfPipelines).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as PipelineFolderImpl); } /// <summary> /// Returns true if PipelineFolderImpl instances are equal /// </summary> /// <param name="input">Instance of PipelineFolderImpl to be compared</param> /// <returns>Boolean</returns> public bool Equals(PipelineFolderImpl input) { if (input == null) return false; return ( this.Class == input.Class || (this.Class != null && this.Class.Equals(input.Class)) ) && ( this.DisplayName == input.DisplayName || (this.DisplayName != null && this.DisplayName.Equals(input.DisplayName)) ) && ( this.FullName == input.FullName || (this.FullName != null && this.FullName.Equals(input.FullName)) ) && ( this.Name == input.Name || (this.Name != null && this.Name.Equals(input.Name)) ) && ( this.Organization == input.Organization || (this.Organization != null && this.Organization.Equals(input.Organization)) ) && ( this.NumberOfFolders == input.NumberOfFolders || (this.NumberOfFolders != null && this.NumberOfFolders.Equals(input.NumberOfFolders)) ) && ( this.NumberOfPipelines == input.NumberOfPipelines || (this.NumberOfPipelines != null && this.NumberOfPipelines.Equals(input.NumberOfPipelines)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Class != null) hashCode = hashCode * 59 + this.Class.GetHashCode(); if (this.DisplayName != null) hashCode = hashCode * 59 + this.DisplayName.GetHashCode(); if (this.FullName != null) hashCode = hashCode * 59 + this.FullName.GetHashCode(); if (this.Name != null) hashCode = hashCode * 59 + this.Name.GetHashCode(); if (this.Organization != null) hashCode = hashCode * 59 + this.Organization.GetHashCode(); if (this.NumberOfFolders != null) hashCode = hashCode * 59 + this.NumberOfFolders.GetHashCode(); if (this.NumberOfPipelines != null) hashCode = hashCode * 59 + this.NumberOfPipelines.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
#pragma warning disable 0168 using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Xml; using nHydrate.Generator.Common.Util; using System.Windows.Forms; using Microsoft.VisualStudio.Modeling; using System.IO.Compression; namespace nHydrate.Dsl.Custom { public static class SQLFileManagement { private const string FOLDER_ET = "_Entities"; private const string FOLDER_VW = "_Views"; public static string GetModelFolder(string rootFolder, string modelName) { return Path.Combine(rootFolder, "_" + modelName); } public static void SaveToDisk(nHydrateModel modelRoot, string rootFolder, string modelName, nHydrateDiagram diagram) { modelRoot.IsSaving = true; try { var folderName = modelName.Replace(".nhydrate", ".model"); var modelFolder = GetModelFolder(rootFolder, folderName); var generatedFileList = new List<string>(); nHydrate.Dsl.Custom.SQLFileManagement.SaveToDisk(modelRoot, modelRoot.Views, modelFolder, diagram, generatedFileList); //must come before entities nHydrate.Dsl.Custom.SQLFileManagement.SaveToDisk(modelRoot, modelRoot.Entities, modelFolder, diagram, generatedFileList); nHydrate.Dsl.Custom.SQLFileManagement.SaveDiagramFiles(modelFolder, diagram, generatedFileList); RemoveOrphans(modelFolder, generatedFileList); try { var compressedFile = Path.Combine(rootFolder, modelName + ".zip"); if (File.Exists(compressedFile)) { File.Delete(compressedFile); System.Threading.Thread.Sleep(300); } //Create ZIP file with entire model folder System.IO.Compression.ZipFile.CreateFromDirectory(modelFolder, compressedFile, System.IO.Compression.CompressionLevel.Fastest, true); //Now add the top level model artifacts var artifacts = Directory.GetFiles(rootFolder, $"{modelName}.*").ToList(); artifacts.RemoveAll(x => x == compressedFile); using (var zipToOpen = System.IO.Compression.ZipFile.Open(compressedFile, System.IO.Compression.ZipArchiveMode.Update)) { foreach (var ff in artifacts) { var fi = new FileInfo(ff); zipToOpen.CreateEntryFromFile(ff, fi.Name); } } } catch (Exception ex) { //Do Nothing } } catch (Exception ex) { throw; } finally { modelRoot.IsSaving = false; } } /// <summary> /// Saves Stored Procedures to disk /// </summary> private static void SaveToDisk(nHydrateModel modelRoot, IEnumerable<Entity> list, string rootFolder, nHydrateDiagram diagram, List<string> generatedFileList) { var folder = Path.Combine(rootFolder, FOLDER_ET); if (!Directory.Exists(folder)) Directory.CreateDirectory(folder); #region Save other parameter/field information foreach (var item in list) { var document = new XmlDocument(); document.LoadXml(@"<configuration type=""entity"" name=""" + item.Name + @"""></configuration>"); XmlHelper.AddLineBreak(document.DocumentElement); XmlHelper.AddCData(document.DocumentElement, "summary", item.Summary); XmlHelper.AddLineBreak(document.DocumentElement); XmlHelper.AddAttribute(document.DocumentElement, "id", item.Id); XmlHelper.AddAttribute(document.DocumentElement, "allowcreateaudit", item.AllowCreateAudit); XmlHelper.AddAttribute(document.DocumentElement, "allowmodifyaudit", item.AllowModifyAudit); XmlHelper.AddAttribute(document.DocumentElement, "allowtimestamp", item.AllowTimestamp); XmlHelper.AddAttribute(document.DocumentElement, "codefacade", item.CodeFacade); XmlHelper.AddAttribute(document.DocumentElement, "immutable", item.Immutable); XmlHelper.AddAttribute(document.DocumentElement, "isassociative", item.IsAssociative); XmlHelper.AddAttribute(document.DocumentElement, "typedentity", item.TypedEntity.ToString()); XmlHelper.AddAttribute(document.DocumentElement, "schema", item.Schema); XmlHelper.AddAttribute(document.DocumentElement, "generatesdoublederived", item.GeneratesDoubleDerived); XmlHelper.AddAttribute(document.DocumentElement, "isTenant", item.IsTenant); #region Fields { var fieldsNodes = XmlHelper.AddElement(document.DocumentElement, "fieldset") as XmlElement; XmlHelper.AddLineBreak((XmlElement)fieldsNodes); foreach (var field in item.Fields.OrderBy(x => x.Name)) { var fieldNode = XmlHelper.AddElement(fieldsNodes, "field"); XmlHelper.AddLineBreak((XmlElement)fieldNode); XmlHelper.AddCData((XmlElement)fieldNode, "summary", field.Summary); XmlHelper.AddLineBreak((XmlElement)fieldNode); XmlHelper.AddAttribute(fieldNode, "id", field.Id); XmlHelper.AddAttribute(fieldNode, "name", field.Name); XmlHelper.AddAttribute(fieldNode, "nullable", field.Nullable); XmlHelper.AddAttribute(fieldNode, "datatype", field.DataType.ToString()); XmlHelper.AddAttribute(fieldNode, "identity", field.Identity.ToString()); XmlHelper.AddAttribute(fieldNode, "codefacade", field.CodeFacade); XmlHelper.AddAttribute(fieldNode, "dataformatstring", field.DataFormatString); XmlHelper.AddAttribute(fieldNode, "default", field.Default); XmlHelper.AddAttribute(fieldNode, "defaultisfunc", field.DefaultIsFunc); XmlHelper.AddAttribute(fieldNode, "formula", field.Formula); XmlHelper.AddAttribute(fieldNode, "isindexed", field.IsIndexed); XmlHelper.AddAttribute(fieldNode, "isprimarykey", field.IsPrimaryKey); XmlHelper.AddAttribute(fieldNode, "Iscalculated", field.IsCalculated); XmlHelper.AddAttribute(fieldNode, "isunique", field.IsUnique); XmlHelper.AddAttribute(fieldNode, "length", field.Length); XmlHelper.AddAttribute(fieldNode, "scale", field.Scale); XmlHelper.AddAttribute(fieldNode, "sortorder", field.SortOrder); XmlHelper.AddAttribute(fieldNode, "isreadonly", field.IsReadOnly); XmlHelper.AddAttribute(fieldNode, "obsolete", field.Obsolete); XmlHelper.AddLineBreak((XmlElement)fieldsNodes); } XmlHelper.AddLineBreak((XmlElement)document.DocumentElement); } #endregion XmlHelper.AddLineBreak(document.DocumentElement); var f = Path.Combine(folder, item.Name + ".configuration.xml"); WriteFileIfNeedBe(f, document.ToIndentedString(), generatedFileList); //Save other files SaveEntityIndexes(folder, item, generatedFileList); SaveRelations(folder, item, generatedFileList); SaveEntityStaticData(folder, item, generatedFileList); } #endregion WriteReadMeFile(folder, generatedFileList); } private static void SaveEntityIndexes(string folder, Entity item, List<string> generatedFileList) { var document = new XmlDocument(); document.LoadXml(@"<configuration type=""entity.indexes"" id=""" + item.Id + @"""></configuration>"); XmlHelper.AddLineBreak((XmlElement)document.DocumentElement); foreach (var index in item.Indexes) { var indexNode = XmlHelper.AddElement(document.DocumentElement, "index"); XmlHelper.AddLineBreak((XmlElement)indexNode); XmlHelper.AddCData((XmlElement)indexNode, "summary", index.Summary); XmlHelper.AddLineBreak((XmlElement)indexNode); XmlHelper.AddAttribute(indexNode, "id", index.Id); XmlHelper.AddAttribute(indexNode, "clustered", index.Clustered); XmlHelper.AddAttribute(indexNode, "importedname", index.ImportedName); XmlHelper.AddAttribute(indexNode, "indextype", index.IndexType.ToString("d")); XmlHelper.AddAttribute(indexNode, "isunique", index.IsUnique); XmlHelper.AddLineBreak((XmlElement)document.DocumentElement); //Process the columns var indexColumnsNodes = XmlHelper.AddElement((XmlElement)indexNode, "indexcolumnset") as XmlElement; XmlHelper.AddLineBreak((XmlElement)indexColumnsNodes); foreach (var indexColumn in index.IndexColumns) { var indexColumnNode = XmlHelper.AddElement(indexColumnsNodes, "column"); XmlHelper.AddAttribute(indexColumnNode, "id", indexColumn.Id); XmlHelper.AddAttribute(indexColumnNode, "ascending", indexColumn.Ascending); XmlHelper.AddAttribute(indexColumnNode, "fieldid", indexColumn.FieldID); XmlHelper.AddAttribute(indexColumnNode, "sortorder", indexColumn.SortOrder); XmlHelper.AddLineBreak((XmlElement)indexColumnsNodes); } } var f = Path.Combine(folder, item.Name + ".indexes.xml"); WriteFileIfNeedBe(f, document.ToIndentedString(), generatedFileList); } private static void SaveEntityStaticData(string folder, Entity item, List<string> generatedFileList) { var f = Path.Combine(folder, item.Name + ".staticdata.xml"); if (item.StaticDatum.Count == 0) return; var document = new XmlDocument(); document.LoadXml(@"<configuration type=""entity.staticdata"" id=""" + item.Id + @"""></configuration>"); XmlHelper.AddLineBreak((XmlElement)document.DocumentElement); foreach (var data in item.StaticDatum) { var dataNode = XmlHelper.AddElement(document.DocumentElement, "data"); XmlHelper.AddAttribute(dataNode, "columnkey", data.ColumnKey); XmlHelper.AddAttribute(dataNode, "value", data.Value); XmlHelper.AddAttribute(dataNode, "orderkey", data.OrderKey); XmlHelper.AddLineBreak((XmlElement)document.DocumentElement); } WriteFileIfNeedBe(f, document.ToIndentedString(), generatedFileList); } private static void SaveRelations(string folder, Entity item, List<string> generatedFileList) { var document = new XmlDocument(); document.LoadXml(@"<configuration type=""entity.relations"" id=""" + item.Id + @"""></configuration>"); XmlHelper.AddLineBreak((XmlElement)document.DocumentElement); foreach (var relation in item.RelationshipList) { var relationNode = XmlHelper.AddElement(document.DocumentElement, "relation"); XmlHelper.AddLineBreak((XmlElement)relationNode); XmlHelper.AddCData((XmlElement)relationNode, "summary", relation.Summary); XmlHelper.AddLineBreak((XmlElement)relationNode); XmlHelper.AddAttribute(relationNode, "id", relation.InternalId); XmlHelper.AddAttribute(relationNode, "childid", relation.ChildEntity.Id); XmlHelper.AddAttribute(relationNode, "isenforced", relation.IsEnforced); XmlHelper.AddAttribute(relationNode, "deleteaction", relation.DeleteAction.ToString()); XmlHelper.AddAttribute(relationNode, "rolename", relation.RoleName); XmlHelper.AddLineBreak((XmlElement)document.DocumentElement); //Process the columns var relationColumnsNodes = XmlHelper.AddElement((XmlElement)relationNode, "relationfieldset") as XmlElement; XmlHelper.AddLineBreak((XmlElement)relationColumnsNodes); foreach (var relationField in relation.FieldMapList()) { var realtionFieldNode = XmlHelper.AddElement(relationColumnsNodes, "field"); XmlHelper.AddAttribute(realtionFieldNode, "id", relationField.Id); XmlHelper.AddAttribute(realtionFieldNode, "sourcefieldid", relationField.SourceFieldId); XmlHelper.AddAttribute(realtionFieldNode, "targetfieldid", relationField.TargetFieldId); XmlHelper.AddLineBreak((XmlElement)relationColumnsNodes); } } var f = Path.Combine(folder, item.Name + ".relations.xml"); WriteFileIfNeedBe(f, document.ToIndentedString(), generatedFileList); } private static void SaveDiagramFiles(string rootFolder, nHydrateDiagram diagram, List<string> generatedFileList) { var fileName = Path.Combine(rootFolder, "diagram.xml"); var document = new XmlDocument(); document.LoadXml(@"<configuration type=""diagram""></configuration>"); foreach (var shape in diagram.NestedChildShapes) { if (shape is EntityShape) { var item = ((shape as EntityShape).ModelElement as Entity); var node = XmlHelper.AddElement(document.DocumentElement, "element"); node.AddAttribute("id", shape.ModelElement.Id); node.AddAttribute("bounds", shape.AbsoluteBoundingBox.ToXmlValue()); } else if (shape is ViewShape) { var item = ((shape as ViewShape).ModelElement as View); var node = XmlHelper.AddElement(document.DocumentElement, "element"); node.AddAttribute("id", shape.ModelElement.Id); node.AddAttribute("bounds", shape.AbsoluteBoundingBox.ToXmlValue()); } } WriteFileIfNeedBe(fileName, document.ToIndentedString(), generatedFileList); } /// <summary> /// Saves Views to disk /// </summary> private static void SaveToDisk(nHydrateModel modelRoot, IEnumerable<View> list, string rootFolder, nHydrateDiagram diagram, List<string> generatedFileList) { var folder = Path.Combine(rootFolder, FOLDER_VW); if (!Directory.Exists(folder)) Directory.CreateDirectory(folder); foreach (var item in list) { var f = Path.Combine(folder, item.Name + ".sql"); WriteFileIfNeedBe(f, item.SQL, generatedFileList); } #region Save other parameter/field information foreach (var item in list) { var document = new XmlDocument(); document.LoadXml(@"<configuration type=""view"" name=""" + item.Name + @"""></configuration>"); XmlHelper.AddLineBreak(document.DocumentElement); XmlHelper.AddCData(document.DocumentElement, "summary", item.Summary); XmlHelper.AddLineBreak(document.DocumentElement); XmlHelper.AddAttribute(document.DocumentElement, "id", item.Id); XmlHelper.AddAttribute(document.DocumentElement, "codefacade", item.CodeFacade); XmlHelper.AddAttribute(document.DocumentElement, "schema", item.Schema); XmlHelper.AddAttribute(document.DocumentElement, "generatesdoublederived", item.GeneratesDoubleDerived); var fieldsNodes = XmlHelper.AddElement(document.DocumentElement, "fieldset") as XmlElement; XmlHelper.AddLineBreak((XmlElement)fieldsNodes); foreach (var field in item.Fields.OrderBy(x => x.Name)) { var fieldNode = XmlHelper.AddElement(fieldsNodes, "field"); XmlHelper.AddLineBreak((XmlElement)fieldNode); XmlHelper.AddCData((XmlElement)fieldNode, "summary", field.Summary); XmlHelper.AddLineBreak((XmlElement)fieldNode); XmlHelper.AddAttribute(fieldNode, "id", field.Id); XmlHelper.AddAttribute(fieldNode, "name", field.Name); XmlHelper.AddAttribute(fieldNode, "nullable", field.Nullable); XmlHelper.AddAttribute(fieldNode, "datatype", field.DataType.ToString()); XmlHelper.AddAttribute(fieldNode, "codefacade", field.CodeFacade); XmlHelper.AddAttribute(fieldNode, "default", field.Default); XmlHelper.AddAttribute(fieldNode, "length", field.Length); XmlHelper.AddAttribute(fieldNode, "scale", field.Scale); XmlHelper.AddAttribute(fieldNode, "isprimarykey", field.IsPrimaryKey); XmlHelper.AddLineBreak((XmlElement)fieldsNodes); } XmlHelper.AddLineBreak(document.DocumentElement); var f = Path.Combine(folder, item.Name + ".configuration.xml"); WriteFileIfNeedBe(f, document.ToIndentedString(), generatedFileList); } #endregion WriteReadMeFile(folder, generatedFileList); } public static void LoadFromDisk(nHydrateModel model, string rootFolder, Microsoft.VisualStudio.Modeling.Store store, string modelName) { model.IsSaving = true; try { var modelFile = Path.Combine(rootFolder, modelName); var fi = new FileInfo(modelFile); var showError = (fi.Length > 10); //New file is small so show no error if creating new var folderName = modelName.Replace(".nhydrate", ".model"); var modelFolder = GetModelFolder(rootFolder, folderName); //If the model folder does NOT exist if (showError && !Directory.Exists(modelFolder)) { //Try to use the ZIP file var compressedFile = Path.Combine(rootFolder, modelName + ".zip"); if (!File.Exists(compressedFile)) { MessageBox.Show("The model folder was not found and the ZIP file is missing. One of these must exist to continue.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } //Unzip the whole file //System.IO.Compression.ZipFile.ExtractToDirectory(compressedFile, rootFolder); ExtractToDirectory(compressedFile, rootFolder, false); } nHydrate.Dsl.Custom.SQLFileManagement.LoadFromDisk(model.Views, model, modelFolder, store); //must come before entities nHydrate.Dsl.Custom.SQLFileManagement.LoadFromDisk(model.Entities, model, modelFolder, store); } catch (Exception ex) { throw; } finally { model.IsSaving = false; } } private static void LoadFromDisk(IEnumerable<Entity> list, nHydrateModel model, string rootFolder, Microsoft.VisualStudio.Modeling.Store store) { var folder = Path.Combine(rootFolder, FOLDER_ET); if (!Directory.Exists(folder)) return; #region Load other parameter/field information var fList = Directory.GetFiles(folder, "*.configuration.xml"); foreach (var f in fList) { var document = new XmlDocument(); try { document.Load(f); } catch (Exception ex) { //Do Nothing MessageBox.Show("The file '" + f + "' is not valid and could not be loaded!", "Load Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } var fi = new FileInfo(f); var name = fi.Name.Substring(0, fi.Name.Length - ".configuration.xml".Length).ToLower(); var itemID = XmlHelper.GetAttributeValue(document.DocumentElement, "id", Guid.Empty); var item = list.FirstOrDefault(x => x.Id == itemID); if (item == null) { item = new Entity(model.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, XmlHelper.GetAttributeValue(document.DocumentElement, "id", Guid.NewGuid())) }); model.Entities.Add(item); } System.Windows.Forms.Application.DoEvents(); #region Properties item.Name = XmlHelper.GetAttributeValue(document.DocumentElement, "name", item.Name); item.AllowCreateAudit = XmlHelper.GetAttributeValue(document.DocumentElement, "allowcreateaudit", item.AllowCreateAudit); item.AllowModifyAudit = XmlHelper.GetAttributeValue(document.DocumentElement, "allowmodifyaudit", item.AllowModifyAudit); item.AllowTimestamp = XmlHelper.GetAttributeValue(document.DocumentElement, "allowtimestamp", item.AllowTimestamp); item.CodeFacade = XmlHelper.GetAttributeValue(document.DocumentElement, "codefacade", item.CodeFacade); item.Immutable = XmlHelper.GetAttributeValue(document.DocumentElement, "immutable", item.Immutable); item.IsAssociative = XmlHelper.GetAttributeValue(document.DocumentElement, "isassociative", item.IsAssociative); item.GeneratesDoubleDerived = XmlHelper.GetAttributeValue(document.DocumentElement, "generatesdoublederived", item.GeneratesDoubleDerived); item.IsTenant = XmlHelper.GetAttributeValue(document.DocumentElement, "isTenant", item.IsTenant); var tev = XmlHelper.GetAttributeValue(document.DocumentElement, "typedentity", item.TypedEntity.ToString()); if (Enum.TryParse<TypedEntityConstants>(tev, true, out var te)) item.TypedEntity = te; item.Schema = XmlHelper.GetAttributeValue(document.DocumentElement, "schema", item.Schema); item.Summary = XmlHelper.GetNodeValue(document.DocumentElement, "summary", item.Summary); #endregion #region Fields var fieldsNodes = document.DocumentElement.SelectSingleNode("//fieldset"); if (fieldsNodes != null) { var nameList = new List<string>(); foreach (XmlNode n in fieldsNodes.ChildNodes) { var subItemID = XmlHelper.GetAttributeValue(n, "id", Guid.Empty); var field = item.Fields.FirstOrDefault(x => x.Id == subItemID); if (field == null) { field = new Field(item.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, XmlHelper.GetAttributeValue(n, "id", Guid.NewGuid())) }); item.Fields.Add(field); } field.Name = XmlHelper.GetAttributeValue(n, "name", string.Empty); field.CodeFacade = XmlHelper.GetAttributeValue(n, "codefacade", field.CodeFacade); nameList.Add(field.Name.ToLower()); field.Nullable = XmlHelper.GetAttributeValue(n, "nullable", field.Nullable); var dtv = XmlHelper.GetAttributeValue(n, "datatype", field.DataType.ToString()); if (Enum.TryParse<DataTypeConstants>(dtv, true, out var dt)) field.DataType = dt; var itv = XmlHelper.GetAttributeValue(n, "identity", field.Identity.ToString()); if (Enum.TryParse<IdentityTypeConstants>(itv, true, out var it)) field.Identity = it; field.DataFormatString = XmlHelper.GetNodeValue(n, "dataformatstring", field.DataFormatString); field.Default = XmlHelper.GetAttributeValue(n, "default", field.Default); field.DefaultIsFunc = XmlHelper.GetAttributeValue(n, "defaultisfunc", field.DefaultIsFunc); field.Formula = XmlHelper.GetAttributeValue(n, "formula", field.Formula); field.IsIndexed = XmlHelper.GetAttributeValue(n, "isindexed", field.IsIndexed); field.IsPrimaryKey = XmlHelper.GetAttributeValue(n, "isprimarykey", field.IsPrimaryKey); field.IsCalculated = XmlHelper.GetAttributeValue(n, "Iscalculated", field.IsCalculated); field.IsUnique = XmlHelper.GetAttributeValue(n, "isunique", field.IsUnique); field.Length = XmlHelper.GetAttributeValue(n, "length", field.Length); field.Scale = XmlHelper.GetAttributeValue(n, "scale", field.Scale); field.SortOrder = XmlHelper.GetAttributeValue(n, "sortorder", field.SortOrder); field.IsReadOnly = XmlHelper.GetAttributeValue(n, "isreadonly", field.IsReadOnly); field.Obsolete = XmlHelper.GetAttributeValue(n, "obsolete", field.Obsolete); field.Summary = XmlHelper.GetNodeValue(n, "summary", field.Summary); } if (item.Fields.Remove(x => !nameList.Contains(x.Name.ToLower())) > 0) item.nHydrateModel.IsDirty = true; } #endregion LoadEntityIndexes(folder, item); //Order fields (skip for model that did not have sort order when saved) var fc = new FieldOrderComparer(); if (item.Fields.Count(x => x.SortOrder > 0) > 0) item.Fields.Sort(fc.Compare); } //Must load relations AFTER ALL entities are loaded foreach (var item in model.Entities) { LoadEntityRelations(folder, item); LoadEntityStaticData(folder, item); } #endregion } private static void LoadEntityIndexes(string folder, Entity entity) { XmlDocument document = null; var fileName = Path.Combine(folder, entity.Name + ".indexes.xml"); if (!File.Exists(fileName)) return; try { document = new XmlDocument(); document.Load(fileName); } catch (Exception ex) { //Do Nothing MessageBox.Show("The file '" + fileName + "' is not valid and could not be loaded!", "Load Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } foreach (XmlNode n in document.DocumentElement) { var id = XmlHelper.GetAttributeValue(n, "id", Guid.NewGuid()); var newIndex = entity.Indexes.FirstOrDefault(x => x.Id == id); if (newIndex == null) { newIndex = new Index(entity.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, id) }); entity.Indexes.Add(newIndex); } newIndex.Clustered = XmlHelper.GetAttributeValue(n, "clustered", newIndex.Clustered); newIndex.ImportedName = XmlHelper.GetAttributeValue(n, "importedname", newIndex.ImportedName); newIndex.IndexType = (IndexTypeConstants)XmlHelper.GetAttributeValue(n, "indextype", int.Parse(newIndex.IndexType.ToString("d"))); newIndex.IsUnique = XmlHelper.GetAttributeValue(n, "isunique", newIndex.IsUnique); var indexColumnsNode = n.SelectSingleNode("indexcolumnset"); if (indexColumnsNode != null) { foreach (XmlNode m in indexColumnsNode.ChildNodes) { id = XmlHelper.GetAttributeValue(m, "id", Guid.NewGuid()); var newIndexColumn = newIndex.IndexColumns.FirstOrDefault(x => x.Id == id); if (newIndexColumn == null) { newIndexColumn = new IndexColumn(entity.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, id) }); newIndex.IndexColumns.Add(newIndexColumn); } newIndexColumn.Ascending = XmlHelper.GetAttributeValue(m, "ascending", newIndexColumn.Ascending); newIndexColumn.FieldID = XmlHelper.GetAttributeValue(m, "fieldid", newIndexColumn.FieldID); newIndexColumn.SortOrder = XmlHelper.GetAttributeValue(m, "sortorder", newIndexColumn.SortOrder); newIndexColumn.IsInternal = true; } } } } private static void LoadEntityRelations(string folder, Entity entity) { XmlDocument document = null; var fileName = Path.Combine(folder, entity.Name + ".relations.xml"); if (!File.Exists(fileName)) return; try { document = new XmlDocument(); document.Load(fileName); } catch (Exception ex) { //Do Nothing MessageBox.Show("The file '" + fileName + "' is not valid and could not be loaded!", "Load Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } foreach (XmlNode n in document.DocumentElement) { var childid = XmlHelper.GetAttributeValue(n, "childid", Guid.Empty); var child = entity.nHydrateModel.Entities.FirstOrDefault(x => x.Id == childid); if (child != null) { entity.ChildEntities.Add(child); var connection = entity.Store.CurrentContext.Partitions.First().Value.ElementDirectory.AllElements.Last() as EntityHasEntities; connection.InternalId = XmlHelper.GetAttributeValue(n, "id", Guid.Empty); connection.IsEnforced = XmlHelper.GetAttributeValue(n, "isenforced", connection.IsEnforced); connection.DeleteAction = (DeleteActionConstants) Enum.Parse(typeof(DeleteActionConstants), XmlHelper.GetAttributeValue(n, "deleteaction", connection.DeleteAction.ToString())); connection.RoleName = XmlHelper.GetAttributeValue(n, "rolename", connection.RoleName); var relationColumnsNode = n.SelectSingleNode("relationfieldset"); if (relationColumnsNode != null) { foreach (XmlNode m in relationColumnsNode.ChildNodes) { var sourceFieldID = XmlHelper.GetAttributeValue(m, "sourcefieldid", Guid.Empty); var targetFieldID = XmlHelper.GetAttributeValue(m, "targetfieldid", Guid.Empty); var sourceField = entity.Fields.FirstOrDefault(x => x.Id == sourceFieldID); var targetField = entity.nHydrateModel.Entities.SelectMany(x => x.Fields).FirstOrDefault(x => x.Id == targetFieldID); if ((sourceField != null) && (targetField != null)) { var id = XmlHelper.GetAttributeValue(m, "id", Guid.NewGuid()); var newRelationField = new RelationField(entity.Partition, new PropertyAssignment[] {new PropertyAssignment(ElementFactory.IdPropertyAssignment, id)}); newRelationField.SourceFieldId = sourceFieldID; newRelationField.TargetFieldId = targetFieldID; newRelationField.RelationID = connection.Id; entity.nHydrateModel.RelationFields.Add(newRelationField); } } } } } } private static void LoadEntityStaticData(string folder, Entity entity) { XmlDocument document = null; var fileName = Path.Combine(folder, entity.Name + ".staticdata.xml"); if (!File.Exists(fileName)) return; try { document = new XmlDocument(); document.Load(fileName); } catch (Exception ex) { //Do Nothing MessageBox.Show("The file '" + fileName + "' is not valid and could not be loaded!", "Load Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } foreach (XmlNode n in document.DocumentElement) { var newData = new StaticData(entity.Partition); entity.StaticDatum.Add(newData); newData.OrderKey = XmlHelper.GetAttributeValue(n, "orderkey", newData.OrderKey); newData.Value = XmlHelper.GetAttributeValue(n, "value", newData.Value); newData.ColumnKey = XmlHelper.GetAttributeValue(n, "columnkey", newData.ColumnKey); } } private static void LoadFromDisk(IEnumerable<View> list, nHydrateModel model, string rootFolder, Microsoft.VisualStudio.Modeling.Store store) { var folder = Path.Combine(rootFolder, FOLDER_VW); if (!Directory.Exists(folder)) return; #region Load other parameter/field information var fList = Directory.GetFiles(folder, "*.configuration.xml"); foreach (var f in fList) { var document = new XmlDocument(); try { document.Load(f); } catch (Exception ex) { //Do Nothing MessageBox.Show("The file '" + f + "' is not valid and could not be loaded!", "Load Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } var fi = new FileInfo(f); var name = fi.Name.Substring(0, fi.Name.Length - ".configuration.xml".Length).ToLower(); var itemID = XmlHelper.GetAttributeValue(document.DocumentElement, "id", Guid.Empty); var item = list.FirstOrDefault(x => x.Id == itemID); if (item == null) { item = new View(model.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, XmlHelper.GetAttributeValue(document.DocumentElement, "id", Guid.NewGuid())) }); model.Views.Add(item); } System.Windows.Forms.Application.DoEvents(); item.Name = XmlHelper.GetAttributeValue(document.DocumentElement, "name", item.Name); item.CodeFacade = XmlHelper.GetAttributeValue(document.DocumentElement, "codefacade", item.CodeFacade); item.Schema = XmlHelper.GetAttributeValue(document.DocumentElement, "schema", item.Schema); item.GeneratesDoubleDerived = XmlHelper.GetAttributeValue(document.DocumentElement, "generatesdoublederived", item.GeneratesDoubleDerived); item.Summary = XmlHelper.GetNodeValue(document.DocumentElement, "summary", item.Summary); //Fields var fieldsNodes = document.DocumentElement.SelectSingleNode("//fieldset"); if (fieldsNodes != null) { var nameList = new List<string>(); foreach (XmlNode n in fieldsNodes.ChildNodes) { var subItemID = XmlHelper.GetAttributeValue(n, "id", Guid.Empty); var field = item.Fields.FirstOrDefault(x => x.Id == subItemID); if (field == null) { field = new ViewField(item.Partition, new PropertyAssignment[] { new PropertyAssignment(ElementFactory.IdPropertyAssignment, XmlHelper.GetAttributeValue(n, "id", Guid.NewGuid())) }); item.Fields.Add(field); } field.Name = XmlHelper.GetAttributeValue(n, "name", field.Name); field.CodeFacade = XmlHelper.GetAttributeValue(n, "codefacade", field.CodeFacade); nameList.Add(field.Name.ToLower()); field.Nullable = XmlHelper.GetAttributeValue(n, "nullable", field.Nullable); var dtv = XmlHelper.GetAttributeValue(n, "datatype", field.DataType.ToString()); if (Enum.TryParse<DataTypeConstants>(dtv, true, out var dt)) field.DataType = dt; field.Default = XmlHelper.GetAttributeValue(n, "default", field.Default); field.Length = XmlHelper.GetAttributeValue(n, "length", field.Length); field.Scale = XmlHelper.GetAttributeValue(n, "scale", field.Scale); field.Summary = XmlHelper.GetNodeValue(n, "summary", field.Summary); field.IsPrimaryKey = XmlHelper.GetAttributeValue(n, "isprimarykey", field.IsPrimaryKey); } if (item.Fields.Remove(x => !nameList.Contains(x.Name.ToLower())) > 0) item.nHydrateModel.IsDirty = true; } } #endregion #region Load SQL fList = Directory.GetFiles(folder, "*.sql"); foreach (var f in fList) { var fi = new FileInfo(f); if (fi.Name.ToLower().EndsWith(".sql")) { var name = fi.Name.Substring(0, fi.Name.Length - 4).ToLower(); var item = list.FirstOrDefault(x => x.Name.ToLower() == name); if (item != null) { item.SQL = File.ReadAllText(f); System.Windows.Forms.Application.DoEvents(); } } } #endregion } public static void LoadDiagramFiles(nHydrateModel model, string rootFolder, string modelName, nHydrateDiagram diagram) { if (!model.ModelToDisk) return; var fileName = Path.Combine(GetModelFolder(rootFolder, modelName), "diagram.xml"); if (!File.Exists(fileName)) return; using (var transaction = model.Store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString())) { var document = new XmlDocument(); var id = Guid.Empty; try { document.Load(fileName); if (document.DocumentElement == null) throw new Exception("No Root"); //this is thrown away foreach (XmlNode node in document.DocumentElement.ChildNodes) { id = XmlHelper.GetAttributeValue(node, "id", Guid.Empty); var shape = diagram.NestedChildShapes.FirstOrDefault(x => x.ModelElement.Id == id) as Microsoft.VisualStudio.Modeling.Diagrams.NodeShape; if (shape != null) shape.Bounds = Extensions.ConvertRectangleDFromXmlValue(XmlHelper.GetAttributeValue(node, "bounds", string.Empty)); } } catch (Exception ex) { return; } transaction.Commit(); } } #region Private Helpers private static void WriteFileIfNeedBe(string fileName, string contents, List<string> generatedFileList) { if (fileName.ToLower().EndsWith(".xml")) { generatedFileList.Add(fileName); try { //Load formatted original XML var origXML = string.Empty; if (File.Exists(fileName)) { var xmlText = File.ReadAllText(fileName); if (!string.IsNullOrEmpty(xmlText)) { var documentCheck = new XmlDocument(); documentCheck.LoadXml(xmlText); origXML = documentCheck.ToIndentedString(); } } //Load formatted new XML var newXML = string.Empty; { var documentCheck = new XmlDocument(); documentCheck.LoadXml(contents); newXML = documentCheck.ToIndentedString(); } if (origXML == newXML) return; else contents = newXML; } catch (Exception ex) { //If there is an error then process like a non-XML file //Do Nothing } } else { //Check if this is the same content and if so do nothing generatedFileList.Add(fileName); if (File.Exists(fileName)) { var t = File.ReadAllText(fileName); if (t == contents) return; } } File.WriteAllText(fileName, contents); System.Windows.Forms.Application.DoEvents(); } private static void WriteReadMeFile(string folder, List<string> generatedFileList) { var f = Path.Combine(folder, "ReadMe.nHydrate.txt"); WriteFileIfNeedBe(f, "This is a managed folder of a nHydrate model. You may change '*.configuration.xml' and '*.sql' files in any text editor if desired but do not add or remove files from this folder. This is a distributed model and making changes can break the model load.", generatedFileList); } private static void RemoveOrphans(string rootFolder, List<string> generatedFiles) { //Only get these specific folder in case there is version control or some other third-party application running //Only touch the files we know about var files = new List<string>(); files.AddRange(Directory.GetFiles(rootFolder, "*.*", SearchOption.TopDirectoryOnly)); files.AddRange(Directory.GetFiles(Path.Combine(rootFolder, "_Entities"), "*.*", SearchOption.TopDirectoryOnly)); files.AddRange(Directory.GetFiles(Path.Combine(rootFolder, "_Views"), "*.*", SearchOption.TopDirectoryOnly)); files.ToList().ForEach(x => x = x.ToLower()); generatedFiles.ToList().ForEach(x => x = x.ToLower()); foreach (var f in files) { var fi = new FileInfo(f); if (fi.Name.ToLower().Contains("readme.nhydrate.txt")) { //Skip } else if (generatedFiles.Contains(f)) { //Skip } else { File.Delete(f); } } } private static void ExtractToDirectory(string compressedFile, string destinationDirectoryName, bool overwrite) { using (var archive = System.IO.Compression.ZipFile.Open(compressedFile, System.IO.Compression.ZipArchiveMode.Update)) { var di = Directory.CreateDirectory(destinationDirectoryName); var destinationDirectoryFullPath = di.FullName; foreach (var file in archive.Entries) { var completeFileName = Path.GetFullPath(Path.Combine(destinationDirectoryFullPath, file.FullName)); if (!completeFileName.StartsWith(destinationDirectoryFullPath, StringComparison.OrdinalIgnoreCase)) { throw new IOException("Trying to extract file outside of destination directory. See this link for more info: https://snyk.io/research/zip-slip-vulnerability"); } if (file.Name == string.Empty) { // Assuming Empty for Directory Directory.CreateDirectory(Path.GetDirectoryName(completeFileName)); continue; } if (!File.Exists(completeFileName)) { var folder = (new FileInfo(completeFileName)).DirectoryName; if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); System.Threading.Thread.Sleep(200); } file.ExtractToFile(completeFileName, overwrite); } } } } #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 NPOI.XSSF.Model; using NPOI.OpenXmlFormats.Spreadsheet; using NPOI.XSSF.UserModel.Extensions; using NUnit.Framework; using NPOI.SS.UserModel; using NPOI.HSSF.UserModel; using System.Drawing; using NPOI.HSSF.Util; namespace NPOI.XSSF.UserModel { [TestFixture] public class TestXSSFCellStyle { private StylesTable stylesTable; private CT_Border ctBorderA; private CT_Fill ctFill; private CT_Font ctFont; private CT_Xf cellStyleXf; private CT_Xf cellXf; private CT_CellXfs cellXfs; private XSSFCellStyle cellStyle; private CT_Stylesheet ctStylesheet; [SetUp] public void SetUp() { stylesTable = new StylesTable(); ctStylesheet = stylesTable.GetCTStylesheet(); ctBorderA = new CT_Border(); XSSFCellBorder borderA = new XSSFCellBorder(ctBorderA); long borderId = stylesTable.PutBorder(borderA); Assert.AreEqual(1, borderId); XSSFCellBorder borderB = new XSSFCellBorder(); Assert.AreEqual(1, stylesTable.PutBorder(borderB)); ctFill = new CT_Fill(); XSSFCellFill fill = new XSSFCellFill(ctFill); long fillId = stylesTable.PutFill(fill); Assert.AreEqual(2, fillId); ctFont = new CT_Font(); XSSFFont font = new XSSFFont(ctFont); long fontId = stylesTable.PutFont(font); Assert.AreEqual(1, fontId); cellStyleXf = ctStylesheet.AddNewCellStyleXfs().AddNewXf(); cellStyleXf.borderId = 1; cellStyleXf.fillId = 1; cellStyleXf.fontId = 1; cellXfs = ctStylesheet.AddNewCellXfs(); cellXf = cellXfs.AddNewXf(); cellXf.xfId = (1); cellXf.borderId = (1); cellXf.fillId = (1); cellXf.fontId = (1); stylesTable.PutCellStyleXf(cellStyleXf); stylesTable.PutCellXf(cellXf); cellStyle = new XSSFCellStyle(1, 1, stylesTable, null); Assert.IsNotNull(stylesTable.GetFillAt(1).GetCTFill().patternFill); Assert.AreEqual(ST_PatternType.darkGray, stylesTable.GetFillAt(1).GetCTFill().patternFill.patternType); } [Test] public void TestGetSetBorderBottom() { //default values Assert.AreEqual(BorderStyle.None, cellStyle.BorderBottom); int num = stylesTable.GetBorders().Count; cellStyle.BorderBottom = (BorderStyle.Medium); Assert.AreEqual(BorderStyle.Medium, cellStyle.BorderBottom); //a new border has been Added Assert.AreEqual(num + 1, stylesTable.GetBorders().Count); //id of the Created border int borderId = (int)cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); //check Changes in the underlying xml bean CT_Border ctBorder = stylesTable.GetBorderAt(borderId).GetCTBorder(); Assert.AreEqual(ST_BorderStyle.medium, ctBorder.bottom.style); num = stylesTable.GetBorders().Count; //setting the same border multiple times should not change borderId for (int i = 0; i < 3; i++) { cellStyle.BorderBottom = (BorderStyle.Medium); Assert.AreEqual(BorderStyle.Medium, cellStyle.BorderBottom); } Assert.AreEqual((uint)borderId, cellStyle.GetCoreXf().borderId); Assert.AreEqual(num, stylesTable.GetBorders().Count); Assert.AreSame(ctBorder, stylesTable.GetBorderAt(borderId).GetCTBorder()); //setting border to none Removes the <bottom> element cellStyle.BorderBottom = (BorderStyle.None); Assert.AreEqual(num, stylesTable.GetBorders().Count); borderId = (int)cellStyle.GetCoreXf().borderId; ctBorder = stylesTable.GetBorderAt(borderId).GetCTBorder(); Assert.IsFalse(ctBorder.IsSetBottom()); } [Test] public void TestSetServeralBordersOnSameCell() { Assert.AreEqual(BorderStyle.None, cellStyle.BorderRight); Assert.AreEqual(BorderStyle.None, cellStyle.BorderLeft); Assert.AreEqual(BorderStyle.None, cellStyle.BorderTop); Assert.AreEqual(BorderStyle.None, cellStyle.BorderBottom); Assert.AreEqual(2, stylesTable.GetBorders().Count); cellStyle.BorderBottom = BorderStyle.Thin; cellStyle.BottomBorderColor = HSSFColor.Black.Index; cellStyle.BorderLeft = BorderStyle.DashDotDot; cellStyle.LeftBorderColor = HSSFColor.Green.Index; cellStyle.BorderRight = BorderStyle.Hair; cellStyle.RightBorderColor = HSSFColor.Blue.Index; cellStyle.BorderTop = BorderStyle.MediumDashed; cellStyle.TopBorderColor = HSSFColor.Orange.Index; //only one border style should be generated Assert.AreEqual(3, stylesTable.GetBorders().Count); } [Test] public void TestGetSetBorderDiagonal() { Assert.AreEqual(BorderDiagonal.None, cellStyle.BorderDiagonal); int num = stylesTable.GetBorders().Count; cellStyle.BorderDiagonalLineStyle = BorderStyle.Medium; cellStyle.BorderDiagonalColor = HSSFColor.Red.Index; cellStyle.BorderDiagonal = BorderDiagonal.Backward; Assert.AreEqual(BorderStyle.Medium, cellStyle.BorderDiagonalLineStyle); //a new border has been added Assert.AreEqual(num + 1, stylesTable.GetBorders().Count); //id of the created border uint borderId = cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); CT_Border ctBorder = stylesTable.GetBorderAt((int)borderId).GetCTBorder(); Assert.AreEqual(ST_BorderStyle.medium, ctBorder.diagonal.style); num = stylesTable.GetBorders().Count; //setting the same border multiple times should not change borderId for (int i = 0; i < 3; i++) { cellStyle.BorderDiagonal = BorderDiagonal.Backward; Assert.AreEqual(BorderDiagonal.Backward, cellStyle.BorderDiagonal); } Assert.AreEqual(borderId, cellStyle.GetCoreXf().borderId); Assert.AreEqual(num, stylesTable.GetBorders().Count); Assert.AreSame(ctBorder, stylesTable.GetBorderAt((int)borderId).GetCTBorder()); cellStyle.BorderDiagonal = (BorderDiagonal.None); Assert.AreEqual(num, stylesTable.GetBorders().Count); borderId = cellStyle.GetCoreXf().borderId; ctBorder = stylesTable.GetBorderAt((int)borderId).GetCTBorder(); Assert.IsFalse(ctBorder.IsSetDiagonal()); } [Test] public void TestGetSetBorderRight() { //default values Assert.AreEqual(BorderStyle.None, cellStyle.BorderRight); int num = stylesTable.GetBorders().Count; cellStyle.BorderRight = (BorderStyle.Medium); Assert.AreEqual(BorderStyle.Medium, cellStyle.BorderRight); //a new border has been Added Assert.AreEqual(num + 1, stylesTable.GetBorders().Count); //id of the Created border uint borderId = cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); //check Changes in the underlying xml bean CT_Border ctBorder = stylesTable.GetBorderAt((int)borderId).GetCTBorder(); Assert.AreEqual(ST_BorderStyle.medium, ctBorder.right.style); num = stylesTable.GetBorders().Count; //setting the same border multiple times should not change borderId for (int i = 0; i < 3; i++) { cellStyle.BorderRight = (BorderStyle.Medium); Assert.AreEqual(BorderStyle.Medium, cellStyle.BorderRight); } Assert.AreEqual(borderId, cellStyle.GetCoreXf().borderId); Assert.AreEqual(num, stylesTable.GetBorders().Count); Assert.AreSame(ctBorder, stylesTable.GetBorderAt((int)borderId).GetCTBorder()); //setting border to none Removes the <right> element cellStyle.BorderRight = (BorderStyle.None); Assert.AreEqual(num, stylesTable.GetBorders().Count); borderId = cellStyle.GetCoreXf().borderId; ctBorder = stylesTable.GetBorderAt((int)borderId).GetCTBorder(); Assert.IsFalse(ctBorder.IsSetRight()); } [Test] public void TestGetSetBorderLeft() { //default values Assert.AreEqual(BorderStyle.None, cellStyle.BorderLeft); int num = stylesTable.GetBorders().Count; cellStyle.BorderLeft = (BorderStyle.Medium); Assert.AreEqual(BorderStyle.Medium, cellStyle.BorderLeft); //a new border has been Added Assert.AreEqual(num + 1, stylesTable.GetBorders().Count); //id of the Created border uint borderId = cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); //check Changes in the underlying xml bean CT_Border ctBorder = stylesTable.GetBorderAt((int)borderId).GetCTBorder(); Assert.AreEqual(ST_BorderStyle.medium, ctBorder.left.style); num = stylesTable.GetBorders().Count; //setting the same border multiple times should not change borderId for (int i = 0; i < 3; i++) { cellStyle.BorderLeft = (BorderStyle.Medium); Assert.AreEqual(BorderStyle.Medium, cellStyle.BorderLeft); } Assert.AreEqual(borderId, cellStyle.GetCoreXf().borderId); Assert.AreEqual(num, stylesTable.GetBorders().Count); Assert.AreSame(ctBorder, stylesTable.GetBorderAt((int)borderId).GetCTBorder()); //setting border to none Removes the <left> element cellStyle.BorderLeft = (BorderStyle.None); Assert.AreEqual(num, stylesTable.GetBorders().Count); borderId = cellStyle.GetCoreXf().borderId; ctBorder = stylesTable.GetBorderAt((int)borderId).GetCTBorder(); Assert.IsFalse(ctBorder.IsSetLeft()); } [Test] public void TestGetSetBorderTop() { //default values Assert.AreEqual(BorderStyle.None, cellStyle.BorderTop); int num = stylesTable.GetBorders().Count; cellStyle.BorderTop = BorderStyle.Medium; Assert.AreEqual(BorderStyle.Medium, cellStyle.BorderTop); //a new border has been Added Assert.AreEqual(num + 1, stylesTable.GetBorders().Count); //id of the Created border uint borderId = cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); //check Changes in the underlying xml bean CT_Border ctBorder = stylesTable.GetBorderAt((int)borderId).GetCTBorder(); Assert.AreEqual(ST_BorderStyle.medium, ctBorder.top.style); num = stylesTable.GetBorders().Count; //setting the same border multiple times should not change borderId for (int i = 0; i < 3; i++) { cellStyle.BorderTop = BorderStyle.Medium; Assert.AreEqual(BorderStyle.Medium, cellStyle.BorderTop); } Assert.AreEqual((uint)borderId, cellStyle.GetCoreXf().borderId); Assert.AreEqual(num, stylesTable.GetBorders().Count); Assert.AreSame(ctBorder, stylesTable.GetBorderAt((int)borderId).GetCTBorder()); //setting border to none Removes the <top> element cellStyle.BorderTop = BorderStyle.None; Assert.AreEqual(num, stylesTable.GetBorders().Count); borderId = cellStyle.GetCoreXf().borderId; ctBorder = stylesTable.GetBorderAt((int)borderId).GetCTBorder(); Assert.IsFalse(ctBorder.IsSetTop()); } [Test] public void TestGetSetBorderThin() { cellStyle.BorderTop = (BorderStyle.Thin); Assert.AreEqual(BorderStyle.Thin, cellStyle.BorderTop); int borderId = (int)cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); //check changes in the underlying xml bean CT_Border ctBorder = stylesTable.GetBorderAt(borderId).GetCTBorder(); Assert.AreEqual(ST_BorderStyle.thin, ctBorder.top.style); } [Test] public void TestGetSetBorderMedium() { cellStyle.BorderTop = (BorderStyle.Medium); Assert.AreEqual(BorderStyle.Medium, cellStyle.BorderTop); int borderId = (int)cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); //check changes in the underlying xml bean CT_Border ctBorder = stylesTable.GetBorderAt(borderId).GetCTBorder(); Assert.AreEqual(ST_BorderStyle.medium, ctBorder.top.style); } [Test] public void TestGetSetBorderThick() { cellStyle.BorderTop = (BorderStyle.Thick); Assert.AreEqual(BorderStyle.Thick, cellStyle.BorderTop); int borderId = (int)cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); //check changes in the underlying xml bean CT_Border ctBorder = stylesTable.GetBorderAt(borderId).GetCTBorder(); Assert.AreEqual(ST_BorderStyle.thick, ctBorder.top.style); } [Test] public void TestGetSetBorderHair() { cellStyle.BorderTop = (BorderStyle.Hair); Assert.AreEqual(BorderStyle.Hair, cellStyle.BorderTop); int borderId = (int)cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); //check changes in the underlying xml bean CT_Border ctBorder = stylesTable.GetBorderAt(borderId).GetCTBorder(); Assert.AreEqual(ST_BorderStyle.hair, ctBorder.top.style); } [Test] public void TestGetSetBorderDotted() { cellStyle.BorderTop = (BorderStyle.Dotted); Assert.AreEqual(BorderStyle.Dotted, cellStyle.BorderTop); int borderId = (int)cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); //check changes in the underlying xml bean CT_Border ctBorder = stylesTable.GetBorderAt(borderId).GetCTBorder(); Assert.AreEqual(ST_BorderStyle.dotted, ctBorder.top.style); } [Test] public void TestGetSetBorderDashed() { cellStyle.BorderTop = (BorderStyle.Dashed); Assert.AreEqual(BorderStyle.Dashed, cellStyle.BorderTop); int borderId = (int)cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); //check changes in the underlying xml bean CT_Border ctBorder = stylesTable.GetBorderAt(borderId).GetCTBorder(); Assert.AreEqual(ST_BorderStyle.dashed, ctBorder.top.style); } [Test] public void TestGetSetBorderDashDot() { cellStyle.BorderTop = (BorderStyle.DashDot); Assert.AreEqual(BorderStyle.DashDot, cellStyle.BorderTop); int borderId = (int)cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); //check changes in the underlying xml bean CT_Border ctBorder = stylesTable.GetBorderAt(borderId).GetCTBorder(); Assert.AreEqual(ST_BorderStyle.dashDot, ctBorder.top.style); } [Test] public void TestGetSetBorderDashDotDot() { cellStyle.BorderTop=(BorderStyle.DashDotDot); Assert.AreEqual(BorderStyle.DashDotDot, cellStyle.BorderTop); int borderId = (int)cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); //check changes in the underlying xml bean CT_Border ctBorder = stylesTable.GetBorderAt(borderId).GetCTBorder(); Assert.AreEqual(ST_BorderStyle.dashDotDot, ctBorder.top.style); } [Test] public void TestGetSetBorderMediumDashDot() { cellStyle.BorderTop = (BorderStyle.MediumDashDot); Assert.AreEqual(BorderStyle.MediumDashDot, cellStyle.BorderTop); int borderId = (int)cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); //check changes in the underlying xml bean CT_Border ctBorder = stylesTable.GetBorderAt(borderId).GetCTBorder(); Assert.AreEqual(ST_BorderStyle.mediumDashDot, ctBorder.top.style); } [Test] public void TestGetSetBorderMediumDashDotDot() { cellStyle.BorderTop = (BorderStyle.MediumDashDotDot); Assert.AreEqual(BorderStyle.MediumDashDotDot, cellStyle.BorderTop); int borderId = (int)cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); //check changes in the underlying xml bean CT_Border ctBorder = stylesTable.GetBorderAt(borderId).GetCTBorder(); Assert.AreEqual(ST_BorderStyle.mediumDashDotDot, ctBorder.top.style); } [Test] public void TestGetSetBorderMediumDashed() { cellStyle.BorderTop=(BorderStyle.MediumDashed); Assert.AreEqual(BorderStyle.MediumDashed, cellStyle.BorderTop); int borderId = (int)cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); //check changes in the underlying xml bean CT_Border ctBorder = stylesTable.GetBorderAt(borderId).GetCTBorder(); Assert.AreEqual(ST_BorderStyle.mediumDashed, ctBorder.top.style); } [Test] public void TestGetSetBorderSlantDashDot() { cellStyle.BorderTop = (BorderStyle.SlantedDashDot); Assert.AreEqual(BorderStyle.SlantedDashDot, cellStyle.BorderTop); int borderId = (int)cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); //check changes in the underlying xml bean CT_Border ctBorder = stylesTable.GetBorderAt(borderId).GetCTBorder(); Assert.AreEqual(ST_BorderStyle.slantDashDot, ctBorder.top.style); } [Test] public void TestGetSetBorderDouble() { cellStyle.BorderTop=(BorderStyle.Double); Assert.AreEqual(BorderStyle.Double, cellStyle.BorderTop); int borderId = (int)cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); //check changes in the underlying xml bean CT_Border ctBorder = stylesTable.GetBorderAt(borderId).GetCTBorder(); Assert.AreEqual(ST_BorderStyle.@double, ctBorder.top.style); } [Test] public void TestGetSetBottomBorderColor() { //defaults Assert.AreEqual(IndexedColors.Black.Index, cellStyle.BottomBorderColor); Assert.IsNull(cellStyle.BottomBorderXSSFColor); int num = stylesTable.GetBorders().Count; XSSFColor clr; //setting indexed color cellStyle.BottomBorderColor = (IndexedColors.BlueGrey.Index); Assert.AreEqual(IndexedColors.BlueGrey.Index, cellStyle.BottomBorderColor); clr = cellStyle.BottomBorderXSSFColor; Assert.IsTrue(clr.GetCTColor().IsSetIndexed()); Assert.AreEqual(IndexedColors.BlueGrey.Index, clr.Indexed); //a new border was Added to the styles table Assert.AreEqual(num + 1, stylesTable.GetBorders().Count); //id of the Created border uint borderId = cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); //check Changes in the underlying xml bean CT_Border ctBorder = stylesTable.GetBorderAt((int)borderId).GetCTBorder(); Assert.AreEqual((uint)IndexedColors.BlueGrey.Index, ctBorder.bottom.color.indexed); //setting XSSFColor num = stylesTable.GetBorders().Count; clr = new XSSFColor(Color.Cyan); cellStyle.SetBottomBorderColor(clr); Assert.AreEqual(clr.GetCTColor().ToString(), cellStyle.BottomBorderXSSFColor.GetCTColor().ToString()); byte[] rgb = cellStyle.BottomBorderXSSFColor.GetRgb(); Assert.AreEqual(Color.Cyan.ToArgb(), Color.FromArgb(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF).ToArgb()); //another border was Added to the styles table Assert.AreEqual(num, stylesTable.GetBorders().Count); //passing null unsets the color cellStyle.SetBottomBorderColor(null); Assert.IsNull(cellStyle.BottomBorderXSSFColor); } [Test] public void TestGetSetTopBorderColor() { //defaults Assert.AreEqual(IndexedColors.Black.Index, cellStyle.TopBorderColor); Assert.IsNull(cellStyle.TopBorderXSSFColor); int num = stylesTable.GetBorders().Count; XSSFColor clr; //setting indexed color cellStyle.TopBorderColor = (IndexedColors.BlueGrey.Index); Assert.AreEqual(IndexedColors.BlueGrey.Index, cellStyle.TopBorderColor); clr = cellStyle.TopBorderXSSFColor; Assert.IsTrue(clr.GetCTColor().IsSetIndexed()); Assert.AreEqual(IndexedColors.BlueGrey.Index, clr.Indexed); //a new border was added to the styles table Assert.AreEqual(num + 1, stylesTable.GetBorders().Count); //id of the Created border int borderId = (int)cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); //check Changes in the underlying xml bean CT_Border ctBorder = stylesTable.GetBorderAt(borderId).GetCTBorder(); Assert.AreEqual((uint)IndexedColors.BlueGrey.Index, ctBorder.top.color.indexed); //setting XSSFColor num = stylesTable.GetBorders().Count; clr = new XSSFColor(Color.Cyan); cellStyle.SetTopBorderColor(clr); Assert.AreEqual(clr.GetCTColor().ToString(), cellStyle.TopBorderXSSFColor.GetCTColor().ToString()); byte[] rgb = cellStyle.TopBorderXSSFColor.GetRgb(); Assert.AreEqual(Color.Cyan.ToArgb(), Color.FromArgb(rgb[0], rgb[1], rgb[2]).ToArgb()); //another border was added to the styles table Assert.AreEqual(num, stylesTable.GetBorders().Count); //passing null unsets the color cellStyle.SetTopBorderColor(null); Assert.IsNull(cellStyle.TopBorderXSSFColor); } [Test] public void TestGetSetLeftBorderColor() { //defaults Assert.AreEqual(IndexedColors.Black.Index, cellStyle.LeftBorderColor); Assert.IsNull(cellStyle.LeftBorderXSSFColor); int num = stylesTable.GetBorders().Count; XSSFColor clr; //setting indexed color cellStyle.LeftBorderColor = (IndexedColors.BlueGrey.Index); Assert.AreEqual(IndexedColors.BlueGrey.Index, cellStyle.LeftBorderColor); clr = cellStyle.LeftBorderXSSFColor; Assert.IsTrue(clr.GetCTColor().IsSetIndexed()); Assert.AreEqual(IndexedColors.BlueGrey.Index, clr.Indexed); //a new border was Added to the styles table Assert.AreEqual(num + 1, stylesTable.GetBorders().Count); //id of the Created border int borderId = (int)cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); //check Changes in the underlying xml bean CT_Border ctBorder = stylesTable.GetBorderAt(borderId).GetCTBorder(); Assert.AreEqual((uint)IndexedColors.BlueGrey.Index, ctBorder.left.color.indexed); //setting XSSFColor num = stylesTable.GetBorders().Count; clr = new XSSFColor(Color.Cyan); cellStyle.SetLeftBorderColor(clr); Assert.AreEqual(clr.GetCTColor().ToString(), cellStyle.LeftBorderXSSFColor.GetCTColor().ToString()); byte[] rgb = cellStyle.LeftBorderXSSFColor.GetRgb(); Assert.AreEqual(Color.Cyan.ToArgb(), Color.FromArgb(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF).ToArgb()); //another border was Added to the styles table Assert.AreEqual(num, stylesTable.GetBorders().Count); //passing null unsets the color cellStyle.SetLeftBorderColor(null); Assert.IsNull(cellStyle.LeftBorderXSSFColor); } [Test] public void TestGetSetRightBorderColor() { //defaults Assert.AreEqual(IndexedColors.Black.Index, cellStyle.RightBorderColor); Assert.IsNull(cellStyle.RightBorderXSSFColor); int num = stylesTable.GetBorders().Count; XSSFColor clr; //setting indexed color cellStyle.RightBorderColor = (IndexedColors.BlueGrey.Index); Assert.AreEqual(IndexedColors.BlueGrey.Index, cellStyle.RightBorderColor); clr = cellStyle.RightBorderXSSFColor; Assert.IsTrue(clr.GetCTColor().IsSetIndexed()); Assert.AreEqual(IndexedColors.BlueGrey.Index, clr.Indexed); //a new border was Added to the styles table Assert.AreEqual(num + 1, stylesTable.GetBorders().Count); //id of the Created border int borderId = (int)cellStyle.GetCoreXf().borderId; Assert.IsTrue(borderId > 0); //check Changes in the underlying xml bean CT_Border ctBorder = stylesTable.GetBorderAt(borderId).GetCTBorder(); Assert.AreEqual((uint)IndexedColors.BlueGrey.Index, ctBorder.right.color.indexed); //setting XSSFColor num = stylesTable.GetBorders().Count; clr = new XSSFColor(Color.Cyan); cellStyle.SetRightBorderColor(clr); Assert.AreEqual(clr.GetCTColor().ToString(), cellStyle.RightBorderXSSFColor.GetCTColor().ToString()); byte[] rgb = cellStyle.RightBorderXSSFColor.GetRgb(); Assert.AreEqual(Color.Cyan.ToArgb(), Color.FromArgb(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF).ToArgb()); //another border was Added to the styles table Assert.AreEqual(num, stylesTable.GetBorders().Count); //passing null unsets the color cellStyle.SetRightBorderColor(null); Assert.IsNull(cellStyle.RightBorderXSSFColor); } [Test] public void TestGetSetFillBackgroundColor() { Assert.AreEqual(IndexedColors.Automatic.Index, cellStyle.FillBackgroundColor); Assert.IsNull(cellStyle.FillBackgroundColorColor); XSSFColor clr; int num = stylesTable.GetFills().Count; //setting indexed color cellStyle.FillBackgroundColor = (IndexedColors.Red.Index); Assert.AreEqual(IndexedColors.Red.Index, cellStyle.FillBackgroundColor); clr = (XSSFColor)cellStyle.FillBackgroundColorColor; Assert.IsTrue(clr.GetCTColor().IsSetIndexed()); Assert.AreEqual(IndexedColors.Red.Index, clr.Indexed); //a new fill was Added to the styles table Assert.AreEqual(num + 1, stylesTable.GetFills().Count); //id of the Created border int FillId = (int)cellStyle.GetCoreXf().fillId; Assert.IsTrue(FillId > 0); //check changes in the underlying xml bean CT_Fill ctFill = stylesTable.GetFillAt(FillId).GetCTFill(); Assert.AreEqual((uint)IndexedColors.Red.Index, ctFill.GetPatternFill().bgColor.indexed); //setting XSSFColor num = stylesTable.GetFills().Count; clr = new XSSFColor(Color.Cyan); cellStyle.SetFillBackgroundColor(clr); // TODO this testcase assumes that cellStyle creates a new CT_Fill, but the implementation changes the existing style. - do not know whats right 8-( Assert.AreEqual(clr.GetCTColor().ToString(), ((XSSFColor)cellStyle.FillBackgroundColorColor).GetCTColor().ToString()); byte[] rgb = ((XSSFColor)cellStyle.FillBackgroundColorColor).GetRgb(); Assert.AreEqual(Color.Cyan.ToArgb(), Color.FromArgb(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF).ToArgb()); //another border was added to the styles table Assert.AreEqual(num + 1, stylesTable.GetFills().Count); //passing null unsets the color cellStyle.SetFillBackgroundColor(null); Assert.IsNull(cellStyle.FillBackgroundColorColor); Assert.AreEqual(IndexedColors.Automatic.Index, cellStyle.FillBackgroundColor); } [Test] public void TestDefaultStyles() { XSSFWorkbook wb1 = new XSSFWorkbook(); XSSFCellStyle style1 = (XSSFCellStyle)wb1.CreateCellStyle(); Assert.AreEqual(IndexedColors.Automatic.Index, style1.FillBackgroundColor); Assert.IsNull(style1.FillBackgroundColorColor); Assert.IsNotNull(XSSFTestDataSamples.WriteOutAndReadBack(wb1)); //compatibility with HSSF HSSFWorkbook wb2 = new HSSFWorkbook(); HSSFCellStyle style2 = (HSSFCellStyle)wb2.CreateCellStyle(); Assert.AreEqual(style2.FillBackgroundColor, style1.FillBackgroundColor); Assert.AreEqual(style2.FillForegroundColor, style1.FillForegroundColor); Assert.AreEqual(style2.FillPattern, style1.FillPattern); Assert.AreEqual(style2.LeftBorderColor, style1.LeftBorderColor); Assert.AreEqual(style2.TopBorderColor, style1.TopBorderColor); Assert.AreEqual(style2.RightBorderColor, style1.RightBorderColor); Assert.AreEqual(style2.BottomBorderColor, style1.BottomBorderColor); Assert.AreEqual(style2.BorderBottom, style1.BorderBottom); Assert.AreEqual(style2.BorderLeft, style1.BorderLeft); Assert.AreEqual(style2.BorderRight, style1.BorderRight); Assert.AreEqual(style2.BorderTop, style1.BorderTop); wb2.Close(); } [Ignore] public void TestGetFillForegroundColor() { XSSFWorkbook wb = new XSSFWorkbook(); StylesTable styles = wb.GetStylesSource(); Assert.AreEqual(1, wb.NumCellStyles); Assert.AreEqual(2, styles.GetFills().Count); XSSFCellStyle defaultStyle = (XSSFCellStyle)wb.GetCellStyleAt((short)0); Assert.AreEqual(IndexedColors.Automatic.Index, defaultStyle.FillForegroundColor); Assert.AreEqual(null, defaultStyle.FillForegroundColorColor); Assert.AreEqual(FillPattern.NoFill, defaultStyle.FillPattern); XSSFCellStyle customStyle = (XSSFCellStyle)wb.CreateCellStyle(); customStyle.FillPattern = (FillPattern.SolidForeground); Assert.AreEqual(FillPattern.SolidForeground, customStyle.FillPattern); Assert.AreEqual(3, styles.GetFills().Count); customStyle.FillForegroundColor = (IndexedColors.BrightGreen.Index); Assert.AreEqual(IndexedColors.BrightGreen.Index, customStyle.FillForegroundColor); Assert.AreEqual(4, styles.GetFills().Count); for (int i = 0; i < 3; i++) { XSSFCellStyle style = (XSSFCellStyle)wb.CreateCellStyle(); style.FillPattern = (FillPattern.SolidForeground); Assert.AreEqual(FillPattern.SolidForeground, style.FillPattern); Assert.AreEqual(4, styles.GetFills().Count); style.FillForegroundColor = (IndexedColors.BrightGreen.Index); Assert.AreEqual(IndexedColors.BrightGreen.Index, style.FillForegroundColor); Assert.AreEqual(4, styles.GetFills().Count); } Assert.IsNotNull(XSSFTestDataSamples.WriteOutAndReadBack(wb)); } [Test] public void TestGetFillPattern() { //??? //assertEquals(STPatternType.INT_DARK_GRAY-1, cellStyle.getFillPattern()); Assert.AreEqual((int)ST_PatternType.darkGray, (int)cellStyle.FillPattern); int num = stylesTable.GetFills().Count; cellStyle.FillPattern = (FillPattern.SolidForeground); Assert.AreEqual(FillPattern.SolidForeground, cellStyle.FillPattern); Assert.AreEqual(num + 1, stylesTable.GetFills().Count); int FillId = (int)cellStyle.GetCoreXf().fillId; Assert.IsTrue(FillId > 0); //check Changes in the underlying xml bean CT_Fill ctFill = stylesTable.GetFillAt(FillId).GetCTFill(); Assert.AreEqual(ST_PatternType.solid, ctFill.GetPatternFill().patternType); //setting the same fill multiple time does not update the styles table for (int i = 0; i < 3; i++) { cellStyle.FillPattern = (FillPattern.SolidForeground); } Assert.AreEqual(num + 1, stylesTable.GetFills().Count); cellStyle.FillPattern = (FillPattern.NoFill); Assert.AreEqual(FillPattern.NoFill, cellStyle.FillPattern); FillId = (int)cellStyle.GetCoreXf().fillId; ctFill = stylesTable.GetFillAt(FillId).GetCTFill(); Assert.IsFalse(ctFill.GetPatternFill().IsSetPatternType()); } [Test] public void TestGetFont() { Assert.IsNotNull(cellStyle.GetFont()); } [Test] public void TestGetSetHidden() { Assert.IsFalse(cellStyle.IsHidden); cellStyle.IsHidden = (true); Assert.IsTrue(cellStyle.IsHidden); cellStyle.IsHidden = (false); Assert.IsFalse(cellStyle.IsHidden); } [Test] public void TestGetSetLocked() { Assert.IsTrue(cellStyle.IsLocked); cellStyle.IsLocked = (true); Assert.IsTrue(cellStyle.IsLocked); cellStyle.IsLocked = (false); Assert.IsFalse(cellStyle.IsLocked); } [Test] public void TestGetSetIndent() { Assert.AreEqual((short)0, cellStyle.Indention); cellStyle.Indention = ((short)3); Assert.AreEqual((short)3, cellStyle.Indention); cellStyle.Indention = ((short)13); Assert.AreEqual((short)13, cellStyle.Indention); } [Test] public void TestGetSetAlignement() { Assert.IsTrue(!cellStyle.GetCellAlignment().GetCTCellAlignment().horizontalSpecified); Assert.AreEqual(HorizontalAlignment.General, cellStyle.Alignment); cellStyle.Alignment = HorizontalAlignment.Left; Assert.AreEqual(HorizontalAlignment.Left, cellStyle.Alignment); Assert.AreEqual(ST_HorizontalAlignment.left, cellStyle.GetCellAlignment().GetCTCellAlignment().horizontal); cellStyle.Alignment = (HorizontalAlignment.Justify); Assert.AreEqual(HorizontalAlignment.Justify, cellStyle.Alignment); Assert.AreEqual(ST_HorizontalAlignment.justify, cellStyle.GetCellAlignment().GetCTCellAlignment().horizontal); cellStyle.Alignment = (HorizontalAlignment.Center); Assert.AreEqual(HorizontalAlignment.Center, cellStyle.Alignment); Assert.AreEqual(ST_HorizontalAlignment.center, cellStyle.GetCellAlignment().GetCTCellAlignment().horizontal); } [Test] public void TestGetSetVerticalAlignment() { Assert.AreEqual(VerticalAlignment.Bottom, cellStyle.VerticalAlignment); Assert.IsTrue(!cellStyle.GetCellAlignment().GetCTCellAlignment().verticalSpecified); cellStyle.VerticalAlignment = (VerticalAlignment.Top); Assert.AreEqual(VerticalAlignment.Top, cellStyle.VerticalAlignment); Assert.AreEqual(ST_VerticalAlignment.top, cellStyle.GetCellAlignment().GetCTCellAlignment().vertical); cellStyle.VerticalAlignment = (VerticalAlignment.Center); Assert.AreEqual(VerticalAlignment.Center, cellStyle.VerticalAlignment); Assert.AreEqual(ST_VerticalAlignment.center, cellStyle.GetCellAlignment().GetCTCellAlignment().vertical); cellStyle.VerticalAlignment = VerticalAlignment.Justify; Assert.AreEqual(VerticalAlignment.Justify, cellStyle.VerticalAlignment); Assert.AreEqual(ST_VerticalAlignment.justify, cellStyle.GetCellAlignment().GetCTCellAlignment().vertical); cellStyle.VerticalAlignment = (VerticalAlignment.Bottom); Assert.AreEqual(VerticalAlignment.Bottom, cellStyle.VerticalAlignment); Assert.AreEqual(ST_VerticalAlignment.bottom, cellStyle.GetCellAlignment().GetCTCellAlignment().vertical); } [Test] public void TestGetSetWrapText() { Assert.IsFalse(cellStyle.WrapText); cellStyle.WrapText = (true); Assert.IsTrue(cellStyle.WrapText); cellStyle.WrapText = (false); Assert.IsFalse(cellStyle.WrapText); } /** * Cloning one XSSFCellStyle onto Another, same XSSFWorkbook */ [Test] public void TestCloneStyleSameWB() { XSSFWorkbook wb = new XSSFWorkbook(); Assert.AreEqual(1, wb.NumberOfFonts); XSSFFont fnt = (XSSFFont)wb.CreateFont(); fnt.FontName = ("TestingFont"); Assert.AreEqual(2, wb.NumberOfFonts); XSSFCellStyle orig = (XSSFCellStyle)wb.CreateCellStyle(); orig.Alignment = (HorizontalAlignment.Right); orig.SetFont(fnt); orig.DataFormat = (short)18; Assert.AreEqual(HorizontalAlignment.Right, orig.Alignment); Assert.AreEqual(fnt, orig.GetFont()); Assert.AreEqual(18, orig.DataFormat); XSSFCellStyle clone = (XSSFCellStyle)wb.CreateCellStyle(); Assert.AreNotEqual(HorizontalAlignment.Right, clone.Alignment); Assert.AreNotEqual(fnt, clone.GetFont()); Assert.AreNotEqual(18, clone.DataFormat); clone.CloneStyleFrom(orig); Assert.AreEqual(HorizontalAlignment.Right, clone.Alignment); Assert.AreEqual(fnt, clone.GetFont()); Assert.AreEqual(18, clone.DataFormat); Assert.AreEqual(2, wb.NumberOfFonts); clone.Alignment = HorizontalAlignment.Left; clone.DataFormat = 17; Assert.AreEqual(HorizontalAlignment.Right, orig.Alignment); Assert.AreEqual(18, orig.DataFormat); Assert.IsNotNull(XSSFTestDataSamples.WriteOutAndReadBack(wb)); } /** * Cloning one XSSFCellStyle onto Another, different XSSFWorkbooks */ [Test] public void TestCloneStyleDiffWB() { XSSFWorkbook wbOrig = new XSSFWorkbook(); Assert.AreEqual(1, wbOrig.NumberOfFonts); Assert.AreEqual(0, wbOrig.GetStylesSource().GetNumberFormats().Count); XSSFFont fnt = (XSSFFont)wbOrig.CreateFont(); fnt.FontName = ("TestingFont"); Assert.AreEqual(2, wbOrig.NumberOfFonts); Assert.AreEqual(0, wbOrig.GetStylesSource().GetNumberFormats().Count); XSSFDataFormat fmt = (XSSFDataFormat)wbOrig.CreateDataFormat(); fmt.GetFormat("MadeUpOne"); fmt.GetFormat("MadeUpTwo"); XSSFCellStyle orig = (XSSFCellStyle)wbOrig.CreateCellStyle(); orig.Alignment = (HorizontalAlignment.Right); orig.SetFont(fnt); orig.DataFormat = (fmt.GetFormat("Test##")); Assert.IsTrue(HorizontalAlignment.Right == orig.Alignment); Assert.IsTrue(fnt == orig.GetFont()); Assert.IsTrue(fmt.GetFormat("Test##") == orig.DataFormat); Assert.AreEqual(2, wbOrig.NumberOfFonts); Assert.AreEqual(3, wbOrig.GetStylesSource().GetNumberFormats().Count); // Now a style on another workbook XSSFWorkbook wbClone = new XSSFWorkbook(); Assert.AreEqual(1, wbClone.NumberOfFonts); Assert.AreEqual(0, wbClone.GetStylesSource().GetNumberFormats().Count); Assert.AreEqual(1, wbClone.NumCellStyles); XSSFDataFormat fmtClone = (XSSFDataFormat)wbClone.CreateDataFormat(); XSSFCellStyle clone = (XSSFCellStyle)wbClone.CreateCellStyle(); Assert.AreEqual(1, wbClone.NumberOfFonts); Assert.AreEqual(0, wbClone.GetStylesSource().GetNumberFormats().Count); Assert.IsFalse(HorizontalAlignment.Right == clone.Alignment); Assert.IsFalse("TestingFont" == clone.GetFont().FontName); clone.CloneStyleFrom(orig); Assert.AreEqual(2, wbClone.NumberOfFonts); Assert.AreEqual(2, wbClone.NumCellStyles); Assert.AreEqual(1, wbClone.GetStylesSource().GetNumberFormats().Count); Assert.AreEqual(HorizontalAlignment.Right, clone.Alignment); Assert.AreEqual("TestingFont", clone.GetFont().FontName); Assert.AreEqual(fmtClone.GetFormat("Test##"), clone.DataFormat); Assert.IsFalse(fmtClone.GetFormat("Test##") == fmt.GetFormat("Test##")); // Save it and re-check XSSFWorkbook wbReload = (XSSFWorkbook)XSSFTestDataSamples.WriteOutAndReadBack(wbClone); Assert.AreEqual(2, wbReload.NumberOfFonts); Assert.AreEqual(2, wbReload.NumCellStyles); Assert.AreEqual(1, wbReload.GetStylesSource().GetNumberFormats().Count); XSSFCellStyle reload = (XSSFCellStyle)wbReload.GetCellStyleAt((short)1); Assert.AreEqual(HorizontalAlignment.Right, reload.Alignment); Assert.AreEqual("TestingFont", reload.GetFont().FontName); Assert.AreEqual(fmtClone.GetFormat("Test##"), reload.DataFormat); Assert.IsFalse(fmtClone.GetFormat("Test##") == fmt.GetFormat("Test##")); Assert.IsNotNull(XSSFTestDataSamples.WriteOutAndReadBack(wbOrig)); Assert.IsNotNull(XSSFTestDataSamples.WriteOutAndReadBack(wbClone)); } /** * Avoid ArrayIndexOutOfBoundsException when creating cell style * in a workbook that has an empty xf table. */ [Test] public void TestBug52348() { XSSFWorkbook workbook = XSSFTestDataSamples.OpenSampleWorkbook("52348.xlsx"); StylesTable st = workbook.GetStylesSource(); Assert.AreEqual(0, st.StyleXfsSize); XSSFCellStyle style = workbook.CreateCellStyle() as XSSFCellStyle; // no exception at this point Assert.IsNull(style.GetStyleXf()); Assert.IsNotNull(XSSFTestDataSamples.WriteOutAndReadBack(workbook)); } /** * Avoid ArrayIndexOutOfBoundsException when getting cell style * in a workbook that has an empty xf table. */ [Test] public void TestBug55650() { XSSFWorkbook workbook = XSSFTestDataSamples.OpenSampleWorkbook("52348.xlsx"); StylesTable st = workbook.GetStylesSource(); Assert.AreEqual(0, st.StyleXfsSize); // no exception at this point XSSFCellStyle style = workbook.GetSheetAt(0).GetRow(0).GetCell(0).CellStyle as XSSFCellStyle; Assert.IsNull(style.GetStyleXf()); Assert.IsNotNull(XSSFTestDataSamples.WriteOutAndReadBack(workbook)); } [Test] public void TestShrinkToFit() { // Existing file XSSFWorkbook wb = XSSFTestDataSamples.OpenSampleWorkbook("ShrinkToFit.xlsx"); ISheet s = wb.GetSheetAt(0); IRow r = s.GetRow(0); ICellStyle cs = r.GetCell(0).CellStyle; Assert.AreEqual(true, cs.ShrinkToFit); // New file XSSFWorkbook wbOrig = new XSSFWorkbook(); s = wbOrig.CreateSheet(); r = s.CreateRow(0); cs = wbOrig.CreateCellStyle(); cs.ShrinkToFit = (/*setter*/false); r.CreateCell(0).CellStyle = (/*setter*/cs); cs = wbOrig.CreateCellStyle(); cs.ShrinkToFit = (/*setter*/true); r.CreateCell(1).CellStyle = (/*setter*/cs); // Write out1, Read, and check wb = XSSFTestDataSamples.WriteOutAndReadBack(wbOrig) as XSSFWorkbook; s = wb.GetSheetAt(0); r = s.GetRow(0); Assert.AreEqual(false, r.GetCell(0).CellStyle.ShrinkToFit); Assert.AreEqual(true, r.GetCell(1).CellStyle.ShrinkToFit); Assert.IsNotNull(XSSFTestDataSamples.WriteOutAndReadBack(wb)); Assert.IsNotNull(XSSFTestDataSamples.WriteOutAndReadBack(wbOrig)); } [Test] public void TestSetColor() { IWorkbook wb = new XSSFWorkbook(); ISheet sheet = wb.CreateSheet(); IRow row = sheet.CreateRow(0); //CreationHelper ch = wb.GetCreationHelper(); IDataFormat format = wb.CreateDataFormat(); ICell cell = row.CreateCell(1); cell.SetCellValue("somEvalue"); ICellStyle cellStyle = wb.CreateCellStyle(); cellStyle.DataFormat = (/*setter*/format.GetFormat("###0")); cellStyle.FillBackgroundColor = (/*setter*/IndexedColors.DarkBlue.Index); cellStyle.FillForegroundColor = (/*setter*/IndexedColors.DarkBlue.Index); cellStyle.FillPattern = FillPattern.SolidForeground; cellStyle.Alignment = HorizontalAlignment.Right; cellStyle.VerticalAlignment = VerticalAlignment.Top; cell.CellStyle = (/*setter*/cellStyle); /*OutputStream stream = new FileOutputStream("C:\\temp\\CellColor.xlsx"); try { wb.Write(stream); } finally { stream.Close(); }*/ IWorkbook wbBack = XSSFTestDataSamples.WriteOutAndReadBack(wb); ICell cellBack = wbBack.GetSheetAt(0).GetRow(0).GetCell(1); Assert.IsNotNull(cellBack); ICellStyle styleBack = cellBack.CellStyle; Assert.AreEqual(IndexedColors.DarkBlue.Index, styleBack.FillBackgroundColor); Assert.AreEqual(IndexedColors.DarkBlue.Index, styleBack.FillForegroundColor); Assert.AreEqual(HorizontalAlignment.Right, styleBack.Alignment); Assert.AreEqual(VerticalAlignment.Top, styleBack.VerticalAlignment); Assert.AreEqual(FillPattern.SolidForeground, styleBack.FillPattern); wbBack.Close(); wb.Close(); } } }
// 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.Net.Sockets; using System.Net.Test.Common; using Xunit; namespace System.Net.NameResolution.PalTests { public class NameResolutionPalTests { static NameResolutionPalTests() { NameResolutionPal.EnsureSocketsAreInitialized(); } [Fact] public void HostName_NotNull() { Assert.NotNull(NameResolutionPal.GetHostName()); } [Fact] public void GetHostByName_LocalHost() { IPHostEntry hostEntry = NameResolutionPal.GetHostByName("localhost"); Assert.NotNull(hostEntry); Assert.NotNull(hostEntry.HostName); Assert.NotNull(hostEntry.AddressList); Assert.NotNull(hostEntry.Aliases); } [Fact] public void GetHostByName_HostName() { string hostName = NameResolutionPal.GetHostName(); Assert.NotNull(hostName); IPHostEntry hostEntry = NameResolutionPal.GetHostByName(hostName); Assert.NotNull(hostEntry); Assert.NotNull(hostEntry.HostName); Assert.NotNull(hostEntry.AddressList); Assert.NotNull(hostEntry.Aliases); } [Fact] public void GetHostByAddr_LocalHost() { Assert.NotNull(NameResolutionPal.GetHostByAddr(new IPAddress(0x0100007f))); } [Fact] public void GetHostByName_LocalHost_GetHostByAddr() { IPHostEntry hostEntry1 = NameResolutionPal.GetHostByName("localhost"); Assert.NotNull(hostEntry1); IPHostEntry hostEntry2 = NameResolutionPal.GetHostByAddr(hostEntry1.AddressList[0]); Assert.NotNull(hostEntry2); IPAddress[] list1 = hostEntry1.AddressList; IPAddress[] list2 = hostEntry2.AddressList; for (int i = 0; i < list1.Length; i++) { Assert.NotEqual(-1, Array.IndexOf(list2, list1[i])); } } [Fact] public void GetHostByName_HostName_GetHostByAddr() { IPHostEntry hostEntry1 = NameResolutionPal.GetHostByName(TestSettings.Http.Http2Host); Assert.NotNull(hostEntry1); IPAddress[] list1 = hostEntry1.AddressList; Assert.InRange(list1.Length, 1, Int32.MaxValue); foreach (IPAddress addr1 in list1) { IPHostEntry hostEntry2 = NameResolutionPal.GetHostByAddr(addr1); Assert.NotNull(hostEntry2); IPAddress[] list2 = hostEntry2.AddressList; Assert.InRange(list2.Length, 1, list1.Length); foreach (IPAddress addr2 in list2) { Assert.NotEqual(-1, Array.IndexOf(list1, addr2)); } } } [Fact] public void TryGetAddrInfo_LocalHost() { IPHostEntry hostEntry; int nativeErrorCode; SocketError error = NameResolutionPal.TryGetAddrInfo("localhost", out hostEntry, out nativeErrorCode); Assert.Equal(SocketError.Success, error); Assert.NotNull(hostEntry); Assert.NotNull(hostEntry.HostName); Assert.NotNull(hostEntry.AddressList); Assert.NotNull(hostEntry.Aliases); } [Fact] public void TryGetAddrInfo_HostName() { string hostName = NameResolutionPal.GetHostName(); Assert.NotNull(hostName); IPHostEntry hostEntry; int nativeErrorCode; SocketError error = NameResolutionPal.TryGetAddrInfo(hostName, out hostEntry, out nativeErrorCode); Assert.Equal(SocketError.Success, error); Assert.NotNull(hostEntry); Assert.NotNull(hostEntry.HostName); Assert.NotNull(hostEntry.AddressList); Assert.NotNull(hostEntry.Aliases); } [Fact] public void TryGetNameInfo_LocalHost_IPv4() { SocketError error; int nativeErrorCode; string name = NameResolutionPal.TryGetNameInfo(new IPAddress(new byte[] { 127, 0, 0, 1 }), out error, out nativeErrorCode); Assert.Equal(SocketError.Success, error); Assert.NotNull(name); } [Fact] public void TryGetNameInfo_LocalHost_IPv6() { SocketError error; int nativeErrorCode; string name = NameResolutionPal.TryGetNameInfo(new IPAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }), out error, out nativeErrorCode); Assert.Equal(SocketError.Success, error); Assert.NotNull(name); } [Fact] public void TryGetAddrInfo_LocalHost_TryGetNameInfo() { IPHostEntry hostEntry; int nativeErrorCode; SocketError error = NameResolutionPal.TryGetAddrInfo("localhost", out hostEntry, out nativeErrorCode); Assert.Equal(SocketError.Success, error); Assert.NotNull(hostEntry); string name = NameResolutionPal.TryGetNameInfo(hostEntry.AddressList[0], out error, out nativeErrorCode); Assert.Equal(SocketError.Success, error); Assert.NotNull(name); } [Fact] public void TryGetAddrInfo_HostName_TryGetNameInfo() { string hostName = NameResolutionPal.GetHostName(); Assert.NotNull(hostName); IPHostEntry hostEntry; int nativeErrorCode; SocketError error = NameResolutionPal.TryGetAddrInfo(hostName, out hostEntry, out nativeErrorCode); Assert.Equal(SocketError.Success, error); Assert.NotNull(hostEntry); string name = NameResolutionPal.TryGetNameInfo(hostEntry.AddressList[0], out error, out nativeErrorCode); Assert.Equal(SocketError.Success, error); Assert.NotNull(name); } [Fact] public void TryGetNameInfo_LocalHost_IPv4_TryGetAddrInfo() { SocketError error; int nativeErrorCode; string name = NameResolutionPal.TryGetNameInfo(new IPAddress(new byte[] { 127, 0, 0, 1 }), out error, out nativeErrorCode); Assert.Equal(SocketError.Success, error); Assert.NotNull(name); IPHostEntry hostEntry; error = NameResolutionPal.TryGetAddrInfo(name, out hostEntry, out nativeErrorCode); Assert.Equal(SocketError.Success, error); Assert.NotNull(hostEntry); } [Fact] public void TryGetNameInfo_LocalHost_IPv6_TryGetAddrInfo() { SocketError error; int nativeErrorCode; string name = NameResolutionPal.TryGetNameInfo(new IPAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }), out error, out nativeErrorCode); Assert.Equal(SocketError.Success, error); Assert.NotNull(name); IPHostEntry hostEntry; error = NameResolutionPal.TryGetAddrInfo(name, out hostEntry, out nativeErrorCode); Assert.Equal(SocketError.Success, error); Assert.NotNull(hostEntry); } } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // James Driscoll, mailto:jamesdriscoll@btinternet.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion // All code in this file requires .NET Framework 2.0 or later. #if !NET_1_1 && !NET_1_0 [assembly: Elmah.Scc("$Id: VistaDBErrorLog.cs 566 2009-05-11 10:37:10Z azizatif $")] namespace Elmah { #region Imports using System; using System.Data; using System.Globalization; using System.IO; using System.Text.RegularExpressions; using VistaDB; using VistaDB.DDA; using VistaDB.Provider; using IDictionary = System.Collections.IDictionary; using IList = System.Collections.IList; #endregion /// <summary> /// An <see cref="ErrorLog"/> implementation that uses VistaDB as its backing store. /// </summary> public class VistaDBErrorLog : ErrorLog { private readonly string _connectionString; private readonly string _databasePath; // TODO - don't think we have to limit strings in VistaDB, so decide if we really need this // Is it better to keep it for consistency, or better to exploit the full potential of the database?? private const int _maxAppNameLength = 60; /// <summary> /// Initializes a new instance of the <see cref="VistaDBErrorLog"/> class /// using a dictionary of configured settings. /// </summary> public VistaDBErrorLog(IDictionary config) { if (config == null) throw new ArgumentNullException("config"); _connectionString = ConnectionStringHelper.GetConnectionString(config); // // If there is no connection string to use then throw an // exception to abort construction. // if (_connectionString.Length == 0) throw new ApplicationException("Connection string is missing for the VistaDB error log."); _databasePath = ConnectionStringHelper.GetDataSourceFilePath(_connectionString); InitializeDatabase(); string appName = Mask.NullString((string)config["applicationName"]); if (appName.Length > _maxAppNameLength) { throw new ApplicationException(string.Format( "Application name is too long. Maximum length allowed is {0} characters.", _maxAppNameLength.ToString("N0"))); } ApplicationName = appName; } /// <summary> /// Initializes a new instance of the <see cref="VistaDBErrorLog"/> class /// to use a specific connection string for connecting to the database. /// </summary> public VistaDBErrorLog(string connectionString) { if (connectionString == null) throw new ArgumentNullException("connectionString"); if (connectionString.Length == 0) throw new ArgumentException(null, "connectionString"); _connectionString = connectionString; _databasePath = ConnectionStringHelper.GetDataSourceFilePath(_connectionString); InitializeDatabase(); } /// <summary> /// Gets the name of this error log implementation. /// </summary> public override string Name { get { return "VistaDB Error Log"; } } /// <summary> /// Gets the connection string used by the log to connect to the database. /// </summary> public virtual string ConnectionString { get { return _connectionString; } } /// <summary> /// Logs an error to the database. /// </summary> /// <remarks> /// Use the stored procedure called by this implementation to set a /// policy on how long errors are kept in the log. The default /// implementation stores all errors for an indefinite time. /// </remarks> public override string Log(Error error) { if (error == null) throw new ArgumentNullException("error"); string errorXml = ErrorXml.EncodeString(error); using (VistaDBConnection connection = new VistaDBConnection(this.ConnectionString)) using (VistaDBCommand command = connection.CreateCommand()) { connection.Open(); command.CommandText = @"INSERT INTO ELMAH_Error (Application, Host, Type, Source, Message, [User], AllXml, StatusCode, TimeUtc) VALUES (@Application, @Host, @Type, @Source, @Message, @User, @AllXml, @StatusCode, @TimeUtc); SELECT @@IDENTITY"; command.CommandType = CommandType.Text; VistaDBParameterCollection parameters = command.Parameters; parameters.Add("@Application", VistaDBType.NVarChar, _maxAppNameLength).Value = ApplicationName; parameters.Add("@Host", VistaDBType.NVarChar, 30).Value = error.HostName; parameters.Add("@Type", VistaDBType.NVarChar, 100).Value = error.Type; parameters.Add("@Source", VistaDBType.NVarChar, 60).Value = error.Source; parameters.Add("@Message", VistaDBType.NVarChar, 500).Value = error.Message; parameters.Add("@User", VistaDBType.NVarChar, 50).Value = error.User; parameters.Add("@AllXml", VistaDBType.NText).Value = errorXml; parameters.Add("@StatusCode", VistaDBType.Int).Value = error.StatusCode; parameters.Add("@TimeUtc", VistaDBType.DateTime).Value = error.Time.ToUniversalTime(); return Convert.ToString(command.ExecuteScalar(), CultureInfo.InvariantCulture); } } /// <summary> /// Returns a page of errors from the databse in descending order /// of logged time. /// </summary> public override int GetErrors(int pageIndex, int pageSize, IList errorEntryList) { if (pageIndex < 0) throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null); if (pageSize < 0) throw new ArgumentOutOfRangeException("pageSize", pageSize, null); VistaDBConnectionStringBuilder builder = new VistaDBConnectionStringBuilder(_connectionString); // Use the VistaDB Direct Data Access objects IVistaDBDDA ddaObjects = VistaDBEngine.Connections.OpenDDA(); // Create a connection object to a VistaDB database IVistaDBDatabase vistaDB = ddaObjects.OpenDatabase(_databasePath, builder.OpenMode, builder.Password); // Open the table IVistaDBTable elmahTable = vistaDB.OpenTable("ELMAH_Error", false, true); elmahTable.ActiveIndex = "IX_ELMAH_Error_App_Time_Id"; if (errorEntryList != null) { if (!elmahTable.EndOfTable) { // move to the correct record elmahTable.First(); elmahTable.MoveBy(pageIndex * pageSize); int rowsProcessed = 0; // Traverse the table to get the records we want while (!elmahTable.EndOfTable && rowsProcessed < pageSize) { rowsProcessed++; string id = Convert.ToString(elmahTable.Get("ErrorId").Value, CultureInfo.InvariantCulture); Error error = new Error(); error.ApplicationName = (string)elmahTable.Get("Application").Value; error.HostName = (string)elmahTable.Get("Host").Value; error.Type = (string)elmahTable.Get("Type").Value; error.Source = (string)elmahTable.Get("Source").Value; error.Message = (string)elmahTable.Get("Message").Value; error.User = (string)elmahTable.Get("User").Value; error.StatusCode = (int)elmahTable.Get("StatusCode").Value; error.Time = ((DateTime)elmahTable.Get("TimeUtc").Value).ToLocalTime(); errorEntryList.Add(new ErrorLogEntry(this, id, error)); // move to the next record elmahTable.Next(); } } } return Convert.ToInt32(elmahTable.RowCount); } /// <summary> /// Returns the specified error from the database, or null /// if it does not exist. /// </summary> public override ErrorLogEntry GetError(string id) { if (id == null) throw new ArgumentNullException("id"); if (id.Length == 0) throw new ArgumentException(null, "id"); int errorId; try { errorId = int.Parse(id, CultureInfo.InvariantCulture); } catch (FormatException e) { throw new ArgumentException(e.Message, "id", e); } catch (OverflowException e) { throw new ArgumentException(e.Message, "id", e); } string errorXml; using (VistaDBConnection connection = new VistaDBConnection(this.ConnectionString)) using (VistaDBCommand command = connection.CreateCommand()) { command.CommandText = @"SELECT AllXml FROM ELMAH_Error WHERE ErrorId = @ErrorId"; command.CommandType = CommandType.Text; VistaDBParameterCollection parameters = command.Parameters; parameters.Add("@ErrorId", VistaDBType.Int).Value = errorId; connection.Open(); // NB this has been deliberately done like this as command.ExecuteScalar // is not exhibiting the expected behaviour in VistaDB at the moment using (VistaDBDataReader dr = command.ExecuteReader()) { if (dr.Read()) errorXml = dr[0] as string; else errorXml = null; } } if (errorXml == null) return null; Error error = ErrorXml.DecodeString(errorXml); return new ErrorLogEntry(this, id, error); } private static string EscapeApostrophes(string text) { return text.Replace("'", "''"); } private static readonly object _lock = new object(); private void InitializeDatabase() { string connectionString = ConnectionString; Debug.AssertStringNotEmpty(connectionString); if (File.Exists(_databasePath)) return; // // Make sure that we don't have multiple threads all trying to create the database // lock (_lock) { // // Just double check that no other thread has created the database while // we were waiting for the lock // if (File.Exists(_databasePath)) return; VistaDBConnectionStringBuilder builder = new VistaDBConnectionStringBuilder(connectionString); using (VistaDBConnection connection = new VistaDBConnection()) using (VistaDBCommand command = connection.CreateCommand()) { string passwordClause = string.Empty; if (!string.IsNullOrEmpty(builder.Password)) passwordClause = " PASSWORD '" + EscapeApostrophes(builder.Password) + "',"; // create the database using the webserver's default locale command.CommandText = "CREATE DATABASE '" + EscapeApostrophes(_databasePath) + "'" + passwordClause + ", PAGE SIZE 1, CASE SENSITIVE FALSE;"; command.ExecuteNonQuery(); const string ddlScript = @" CREATE TABLE [ELMAH_Error] ( [ErrorId] INT NOT NULL, [Application] NVARCHAR (60) NOT NULL, [Host] NVARCHAR (50) NOT NULL, [Type] NVARCHAR (100) NOT NULL, [Source] NVARCHAR (60) NOT NULL, [Message] NVARCHAR (500) NOT NULL, [User] NVARCHAR (50) NOT NULL, [StatusCode] INT NOT NULL, [TimeUtc] DATETIME NOT NULL, [AllXml] NTEXT NOT NULL, CONSTRAINT [PK_ELMAH_Error] PRIMARY KEY ([ErrorId]) ) GO ALTER TABLE [ELMAH_Error] ALTER COLUMN [ErrorId] INT NOT NULL IDENTITY (1, 1) GO CREATE INDEX [IX_ELMAH_Error_App_Time_Id] ON [ELMAH_Error] ([TimeUtc] DESC, [ErrorId] DESC)"; foreach (string batch in ScriptToBatches(ddlScript)) { command.CommandText = batch; command.ExecuteNonQuery(); } } } } private static string[] ScriptToBatches(string script) { return Regex.Split(script, @"^ \s* GO \s* $\n?", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace); } } } #endif //!NET_1_1 && !NET_1_0
using System; using System.IO; using System.Collections.Specialized; using System.Collections.Generic; using System.Text; using System.Net; using LumiSoft.Net.SIP.Message; namespace LumiSoft.Net.SIP.Stack { /// <summary> /// SIP server request. Related RFC 3261. /// </summary> public class SIP_Request : SIP_Message { private SIP_RequestLine m_pRequestLine = null; private SIP_Flow m_pFlow = null; private IPEndPoint m_pLocalEP = null; private IPEndPoint m_pRemoteEP = null; /// <summary> /// Default constructor. /// </summary> /// <param name="method">SIP request method.</param> /// <exception cref="ArgumentNullException">Is raised when <b>method</b> is null reference.</exception> public SIP_Request(string method) { if(method == null){ throw new ArgumentNullException("method"); } m_pRequestLine = new SIP_RequestLine(method,new AbsoluteUri()); } #region method Copy /// <summary> /// Clones this request. /// </summary> /// <returns>Returns new cloned request.</returns> public SIP_Request Copy() { SIP_Request retVal = SIP_Request.Parse(this.ToByteData()); retVal.Flow = m_pFlow; retVal.LocalEndPoint = m_pLocalEP; retVal.RemoteEndPoint = m_pRemoteEP; return retVal; } #endregion #region method Validate /// <summary> /// Checks if SIP request has all required values as request line,header fields and their values. /// Throws Exception if not valid SIP request. /// </summary> public void Validate() { // Request SIP version // Via: + branch prameter // To: // From: // CallID: // CSeq // Max-Forwards RFC 3261 8.1.1. if(!this.RequestLine.Version.ToUpper().StartsWith("SIP/2.0")){ throw new SIP_ParseException("Not supported SIP version '" + this.RequestLine.Version + "' !"); } if(this.Via.GetTopMostValue() == null){ throw new SIP_ParseException("Via: header field is missing !"); } if(this.Via.GetTopMostValue().Branch == null){ throw new SIP_ParseException("Via: header field branch parameter is missing !"); } if(this.To == null){ throw new SIP_ParseException("To: header field is missing !"); } if(this.From == null){ throw new SIP_ParseException("From: header field is missing !"); } if(this.CallID == null){ throw new SIP_ParseException("CallID: header field is missing !"); } if(this.CSeq == null){ throw new SIP_ParseException("CSeq: header field is missing !"); } if(this.MaxForwards == -1){ // We can fix it by setting it to default value 70. this.MaxForwards = 70; } /* RFC 3261 12.1.2 When a UAC sends a request that can establish a dialog (such as an INVITE) it MUST provide a SIP or SIPS URI with global scope (i.e., the same SIP URI can be used in messages outside this dialog) in the Contact header field of the request. If the request has a Request-URI or a topmost Route header field value with a SIPS URI, the Contact header field MUST contain a SIPS URI. */ if(SIP_Utils.MethodCanEstablishDialog(this.RequestLine.Method)){ if(this.Contact.GetAllValues().Length == 0){ throw new SIP_ParseException("Contact: header field is missing, method that can establish a dialog MUST provide a SIP or SIPS URI !"); } if(this.Contact.GetAllValues().Length > 1){ throw new SIP_ParseException("There may be only 1 Contact: header for the method that can establish a dialog !"); } if(!this.Contact.GetTopMostValue().Address.IsSipOrSipsUri){ throw new SIP_ParseException("Method that can establish a dialog MUST have SIP or SIPS uri in Contact: header !"); } } // TODO: Invite must have From:/To: tag // TODO: Check that request-Method equals CSeq method // TODO: PRACK must have RAck and RSeq header fields. // TODO: get in transport made request, so check if sips and sip set as needed. } #endregion #region method Parse /// <summary> /// Parses SIP_Request from byte array. /// </summary> /// <param name="data">Valid SIP request data.</param> /// <returns>Returns parsed SIP_Request obeject.</returns> /// <exception cref="ArgumentNullException">Raised when <b>data</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public static SIP_Request Parse(byte[] data) { if(data == null){ throw new ArgumentNullException("data"); } return Parse(new MemoryStream(data)); } /// <summary> /// Parses SIP_Request from stream. /// </summary> /// <param name="stream">Stream what contains valid SIP request.</param> /// <returns>Returns parsed SIP_Request obeject.</returns> /// <exception cref="ArgumentNullException">Raised when <b>stream</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public static SIP_Request Parse(Stream stream) { /* Syntax: SIP-Method SIP-URI SIP-Version SIP-Message */ if(stream == null){ throw new ArgumentNullException("stream"); } // Parse Response-line StreamLineReader r = new StreamLineReader(stream); r.Encoding = "utf-8"; string[] method_uri_version = r.ReadLineString().Split(' '); if(method_uri_version.Length != 3){ throw new Exception("Invalid SIP request data ! Method line doesn't contain: SIP-Method SIP-URI SIP-Version."); } SIP_Request retVal = new SIP_Request(method_uri_version[0]); retVal.RequestLine.Uri = AbsoluteUri.Parse(method_uri_version[1]); retVal.RequestLine.Version = method_uri_version[2]; // Parse SIP message retVal.InternalParse(stream); return retVal; } #endregion #region method ToStream /// <summary> /// Stores SIP_Request to specified stream. /// </summary> /// <param name="stream">Stream where to store.</param> public void ToStream(Stream stream) { // Add request-line byte[] responseLine = Encoding.UTF8.GetBytes(m_pRequestLine.ToString()); stream.Write(responseLine,0,responseLine.Length); // Add SIP-message this.InternalToStream(stream); } #endregion #region method ToByteData /// <summary> /// Converts this request to raw srver request data. /// </summary> /// <returns></returns> public byte[] ToByteData() { MemoryStream retVal = new MemoryStream(); ToStream(retVal); return retVal.ToArray(); } #endregion #region method ToString /// <summary> /// Returns request as string. /// </summary> /// <returns>Returns request as string.</returns> public override string ToString() { return Encoding.UTF8.GetString(ToByteData()); } #endregion #region Properties Implementation /// <summary> /// Gets request-line. /// </summary> public SIP_RequestLine RequestLine { get{ return m_pRequestLine; } } /// <summary> /// Gets or sets flow what received or sent this request. Returns null if this request isn't sent or received. /// </summary> internal SIP_Flow Flow { get{ return m_pFlow; } set{ m_pFlow = value; } } /// <summary> /// Gets or sets local end point what sent/received this request. Returns null if this request isn't sent or received. /// </summary> internal IPEndPoint LocalEndPoint { get{ return m_pLocalEP; } set{ m_pLocalEP = value; } } /// <summary> /// Gets or sets remote end point what sent/received this request. Returns null if this request isn't sent or received. /// </summary> internal IPEndPoint RemoteEndPoint { get{ return m_pRemoteEP; } set{ m_pRemoteEP = value; } } #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; using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace System.Runtime.InteropServices.WindowsRuntime { // An event registration token table stores mappings from delegates to event tokens, in order to support // sourcing WinRT style events from managed code. public sealed class EventRegistrationTokenTable<T> where T : class { // Note this dictionary is also used as the synchronization object for this table private Dictionary<EventRegistrationToken, T> m_tokens = new Dictionary<EventRegistrationToken, T>(); // Cached multicast delegate which will invoke all of the currently registered delegates. This // will be accessed frequently in common coding paterns, so we don't want to calculate it repeatedly. private volatile T m_invokeList; public EventRegistrationTokenTable() { // T must be a delegate type, but we cannot constrain on being a delegate. Therefore, we'll do a // static check at construction time if (!typeof(Delegate).IsAssignableFrom(typeof(T))) { throw new InvalidOperationException(SR.Format(SR.InvalidOperation_EventTokenTableRequiresDelegate, typeof (T))); } } // The InvocationList property provides access to a delegate which will invoke every registered event handler // in this table. If the property is set, the new value will replace any existing token registrations. public T InvocationList { get { return m_invokeList; } set { lock (m_tokens) { // The value being set replaces any of the existing values m_tokens.Clear(); m_invokeList = null; if (value != null) { AddEventHandlerNoLock(value); } } } } public EventRegistrationToken AddEventHandler(T handler) { // Windows Runtime allows null handlers. Assign those a token value of 0 for easy identity if (handler == null) { return new EventRegistrationToken(0); } lock (m_tokens) { return AddEventHandlerNoLock(handler); } } private EventRegistrationToken AddEventHandlerNoLock(T handler) { Debug.Assert(handler != null); // Get a registration token, making sure that we haven't already used the value. This should be quite // rare, but in the case it does happen, just keep trying until we find one that's unused. EventRegistrationToken token = GetPreferredToken(handler); while (m_tokens.ContainsKey(token)) { token = new EventRegistrationToken(token.Value + 1); } m_tokens[token] = handler; // Update the current invocation list to include the newly added delegate Delegate invokeList = (Delegate)(object)m_invokeList; invokeList = MulticastDelegate.Combine(invokeList, (Delegate)(object)handler); m_invokeList = (T)(object)invokeList; return token; } // Get the delegate associated with an event registration token if it exists. Additionally, // remove the registration from the table at the same time. If the token is not registered, // Extract returns null and does not modify the table. // [System.Runtime.CompilerServices.FriendAccessAllowed] internal T ExtractHandler(EventRegistrationToken token) { T handler = null; lock (m_tokens) { if (m_tokens.TryGetValue(token, out handler)) { RemoveEventHandlerNoLock(token); } } return handler; } // Generate a token that may be used for a particular event handler. We will frequently be called // upon to look up a token value given only a delegate to start from. Therefore, we want to make // an initial token value that is easily determined using only the delegate instance itself. Although // in the common case this token value will be used to uniquely identify the handler, it is not // the only possible token that can represent the handler. // // This means that both: // * if there is a handler assigned to the generated initial token value, it is not necessarily // this handler. // * if there is no handler assigned to the generated initial token value, the handler may still // be registered under a different token // // Effectively the only reasonable thing to do with this value is either to: // 1. Use it as a good starting point for generating a token for handler // 2. Use it as a guess to quickly see if the handler was really assigned this token value private static EventRegistrationToken GetPreferredToken(T handler) { Debug.Assert(handler != null); // We want to generate a token value that has the following properties: // 1. is quickly obtained from the handler instance // 2. uses bits in the upper 32 bits of the 64 bit value, in order to avoid bugs where code // may assume the value is realy just 32 bits // 3. uses bits in the bottom 32 bits of the 64 bit value, in order to ensure that code doesn't // take a dependency on them always being 0. // // The simple algorithm chosen here is to simply assign the upper 32 bits the metadata token of the // event handler type, and the lower 32 bits the hash code of the handler instance itself. Using the // metadata token for the upper 32 bits gives us at least a small chance of being able to identify a // totally corrupted token if we ever come across one in a minidump or other scenario. // // The hash code of a unicast delegate is not tied to the method being invoked, so in the case // of a unicast delegate, the hash code of the target method is used instead of the full delegate // hash code. // // While calculating this initial value will be somewhat more expensive than just using a counter // for events that have few registrations, it will also gives us a shot at preventing unregistration // from becoming an O(N) operation. // // We should feel free to change this algorithm as other requirements / optimizations become // available. This implementation is sufficiently random that code cannot simply guess the value to // take a dependency upon it. (Simply applying the hash-value algorithm directly won't work in the // case of collisions, where we'll use a different token value). uint handlerHashCode = 0; Delegate[] invocationList = ((Delegate)(object)handler).GetInvocationList(); if (invocationList.Length == 1) { handlerHashCode = (uint)invocationList[0].Method.GetHashCode(); } else { handlerHashCode = (uint)handler.GetHashCode(); } ulong tokenValue = ((ulong)(uint)typeof(T).MetadataToken << 32) | handlerHashCode; return new EventRegistrationToken(tokenValue); } public void RemoveEventHandler(EventRegistrationToken token) { // The 0 token is assigned to null handlers, so there's nothing to do if (token.Value == 0) { return; } lock (m_tokens) { RemoveEventHandlerNoLock(token); } } public void RemoveEventHandler(T handler) { // To match the Windows Runtime behaivor when adding a null handler, removing one is a no-op if (handler == null) { return; } lock (m_tokens) { // Fast path - if the delegate is stored with its preferred token, then there's no need to do // a full search of the table for it. Note that even if we find something stored using the // preferred token value, it's possible we have a collision and another delegate was using that // value. Therefore we need to make sure we really have the handler we want before taking the // fast path. EventRegistrationToken preferredToken = GetPreferredToken(handler); T registeredHandler; if (m_tokens.TryGetValue(preferredToken, out registeredHandler)) { if (registeredHandler == handler) { RemoveEventHandlerNoLock(preferredToken); return; } } // Slow path - we didn't find the delegate with its preferred token, so we need to fall // back to a search of the table foreach (KeyValuePair<EventRegistrationToken, T> registration in m_tokens) { if (registration.Value == (T)(object)handler) { RemoveEventHandlerNoLock(registration.Key); // If a delegate has been added multiple times to handle an event, then it // needs to be removed the same number of times to stop handling the event. // Stop after the first one we find. return; } } // Note that falling off the end of the loop is not an error, as removing a registration // for a handler that is not currently registered is simply a no-op } } private void RemoveEventHandlerNoLock(EventRegistrationToken token) { T handler; if (m_tokens.TryGetValue(token, out handler)) { m_tokens.Remove(token); // Update the current invocation list to remove the delegate Delegate invokeList = (Delegate)(object)m_invokeList; invokeList = MulticastDelegate.Remove(invokeList, (Delegate)(object)handler); m_invokeList = (T)(object)invokeList; } } public static EventRegistrationTokenTable<T> GetOrCreateEventRegistrationTokenTable(ref EventRegistrationTokenTable<T> refEventTable) { if (refEventTable == null) { Interlocked.CompareExchange(ref refEventTable, new EventRegistrationTokenTable<T>(), null); } return refEventTable; } } }
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using WriterException = com.google.zxing.WriterException; using EncodeHintType = com.google.zxing.EncodeHintType; using ByteArray = com.google.zxing.common.ByteArray; using ByteMatrix = com.google.zxing.common.ByteMatrix; using CharacterSetECI = com.google.zxing.common.CharacterSetECI; using GF256 = com.google.zxing.common.reedsolomon.GF256; using ReedSolomonEncoder = com.google.zxing.common.reedsolomon.ReedSolomonEncoder; using ErrorCorrectionLevel = com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; using Mode = com.google.zxing.qrcode.decoder.Mode; using Version = com.google.zxing.qrcode.decoder.Version; namespace com.google.zxing.qrcode.encoder { /// <author> satorux@google.com (Satoru Takabayashi) - creator /// </author> /// <author> dswitkin@google.com (Daniel Switkin) - ported from C++ /// </author> /// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source /// </author> public sealed class Encoder { // The original table is defined in the table 5 of JISX0510:2004 (p.19). //UPGRADE_NOTE: Final was removed from the declaration of 'ALPHANUMERIC_TABLE'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" private static readonly int[] ALPHANUMERIC_TABLE = new int[]{- 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, 36, - 1, - 1, - 1, 37, 38, - 1, - 1, - 1, - 1, 39, 40, - 1, 41, 42, 43, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, - 1, - 1, - 1, - 1, - 1, - 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, - 1, - 1, - 1, - 1, - 1}; internal const System.String DEFAULT_BYTE_MODE_ENCODING = "ISO-8859-1"; private Encoder() { } // The mask penalty calculation is complicated. See Table 21 of JISX0510:2004 (p.45) for details. // Basically it applies four rules and summate all penalties. private static int calculateMaskPenalty(ByteMatrix matrix) { int penalty = 0; penalty += MaskUtil.applyMaskPenaltyRule1(matrix); penalty += MaskUtil.applyMaskPenaltyRule2(matrix); penalty += MaskUtil.applyMaskPenaltyRule3(matrix); penalty += MaskUtil.applyMaskPenaltyRule4(matrix); return penalty; } /// <summary> Encode "bytes" with the error correction level "ecLevel". The encoding mode will be chosen /// internally by chooseMode(). On success, store the result in "qrCode". /// /// We recommend you to use QRCode.EC_LEVEL_L (the lowest level) for /// "getECLevel" since our primary use is to show QR code on desktop screens. We don't need very /// strong error correction for this purpose. /// /// Note that there is no way to encode bytes in MODE_KANJI. We might want to add EncodeWithMode() /// with which clients can specify the encoding mode. For now, we don't need the functionality. /// </summary> public static void encode(System.String content, ErrorCorrectionLevel ecLevel, QRCode qrCode) { encode(content, ecLevel, null, qrCode); } public static void encode(System.String content, ErrorCorrectionLevel ecLevel, System.Collections.Hashtable hints, QRCode qrCode) { System.String encoding = hints == null?null:(System.String) hints[EncodeHintType.CHARACTER_SET]; if (encoding == null) { encoding = DEFAULT_BYTE_MODE_ENCODING; } // Step 1: Choose the mode (encoding). Mode mode = chooseMode(content, encoding); // Step 2: Append "bytes" into "dataBits" in appropriate encoding. BitVector dataBits = new BitVector(); appendBytes(content, mode, dataBits, encoding); // Step 3: Initialize QR code that can contain "dataBits". int numInputBytes = dataBits.sizeInBytes(); initQRCode(numInputBytes, ecLevel, mode, qrCode); // Step 4: Build another bit vector that contains header and data. BitVector headerAndDataBits = new BitVector(); // Step 4.5: Append ECI message if applicable if (mode == Mode.BYTE && !DEFAULT_BYTE_MODE_ENCODING.Equals(encoding)) { CharacterSetECI eci = CharacterSetECI.getCharacterSetECIByName(encoding); if (eci != null) { appendECI(eci, headerAndDataBits); } } appendModeInfo(mode, headerAndDataBits); int numLetters = mode.Equals(Mode.BYTE)?dataBits.sizeInBytes():content.Length; appendLengthInfo(numLetters, qrCode.Version, mode, headerAndDataBits); headerAndDataBits.appendBitVector(dataBits); // Step 5: Terminate the bits properly. terminateBits(qrCode.NumDataBytes, headerAndDataBits); // Step 6: Interleave data bits with error correction code. BitVector finalBits = new BitVector(); interleaveWithECBytes(headerAndDataBits, qrCode.NumTotalBytes, qrCode.NumDataBytes, qrCode.NumRSBlocks, finalBits); // Step 7: Choose the mask pattern and set to "qrCode". ByteMatrix matrix = new ByteMatrix(qrCode.MatrixWidth, qrCode.MatrixWidth); qrCode.MaskPattern = chooseMaskPattern(finalBits, qrCode.ECLevel, qrCode.Version, matrix); // Step 8. Build the matrix and set it to "qrCode". MatrixUtil.buildMatrix(finalBits, qrCode.ECLevel, qrCode.Version, qrCode.MaskPattern, matrix); qrCode.Matrix = matrix; // Step 9. Make sure we have a valid QR Code. if (!qrCode.Valid) { throw new WriterException("Invalid QR code: " + qrCode.ToString()); } } /// <returns> the code point of the table used in alphanumeric mode or /// -1 if there is no corresponding code in the table. /// </returns> internal static int getAlphanumericCode(int code) { if (code < ALPHANUMERIC_TABLE.Length) { return ALPHANUMERIC_TABLE[code]; } return - 1; } public static Mode chooseMode(System.String content) { return chooseMode(content, null); } /// <summary> Choose the best mode by examining the content. Note that 'encoding' is used as a hint; /// if it is Shift_JIS, and the input is only double-byte Kanji, then we return {@link Mode#KANJI}. /// </summary> public static Mode chooseMode(System.String content, System.String encoding) { if ("Shift_JIS".Equals(encoding)) { // Choose Kanji mode if all input are double-byte characters return isOnlyDoubleByteKanji(content)?Mode.KANJI:Mode.BYTE; } bool hasNumeric = false; bool hasAlphanumeric = false; for (int i = 0; i < content.Length; ++i) { char c = content[i]; if (c >= '0' && c <= '9') { hasNumeric = true; } else if (getAlphanumericCode(c) != - 1) { hasAlphanumeric = true; } else { return Mode.BYTE; } } if (hasAlphanumeric) { return Mode.ALPHANUMERIC; } else if (hasNumeric) { return Mode.NUMERIC; } return Mode.BYTE; } private static bool isOnlyDoubleByteKanji(System.String content) { sbyte[] bytes; try { //UPGRADE_TODO: Method 'java.lang.String.getBytes' was converted to 'System.Text.Encoding.GetEncoding(string).GetBytes(string)' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javalangStringgetBytes_javalangString'" bytes = SupportClass.ToSByteArray(System.Text.Encoding.GetEncoding("Shift_JIS").GetBytes(content)); } catch (System.IO.IOException) { return false; } int length = bytes.Length; if (length % 2 != 0) { return false; } for (int i = 0; i < length; i += 2) { int byte1 = bytes[i] & 0xFF; if ((byte1 < 0x81 || byte1 > 0x9F) && (byte1 < 0xE0 || byte1 > 0xEB)) { return false; } } return true; } private static int chooseMaskPattern(BitVector bits, ErrorCorrectionLevel ecLevel, int version, ByteMatrix matrix) { int minPenalty = System.Int32.MaxValue; // Lower penalty is better. int bestMaskPattern = - 1; // We try all mask patterns to choose the best one. for (int maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++) { MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix); int penalty = calculateMaskPenalty(matrix); if (penalty < minPenalty) { minPenalty = penalty; bestMaskPattern = maskPattern; } } return bestMaskPattern; } /// <summary> Initialize "qrCode" according to "numInputBytes", "ecLevel", and "mode". On success, /// modify "qrCode". /// </summary> private static void initQRCode(int numInputBytes, ErrorCorrectionLevel ecLevel, Mode mode, QRCode qrCode) { qrCode.ECLevel = ecLevel; qrCode.Mode = mode; // In the following comments, we use numbers of Version 7-H. for (int versionNum = 1; versionNum <= 40; versionNum++) { Version version = Version.getVersionForNumber(versionNum); // numBytes = 196 int numBytes = version.TotalCodewords; // getNumECBytes = 130 Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel); int numEcBytes = ecBlocks.TotalECCodewords; // getNumRSBlocks = 5 int numRSBlocks = ecBlocks.NumBlocks; // getNumDataBytes = 196 - 130 = 66 int numDataBytes = numBytes - numEcBytes; // We want to choose the smallest version which can contain data of "numInputBytes" + some // extra bits for the header (mode info and length info). The header can be three bytes // (precisely 4 + 16 bits) at most. Hence we do +3 here. if (numDataBytes >= numInputBytes + 3) { // Yay, we found the proper rs block info! qrCode.Version = versionNum; qrCode.NumTotalBytes = numBytes; qrCode.NumDataBytes = numDataBytes; qrCode.NumRSBlocks = numRSBlocks; // getNumECBytes = 196 - 66 = 130 qrCode.NumECBytes = numEcBytes; // matrix width = 21 + 6 * 4 = 45 qrCode.MatrixWidth = version.DimensionForVersion; return ; } } throw new WriterException("Cannot find proper rs block info (input data too big?)"); } /// <summary> Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24).</summary> internal static void terminateBits(int numDataBytes, BitVector bits) { int capacity = numDataBytes << 3; if (bits.size() > capacity) { throw new WriterException("data bits cannot fit in the QR Code" + bits.size() + " > " + capacity); } // Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details. // TODO: srowen says we can remove this for loop, since the 4 terminator bits are optional if // the last byte has less than 4 bits left. So it amounts to padding the last byte with zeroes // either way. for (int i = 0; i < 4 && bits.size() < capacity; ++i) { bits.appendBit(0); } int numBitsInLastByte = bits.size() % 8; // If the last byte isn't 8-bit aligned, we'll add padding bits. if (numBitsInLastByte > 0) { int numPaddingBits = 8 - numBitsInLastByte; for (int i = 0; i < numPaddingBits; ++i) { bits.appendBit(0); } } // Should be 8-bit aligned here. if (bits.size() % 8 != 0) { throw new WriterException("Number of bits is not a multiple of 8"); } // If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24). int numPaddingBytes = numDataBytes - bits.sizeInBytes(); for (int i = 0; i < numPaddingBytes; ++i) { if (i % 2 == 0) { bits.appendBits(0xec, 8); } else { bits.appendBits(0x11, 8); } } if (bits.size() != capacity) { throw new WriterException("Bits size does not equal capacity"); } } /// <summary> Get number of data bytes and number of error correction bytes for block id "blockID". Store /// the result in "numDataBytesInBlock", and "numECBytesInBlock". See table 12 in 8.5.1 of /// JISX0510:2004 (p.30) /// </summary> internal static void getNumDataBytesAndNumECBytesForBlockID(int numTotalBytes, int numDataBytes, int numRSBlocks, int blockID, int[] numDataBytesInBlock, int[] numECBytesInBlock) { if (blockID >= numRSBlocks) { throw new WriterException("Block ID too large"); } // numRsBlocksInGroup2 = 196 % 5 = 1 int numRsBlocksInGroup2 = numTotalBytes % numRSBlocks; // numRsBlocksInGroup1 = 5 - 1 = 4 int numRsBlocksInGroup1 = numRSBlocks - numRsBlocksInGroup2; // numTotalBytesInGroup1 = 196 / 5 = 39 int numTotalBytesInGroup1 = numTotalBytes / numRSBlocks; // numTotalBytesInGroup2 = 39 + 1 = 40 int numTotalBytesInGroup2 = numTotalBytesInGroup1 + 1; // numDataBytesInGroup1 = 66 / 5 = 13 int numDataBytesInGroup1 = numDataBytes / numRSBlocks; // numDataBytesInGroup2 = 13 + 1 = 14 int numDataBytesInGroup2 = numDataBytesInGroup1 + 1; // numEcBytesInGroup1 = 39 - 13 = 26 int numEcBytesInGroup1 = numTotalBytesInGroup1 - numDataBytesInGroup1; // numEcBytesInGroup2 = 40 - 14 = 26 int numEcBytesInGroup2 = numTotalBytesInGroup2 - numDataBytesInGroup2; // Sanity checks. // 26 = 26 if (numEcBytesInGroup1 != numEcBytesInGroup2) { throw new WriterException("EC bytes mismatch"); } // 5 = 4 + 1. if (numRSBlocks != numRsBlocksInGroup1 + numRsBlocksInGroup2) { throw new WriterException("RS blocks mismatch"); } // 196 = (13 + 26) * 4 + (14 + 26) * 1 if (numTotalBytes != ((numDataBytesInGroup1 + numEcBytesInGroup1) * numRsBlocksInGroup1) + ((numDataBytesInGroup2 + numEcBytesInGroup2) * numRsBlocksInGroup2)) { throw new WriterException("Total bytes mismatch"); } if (blockID < numRsBlocksInGroup1) { numDataBytesInBlock[0] = numDataBytesInGroup1; numECBytesInBlock[0] = numEcBytesInGroup1; } else { numDataBytesInBlock[0] = numDataBytesInGroup2; numECBytesInBlock[0] = numEcBytesInGroup2; } } /// <summary> Interleave "bits" with corresponding error correction bytes. On success, store the result in /// "result". The interleave rule is complicated. See 8.6 of JISX0510:2004 (p.37) for details. /// </summary> internal static void interleaveWithECBytes(BitVector bits, int numTotalBytes, int numDataBytes, int numRSBlocks, BitVector result) { // "bits" must have "getNumDataBytes" bytes of data. if (bits.sizeInBytes() != numDataBytes) { throw new WriterException("Number of bits and data bytes does not match"); } // Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll // store the divided data bytes blocks and error correction bytes blocks into "blocks". int dataBytesOffset = 0; int maxNumDataBytes = 0; int maxNumEcBytes = 0; // Since, we know the number of reedsolmon blocks, we can initialize the vector with the number. System.Collections.ArrayList blocks = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(numRSBlocks)); for (int i = 0; i < numRSBlocks; ++i) { int[] numDataBytesInBlock = new int[1]; int[] numEcBytesInBlock = new int[1]; getNumDataBytesAndNumECBytesForBlockID(numTotalBytes, numDataBytes, numRSBlocks, i, numDataBytesInBlock, numEcBytesInBlock); ByteArray dataBytes = new ByteArray(); dataBytes.set_Renamed(bits.Array, dataBytesOffset, numDataBytesInBlock[0]); ByteArray ecBytes = generateECBytes(dataBytes, numEcBytesInBlock[0]); blocks.Add(new BlockPair(dataBytes, ecBytes)); maxNumDataBytes = System.Math.Max(maxNumDataBytes, dataBytes.size()); maxNumEcBytes = System.Math.Max(maxNumEcBytes, ecBytes.size()); dataBytesOffset += numDataBytesInBlock[0]; } if (numDataBytes != dataBytesOffset) { throw new WriterException("Data bytes does not match offset"); } // First, place data blocks. for (int i = 0; i < maxNumDataBytes; ++i) { for (int j = 0; j < blocks.Count; ++j) { ByteArray dataBytes = ((BlockPair) blocks[j]).DataBytes; if (i < dataBytes.size()) { result.appendBits(dataBytes.at(i), 8); } } } // Then, place error correction blocks. for (int i = 0; i < maxNumEcBytes; ++i) { for (int j = 0; j < blocks.Count; ++j) { ByteArray ecBytes = ((BlockPair) blocks[j]).ErrorCorrectionBytes; if (i < ecBytes.size()) { result.appendBits(ecBytes.at(i), 8); } } } if (numTotalBytes != result.sizeInBytes()) { // Should be same. throw new WriterException("Interleaving error: " + numTotalBytes + " and " + result.sizeInBytes() + " differ."); } } internal static ByteArray generateECBytes(ByteArray dataBytes, int numEcBytesInBlock) { int numDataBytes = dataBytes.size(); int[] toEncode = new int[numDataBytes + numEcBytesInBlock]; for (int i = 0; i < numDataBytes; i++) { toEncode[i] = dataBytes.at(i); } new ReedSolomonEncoder(GF256.QR_CODE_FIELD).encode(toEncode, numEcBytesInBlock); ByteArray ecBytes = new ByteArray(numEcBytesInBlock); for (int i = 0; i < numEcBytesInBlock; i++) { ecBytes.set_Renamed(i, toEncode[numDataBytes + i]); } return ecBytes; } /// <summary> Append mode info. On success, store the result in "bits".</summary> internal static void appendModeInfo(Mode mode, BitVector bits) { bits.appendBits(mode.Bits, 4); } /// <summary> Append length info. On success, store the result in "bits".</summary> internal static void appendLengthInfo(int numLetters, int version, Mode mode, BitVector bits) { int numBits = mode.getCharacterCountBits(Version.getVersionForNumber(version)); if (numLetters > ((1 << numBits) - 1)) { throw new WriterException(numLetters + "is bigger than" + ((1 << numBits) - 1)); } bits.appendBits(numLetters, numBits); } /// <summary> Append "bytes" in "mode" mode (encoding) into "bits". On success, store the result in "bits".</summary> internal static void appendBytes(System.String content, Mode mode, BitVector bits, System.String encoding) { if (mode.Equals(Mode.NUMERIC)) { appendNumericBytes(content, bits); } else if (mode.Equals(Mode.ALPHANUMERIC)) { appendAlphanumericBytes(content, bits); } else if (mode.Equals(Mode.BYTE)) { append8BitBytes(content, bits, encoding); } else if (mode.Equals(Mode.KANJI)) { appendKanjiBytes(content, bits); } else { throw new WriterException("Invalid mode: " + mode); } } internal static void appendNumericBytes(System.String content, BitVector bits) { int length = content.Length; int i = 0; while (i < length) { int num1 = content[i] - '0'; if (i + 2 < length) { // Encode three numeric letters in ten bits. int num2 = content[i + 1] - '0'; int num3 = content[i + 2] - '0'; bits.appendBits(num1 * 100 + num2 * 10 + num3, 10); i += 3; } else if (i + 1 < length) { // Encode two numeric letters in seven bits. int num2 = content[i + 1] - '0'; bits.appendBits(num1 * 10 + num2, 7); i += 2; } else { // Encode one numeric letter in four bits. bits.appendBits(num1, 4); i++; } } } internal static void appendAlphanumericBytes(System.String content, BitVector bits) { int length = content.Length; int i = 0; while (i < length) { int code1 = getAlphanumericCode(content[i]); if (code1 == - 1) { throw new WriterException(); } if (i + 1 < length) { int code2 = getAlphanumericCode(content[i + 1]); if (code2 == - 1) { throw new WriterException(); } // Encode two alphanumeric letters in 11 bits. bits.appendBits(code1 * 45 + code2, 11); i += 2; } else { // Encode one alphanumeric letter in six bits. bits.appendBits(code1, 6); i++; } } } internal static void append8BitBytes(System.String content, BitVector bits, System.String encoding) { sbyte[] bytes; try { //UPGRADE_TODO: Method 'java.lang.String.getBytes' was converted to 'System.Text.Encoding.GetEncoding(string).GetBytes(string)' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javalangStringgetBytes_javalangString'" bytes = SupportClass.ToSByteArray(System.Text.Encoding.GetEncoding(encoding).GetBytes(content)); } catch (System.IO.IOException uee) { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" throw new WriterException(uee.ToString()); } for (int i = 0; i < bytes.Length; ++i) { bits.appendBits(bytes[i], 8); } } internal static void appendKanjiBytes(System.String content, BitVector bits) { sbyte[] bytes; try { //UPGRADE_TODO: Method 'java.lang.String.getBytes' was converted to 'System.Text.Encoding.GetEncoding(string).GetBytes(string)' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javalangStringgetBytes_javalangString'" bytes = SupportClass.ToSByteArray(System.Text.Encoding.GetEncoding("Shift_JIS").GetBytes(content)); } catch (System.IO.IOException uee) { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" throw new WriterException(uee.ToString()); } int length = bytes.Length; for (int i = 0; i < length; i += 2) { int byte1 = bytes[i] & 0xFF; int byte2 = bytes[i + 1] & 0xFF; int code = (byte1 << 8) | byte2; int subtracted = - 1; if (code >= 0x8140 && code <= 0x9ffc) { subtracted = code - 0x8140; } else if (code >= 0xe040 && code <= 0xebbf) { subtracted = code - 0xc140; } if (subtracted == - 1) { throw new WriterException("Invalid byte sequence"); } int encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff); bits.appendBits(encoded, 13); } } private static void appendECI(CharacterSetECI eci, BitVector bits) { bits.appendBits(Mode.ECI.Bits, 4); // This is correct for values up to 127, which is all we need now. bits.appendBits(eci.Value, 8); } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using MonoGame.Extended.ViewportAdapters; using XmasHell.Background; using XmasHell.Performance; using XmasHell.Screens; using XmasHell.Screens.Menu; using XmasHell.Shaders; using XmasHell.Rendering; using XmasHell.Controls; using MonoGame.Extended.Animations; using MonoGame.Extended.Tweening; using XmasHell.Audio; using XmasHell.Entities; using XmasHell.GUI; using XmasHell.PlayerData; #if ANDROID using XmasHellAndroid; using Android.Util; using Android.Content; using XmasHell.PlayerData.Android; #elif LINUX using XmasHell.PlayerData.Desktop; #endif namespace XmasHell { /// <summary> /// This is the main type for your game. /// </summary> public class XmasHell : Game { public GraphicsDeviceManager Graphics; public SpriteBatch SpriteBatch; public SpriteBatchManager SpriteBatchManager; public ViewportAdapter ViewportAdapter; public Camera Camera; public GameManager GameManager; public ScreenManager ScreenManager; public MusicManager MusicManager; public GuiManager GuiManager; public PlayerData.PlayerData PlayerData; public CloudManager CloudManager; public bool Pause; private bool _computeNextFrame = false; #if ANDROID public XmasHellActivity AndroidActivity; #endif // Performance public PerformanceManager PerformanceManager; private static XmasHell _instance = null; public static XmasHell Instance() { return _instance; } #if ANDROID public XmasHell(XmasHellActivity activity) #else public XmasHell() #endif { _instance = this; Graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; #if ANDROID Graphics.SupportedOrientations = DisplayOrientation.Portrait; AndroidActivity = activity; // Used for bloom effect Graphics.PreferredDepthStencilFormat = DepthFormat.Depth16; Graphics.IsFullScreen = true; Graphics.ApplyChanges(); #else Graphics.IsFullScreen = false; Window.AllowUserResizing = true; IsMouseVisible = true; //Graphics.PreferredBackBufferWidth = GameConfig.VirtualResolution.X; //Graphics.PreferredBackBufferHeight = GameConfig.VirtualResolution.Y; Graphics.PreferredBackBufferWidth = 480; Graphics.PreferredBackBufferHeight = 853; // Unlock FPS //IsFixedTimeStep = false; //Graphics.SynchronizeWithVerticalRetrace = false; #endif GameManager = new GameManager(this); SpriteBatchManager = new SpriteBatchManager(this); PerformanceManager = new PerformanceManager(this); CloudManager = new CloudManager(this); } protected override void Initialize() { ViewportAdapter = new BoxingViewportAdapter(Window, GraphicsDevice, GameConfig.VirtualResolution.X, GameConfig.VirtualResolution.Y); Camera = new Camera(this, ViewportAdapter); MusicManager = new MusicManager(); SpriteBatchManager.Initialize(); base.Initialize(); Pause = false; GameManager.Initialize(); // Input manager Components.Add(new InputManager(this)); // Animation and tweening var animationComponent = new AnimationComponent(this); Components.Add(animationComponent); Components.Add(new TweeningComponent(this, animationComponent)); // GUI GuiManager = new GuiManager(this); PerformanceManager.Initialize(); // Player data #if ANDROID ISharedPreferences prefs = AndroidActivity.GetSharedPreferences("XmasHell", FileCreationMode.Private); var androidPreferences = new AndroidPreferences(prefs); PlayerData = new PlayerData.PlayerData(androidPreferences); #elif LINUX var desktopPreferences = new DesktopPreferences(); PlayerData = new PlayerData.PlayerData(desktopPreferences); #endif // Screens ScreenManager = new ScreenManager(this); if (GameConfig.DebugScreen) { ScreenManager.AddScreen(new DebugScreen(this)); ScreenManager.GoTo<DebugScreen>(); } else { ScreenManager.AddScreen(new MainMenuScreen(this)); ScreenManager.AddScreen(new BossSelectionScreen(this)); ScreenManager.AddScreen(new GameScreen(this)); ScreenManager.GoTo<MainMenuScreen>(); } } protected override void LoadContent() { SpriteBatch = new SpriteBatch(GraphicsDevice); #if ANDROID Assets.SetActivity(AndroidActivity); #endif Assets.Load(Content, GraphicsDevice); SpriteBatchManager.LoadContent(); CloudManager.LoadContent(); MusicManager.LoadContent(); PerformanceManager.LoadContent(); var gradientBackground = new GradientBackground(this); var level = BackgroundLevel.Level1; gradientBackground.ChangeGradientColors(GameConfig.BackgroundGradients[level].Item1, GameConfig.BackgroundGradients[level].Item2); SpriteBatchManager.Background = gradientBackground; } #if ANDROID public void OnDestroy() { Log.Debug("XmasHell", "Destroy"); } public void OnPause() { Log.Debug("XmasHell", "Pause"); } public void OnResume() { Log.Debug("XmasHell", "Resume"); } #endif protected override void UnloadContent() { SpriteBatchManager.UnloadContent(); } protected override void Update(GameTime gameTime) { PerformanceManager.StartStopwatch(PerformanceStopwatchType.GlobalFrame); PerformanceManager.StartStopwatch(PerformanceStopwatchType.GlobalUpdate); HandleKeyboardInputs(); base.Update(gameTime); if (Pause && !_computeNextFrame) return; MusicManager.Update(gameTime); Camera.Update(gameTime); ScreenManager.Update(gameTime); GuiManager.Update(gameTime); SpriteBatchManager.Update(gameTime); GameManager.Update(gameTime); PerformanceManager.StartStopwatch(PerformanceStopwatchType.PerformanceManagerUpdate); PerformanceManager.Update(gameTime); PerformanceManager.StopStopwatch(PerformanceStopwatchType.PerformanceManagerUpdate); PerformanceManager.StopStopwatch(PerformanceStopwatchType.GlobalUpdate); } private void HandleKeyboardInputs() { if (InputManager.KeyPressed(Keys.P)) Pause = !Pause; if (InputManager.KeyPressed(Keys.N)) _computeNextFrame = true; //if (InputManager.PressedCancel()) // ScreenManager.Back(); if (GameConfig.EnableBloom) { // Switch to the next bloom settings preset? if (InputManager.KeyPressed(Keys.C)) { SpriteBatchManager.BloomSettingsIndex = (SpriteBatchManager.BloomSettingsIndex + 1) % BloomSettings.PresetSettings.Length; SpriteBatchManager.Bloom.Settings = BloomSettings.PresetSettings[SpriteBatchManager.BloomSettingsIndex]; } // Cycle through the intermediate buffer debug display modes? if (InputManager.KeyPressed(Keys.X)) { SpriteBatchManager.Bloom.ShowBuffer++; if (SpriteBatchManager.Bloom.ShowBuffer > Bloom.IntermediateBuffer.FinalResult) SpriteBatchManager.Bloom.ShowBuffer = 0; } } if (InputManager.KeyPressed(Keys.F10)) { Graphics.IsFullScreen = !Graphics.IsFullScreen; if (Graphics.IsFullScreen) { Graphics.PreferredBackBufferWidth = GameConfig.VirtualResolution.X; Graphics.PreferredBackBufferHeight = GameConfig.VirtualResolution.Y; IsMouseVisible = true; Window.AllowUserResizing = false; } else { Graphics.PreferredBackBufferWidth = 480; Graphics.PreferredBackBufferHeight = 853; IsMouseVisible = true; Window.AllowUserResizing = true; } Graphics.ApplyChanges(); } // Debug if (InputManager.KeyPressed(Keys.F1)) GameConfig.GodMode = !GameConfig.GodMode; else if (InputManager.KeyPressed(Keys.F2)) GameConfig.DebugPhysics = !GameConfig.DebugPhysics; else if (InputManager.KeyPressed(Keys.F3)) GameConfig.DisableCollision = !GameConfig.DisableCollision; else if (InputManager.KeyPressed(Keys.F4)) GameConfig.EnableBloom = !GameConfig.EnableBloom; else if (InputManager.KeyPressed(Keys.F5)) GameConfig.ShowPerformanceInfo = !GameConfig.ShowPerformanceInfo; else if (InputManager.KeyPressed(Keys.F6)) GameConfig.ShowPerformanceGraph = !GameConfig.ShowPerformanceGraph; } protected override void Draw(GameTime gameTime) { PerformanceManager.StartStopwatch(PerformanceStopwatchType.GlobalDraw); PerformanceManager.StartStopwatch(PerformanceStopwatchType.ClearColorDraw); GraphicsDevice.Clear(Color.CornflowerBlue); PerformanceManager.StopStopwatch(PerformanceStopwatchType.ClearColorDraw); PerformanceManager.StartStopwatch(PerformanceStopwatchType.SpriteBatchManagerDraw); SpriteBatchManager.Draw(SpriteBatch); PerformanceManager.StopStopwatch(PerformanceStopwatchType.SpriteBatchManagerDraw); base.Draw(gameTime); if (GameConfig.DebugPhysics) GameManager.CollisionWorld.Draw(); PerformanceManager.StartStopwatch(PerformanceStopwatchType.PerformanceManagerDraw); PerformanceManager.Draw(gameTime); PerformanceManager.StopStopwatch(PerformanceStopwatchType.PerformanceManagerDraw); PerformanceManager.StopStopwatch(PerformanceStopwatchType.GlobalDraw); if (Pause) _computeNextFrame = false; PerformanceManager.StopStopwatch(PerformanceStopwatchType.GlobalFrame); } } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AllReady.Configuration; using AllReady.Constants; using AllReady.Controllers; using AllReady.Extensions; using AllReady.Features.Admin; using AllReady.Features.Manage; using AllReady.Models; using AllReady.UnitTest.Extensions; using AllReady.ViewModels.Account; using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using Moq; using Xunit; using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.AspNetCore.Mvc.Rendering; namespace AllReady.UnitTest.Controllers { public class AdminControllerTests { [Fact] public void RegisterReturnsViewResult() { var sut = CreateAdminControllerWithNoInjectedDependencies(); var result = sut.Register(); Assert.IsType<ViewResult>(result); } [Fact] public void RegisterHasHttpGetAttribute() { var sut = CreateAdminControllerWithNoInjectedDependencies(); var attribute = sut.GetAttributesOn(x => x.Register()).OfType<HttpGetAttribute>().SingleOrDefault(); Assert.NotNull(attribute); } [Fact] public void RegisterHasAllowAnonymousAttribute() { var sut = CreateAdminControllerWithNoInjectedDependencies(); var attribute = sut.GetAttributesOn(x => x.Register()).OfType<AllowAnonymousAttribute>().SingleOrDefault(); Assert.NotNull(attribute); } [Fact] public async Task RegisterReturnsViewResultWhenModelStateIsNotValid() { var sut = CreateAdminControllerWithNoInjectedDependencies(); sut.AddModelStateError(); var result = await sut.Register(It.IsAny<RegisterViewModel>()); Assert.IsType<ViewResult>(result); } [Fact] public async Task RegisterReturnsCorrectModelWhenModelStateIsNotValid() { var model = new RegisterViewModel(); var sut = CreateAdminControllerWithNoInjectedDependencies(); sut.AddModelStateError(); var result = await sut.Register(model) as ViewResult; var modelResult = result.ViewData.Model as RegisterViewModel; Assert.IsType<RegisterViewModel>(modelResult); Assert.Same(model, modelResult); } [Fact] public async Task RegisterInvokesCreateAsyncWithCorrectUserAndPassword() { const string defaultTimeZone = "DefaultTimeZone"; var model = new RegisterViewModel { Email = "email", Password = "Password" }; var generalSettings = new Mock<IOptions<GeneralSettings>>(); generalSettings.Setup(x => x.Value).Returns(new GeneralSettings { DefaultTimeZone = defaultTimeZone }); var userManager = UserManagerMockHelper.CreateUserManagerMock(); userManager.Setup(x => x.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync(IdentityResult.Failed()); var sut = new AdminController(userManager.Object, null, null, null, generalSettings.Object); await sut.Register(model); userManager.Verify(x => x.CreateAsync(It.Is<ApplicationUser>(au => au.UserName == model.Email && au.Email == model.Email && au.TimeZoneId == defaultTimeZone), model.Password)); } [Fact] public async Task RegisterInvokesGenerateEmailConfirmationTokenAsyncWithCorrectUserWhenUserCreationIsSuccessful() { const string defaultTimeZone = "DefaultTimeZone"; var model = new RegisterViewModel { Email = "email", Password = "Password" }; var generalSettings = new Mock<IOptions<GeneralSettings>>(); generalSettings.Setup(x => x.Value).Returns(new GeneralSettings { DefaultTimeZone = defaultTimeZone }); var userManager = UserManagerMockHelper.CreateUserManagerMock(); userManager.Setup(x => x.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync(IdentityResult.Success); var sut = new AdminController(userManager.Object, null, Mock.Of<IMediator>(), null, generalSettings.Object); sut.SetFakeHttpRequestSchemeTo(It.IsAny<string>()); sut.Url = Mock.Of<IUrlHelper>(); await sut.Register(model); userManager.Verify(x => x.GenerateEmailConfirmationTokenAsync(It.Is<ApplicationUser>(au => au.UserName == model.Email && au.Email == model.Email && au.TimeZoneId == defaultTimeZone))); } [Fact] public async Task RegisterInvokesUrlActionWithCorrectParametersWhenUserCreationIsSuccessful() { const string requestScheme = "requestScheme"; var generalSettings = new Mock<IOptions<GeneralSettings>>(); generalSettings.Setup(x => x.Value).Returns(new GeneralSettings()); var userManager = UserManagerMockHelper.CreateUserManagerMock(); userManager.Setup(x => x.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync(IdentityResult.Success); userManager.Setup(x => x.GenerateEmailConfirmationTokenAsync(It.IsAny<ApplicationUser>())).ReturnsAsync(It.IsAny<string>()); var sut = new AdminController(userManager.Object, null, Mock.Of<IMediator>(), null, generalSettings.Object); sut.SetFakeHttpRequestSchemeTo(requestScheme); var urlHelper = new Mock<IUrlHelper>(); sut.Url = urlHelper.Object; await sut.Register(new RegisterViewModel()); //note: I can't test the Values part here b/c I do not have control over the Id generation (which is a guid represented as as string) on ApplicationUser b/c it's new'ed up in the controller urlHelper.Verify(mock => mock.Action(It.Is<UrlActionContext>(uac => uac.Action == "ConfirmEmail" && uac.Controller == ControllerNames.Admin && uac.Protocol == requestScheme)), Times.Once); } [Fact] public async Task RegisterSendsSendConfirmAccountEmailWithCorrectDataWhenUserCreationIsSuccessful() { const string callbackUrl = "callbackUrl"; var model = new RegisterViewModel { Email = "email" }; var generalSettings = new Mock<IOptions<GeneralSettings>>(); generalSettings.Setup(x => x.Value).Returns(new GeneralSettings()); var userManager = UserManagerMockHelper.CreateUserManagerMock(); userManager.Setup(x => x.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync(IdentityResult.Success); userManager.Setup(x => x.GenerateEmailConfirmationTokenAsync(It.IsAny<ApplicationUser>())).ReturnsAsync(It.IsAny<string>()); var urlHelper = new Mock<IUrlHelper>(); urlHelper.Setup(x => x.Action(It.IsAny<UrlActionContext>())).Returns(callbackUrl); var mediator = new Mock<IMediator>(); var sut = new AdminController(userManager.Object, null, mediator.Object, null, generalSettings.Object); sut.SetFakeHttpRequestSchemeTo(It.IsAny<string>()); sut.Url = urlHelper.Object; await sut.Register(model); mediator.Verify(x => x.SendAsync(It.Is<SendConfirmAccountEmail>(y => y.Email == model.Email && y.CallbackUrl == callbackUrl))); } [Fact] public async Task RegisterRedirectsToCorrectActionWhenUserCreationIsSuccessful() { var generalSettings = new Mock<IOptions<GeneralSettings>>(); generalSettings.Setup(x => x.Value).Returns(new GeneralSettings()); var userManager = UserManagerMockHelper.CreateUserManagerMock(); userManager.Setup(x => x.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync((IdentityResult.Success)); userManager.Setup(x => x.GenerateEmailConfirmationTokenAsync(It.IsAny<ApplicationUser>())).ReturnsAsync(It.IsAny<string>()); var urlHelper = new Mock<IUrlHelper>(); urlHelper.Setup(x => x.Action(It.IsAny<UrlActionContext>())).Returns(It.IsAny<string>()); var sut = new AdminController(userManager.Object, null, Mock.Of<IMediator>(), null, generalSettings.Object); sut.SetFakeHttpRequestSchemeTo(It.IsAny<string>()); sut.Url = urlHelper.Object; var result = await sut.Register(new RegisterViewModel()) as RedirectToActionResult; Assert.Equal(nameof(AdminController.DisplayEmail), result.ActionName); Assert.Equal(ControllerNames.Admin, result.ControllerName); } [Fact] public async Task RegisterAddsIdentityResultErrorsToModelStateErrorsWhenUserCreationIsNotSuccessful() { var generalSettings = new Mock<IOptions<GeneralSettings>>(); generalSettings.Setup(x => x.Value).Returns(new GeneralSettings()); var identityResult = IdentityResult.Failed(new IdentityError { Description = "IdentityErrorDescription" }); var userManager = UserManagerMockHelper.CreateUserManagerMock(); userManager.Setup(x => x.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync(identityResult); var sut = new AdminController(userManager.Object, null, null, null, generalSettings.Object); sut.SetFakeHttpRequestSchemeTo(It.IsAny<string>()); await sut.Register(new RegisterViewModel()); var errorMessages = sut.ModelState.GetErrorMessages(); Assert.Equal(errorMessages.Single(), identityResult.Errors.Select(x => x.Description).Single()); } [Fact] public async Task RegisterReturnsViewResultAndCorrectModelWhenUserCreationIsNotSuccessful() { var model = new RegisterViewModel(); var generalSettings = new Mock<IOptions<GeneralSettings>>(); generalSettings.Setup(x => x.Value).Returns(new GeneralSettings()); var userManager = UserManagerMockHelper.CreateUserManagerMock(); userManager.Setup(x => x.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync(IdentityResult.Failed()); var sut = new AdminController(userManager.Object, null, null, null, generalSettings.Object); sut.SetFakeHttpRequestSchemeTo(It.IsAny<string>()); var result = await sut.Register(model) as ViewResult; var modelResult = result.ViewData.Model as RegisterViewModel; Assert.IsType<ViewResult>(result); Assert.IsType<RegisterViewModel>(modelResult); Assert.Same(model, modelResult); } [Fact] public void DisplayEmailReturnsViewResult() { var sut = CreateAdminControllerWithNoInjectedDependencies(); var result = sut.DisplayEmail(); Assert.IsType<ViewResult>(result); } [Fact] public void DisplayEmailHasHttpGetAttribute() { var sut = CreateAdminControllerWithNoInjectedDependencies(); var attribute = sut.GetAttributesOn(x => x.DisplayEmail()).OfType<HttpGetAttribute>().SingleOrDefault(); Assert.NotNull(attribute); } [Fact] public void DisplayEmailHasAllowAnonymousAttribute() { var sut = CreateAdminControllerWithNoInjectedDependencies(); var attribute = sut.GetAttributesOn(x => x.DisplayEmail()).OfType<AllowAnonymousAttribute>().SingleOrDefault(); Assert.NotNull(attribute); } [Fact] public async Task ConfirmEmailReturnsErrorWhenCodeIsNull() { var sut = CreateAdminControllerWithNoInjectedDependencies(); var result = await sut.ConfirmEmail(null, null) as ViewResult; Assert.Equal("Error", result.ViewName); } [Fact] public async Task ConfirmEmailReturnsErrorWhenCannotFindUserByUserId() { var userManager = UserManagerMockHelper.CreateUserManagerMock(); var sut = new AdminController(userManager.Object, null, null, null, null); var result = await sut.ConfirmEmail(null, "code") as ViewResult; Assert.Equal("Error", result.ViewName); } [Fact] public async Task ConfirmEmailInvokesFindByIdAsyncWithCorrectUserId() { const string userId = "userId"; var userManager = UserManagerMockHelper.CreateUserManagerMock(); var sut = new AdminController(userManager.Object, null, null, null, null); await sut.ConfirmEmail(userId, "code"); userManager.Verify(x => x.FindByIdAsync(userId), Times.Once); } [Fact] public async Task ConfirmEmailInvokesConfirmEmailAsyncWithCorrectUserAndCode() { const string code = "code"; var user = new ApplicationUser(); var userManager = UserManagerMockHelper.CreateUserManagerMock(); userManager.Setup(x => x.FindByIdAsync(It.IsAny<string>())).ReturnsAsync(user); userManager.Setup(x => x.ConfirmEmailAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync(IdentityResult.Failed()); var sut = new AdminController(userManager.Object, null, null, null, null); await sut.ConfirmEmail(null, code); userManager.Verify(x => x.ConfirmEmailAsync(user, code), Times.Once); } [Fact] public async Task ConfirmEmailInvokesUrlActionWithCorrectParametersWhenUsersEmailIsConfirmedSuccessfully() { const string requestScheme = "requestScheme"; const string userId = "1"; var userManager = UserManagerMockHelper.CreateUserManagerMock(); userManager.Setup(x => x.FindByIdAsync(It.IsAny<string>())).ReturnsAsync(new ApplicationUser { Id = userId }); userManager.Setup(x => x.ConfirmEmailAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync(IdentityResult.Success); var settings = new Mock<IOptions<SampleDataSettings>>(); settings.Setup(x => x.Value).Returns(new SampleDataSettings()); var urlHelper = new Mock<IUrlHelper>(); var sut = new AdminController(userManager.Object, null, Mock.Of<IMediator>(), settings.Object, null); sut.SetFakeHttpRequestSchemeTo(requestScheme); sut.Url = urlHelper.Object; await sut.ConfirmEmail(It.IsAny<string>(), "code"); urlHelper.Verify(x => x.Action(It.Is<UrlActionContext>(uac => uac.Action == "EditUser" && uac.Controller == "Site" && uac.Protocol == requestScheme && uac.Values.ToString() == $"{{ area = Admin, userId = {userId} }}")), Times.Once); } [Fact] public async Task ConfirmEmailSendsSendApproveOrganizationUserAccountEmailWithCorrectDataWhenUsersEmailIsConfirmedSuccessfully() { const string defaultAdminUserName = "requestScheme"; const string callbackUrl = "callbackUrl"; var userManager = UserManagerMockHelper.CreateUserManagerMock(); userManager.Setup(x => x.FindByIdAsync(It.IsAny<string>())).ReturnsAsync(new ApplicationUser()); userManager.Setup(x => x.ConfirmEmailAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync(IdentityResult.Success); var settings = new Mock<IOptions<SampleDataSettings>>(); settings.Setup(x => x.Value).Returns(new SampleDataSettings { DefaultAdminUsername = defaultAdminUserName }); var urlHelper = new Mock<IUrlHelper>(); urlHelper.Setup(x => x.Action(It.IsAny<UrlActionContext>())).Returns(callbackUrl); var mediator = new Mock<IMediator>(); var sut = new AdminController(userManager.Object, null, mediator.Object, settings.Object, null); sut.SetFakeHttpRequestSchemeTo(It.IsAny<string>()); sut.Url = urlHelper.Object; await sut.ConfirmEmail(It.IsAny<string>(), "code"); mediator.Verify(x => x.SendAsync(It.Is<SendApproveOrganizationUserAccountEmail>(y => y.DefaultAdminUsername == defaultAdminUserName && y.CallbackUrl == callbackUrl))); } [Fact] public async Task ConfirmEmailReturnsCorrectViewWhenUsersConfirmationIsSuccessful() { var userManager = UserManagerMockHelper.CreateUserManagerMock(); userManager.Setup(x => x.FindByIdAsync(It.IsAny<string>())).ReturnsAsync(new ApplicationUser()); userManager.Setup(x => x.ConfirmEmailAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync(IdentityResult.Success); var urlHelper = new Mock<IUrlHelper>(); urlHelper.Setup(x => x.Action(It.IsAny<UrlActionContext>())).Returns(It.IsAny<string>()); var settings = new Mock<IOptions<SampleDataSettings>>(); settings.Setup(x => x.Value).Returns(new SampleDataSettings { DefaultAdminUsername = It.IsAny<string>() }); var sut = new AdminController(userManager.Object, null, Mock.Of<IMediator>(), settings.Object, null); sut.SetFakeHttpRequestSchemeTo(It.IsAny<string>()); sut.Url = urlHelper.Object; var result = await sut.ConfirmEmail("userId", "code") as ViewResult; Assert.Equal("ConfirmEmail", result.ViewName); } [Fact] public async Task ConfirmEmailReturnsCorrectViewWhenUsersConfirmationIsUnsuccessful() { var userManager = UserManagerMockHelper.CreateUserManagerMock(); userManager.Setup(x => x.FindByIdAsync(It.IsAny<string>())).ReturnsAsync(new ApplicationUser()); userManager.Setup(x => x.ConfirmEmailAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync(IdentityResult.Failed()); var sut = new AdminController(userManager.Object, null, null, null, null); var result = await sut.ConfirmEmail("userId", "code") as ViewResult; Assert.Equal("Error", result.ViewName); } [Fact] public void ConfirmEmailHasHttpGetAttribute() { var sut = CreateAdminControllerWithNoInjectedDependencies(); var attribute = sut.GetAttributesOn(x => x.ConfirmEmail(It.IsAny<string>(), It.IsAny<string>())).OfType<HttpGetAttribute>().SingleOrDefault(); Assert.NotNull(attribute); } [Fact] public void ConfirmEmailHasAllowAnonymousAttribute() { var sut = CreateAdminControllerWithNoInjectedDependencies(); var attribute = sut.GetAttributesOn(x => x.ConfirmEmail(It.IsAny<string>(), It.IsAny<string>())).OfType<AllowAnonymousAttribute>().SingleOrDefault(); Assert.NotNull(attribute); } [Fact] public async Task SendCodeGetInvokesGetTwoFactorAuthenticationUserAsync() { var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(); var sut = new AdminController(null, signInManager.Object, null, null, null); await sut.SendCode(It.IsAny<string>(), It.IsAny<bool>()); signInManager.Verify(x => x.GetTwoFactorAuthenticationUserAsync(), Times.Once); } [Fact] public async Task SendCodeGetReturnsErrorViewWhenCannotFindUser() { var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(); var sut = new AdminController(null, signInManager.Object, null, null, null); var result = await sut.SendCode(null, It.IsAny<bool>()) as ViewResult; Assert.Equal("Error", result.ViewName); } [Fact] public async Task SendCodeGetInvokesGetValidTwoFactorProvidersAsyncWithCorrectUser() { var applicationUser = new ApplicationUser(); var userManager = UserManagerMockHelper.CreateUserManagerMock(); var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(userManager); signInManager.Setup(x => x.GetTwoFactorAuthenticationUserAsync()).ReturnsAsync(applicationUser); userManager.Setup(x => x.GetValidTwoFactorProvidersAsync(It.IsAny<ApplicationUser>())).ReturnsAsync(new List<string>()); var sut = new AdminController(userManager.Object, signInManager.Object, null, null, null); await sut.SendCode(null, It.IsAny<bool>()); userManager.Verify(x => x.GetValidTwoFactorProvidersAsync(applicationUser), Times.Once); } [Fact] public async Task SendCodeGetReturnsSendCodeViewModelWithCorrectData() { const string returnUrl = "returnUrl"; const bool rememberMe = true; var userFactors = new List<string> { "userFactor1", "userFactor2" }; var expectedProviders = userFactors.Select(factor => new SelectListItem { Text = factor, Value = factor }).ToList(); var userManager = UserManagerMockHelper.CreateUserManagerMock(); var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(userManager); signInManager.Setup(x => x.GetTwoFactorAuthenticationUserAsync()).ReturnsAsync(new ApplicationUser()); userManager.Setup(x => x.GetValidTwoFactorProvidersAsync(It.IsAny<ApplicationUser>())).ReturnsAsync(userFactors); var sut = new AdminController(userManager.Object, signInManager.Object, null, null, null); var result = await sut.SendCode(returnUrl, rememberMe) as ViewResult; var modelResult = result.ViewData.Model as SendCodeViewModel; Assert.Equal(modelResult.ReturnUrl, returnUrl); Assert.Equal(modelResult.RememberMe, rememberMe); Assert.Equal(expectedProviders, modelResult.Providers, new SelectListItemComparer()); } [Fact] public void SendCodeGetHasHttpGetAttribute() { var sut = CreateAdminControllerWithNoInjectedDependencies(); var attribute = sut.GetAttributesOn(x => x.SendCode(It.IsAny<string>(), It.IsAny<bool>())).OfType<HttpGetAttribute>().SingleOrDefault(); Assert.NotNull(attribute); } [Fact] public void SendCodeGetHasAllowAnonymousAttribute() { var sut = CreateAdminControllerWithNoInjectedDependencies(); var attribute = sut.GetAttributesOn(x => x.SendCode(It.IsAny<string>(), It.IsAny<bool>())).OfType<AllowAnonymousAttribute>().SingleOrDefault(); Assert.NotNull(attribute); } [Fact] public async Task SendCodePostWithInvalidModelStateReturnsView() { var sut = CreateAdminControllerWithNoInjectedDependencies(); sut.AddModelStateError(); var result = await sut.SendCode(It.IsAny<SendCodeViewModel>()); Assert.IsType<ViewResult>(result); } [Fact] public async Task SendCodePostInvokesGetTwoFactorAuthenticationUserAsync() { var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(); var sut = new AdminController(null, signInManager.Object, null, null, null); await sut.SendCode(It.IsAny<SendCodeViewModel>()); signInManager.Verify(x => x.GetTwoFactorAuthenticationUserAsync(), Times.Once); } [Fact] public async Task SendCodePosReturnsErrorViewWhenUserIsNotFound() { var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(); var sut = new AdminController(null, signInManager.Object, null, null, null); var result = await sut.SendCode(It.IsAny<SendCodeViewModel>()) as ViewResult; Assert.Equal("Error", result.ViewName); } [Fact] public async Task SendCodePostInvokesGenerateTwoFactorTokenAsyncWithCorrectUserAndTokenProvider() { var applicationUser = new ApplicationUser(); var model = new SendCodeViewModel { SelectedProvider = "Email" }; var userManager = UserManagerMockHelper.CreateUserManagerMock(); var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(userManager); signInManager.Setup(x => x.GetTwoFactorAuthenticationUserAsync()).ReturnsAsync(applicationUser); var sut = new AdminController(userManager.Object, signInManager.Object, null, null, null); await sut.SendCode(model); userManager.Verify(x => x.GenerateTwoFactorTokenAsync(applicationUser, model.SelectedProvider), Times.Once); } [Fact] public async Task SendCodePostReturnsErrorViewWhenAuthenticationTokenIsNull() { var userManager = UserManagerMockHelper.CreateUserManagerMock(); var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(userManager); signInManager.Setup(x => x.GetTwoFactorAuthenticationUserAsync()).ReturnsAsync(new ApplicationUser()); var sut = new AdminController(userManager.Object, signInManager.Object, null, null, null); var result = await sut.SendCode(new SendCodeViewModel()) as ViewResult; Assert.Equal("Error", result.ViewName); } [Fact] public async Task SendCodePostSendsSendSecurityCodeEmailWithCorrectDataWhenSelectedProviderIsEmail() { const string token = "token"; const string usersEmailAddress = "usersEmailAddress"; var applicationUser = new ApplicationUser(); var model = new SendCodeViewModel { SelectedProvider = "Email" }; var userManager = UserManagerMockHelper.CreateUserManagerMock(); var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(userManager); var mediator = new Mock<IMediator>(); userManager.Setup(x => x.GenerateTwoFactorTokenAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync(token); userManager.Setup(x => x.GetEmailAsync(applicationUser)).ReturnsAsync(usersEmailAddress); signInManager.Setup(x => x.GetTwoFactorAuthenticationUserAsync()).ReturnsAsync(applicationUser); var sut = new AdminController(userManager.Object, signInManager.Object, mediator.Object, null, null); await sut.SendCode(model); mediator.Verify(x => x.SendAsync(It.Is<SendSecurityCodeEmail>(y => y.Email == usersEmailAddress && y.Token == token))); } [Fact] public async Task SendCodePostSendsSendSecurityCodeSmsWithCorrectDataWhenSelectedProviderIsPhone() { const string token = "token"; const string usersPhoneNumber = "usersPhoneNumber"; var applicationUser = new ApplicationUser(); var model = new SendCodeViewModel { SelectedProvider = "Phone" }; var userManager = UserManagerMockHelper.CreateUserManagerMock(); var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(userManager); var mediator = new Mock<IMediator>(); userManager.Setup(x => x.GenerateTwoFactorTokenAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync(token); userManager.Setup(x => x.GetPhoneNumberAsync(applicationUser)).ReturnsAsync(usersPhoneNumber); signInManager.Setup(x => x.GetTwoFactorAuthenticationUserAsync()).ReturnsAsync(applicationUser); var sut = new AdminController(userManager.Object, signInManager.Object, mediator.Object, null, null); await sut.SendCode(model); mediator.Verify(x => x.SendAsync(It.Is<SendAccountSecurityTokenSms>(y => y.PhoneNumber == usersPhoneNumber && y.Token == token))); } [Fact] public async Task SendCodePostReturnsRedirectToActionResult() { var model = new SendCodeViewModel { SelectedProvider = string.Empty, ReturnUrl = "ReturnUrl", RememberMe = true }; var routeValues = new Dictionary<string, object> { ["Provider"] = model.SelectedProvider, ["ReturnUrl"] = model.ReturnUrl, ["RememberMe"] = model.RememberMe }; var userManager = UserManagerMockHelper.CreateUserManagerMock(); var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(userManager); signInManager.Setup(x => x.GetTwoFactorAuthenticationUserAsync()).ReturnsAsync(new ApplicationUser()); userManager.Setup(x => x.GenerateTwoFactorTokenAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())).ReturnsAsync("token"); var sut = new AdminController(userManager.Object, signInManager.Object, null, null, null); var result = await sut.SendCode(model) as RedirectToActionResult; Assert.Equal(nameof(AdminController.VerifyCode), result.ActionName); Assert.Equal(result.RouteValues, routeValues); } [Fact] public void SendCodePostGetHasHttpPostAttribute() { var sut = CreateAdminControllerWithNoInjectedDependencies(); var attribute = sut.GetAttributesOn(x => x.SendCode(It.IsAny<SendCodeViewModel>())).OfType<HttpPostAttribute>().SingleOrDefault(); Assert.NotNull(attribute); } [Fact] public void SendCodePostHasAllowAnonymousAttribute() { var sut = CreateAdminControllerWithNoInjectedDependencies(); var attribute = sut.GetAttributesOn(x => x.SendCode(It.IsAny<SendCodeViewModel>())).OfType<AllowAnonymousAttribute>().SingleOrDefault(); Assert.NotNull(attribute); } [Fact] public void SendCodePostHasValidateAntiForgeryTokenAttribute() { var sut = CreateAdminControllerWithNoInjectedDependencies(); var attribute = sut.GetAttributesOn(x => x.SendCode(It.IsAny<SendCodeViewModel>())).OfType<ValidateAntiForgeryTokenAttribute>().SingleOrDefault(); Assert.NotNull(attribute); } [Fact] public async Task VerifyCodeGetInvokesGetTwoFactorAuthenticationUserAsync() { var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(); var sut = new AdminController(null, signInManager.Object, null, null, null); await sut.VerifyCode(It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<string>()); signInManager.Verify(x => x.GetTwoFactorAuthenticationUserAsync(), Times.Once); } [Fact] public async Task VerifyCodeGetReturnsErrorViewWhenUserIsNull() { var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(); var sut = new AdminController(null, signInManager.Object, null, null, null); var result = await sut.VerifyCode(It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<string>()) as ViewResult; Assert.Equal("Error", result.ViewName); } [Fact] public async Task VerifyCodeGetReturnsCorrectViewModel() { const string provider = "provider"; const bool rememberMe = true; const string returnUrl = "returnUrl"; var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(); signInManager.Setup(x => x.GetTwoFactorAuthenticationUserAsync()).ReturnsAsync(new ApplicationUser()); var sut = new AdminController(null, signInManager.Object, null, null, null); var result = await sut.VerifyCode(provider, rememberMe, returnUrl) as ViewResult; var modelResult = result.ViewData.Model as VerifyCodeViewModel; Assert.Equal(modelResult.Provider, provider); Assert.Equal(modelResult.ReturnUrl, returnUrl); Assert.Equal(modelResult.RememberMe, rememberMe); } [Fact] public void VerifyCodeGetHasAllowAnonymousAttribute() { var sut = CreateAdminControllerWithNoInjectedDependencies(); var attribute = sut.GetAttributesOn(x => x.VerifyCode(It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<string>())).OfType<AllowAnonymousAttribute>().SingleOrDefault(); Assert.NotNull(attribute); } [Fact] public void VerifyCodeGetHasHttpGetAttribute() { var sut = CreateAdminControllerWithNoInjectedDependencies(); var attribute = sut.GetAttributesOn(x => x.VerifyCode(It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<string>())).OfType<HttpGetAttribute>().SingleOrDefault(); Assert.NotNull(attribute); } [Fact] public async Task VerifyCodePostReturnsReturnsCorrectViewAndCorrectModelWhenModelStateIsInvalid() { var sut = CreateAdminControllerWithNoInjectedDependencies(); sut.AddModelStateError(); var result = await sut.VerifyCode(new VerifyCodeViewModel()) as ViewResult; var modelResult = result.ViewData.Model as VerifyCodeViewModel; Assert.IsType<ViewResult>(result); Assert.IsType<VerifyCodeViewModel>(modelResult); } [Fact] public async Task VerifyCodePostInvokesTwoFactorSignInAsyncWithCorrectParameters() { var model = new VerifyCodeViewModel { Provider = "provider", Code = "code", RememberBrowser = true, RememberMe = true }; var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(); signInManager.Setup(x => x.TwoFactorSignInAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<bool>())).ReturnsAsync(new Microsoft.AspNetCore.Identity.SignInResult()); var sut = new AdminController(null, signInManager.Object, null, null, null); await sut.VerifyCode(model); signInManager.Verify(x => x.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser)); } [Fact] public async Task VerifyCodePostAddsErrorMessageToModelStateErrorWhenTwoFactorSignInAsyncIsNotSuccessful() { var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(); signInManager.Setup(x => x.TwoFactorSignInAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<bool>())).ReturnsAsync(new Microsoft.AspNetCore.Identity.SignInResult()); var sut = new AdminController(null, signInManager.Object, null, null, null); await sut.VerifyCode(new VerifyCodeViewModel()); var errorMessage = sut.ModelState.GetErrorMessages().Single(); Assert.Equal("Invalid code.", errorMessage); } [Fact] public async Task VerifyCodePostReturnsLockoutViewIfTwoFactorSignInAsyncFailsAndIsLockedOut() { var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(); signInManager.Setup(x => x.TwoFactorSignInAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<bool>())).ReturnsAsync(Microsoft.AspNetCore.Identity.SignInResult.LockedOut); var sut = new AdminController(null, signInManager.Object, null, null, null); var result = await sut.VerifyCode(new VerifyCodeViewModel()) as ViewResult; Assert.Equal("Lockout", result.ViewName); } [Fact] public async Task VerifyCodePostRedirectsToReturnUrlWhenTwoFactorSignInAsyncSucceedsAndReturnUrlIsLocalUrl() { var model = new VerifyCodeViewModel { ReturnUrl = "returnUrl" }; var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(); signInManager.Setup(x => x.TwoFactorSignInAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<bool>())).ReturnsAsync(Microsoft.AspNetCore.Identity.SignInResult.Success); var urlHelper = new Mock<IUrlHelper>(); urlHelper.Setup(x => x.IsLocalUrl(model.ReturnUrl)).Returns(true); var sut = new AdminController(null, signInManager.Object, null, null, null) { Url = urlHelper.Object }; var result = await sut.VerifyCode(model) as RedirectResult; Assert.Equal(result.Url, model.ReturnUrl); } [Fact] public async Task VerifyCodePostRedirectsToHomeControllerIndexWhenTwoFactorSignInAsyncSucceedsAndReturnUrlIsNotLocalUrl() { var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(); signInManager.Setup(x => x.TwoFactorSignInAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<bool>())) .ReturnsAsync(Microsoft.AspNetCore.Identity.SignInResult.Success); var urlHelper = new Mock<IUrlHelper>(); urlHelper.Setup(x => x.IsLocalUrl(It.IsAny<string>())).Returns(false); var sut = new AdminController(null, signInManager.Object, null, null, null) { Url = urlHelper.Object }; var result = await sut.VerifyCode(new VerifyCodeViewModel()) as RedirectToPageResult; Assert.Equal(result.PageName, "/Index"); } [Fact] public void VerifyCodePostHasAllowAnonymousAttribute() { var sut = CreateAdminControllerWithNoInjectedDependencies(); var attribute = sut.GetAttributesOn(x => x.VerifyCode(It.IsAny<VerifyCodeViewModel>())).OfType<AllowAnonymousAttribute>().SingleOrDefault(); Assert.NotNull(attribute); } [Fact] public void VerifyCodePostHasHttpPostAttribute() { var sut = CreateAdminControllerWithNoInjectedDependencies(); var attribute = sut.GetAttributesOn(x => x.VerifyCode(It.IsAny<VerifyCodeViewModel>())).OfType<HttpPostAttribute>().SingleOrDefault(); Assert.NotNull(attribute); } [Fact] public void VerifyCodePostHasValidateAntiForgeryTokenAttribute() { var sut = CreateAdminControllerWithNoInjectedDependencies(); var attribute = sut.GetAttributesOn(x => x.VerifyCode(It.IsAny<VerifyCodeViewModel>())).OfType<ValidateAntiForgeryTokenAttribute>().SingleOrDefault(); Assert.NotNull(attribute); } private static AdminController CreateAdminControllerWithNoInjectedDependencies() => new AdminController(null, null, null, null, null); } }
//----------------------------------------------------------------------- // <copyright file="ItemProperties.Designer.cs" company="None"> // Copyright (c) Brandon Wallace and Jesse Calhoun. All rights reserved. // </copyright> //----------------------------------------------------------------------- using TQVaultAE.GUI.Components; using TQVaultAE.Presentation; namespace TQVaultAE.GUI { /// <summary> /// ItemProperties form designer class /// </summary> internal partial class ItemProperties { /// <summary> /// OK Button control /// </summary> private ScalingButton ok; /// <summary> /// WebBrowser1 for first attribute set /// </summary> private System.Windows.Forms.WebBrowser webBrowser1; /// <summary> /// Item Name for the header /// </summary> private System.Windows.Forms.WebBrowser itemName; /// <summary> /// WebBrowser2 for the second attribute set /// </summary> private System.Windows.Forms.WebBrowser webBrowser2; /// <summary> /// Label1 control /// </summary> private ScalingLabel label1; /// <summary> /// Label2 control /// </summary> private ScalingLabel label2; /// <summary> /// Checkbox1 used to turn on and off extended values /// </summary> private ScalingCheckBox checkBox1; /// <summary> /// WebBrowser3 for the third attribute set /// </summary> private System.Windows.Forms.WebBrowser webBrowser3; /// <summary> /// label3 control /// </summary> private ScalingLabel label3; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (this.components != null)) { this.components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.ok = new TQVaultAE.GUI.Components.ScalingButton(); this.webBrowser1 = new System.Windows.Forms.WebBrowser(); this.itemName = new System.Windows.Forms.WebBrowser(); this.webBrowser2 = new System.Windows.Forms.WebBrowser(); this.label1 = new TQVaultAE.GUI.Components.ScalingLabel(); this.label2 = new TQVaultAE.GUI.Components.ScalingLabel(); this.checkBox1 = new TQVaultAE.GUI.Components.ScalingCheckBox(); this.webBrowser3 = new System.Windows.Forms.WebBrowser(); this.label3 = new TQVaultAE.GUI.Components.ScalingLabel(); this.SuspendLayout(); // // ok // this.ok.BackColor = System.Drawing.Color.Transparent; this.ok.DownBitmap = global::TQVaultAE.Presentation.Resources.MainButtonDown; this.ok.FlatAppearance.BorderSize = 0; this.ok.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28))))); this.ok.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28))))); this.ok.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.ok.Font = new System.Drawing.Font("Albertus MT Light", 12F); this.ok.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28))))); this.ok.Image = global::TQVaultAE.Presentation.Resources.MainButtonUp; this.ok.Location = new System.Drawing.Point(781, 419); this.ok.Name = "ok"; this.ok.OverBitmap = global::TQVaultAE.Presentation.Resources.MainButtonOver; this.ok.Size = new System.Drawing.Size(137, 30); this.ok.SizeToGraphic = false; this.ok.TabIndex = 0; this.ok.Text = "OK"; this.ok.UpBitmap = global::TQVaultAE.Presentation.Resources.MainButtonUp; this.ok.UseCustomGraphic = true; this.ok.UseVisualStyleBackColor = false; this.ok.Click += new System.EventHandler(this.OK_Button_Click); // // webBrowser1 // this.webBrowser1.AllowWebBrowserDrop = false; this.webBrowser1.IsWebBrowserContextMenuEnabled = false; this.webBrowser1.Location = new System.Drawing.Point(12, 123); this.webBrowser1.MinimumSize = new System.Drawing.Size(23, 22); this.webBrowser1.Name = "webBrowser1"; this.webBrowser1.Size = new System.Drawing.Size(292, 269); this.webBrowser1.TabIndex = 2; this.webBrowser1.TabStop = false; this.webBrowser1.WebBrowserShortcutsEnabled = false; // // itemName // this.itemName.AllowNavigation = false; this.itemName.IsWebBrowserContextMenuEnabled = false; this.itemName.Location = new System.Drawing.Point(15, 30); this.itemName.MinimumSize = new System.Drawing.Size(23, 22); this.itemName.Name = "itemName"; this.itemName.ScrollBarsEnabled = false; this.itemName.Size = new System.Drawing.Size(730, 39); this.itemName.TabIndex = 3; this.itemName.TabStop = false; this.itemName.WebBrowserShortcutsEnabled = false; this.itemName.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.ItemName_DocumentCompleted); // // webBrowser2 // this.webBrowser2.AllowWebBrowserDrop = false; this.webBrowser2.IsWebBrowserContextMenuEnabled = false; this.webBrowser2.Location = new System.Drawing.Point(327, 123); this.webBrowser2.MinimumSize = new System.Drawing.Size(23, 22); this.webBrowser2.Name = "webBrowser2"; this.webBrowser2.Size = new System.Drawing.Size(292, 269); this.webBrowser2.TabIndex = 4; this.webBrowser2.TabStop = false; this.webBrowser2.WebBrowserShortcutsEnabled = false; // // label1 // this.label1.AutoSize = true; this.label1.BackColor = System.Drawing.Color.Transparent; this.label1.Font = new System.Drawing.Font("Albertus MT Light", 11.25F); this.label1.Location = new System.Drawing.Point(324, 101); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(111, 17); this.label1.TabIndex = 5; this.label1.Text = "Prefix Properties"; // // label2 // this.label2.AutoSize = true; this.label2.BackColor = System.Drawing.Color.Transparent; this.label2.Font = new System.Drawing.Font("Albertus MT Light", 11.25F); this.label2.Location = new System.Drawing.Point(12, 101); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(136, 17); this.label2.TabIndex = 6; this.label2.Text = "Base Item Properties"; // // checkBox1 // this.checkBox1.AutoSize = true; this.checkBox1.BackColor = System.Drawing.Color.Transparent; this.checkBox1.Font = new System.Drawing.Font("Albertus MT Light", 11.25F); this.checkBox1.Location = new System.Drawing.Point(763, 42); this.checkBox1.Name = "checkBox1"; this.checkBox1.Size = new System.Drawing.Size(126, 21); this.checkBox1.TabIndex = 7; this.checkBox1.Text = "Filter Extra Info"; this.checkBox1.UseVisualStyleBackColor = false; this.checkBox1.CheckedChanged += new System.EventHandler(this.CheckBox1_CheckedChanged); // // webBrowser3 // this.webBrowser3.AllowWebBrowserDrop = false; this.webBrowser3.IsWebBrowserContextMenuEnabled = false; this.webBrowser3.Location = new System.Drawing.Point(655, 123); this.webBrowser3.MinimumSize = new System.Drawing.Size(20, 20); this.webBrowser3.Name = "webBrowser3"; this.webBrowser3.Size = new System.Drawing.Size(262, 269); this.webBrowser3.TabIndex = 8; this.webBrowser3.TabStop = false; this.webBrowser3.WebBrowserShortcutsEnabled = false; // // label3 // this.label3.AutoSize = true; this.label3.BackColor = System.Drawing.Color.Transparent; this.label3.Font = new System.Drawing.Font("Albertus MT Light", 11.25F); this.label3.Location = new System.Drawing.Point(655, 101); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(111, 17); this.label3.TabIndex = 9; this.label3.Text = "Suffix Properties"; // // ItemProperties // this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(46)))), ((int)(((byte)(31)))), ((int)(((byte)(21))))); this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.ClientSize = new System.Drawing.Size(944, 461); this.Controls.Add(this.label3); this.Controls.Add(this.webBrowser3); this.Controls.Add(this.checkBox1); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.webBrowser2); this.Controls.Add(this.itemName); this.Controls.Add(this.webBrowser1); this.Controls.Add(this.ok); this.DrawCustomBorder = true; this.Font = new System.Drawing.Font("Albertus MT Light", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.ForeColor = System.Drawing.Color.White; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ItemProperties"; this.ShowInTaskbar = false; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Item Properties"; this.TopMost = true; this.Load += new System.EventHandler(this.ItemProperties_Load); this.Controls.SetChildIndex(this.ok, 0); this.Controls.SetChildIndex(this.webBrowser1, 0); this.Controls.SetChildIndex(this.itemName, 0); this.Controls.SetChildIndex(this.webBrowser2, 0); this.Controls.SetChildIndex(this.label1, 0); this.Controls.SetChildIndex(this.label2, 0); this.Controls.SetChildIndex(this.checkBox1, 0); this.Controls.SetChildIndex(this.webBrowser3, 0); this.Controls.SetChildIndex(this.label3, 0); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
using System; using CocosSharp; using Random = CocosSharp.CCRandom; namespace tests.Extensions { class CCControlButtonTest_HelloVariableSize : CCControlScene { public CCControlButtonTest_HelloVariableSize() { CCSize screenSize = Layer.VisibleBoundsWorldspace.Size; // Defines an array of title to create buttons dynamically var stringArray = new[] { "Hello", "Variable", "Size", "!" }; CCNode layer = new CCNode (); AddChild(layer, 1); float total_width = 0, height = 0; // For each title in the array object pObj = null; int i = 0; foreach(var title in stringArray) { // Creates a button with this string as title var button = standardButtonWithTitle(title); if (i == 0) { button.Opacity = 50; button.Color = new CCColor3B(0, 255, 0); } else if (i == 1) { button.Opacity = 200; button.Color = new CCColor3B(0, 255, 0); } else if (i == 2) { button.Opacity = 100; button.Color = new CCColor3B(0, 0, 255); } button.Position = new CCPoint (total_width + button.ContentSize.Width / 2, button.ContentSize.Height / 2); layer.AddChild(button); // Compute the size of the layer height = button.ContentSize.Height; total_width += button.ContentSize.Width; i++; } layer.AnchorPoint = new CCPoint(0.5f, 0.5f); layer.ContentSize = new CCSize(total_width, height); layer.Position = new CCPoint(screenSize.Width / 2.0f, screenSize.Height / 2.0f); // Add the black background var background = new CCScale9SpriteFile("extensions/buttonBackground"); background.ContentSize = new CCSize(total_width + 14, height + 14); background.Position = new CCPoint(screenSize.Width / 2.0f, screenSize.Height / 2.0f); AddChild(background); } /** Creates and return a button with a default background and title color. */ public CCControlButton standardButtonWithTitle(string title) { /** Creates and return a button with a default background and title color. */ var backgroundButton = new CCScale9SpriteFile("extensions/button"); var backgroundHighlightedButton = new CCScale9SpriteFile("extensions/buttonHighlighted"); var titleButton = new CCLabelTtf(title, "Arial", 30); titleButton.Color = new CCColor3B(159, 168, 176); var button = new CCControlButton(titleButton, backgroundButton); button.SetBackgroundSpriteForState(backgroundHighlightedButton, CCControlState.Highlighted); button.SetTitleColorForState(CCColor3B.White, CCControlState.Highlighted); return button; } public new static CCScene sceneWithTitle(string title) { var pScene = new CCScene (AppDelegate.SharedWindow, AppDelegate.SharedViewport); var controlLayer = new CCControlButtonTest_HelloVariableSize(); controlLayer.getSceneTitleLabel().Text = (title); pScene.AddChild(controlLayer); return pScene; } } class CCControlButtonTest_Inset : CCControlScene { public CCControlButtonTest_Inset() { CCSize screenSize = Layer.VisibleBoundsWorldspace.Size; // Defines an array of title to create buttons dynamically var stringArray = new[] { "Inset", "Inset", "Inset" }; CCNode layer = new CCNode (); AddChild(layer, 1); float total_width = 0, height = 0; // For each title in the array object pObj = null; foreach (var title in stringArray) { // Creates a button with this string as title CCControlButton button = insetButtonWithTitle(title, new CCRect(5, 5, 5, 5)); button.Position = new CCPoint(total_width + button.ContentSize.Width / 2, button.ContentSize.Height / 2); layer.AddChild(button); // Compute the size of the layer height = button.ContentSize.Height; total_width += button.ContentSize.Width; } layer.AnchorPoint = new CCPoint(0.5f, 0.5f); layer.ContentSize = new CCSize(total_width, height); layer.Position = new CCPoint(screenSize.Width / 2.0f, screenSize.Height / 2.0f); // Add the black background var background = new CCScale9SpriteFile("extensions/buttonBackground"); background.ContentSize = new CCSize(total_width + 14, height + 14); background.Position = new CCPoint(screenSize.Width / 2.0f, screenSize.Height / 2.0f); AddChild(background); } /** Creates and return a button with a default background and title color. */ public CCControlButton standardButtonWithTitle(string title) { /** Creates and return a button with a default background and title color. */ var backgroundButton = new CCScale9SpriteFile("extensions/button"); var backgroundHighlightedButton = new CCScale9SpriteFile("extensions/buttonHighlighted"); var titleButton = new CCLabelTtf(title, "Arial", 30); titleButton.Color = new CCColor3B(159, 168, 176); var button = new CCControlButton(titleButton, backgroundButton); button.SetBackgroundSpriteForState(backgroundHighlightedButton, CCControlState.Highlighted); button.SetTitleColorForState(CCColor3B.White, CCControlState.Highlighted); return button; } public CCControlButton insetButtonWithTitle(string title, CCRect inset) { /** Creates and return a button with a default background and title color. */ var backgroundButton = new CCScale9SpriteFile("extensions/button"); var backgroundHighlightedButton = new CCScale9SpriteFile("extensions/buttonHighlighted"); backgroundButton.CapInsets = inset; backgroundHighlightedButton.CapInsets = inset; var titleButton = new CCLabelTtf(title, "Arial", 30); titleButton.Color = new CCColor3B(159, 168, 176); var button = new CCControlButton(titleButton, backgroundButton); button.SetBackgroundSpriteForState(backgroundHighlightedButton, CCControlState.Highlighted); button.SetTitleColorForState(CCColor3B.White, CCControlState.Highlighted); return button; } public new static CCScene sceneWithTitle(string title) { var pScene = new CCScene (AppDelegate.SharedWindow, AppDelegate.SharedViewport); var controlLayer = new CCControlButtonTest_Inset(); controlLayer.getSceneTitleLabel().Text = (title); pScene.AddChild(controlLayer); return pScene; } } class CCControlButtonTest_Event : CCControlScene { public CCControlButtonTest_Event() { CCSize screenSize = Layer.VisibleBoundsWorldspace.Size; // Add a label in which the button events will be displayed setDisplayValueLabel(new CCLabelTtf("No Event", "Arial", 32)); m_pDisplayValueLabel.AnchorPoint = new CCPoint(0.5f, -1); m_pDisplayValueLabel.Position = new CCPoint(screenSize.Width / 2.0f, screenSize.Height / 2.0f); AddChild(m_pDisplayValueLabel, 1); // Add the button var backgroundButton = new CCScale9SpriteFile("extensions/button"); var backgroundHighlightedButton = new CCScale9SpriteFile("extensions/buttonHighlighted"); var titleButton = new CCLabelTtf("Touch Me!", "Arial", 30); titleButton.Color = new CCColor3B(159, 168, 176); var controlButton = new CCControlButton(titleButton, backgroundButton); controlButton.SetBackgroundSpriteForState(backgroundHighlightedButton, CCControlState.Highlighted); controlButton.SetTitleColorForState(CCColor3B.White, CCControlState.Highlighted); controlButton.AnchorPoint = new CCPoint(0.5f, 1); controlButton.Position = new CCPoint(screenSize.Width / 2.0f, screenSize.Height / 2.0f); AddChild(controlButton, 1); // Add the black background var background = new CCScale9SpriteFile("extensions/buttonBackground"); background.ContentSize = new CCSize(300, 170); background.Position = new CCPoint(screenSize.Width / 2.0f, screenSize.Height / 2.0f); AddChild(background); // Sets up event handlers controlButton.AddTargetWithActionForControlEvent(this, touchDownAction, CCControlEvent.TouchDown); controlButton.AddTargetWithActionForControlEvent(this, touchDragInsideAction, CCControlEvent.TouchDragInside); controlButton.AddTargetWithActionForControlEvent(this, touchDragOutsideAction, CCControlEvent.TouchDragOutside); controlButton.AddTargetWithActionForControlEvent(this, touchDragEnterAction, CCControlEvent.TouchDragEnter); controlButton.AddTargetWithActionForControlEvent(this, touchDragExitAction, CCControlEvent.TouchDragExit); controlButton.AddTargetWithActionForControlEvent(this, touchUpInsideAction, CCControlEvent.TouchUpInside); controlButton.AddTargetWithActionForControlEvent(this, touchUpOutsideAction, CCControlEvent.TouchUpOutside); controlButton.AddTargetWithActionForControlEvent(this, touchCancelAction, CCControlEvent.TouchCancel); } public void touchDownAction(object sender, CCControlEvent controlEvent) { m_pDisplayValueLabel.Text = ("Touch Down"); } public void touchDragInsideAction(object sender, CCControlEvent controlEvent) { m_pDisplayValueLabel.Text = ("Drag Inside"); } public void touchDragOutsideAction(object sender, CCControlEvent controlEvent) { m_pDisplayValueLabel.Text = ("Drag Outside"); } public void touchDragEnterAction(object sender, CCControlEvent controlEvent) { m_pDisplayValueLabel.Text = ("Drag Enter"); } public void touchDragExitAction(object sender, CCControlEvent controlEvent) { m_pDisplayValueLabel.Text = ("Drag Exit"); } public void touchUpInsideAction(object sender, CCControlEvent controlEvent) { m_pDisplayValueLabel.Text = ("Touch Up Inside."); } public void touchUpOutsideAction(object sender, CCControlEvent controlEvent) { m_pDisplayValueLabel.Text = ("Touch Up Outside."); } public void touchCancelAction(object sender, CCControlEvent controlEvent) { m_pDisplayValueLabel.Text = ("Touch Cancel"); } private CCLabelTtf m_pDisplayValueLabel; public virtual CCLabelTtf getDisplayValueLabel() { return m_pDisplayValueLabel; } public virtual void setDisplayValueLabel(CCLabelTtf var) { if (m_pDisplayValueLabel != var) { m_pDisplayValueLabel = var; } } public new static CCScene sceneWithTitle(string title) { var pScene = new CCScene (AppDelegate.SharedWindow, AppDelegate.SharedViewport); var controlLayer = new CCControlButtonTest_Event(); if (controlLayer != null) { controlLayer.getSceneTitleLabel().Text = (title); pScene.AddChild(controlLayer); } return pScene; } } class CCControlButtonTest_Styling : CCControlScene { public CCControlButtonTest_Styling() { CCSize screenSize = Layer.VisibleBoundsWorldspace.Size; var layer = new CCNode (); AddChild(layer, 1); int space = 10; // px float max_w = 0, max_h = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { // Add the buttons var button = standardButtonWithTitle(CCRandom.Next(30).ToString()); button.SetAdjustBackgroundImage(false); // Tells the button that the background image must not be adjust // It'll use the prefered size of the background image button.Position = new CCPoint(button.ContentSize.Width / 2 + (button.ContentSize.Width + space) * i, button.ContentSize.Height / 2 + (button.ContentSize.Height + space) * j); layer.AddChild(button); max_w = Math.Max(button.ContentSize.Width * (i + 1) + space * i, max_w); max_h = Math.Max(button.ContentSize.Height * (j + 1) + space * j, max_h); } } layer.AnchorPoint = new CCPoint (0.5f, 0.5f); layer.ContentSize = new CCSize(max_w, max_h); layer.Position = new CCPoint(screenSize.Width / 2.0f, screenSize.Height / 2.0f); // Add the black background var backgroundButton = new CCScale9SpriteFile("extensions/buttonBackground"); backgroundButton.ContentSize = new CCSize(max_w + 14, max_h + 14); backgroundButton.Position = new CCPoint(screenSize.Width / 2.0f, screenSize.Height / 2.0f); AddChild(backgroundButton); } public CCControlButton standardButtonWithTitle(string title) { /** Creates and return a button with a default background and title color. */ var backgroundButton = new CCScale9SpriteFile("extensions/button"); backgroundButton.PreferredSize = new CCSize(55, 55); // Set the prefered size var backgroundHighlightedButton = new CCScale9SpriteFile("extensions/buttonHighlighted"); backgroundHighlightedButton.PreferredSize = new CCSize(55, 55); // Set the prefered size var titleButton = new CCLabelTtf(title, "Arial", 30); titleButton.Color = new CCColor3B(159, 168, 176); var button = new CCControlButton(titleButton, backgroundButton); button.SetBackgroundSpriteForState(backgroundHighlightedButton, CCControlState.Highlighted); button.SetTitleColorForState(CCColor3B.White, CCControlState.Highlighted); return button; } public new static CCScene sceneWithTitle(string title) { var pScene = new CCScene (AppDelegate.SharedWindow, AppDelegate.SharedViewport); var controlLayer = new CCControlButtonTest_Styling(); if (controlLayer != null) { controlLayer.getSceneTitleLabel().Text = (title); pScene.AddChild(controlLayer); } return pScene; } } }
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // nor the names of its contributors may be used to endorse or // promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All // rights reserved. This work is licensed under the BSD open source license, // available at https://www.movesinstitute.org/licenses/bsd.html // // Author: DMcG // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si) using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Xml.Serialization; using OpenDis.Core; namespace OpenDis.Dis1998 { /// <summary> /// Section 5.2.11. This field shall specify information about a particular emitter system /// </summary> [Serializable] [XmlRoot] public partial class EmitterSystem { /// <summary> /// Name of the emitter, 16 bit enumeration /// </summary> private ushort _emitterName; /// <summary> /// function of the emitter, 8 bit enumeration /// </summary> private byte _function; /// <summary> /// emitter ID, 8 bit enumeration /// </summary> private byte _emitterIdNumber; /// <summary> /// Initializes a new instance of the <see cref="EmitterSystem"/> class. /// </summary> public EmitterSystem() { } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(EmitterSystem left, EmitterSystem right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(EmitterSystem left, EmitterSystem right) { if (object.ReferenceEquals(left, right)) { return true; } if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } public virtual int GetMarshalledSize() { int marshalSize = 0; marshalSize += 2; // this._emitterName marshalSize += 1; // this._function marshalSize += 1; // this._emitterIdNumber return marshalSize; } /// <summary> /// Gets or sets the Name of the emitter, 16 bit enumeration /// </summary> [XmlElement(Type = typeof(ushort), ElementName = "emitterName")] public ushort EmitterName { get { return this._emitterName; } set { this._emitterName = value; } } /// <summary> /// Gets or sets the function of the emitter, 8 bit enumeration /// </summary> [XmlElement(Type = typeof(byte), ElementName = "function")] public byte Function { get { return this._function; } set { this._function = value; } } /// <summary> /// Gets or sets the emitter ID, 8 bit enumeration /// </summary> [XmlElement(Type = typeof(byte), ElementName = "emitterIdNumber")] public byte EmitterIdNumber { get { return this._emitterIdNumber; } set { this._emitterIdNumber = value; } } /// <summary> /// Occurs when exception when processing PDU is caught. /// </summary> public event EventHandler<PduExceptionEventArgs> ExceptionOccured; /// <summary> /// Called when exception occurs (raises the <see cref="Exception"/> event). /// </summary> /// <param name="e">The exception.</param> protected void RaiseExceptionOccured(Exception e) { if (Pdu.FireExceptionEvents && this.ExceptionOccured != null) { this.ExceptionOccured(this, new PduExceptionEventArgs(e)); } } /// <summary> /// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Marshal(DataOutputStream dos) { if (dos != null) { try { dos.WriteUnsignedShort((ushort)this._emitterName); dos.WriteUnsignedByte((byte)this._function); dos.WriteUnsignedByte((byte)this._emitterIdNumber); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Unmarshal(DataInputStream dis) { if (dis != null) { try { this._emitterName = dis.ReadUnsignedShort(); this._function = dis.ReadUnsignedByte(); this._emitterIdNumber = dis.ReadUnsignedByte(); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } /// <summary> /// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging. /// This will be modified in the future to provide a better display. Usage: /// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb }); /// where pdu is an object representing a single pdu and sb is a StringBuilder. /// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality /// </summary> /// <param name="sb">The StringBuilder instance to which the PDU is written to.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Reflection(StringBuilder sb) { sb.AppendLine("<EmitterSystem>"); try { sb.AppendLine("<emitterName type=\"ushort\">" + this._emitterName.ToString(CultureInfo.InvariantCulture) + "</emitterName>"); sb.AppendLine("<function type=\"byte\">" + this._function.ToString(CultureInfo.InvariantCulture) + "</function>"); sb.AppendLine("<emitterIdNumber type=\"byte\">" + this._emitterIdNumber.ToString(CultureInfo.InvariantCulture) + "</emitterIdNumber>"); sb.AppendLine("</EmitterSystem>"); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return this == obj as EmitterSystem; } /// <summary> /// Compares for reference AND value equality. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public bool Equals(EmitterSystem obj) { bool ivarsEqual = true; if (obj.GetType() != this.GetType()) { return false; } if (this._emitterName != obj._emitterName) { ivarsEqual = false; } if (this._function != obj._function) { ivarsEqual = false; } if (this._emitterIdNumber != obj._emitterIdNumber) { ivarsEqual = false; } return ivarsEqual; } /// <summary> /// HashCode Helper /// </summary> /// <param name="hash">The hash value.</param> /// <returns>The new hash value.</returns> private static int GenerateHash(int hash) { hash = hash << (5 + hash); return hash; } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int result = 0; result = GenerateHash(result) ^ this._emitterName.GetHashCode(); result = GenerateHash(result) ^ this._function.GetHashCode(); result = GenerateHash(result) ^ this._emitterIdNumber.GetHashCode(); return result; } } }
using System; using System.Linq; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace lanterna.gui2 { /** * Simple layout manager the puts all components on a single line, either horizontally or vertically. */ class LinearLayout : LayoutManager { /** * This enum type will decide the alignment of a component on the counter-axis, meaning the horizontal alignment on * vertical {@code LinearLayout}s and vertical alignment on horizontal {@code LinearLayout}s. */ public enum Alignment : int { /** * The component will be placed to the left (for vertical layouts) or top (for horizontal layouts) */ Beginning = 0, /** * The component will be placed horizontally centered (for vertical layouts) or vertically centered (for * horizontal layouts) */ Center = 1, /** * The component will be placed to the right (for vertical layouts) or bottom (for horizontal layouts) */ End = 2, /** * The component will be forced to take up all the horizontal space (for vertical layouts) or vertical space * (for horizontal layouts) */ Fill = 3 } class LinearLayoutData : LayoutData { private LinearLayout.Alignment alignment; public LinearLayoutData(LinearLayout.Alignment alignment) { this.alignment = alignment; } internal static LinearLayout.Alignment access_000(LinearLayout.LinearLayoutData x0) { return x0.alignment; } } /** * Creates a {@code LayoutData} for {@code LinearLayout} that assigns a component to a particular alignment on its * counter-axis, meaning the horizontal alignment on vertical {@code LinearLayout}s and vertical alignment on * horizontal {@code LinearLayout}s. * @param alignment Alignment to store in the {@code LayoutData} object * @return {@code LayoutData} object created for {@code LinearLayout}s with the specified alignment * @see Alignment */ public static LayoutData createLayoutData(LinearLayout.Alignment alignment) { return new LinearLayout.LinearLayoutData(alignment); } private Direction direction; private int spacing; private bool changed; /** * Default constructor, creates a vertical {@code LinearLayout} * Standard constructor that creates a {@code LinearLayout} with a specified direction to position the components on * @param direction Direction for this {@code Direction} */ public LinearLayout(Direction direction = Direction.VERTICAL) { this.direction = direction; this.spacing = ((direction == Direction.HORIZONTAL) ? 1 : 0); this.changed = true; } /** * Sets the amount of empty space to put in between components. For horizontal layouts, this is number of columns * (by default 1) and for vertical layouts this is number of rows (by default 0). * @param spacing Spacing between components, either in number of columns or rows depending on the direction * @return Itself */ public virtual LinearLayout setSpacing(int spacing) { this.spacing = spacing; this.changed = true; return this; } /** * Returns the amount of empty space to put in between components. For horizontal layouts, this is number of columns * (by default 1) and for vertical layouts this is number of rows (by default 0). * @return Spacing between components, either in number of columns or rows depending on the direction */ public virtual int getSpacing() { return this.spacing; } // public virtual TerminalSize getPreferredSize(List<Component> components) { if (this.direction == Direction.VERTICAL) { return this.getPreferredSizeVertically(components); } return this.getPreferredSizeHorizontally(components); } private TerminalSize getPreferredSizeVertically(List<Component> components) { int maxWidth = 0; int height = 0; foreach (var component in components) { TerminalSize preferredSize = component.getPreferredSize(); if (maxWidth < preferredSize.getColumns()) { maxWidth = preferredSize.getColumns(); } height += preferredSize.getRows(); } height += this.spacing * (components.Count - 1); return new TerminalSize(maxWidth, height); } private TerminalSize getPreferredSizeHorizontally(List<Component> components) { int maxHeight = 0; int width = 0; foreach (var component in components) { TerminalSize preferredSize = component.getPreferredSize(); if (maxHeight < preferredSize.getRows()) { maxHeight = preferredSize.getRows(); } width += preferredSize.getColumns(); } width += this.spacing * (components.Count - 1); return new TerminalSize(width, maxHeight); } public virtual bool hasChanged() { return this.changed; } // public virtual void doLayout(TerminalSize area, List<Component> components) { if (this.direction == Direction.VERTICAL) { this.doVerticalLayout(area, components); } else { this.doHorizontalLayout(area, components); } this.changed = false; } //TODO private void doVerticalLayout(TerminalSize area, List<Component> components) { int remainingVerticalSpace = area.getRows(); int availableHorizontalSpace = area.getColumns(); foreach (var component in components) { if (remainingVerticalSpace > 0) { LinearLayout.LinearLayoutData layoutData = (LinearLayout.LinearLayoutData)component.getLayoutData(); LinearLayout.Alignment alignment = LinearLayout.Alignment.Beginning; if (layoutData != null) { alignment = LinearLayout.LinearLayoutData.access_000(layoutData); } TerminalSize preferredSize = component.getPreferredSize(); TerminalSize decidedSize = new TerminalSize(Math.Min(availableHorizontalSpace, preferredSize.getColumns()), Math.Min(remainingVerticalSpace, preferredSize.getRows())); if (alignment == LinearLayout.Alignment.Fill) { decidedSize = decidedSize.withColumns(availableHorizontalSpace); alignment = LinearLayout.Alignment.Beginning; } TerminalPosition position = component.getPosition(); position = position.withRow(area.getRows() - remainingVerticalSpace); switch (alignment) { case LinearLayout.Alignment.Beginning: position = position.withColumn(availableHorizontalSpace - decidedSize.getColumns()); break; case LinearLayout.Alignment.Center: position = position.withColumn((availableHorizontalSpace - decidedSize.getColumns()) / 2); break; default: goto IL_134; } IL_13F: component.setPosition(position); component.setSize(component.getSize().with(decidedSize)); remainingVerticalSpace -= decidedSize.getRows() + this.spacing; continue; IL_134: position = position.withColumn(0); goto IL_13F; } component.setPosition(TerminalPosition.TOP_LEFT_CORNER); component.setSize(TerminalSize.ZERO); } } //TODO private void doHorizontalLayout(TerminalSize area, List<Component> components) { int remainingHorizontalSpace = area.getColumns(); int availableVerticalSpace = area.getRows(); foreach (var component in components) { if (remainingHorizontalSpace > 0) { LinearLayout.LinearLayoutData layoutData = (LinearLayout.LinearLayoutData)component.getLayoutData(); LinearLayout.Alignment alignment = LinearLayout.Alignment.Beginning; if (layoutData != null) { alignment = LinearLayout.LinearLayoutData.access_000(layoutData); } TerminalSize preferredSize = component.getPreferredSize(); TerminalSize decidedSize = new TerminalSize(Math.Min(remainingHorizontalSpace, preferredSize.getColumns()), Math.Min(availableVerticalSpace, preferredSize.getRows())); if (alignment == LinearLayout.Alignment.Fill) { decidedSize = decidedSize.withRows(availableVerticalSpace); alignment = LinearLayout.Alignment.Beginning; } TerminalPosition position = component.getPosition(); position = position.withColumn(area.getColumns() - remainingHorizontalSpace); switch (alignment) { case LinearLayout.Alignment.Beginning: position = position.withRow(availableVerticalSpace - decidedSize.getRows()); break; case LinearLayout.Alignment.Center: position = position.withRow((availableVerticalSpace - decidedSize.getRows()) / 2); break; default: goto IL_134; } IL_13F: component.setPosition(position); component.setSize(component.getSize().with(decidedSize)); remainingHorizontalSpace -= decidedSize.getColumns() + this.spacing; continue; IL_134: position = position.withRow(0); goto IL_13F; } component.setPosition(TerminalPosition.TOP_LEFT_CORNER); component.setSize(TerminalSize.ZERO); } } } }
// 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 gagvr = Google.Ads.GoogleAds.V9.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V9.Services { /// <summary>Settings for <see cref="FeedItemTargetServiceClient"/> instances.</summary> public sealed partial class FeedItemTargetServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="FeedItemTargetServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="FeedItemTargetServiceSettings"/>.</returns> public static FeedItemTargetServiceSettings GetDefault() => new FeedItemTargetServiceSettings(); /// <summary> /// Constructs a new <see cref="FeedItemTargetServiceSettings"/> object with default settings. /// </summary> public FeedItemTargetServiceSettings() { } private FeedItemTargetServiceSettings(FeedItemTargetServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetFeedItemTargetSettings = existing.GetFeedItemTargetSettings; MutateFeedItemTargetsSettings = existing.MutateFeedItemTargetsSettings; OnCopy(existing); } partial void OnCopy(FeedItemTargetServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>FeedItemTargetServiceClient.GetFeedItemTarget</c> and /// <c>FeedItemTargetServiceClient.GetFeedItemTargetAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetFeedItemTargetSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>FeedItemTargetServiceClient.MutateFeedItemTargets</c> and /// <c>FeedItemTargetServiceClient.MutateFeedItemTargetsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateFeedItemTargetsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="FeedItemTargetServiceSettings"/> object.</returns> public FeedItemTargetServiceSettings Clone() => new FeedItemTargetServiceSettings(this); } /// <summary> /// Builder class for <see cref="FeedItemTargetServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class FeedItemTargetServiceClientBuilder : gaxgrpc::ClientBuilderBase<FeedItemTargetServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public FeedItemTargetServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public FeedItemTargetServiceClientBuilder() { UseJwtAccessWithScopes = FeedItemTargetServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref FeedItemTargetServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<FeedItemTargetServiceClient> task); /// <summary>Builds the resulting client.</summary> public override FeedItemTargetServiceClient Build() { FeedItemTargetServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<FeedItemTargetServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<FeedItemTargetServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private FeedItemTargetServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return FeedItemTargetServiceClient.Create(callInvoker, Settings); } private async stt::Task<FeedItemTargetServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return FeedItemTargetServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => FeedItemTargetServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => FeedItemTargetServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => FeedItemTargetServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>FeedItemTargetService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage feed item targets. /// </remarks> public abstract partial class FeedItemTargetServiceClient { /// <summary> /// The default endpoint for the FeedItemTargetService service, which is a host of "googleads.googleapis.com" /// and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default FeedItemTargetService scopes.</summary> /// <remarks> /// The default FeedItemTargetService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="FeedItemTargetServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="FeedItemTargetServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="FeedItemTargetServiceClient"/>.</returns> public static stt::Task<FeedItemTargetServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new FeedItemTargetServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="FeedItemTargetServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="FeedItemTargetServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="FeedItemTargetServiceClient"/>.</returns> public static FeedItemTargetServiceClient Create() => new FeedItemTargetServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="FeedItemTargetServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="FeedItemTargetServiceSettings"/>.</param> /// <returns>The created <see cref="FeedItemTargetServiceClient"/>.</returns> internal static FeedItemTargetServiceClient Create(grpccore::CallInvoker callInvoker, FeedItemTargetServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } FeedItemTargetService.FeedItemTargetServiceClient grpcClient = new FeedItemTargetService.FeedItemTargetServiceClient(callInvoker); return new FeedItemTargetServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC FeedItemTargetService client</summary> public virtual FeedItemTargetService.FeedItemTargetServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested feed item targets in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::FeedItemTarget GetFeedItemTarget(GetFeedItemTargetRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested feed item targets in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::FeedItemTarget> GetFeedItemTargetAsync(GetFeedItemTargetRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested feed item targets in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::FeedItemTarget> GetFeedItemTargetAsync(GetFeedItemTargetRequest request, st::CancellationToken cancellationToken) => GetFeedItemTargetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested feed item targets in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the feed item targets to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::FeedItemTarget GetFeedItemTarget(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetFeedItemTarget(new GetFeedItemTargetRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested feed item targets in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the feed item targets to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::FeedItemTarget> GetFeedItemTargetAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetFeedItemTargetAsync(new GetFeedItemTargetRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested feed item targets in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the feed item targets to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::FeedItemTarget> GetFeedItemTargetAsync(string resourceName, st::CancellationToken cancellationToken) => GetFeedItemTargetAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested feed item targets in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the feed item targets to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::FeedItemTarget GetFeedItemTarget(gagvr::FeedItemTargetName resourceName, gaxgrpc::CallSettings callSettings = null) => GetFeedItemTarget(new GetFeedItemTargetRequest { ResourceNameAsFeedItemTargetName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested feed item targets in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the feed item targets to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::FeedItemTarget> GetFeedItemTargetAsync(gagvr::FeedItemTargetName resourceName, gaxgrpc::CallSettings callSettings = null) => GetFeedItemTargetAsync(new GetFeedItemTargetRequest { ResourceNameAsFeedItemTargetName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested feed item targets in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the feed item targets to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::FeedItemTarget> GetFeedItemTargetAsync(gagvr::FeedItemTargetName resourceName, st::CancellationToken cancellationToken) => GetFeedItemTargetAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates or removes feed item targets. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedItemTargetError]() /// [FieldError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateFeedItemTargetsResponse MutateFeedItemTargets(MutateFeedItemTargetsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates or removes feed item targets. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedItemTargetError]() /// [FieldError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateFeedItemTargetsResponse> MutateFeedItemTargetsAsync(MutateFeedItemTargetsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates or removes feed item targets. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedItemTargetError]() /// [FieldError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateFeedItemTargetsResponse> MutateFeedItemTargetsAsync(MutateFeedItemTargetsRequest request, st::CancellationToken cancellationToken) => MutateFeedItemTargetsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates or removes feed item targets. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedItemTargetError]() /// [FieldError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose feed item targets are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual feed item targets. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateFeedItemTargetsResponse MutateFeedItemTargets(string customerId, scg::IEnumerable<FeedItemTargetOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateFeedItemTargets(new MutateFeedItemTargetsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates or removes feed item targets. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedItemTargetError]() /// [FieldError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose feed item targets are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual feed item targets. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateFeedItemTargetsResponse> MutateFeedItemTargetsAsync(string customerId, scg::IEnumerable<FeedItemTargetOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateFeedItemTargetsAsync(new MutateFeedItemTargetsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates or removes feed item targets. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedItemTargetError]() /// [FieldError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose feed item targets are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual feed item targets. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateFeedItemTargetsResponse> MutateFeedItemTargetsAsync(string customerId, scg::IEnumerable<FeedItemTargetOperation> operations, st::CancellationToken cancellationToken) => MutateFeedItemTargetsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>FeedItemTargetService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage feed item targets. /// </remarks> public sealed partial class FeedItemTargetServiceClientImpl : FeedItemTargetServiceClient { private readonly gaxgrpc::ApiCall<GetFeedItemTargetRequest, gagvr::FeedItemTarget> _callGetFeedItemTarget; private readonly gaxgrpc::ApiCall<MutateFeedItemTargetsRequest, MutateFeedItemTargetsResponse> _callMutateFeedItemTargets; /// <summary> /// Constructs a client wrapper for the FeedItemTargetService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="FeedItemTargetServiceSettings"/> used within this client.</param> public FeedItemTargetServiceClientImpl(FeedItemTargetService.FeedItemTargetServiceClient grpcClient, FeedItemTargetServiceSettings settings) { GrpcClient = grpcClient; FeedItemTargetServiceSettings effectiveSettings = settings ?? FeedItemTargetServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetFeedItemTarget = clientHelper.BuildApiCall<GetFeedItemTargetRequest, gagvr::FeedItemTarget>(grpcClient.GetFeedItemTargetAsync, grpcClient.GetFeedItemTarget, effectiveSettings.GetFeedItemTargetSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetFeedItemTarget); Modify_GetFeedItemTargetApiCall(ref _callGetFeedItemTarget); _callMutateFeedItemTargets = clientHelper.BuildApiCall<MutateFeedItemTargetsRequest, MutateFeedItemTargetsResponse>(grpcClient.MutateFeedItemTargetsAsync, grpcClient.MutateFeedItemTargets, effectiveSettings.MutateFeedItemTargetsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateFeedItemTargets); Modify_MutateFeedItemTargetsApiCall(ref _callMutateFeedItemTargets); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetFeedItemTargetApiCall(ref gaxgrpc::ApiCall<GetFeedItemTargetRequest, gagvr::FeedItemTarget> call); partial void Modify_MutateFeedItemTargetsApiCall(ref gaxgrpc::ApiCall<MutateFeedItemTargetsRequest, MutateFeedItemTargetsResponse> call); partial void OnConstruction(FeedItemTargetService.FeedItemTargetServiceClient grpcClient, FeedItemTargetServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC FeedItemTargetService client</summary> public override FeedItemTargetService.FeedItemTargetServiceClient GrpcClient { get; } partial void Modify_GetFeedItemTargetRequest(ref GetFeedItemTargetRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_MutateFeedItemTargetsRequest(ref MutateFeedItemTargetsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested feed item targets in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::FeedItemTarget GetFeedItemTarget(GetFeedItemTargetRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetFeedItemTargetRequest(ref request, ref callSettings); return _callGetFeedItemTarget.Sync(request, callSettings); } /// <summary> /// Returns the requested feed item targets in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::FeedItemTarget> GetFeedItemTargetAsync(GetFeedItemTargetRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetFeedItemTargetRequest(ref request, ref callSettings); return _callGetFeedItemTarget.Async(request, callSettings); } /// <summary> /// Creates or removes feed item targets. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedItemTargetError]() /// [FieldError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MutateFeedItemTargetsResponse MutateFeedItemTargets(MutateFeedItemTargetsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateFeedItemTargetsRequest(ref request, ref callSettings); return _callMutateFeedItemTargets.Sync(request, callSettings); } /// <summary> /// Creates or removes feed item targets. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedItemTargetError]() /// [FieldError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateFeedItemTargetsResponse> MutateFeedItemTargetsAsync(MutateFeedItemTargetsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateFeedItemTargetsRequest(ref request, ref callSettings); return _callMutateFeedItemTargets.Async(request, callSettings); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ServerManagement { using Microsoft.Rest.Azure; using Models; /// <summary> /// PowerShellOperations operations. /// </summary> public partial interface IPowerShellOperations { /// <summary> /// Gets a list of the active sessions. /// </summary> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group /// within the user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<PowerShellSessionResources>> ListSessionWithHttpMessagesAsync(string resourceGroupName, string nodeName, string session, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Creates a PowerShell session /// </summary> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group /// within the user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='pssession'> /// The PowerShell sessionId from the user /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<PowerShellSessionResource>> CreateSessionWithHttpMessagesAsync(string resourceGroupName, string nodeName, string session, string pssession, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Creates a PowerShell session /// </summary> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group /// within the user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='pssession'> /// The PowerShell sessionId from the user /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<PowerShellSessionResource>> BeginCreateSessionWithHttpMessagesAsync(string resourceGroupName, string nodeName, string session, string pssession, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Gets the status of a command. /// </summary> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group /// within the user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='pssession'> /// The PowerShell sessionId from the user /// </param> /// <param name='expand'> /// Gets current output from an ongoing call. Possible values include: /// 'output' /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<PowerShellCommandStatus>> GetCommandStatusWithHttpMessagesAsync(string resourceGroupName, string nodeName, string session, string pssession, PowerShellExpandOption? expand = default(PowerShellExpandOption?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// updates a running PowerShell command with more data. /// </summary> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group /// within the user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='pssession'> /// The PowerShell sessionId from the user /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<PowerShellCommandResults>> UpdateCommandWithHttpMessagesAsync(string resourceGroupName, string nodeName, string session, string pssession, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// updates a running PowerShell command with more data. /// </summary> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group /// within the user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='pssession'> /// The PowerShell sessionId from the user /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<PowerShellCommandResults>> BeginUpdateCommandWithHttpMessagesAsync(string resourceGroupName, string nodeName, string session, string pssession, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Creates a PowerShell script and invokes it. /// </summary> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group /// within the user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='pssession'> /// The PowerShell sessionId from the user /// </param> /// <param name='command'> /// Script to execute /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<PowerShellCommandResults>> InvokeCommandWithHttpMessagesAsync(string resourceGroupName, string nodeName, string session, string pssession, string command = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Creates a PowerShell script and invokes it. /// </summary> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group /// within the user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='pssession'> /// The PowerShell sessionId from the user /// </param> /// <param name='command'> /// Script to execute /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<PowerShellCommandResults>> BeginInvokeCommandWithHttpMessagesAsync(string resourceGroupName, string nodeName, string session, string pssession, string command = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Cancels a PowerShell command. /// </summary> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group /// within the user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='pssession'> /// The PowerShell sessionId from the user /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<PowerShellCommandResults>> CancelCommandWithHttpMessagesAsync(string resourceGroupName, string nodeName, string session, string pssession, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Cancels a PowerShell command. /// </summary> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group /// within the user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='pssession'> /// The PowerShell sessionId from the user /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<PowerShellCommandResults>> BeginCancelCommandWithHttpMessagesAsync(string resourceGroupName, string nodeName, string session, string pssession, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// gets tab completion values for a command. /// </summary> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group /// within the user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='pssession'> /// The PowerShell sessionId from the user /// </param> /// <param name='command'> /// Command to get tab completion for. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<PowerShellTabCompletionResults>> TabCompletionWithHttpMessagesAsync(string resourceGroupName, string nodeName, string session, string pssession, string command = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } }
// // MediaProfilerManager.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2007-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Text; using System.Xml; using System.Collections; using System.Collections.Generic; using Banshee.ServiceStack; namespace Banshee.MediaProfiles { public class TestProfileArgs : EventArgs { private bool profile_available = true; private Profile profile; public TestProfileArgs(Profile profile) { this.profile = profile; } public Profile Profile { get { return profile; } } public bool ProfileAvailable { get { return profile_available; } set { profile_available = value; } } } public delegate void TestProfileHandler(object o, TestProfileArgs args); public class MediaProfileManager : IEnumerable<Profile>, IService { internal static System.Globalization.CultureInfo CultureInfo { get { return System.Globalization.CultureInfo.InvariantCulture; } } private XmlDocument document; private List<Profile> profiles; private Dictionary<string, PipelineVariable> preset_variables; public event TestProfileHandler TestProfile; public event EventHandler Initialized; public MediaProfileManager() { } private void Initialize () { if (profiles != null) { return; } uint timer = Hyena.Log.DebugTimerStart (); profiles = new List<Profile> (); preset_variables = new Dictionary<string, PipelineVariable> (); string path = Hyena.Paths.GetInstalledDataDirectory ("audio-profiles"); if(File.Exists(path)) { LoadFromFile(path); } else if(Directory.Exists(path)) { string base_file = Path.Combine(path, "base.xml"); if(File.Exists(base_file)) { LoadFromFile(base_file); } foreach(string file in Directory.GetFiles(path, "*.xml")) { if(Path.GetFileName(file) != "base.xml") { LoadFromFile(file); } } } Hyena.Log.DebugTimerPrint (timer, "Initialized MediaProfileManager: {0}"); EventHandler handler = Initialized; if (handler != null) { handler (this, EventArgs.Empty); } } private void LoadFromFile(string path) { document = new XmlDocument(); try { document.Load(path); Load(); } catch(Exception e) { Console.WriteLine("Could not load profile: {0}\n{1}", path, e); } document = null; } private void Load() { LoadPresetVariables(document.DocumentElement.SelectSingleNode("/audio-profiles/preset-variables")); LoadProfiles(document.DocumentElement.SelectSingleNode("/audio-profiles/profiles")); } private void LoadPresetVariables(XmlNode node) { if(node == null) { return; } foreach(XmlNode variable_node in node.SelectNodes("variable")) { try { PipelineVariable variable = new PipelineVariable(variable_node); if(!preset_variables.ContainsKey(variable.Id)) { preset_variables.Add(variable.Id, variable); } } catch { } } } private void LoadProfiles(XmlNode node) { if(node == null) { return; } foreach(XmlNode profile_node in node.SelectNodes("profile")) { try { Add (new Profile(this, profile_node)); } catch(Exception e) { Console.WriteLine(e); } } } private Dictionary<string, string> mimetype_extensions = new Dictionary<string, string> (); public void Add(Profile profile) { Initialize (); foreach (string mimetype in profile.MimeTypes) { mimetype_extensions[mimetype] = profile.OutputFileExtension; } profiles.Add(profile); } public void Remove(Profile profile) { Initialize (); profiles.Remove(profile); } public PipelineVariable GetPresetPipelineVariableById(string id) { if(id == null) { throw new ArgumentNullException("id"); } Initialize (); return preset_variables[id]; } protected virtual bool OnTestProfile(Profile profile) { TestProfileHandler handler = TestProfile; if(handler == null) { return true; } TestProfileArgs args = new TestProfileArgs(profile); handler(this, args); return args.ProfileAvailable; } public IEnumerable<Profile> GetAvailableProfiles() { Initialize (); foreach(Profile profile in this) { if(profile.Available == null) { profile.Available = OnTestProfile(profile); } if(profile.Available == true) { yield return profile; } } } public ProfileConfiguration GetActiveProfileConfiguration (string id) { Initialize (); return ProfileConfiguration.LoadActive (this, id); } public ProfileConfiguration GetActiveProfileConfiguration(string id, string [] mimetypes) { Initialize (); ProfileConfiguration config = GetActiveProfileConfiguration (id); if (config != null) { // Ensure the profile configuration is valid for the mimetype restriction foreach (string profile_mimetype in config.Profile.MimeTypes) { foreach (string mimetype in mimetypes) { if (mimetype == profile_mimetype) { return config; } } } } foreach(string mimetype in mimetypes) { Profile profile = GetProfileForMimeType(mimetype); if(profile != null) { profile.LoadConfiguration (id); return profile.Configuration; } } return null; } public void TestAll() { Initialize (); foreach(Profile profile in this) { profile.Available = OnTestProfile(profile); } } public Profile GetProfileForMimeType(string mimetype) { Initialize (); foreach(Profile profile in GetAvailableProfiles()) { if(profile.HasMimeType(mimetype)) { return profile; } } return null; } public Profile GetProfileForExtension (string extension) { if (extension == null || extension.Length < 2) return null; if (extension[0] == '.') extension = extension.Substring (1, extension.Length - 1); Initialize (); foreach (Profile profile in this) { if (profile.OutputFileExtension == extension) { return profile; } } return null; } public string GetExtensionForMimeType (string mimetype) { Initialize (); if (mimetype != null && mimetype_extensions.ContainsKey (mimetype)) return mimetype_extensions[mimetype]; return null; } public IEnumerator<Profile> GetEnumerator() { Initialize (); return profiles.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { Initialize (); return profiles.GetEnumerator(); } public int ProfileCount { get { Initialize (); return profiles.Count; } } public int AvailableProfileCount { get { Initialize (); int count = 0; #pragma warning disable 0168, 0219 foreach(Profile profile in GetAvailableProfiles()) { count++; } #pragma warning restore 0168, 0219 return count; } } string Banshee.ServiceStack.IService.ServiceName { get { return "MediaProfileManager"; } } public override string ToString() { Initialize (); StringBuilder builder = new StringBuilder(); builder.Append("Preset Pipeline Variables:\n\n"); foreach(PipelineVariable variable in preset_variables.Values) { builder.Append(variable); builder.Append("\n"); } builder.Append("Profiles:\n\n"); foreach(Profile profile in profiles) { builder.Append(profile); builder.Append("\n\n"); } return builder.ToString().Trim(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using FluentModelBuilder.Alterations; using FluentModelBuilder.Builder.Conventions; using FluentModelBuilder.Builder.Sources; using FluentModelBuilder.Configuration; using FluentModelBuilder.Conventions; using FluentModelBuilder.Extensions; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace FluentModelBuilder.Builder { public class AutoModelBuilder { private readonly List<Func<DbContext, bool>> _dbContextSelectors = new List<Func<DbContext, bool>>(); private readonly AutoConfigurationExpressions _expressions = new AutoConfigurationExpressions(); private readonly List<Type> _ignoredTypes = new List<Type>(); private readonly List<Type> _includedTypes = new List<Type>(); private readonly IList<InlineOverride> _inlineOverrides = new List<InlineOverride>(); private readonly IList<IObjectFactory<ITypeSource>> _tyeSourceFactories = new List<IObjectFactory<ITypeSource>>(); private readonly IList<IObjectFactory<IAutoModelBuilderAlteration>> _alterationFactories = new List<IObjectFactory<IAutoModelBuilderAlteration>>(); private readonly IList<IObjectFactory<IModelBuilderConvention>> _conventionFactories = new List<IObjectFactory<IModelBuilderConvention>>(); public readonly IEntityAutoConfiguration Configuration; private BuilderScope? _scope; private Func<Type, bool> _whereClause; private bool _alterationsApplied; public AutoModelBuilder() : this(new AutoConfigurationExpressions()) { } public AutoModelBuilder(AutoConfigurationExpressions expressions) : this(new ExpressionBasedEntityAutoConfiguration(expressions)) { _expressions = expressions; } public AutoModelBuilder(IEntityAutoConfiguration configuration) { if (configuration == null) throw new ArgumentNullException(nameof(configuration)); Configuration = configuration; Scope = new ScopeBuilder(this); } internal void Apply(BuilderContext parameters) { if (!ShouldApplyToContext(parameters.DbContext)) return; if (!ShouldApplyToScope(parameters.Scope)) return; var serviceProvider = parameters.DbContext.GetInfrastructure(); ApplyAlterations(this, serviceProvider); AddEntities(parameters.ModelBuilder, serviceProvider); ApplyModelBuilderOverrides(parameters.ModelBuilder, serviceProvider); ApplyOverrides(parameters.ModelBuilder); } internal void AddOverride(Type type, Action<object> action) { _inlineOverrides.Add(new InlineOverride(type, action)); } private void OverrideHelper<T>(EntityTypeBuilder<T> builder, IEntityTypeOverride<T> mappingOverride) where T : class { mappingOverride.Override(builder); } private object EntityTypeBuilder(ModelBuilder builder, Type type) { var entityMethod = typeof (ModelBuilder).GetRuntimeMethods() .FirstOrDefault(x => x.Name == "Entity" && x.IsGenericMethod); var genericEntityMethod = entityMethod?.MakeGenericMethod(type); return genericEntityMethod?.Invoke(builder, null); } private void ApplyAlterations(AutoModelBuilder autoModelBuilder, IServiceProvider serviceProvider) { if (_alterationsApplied) return; foreach(var alteration in _alterationFactories.Select(x => x.Create(serviceProvider)).ToList()) alteration.Alter(autoModelBuilder); _alterationsApplied = true; } private void ApplyModelBuilderOverrides(ModelBuilder builder, IServiceProvider serviceProvider) { foreach (var modelBuilderOverride in _conventionFactories.Select(x => x.Create(serviceProvider))) modelBuilderOverride.Apply(builder); } private void AddEntities(ModelBuilder builder, IServiceProvider serviceProvider) { var types = _tyeSourceFactories.Select(x => x.Create(serviceProvider)).SelectMany(x => x.GetTypes()).Distinct(); foreach (var type in types) { if (!Configuration.ShouldMap(type)) continue; if (_whereClause != null && !_whereClause(type)) continue; if (!ShouldMap(type)) continue; builder.Entity(type); } } private void ApplyOverrides(ModelBuilder builder) { foreach (var inlineOverride in _inlineOverrides) { var entityTypeBuilderInstance = EntityTypeBuilder(builder, inlineOverride.Type); inlineOverride.Apply(entityTypeBuilderInstance); } } private bool ShouldApplyToContext(DbContext dbContext) { if (!Configuration.ShouldApplyToContext(dbContext)) return false; foreach (var selector in _dbContextSelectors) { if (!selector(dbContext)) return false; } return true; } private bool ShouldApplyToScope(BuilderScope scope) { if (!Configuration.ShouldApplyToScope(scope)) return false; if (_scope == null) return scope == BuilderScope.PostModelCreating; if (_scope != scope) return false; return true; } private bool ShouldMap(Type type) { if (_includedTypes.Contains(type)) return true; if (_ignoredTypes.Contains(type)) return false; if (type.GetTypeInfo().IsGenericType && _ignoredTypes.Contains(type.GetGenericTypeDefinition())) return false; if (type.GetTypeInfo().IsAbstract) return false; if (type == typeof (object)) return false; return true; } #region Where protected bool HasUserDefinedConfiguration => !(Configuration is ExpressionBasedEntityAutoConfiguration); /// <summary> /// Alter the Expression based configuration options, when not wanting to use user-defined configuration. /// </summary> /// <param name="configurationAction">Action to perform on Expression Configuration</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder Setup(Action<AutoConfigurationExpressions> configurationAction) { if (HasUserDefinedConfiguration) throw new InvalidOperationException( "Cannot use Setup method when using user-defined IEntityAutoConfiguration instance."); configurationAction(_expressions); return this; } /// <summary> /// Specify a criteria to determine which types will be mapped. Cannot be used with user-defined configuration. /// </summary> /// <param name="where">Criteria for determining types</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder Where(Func<Type, bool> where) { if (HasUserDefinedConfiguration) throw new InvalidOperationException( "Cannot use Where method when using user-defined IEntityAutoConfiguration instance."); _whereClause = where; return this; } #endregion #region Scope /// <summary> /// Specify the scope of this AutoModelBuilder, default is PreModelCreating /// <remarks> /// You would use this to change when the changes should be applied to the model - whether PreModelCreating, /// i.e. before Entity Framework's own model creation, or PostModelCreating, i.e. after Entity Framework /// has already created its own model. This is useful for things like overriding the base properties /// of IdentityDbContext entities, like UserName, Email, etc. /// </remarks> /// </summary> public ScopeBuilder Scope { get; } /// <summary> /// Specify the scope of this AutoModelBuilder, default is PreModelCreating /// <remarks> /// You would use this to change when the changes should be applied to the model - whether PreModelCreating, /// i.e. before Entity Framework's own model creation, or PostModelCreating, i.e. after Entity Framework /// has already created its own model. This is useful for things like overriding the base properties /// of IdentityDbContext entities, like UserName, Email, etc. /// </remarks> /// </summary> /// <param name="scope">Scope to use</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder UseScope(BuilderScope? scope) { _scope = scope; return this; } #endregion #region Context /// <summary> /// Add a DbContext selector to be used to determine whether this AutoModelBuilder should be used /// with the provided DbContext /// </summary> /// <typeparam name="TContext">DbContext type to use</typeparam> /// <param name="predicate">Predicate to match DbContext on</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder Context<TContext>(Func<TContext, bool> predicate = null) where TContext : DbContext { if (predicate == null) _dbContextSelectors.Add(x => x.GetType() == typeof (TContext)); else _dbContextSelectors.Add(predicate as Func<DbContext, bool>); return this; } /// <summary> /// Add a DbContext selector to be used to determine whether this AutoModelBuilder should be used /// with the provided DbContext /// </summary> /// <param name="predicate">Predicate to match DbContext on</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder Context(Func<DbContext, bool> predicate) { return Context<DbContext>(predicate); } #endregion #region Alterations /// <summary> /// Adds an alteration to be used with this AutoModelBuilder /// </summary> /// <typeparam name="TAlteration">Alteration to use</typeparam> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder AddAlteration<TAlteration>() where TAlteration : IAutoModelBuilderAlteration => AddAlteration(typeof (TAlteration)); /// <summary> /// Adds alterations to be used with this AutoModelBuilder /// </summary> /// <param name="alterations"></param> /// <returns></returns> public AutoModelBuilder AddAlterations(IEnumerable<IAutoModelBuilderAlteration> alterations) { foreach(var alteration in alterations) _alterationFactories.Add(new InstancedObjectFactory<IAutoModelBuilderAlteration>(alteration)); return this; } /// <summary> /// Adds an alteration to be used with this AutoModelBuilder /// </summary> /// <param name="type">Type of Alteration to use. Expects to be IAutoModelBuilderAlteration</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder AddAlteration(Type type) { if (!type.ClosesInterface(typeof (IAutoModelBuilderAlteration))) throw new ArgumentException($"Type does not implement interface {nameof(IAutoModelBuilderAlteration)}", nameof(type)); _alterationFactories.Add(new TypeBasedObjectFactory<IAutoModelBuilderAlteration>(type)); return this; } /// <summary> /// Adds an alteration to be used with this AutoModelBuilder /// </summary> /// <param name="alteration">Alteration to use</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder AddAlteration(IAutoModelBuilderAlteration alteration) { _alterationFactories.Add(new InstancedObjectFactory<IAutoModelBuilderAlteration>(alteration)); return this; } /// <summary> /// Adds all alterations from provided assembly to be used with this AutoModelBuilder /// </summary> /// <param name="assembly">Assembly to scan for alterations</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder AddAlterationsFromAssembly(Assembly assembly) { var types = assembly.GetTypesImplementingInterface(typeof(IAutoModelBuilderAlteration)); foreach(var type in types) _alterationFactories.Add(new TypeBasedObjectFactory<IAutoModelBuilderAlteration>(type)); return this; } /// <summary> /// Adds all alterations from the assembly of provided type to be used with this AutoModelBuilder /// </summary> /// <typeparam name="T">Type contained in the assembly to be scanned</typeparam> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder AddAlterationsFromAssemblyOf<T>() => AddAlterationsFromAssemblyOf(typeof(T)); /// <summary> /// Adds all alterations from the assembly of provided type to be used with this AutoModelBuilder /// </summary> /// <param name="type">Type contained in the assembly to be scanned</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder AddAlterationsFromAssemblyOf(Type type) => AddAlterationsFromAssembly(type.GetTypeInfo().Assembly); /// <summary> /// Adds all alterations from provided assemblies to be used with this AutoModelBuilder /// </summary> /// <param name="assemblies">Assemblies to scan for alterations</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder AddAlterationsFromAssemblies(IEnumerable<Assembly> assemblies) { foreach (var assembly in assemblies) AddAlterationsFromAssembly(assembly); return this; } #endregion #region Entities /// <summary> /// Adds entities from specific assembly /// </summary> /// <param name="assembly">Assembly to use</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder AddEntitiesFromAssembly(Assembly assembly) => AddTypeSource(new AssemblyTypeSource(assembly)); /// <summary> /// Adds entities from specified assemblies /// </summary> /// <param name="assemblies">Assemblies to use</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder AddEntitiesFromAssemblies(IEnumerable<Assembly> assemblies) { AddTypeSource(new CombinedAssemblyTypeSource(assemblies)); return this; } /// <summary> /// Adds entities from specific assembly /// </summary> /// <typeparam name="T">Type contained in required assembly</typeparam> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder AddEntitiesFromAssemblyOf<T>() => AddEntitiesFromAssembly(typeof(T).GetTypeInfo().Assembly); /// <summary> /// Adds entities from specific assembly /// </summary> /// <param name="type">Type contained in required assembly</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder AddEntitiesFromAssemblyOf(Type type) => AddEntitiesFromAssembly(type.GetTypeInfo().Assembly); /// <summary> /// Explicitly includes a type to be used as part of the model /// </summary> /// <typeparam name="T">Type to include</typeparam> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder IncludeBase<T>() => IncludeBase(typeof(T)); /// <summary> /// Explicitly includes a type to be used as part of the model /// </summary> /// <param name="type">Type to include</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder IncludeBase(Type type) { _includedTypes.Add(type); return this; } /// <summary> /// Ignores a type and ensures it will not be used as part of the model /// </summary> /// <remarks> /// In the event that you wish to ignore an entity that would be otherwise be picked up due to /// <see cref="IEntityAutoConfiguration" />, /// you would want to use this method /// </remarks> /// <typeparam name="T">Type to ignore</typeparam> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder IgnoreBase<T>() => IgnoreBase(typeof(T)); /// <summary> /// Ignores a type and ensures it will not be used as part of the model /// </summary> /// <remarks> /// In the event that you wish to ignore an entity that would be otherwise be picked up due to /// <see cref="IEntityAutoConfiguration" />, /// you would want to use this method /// </remarks> /// <param name="type">Type to ignore</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder IgnoreBase(Type type) { _ignoredTypes.Add(type); return this; } #endregion #region TypeSources /// <summary> /// Adds entities from the <see cref="ITypeSource" /> /// </summary> /// <param name="typeSource"><see cref="ITypeSource" /> to use</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder AddTypeSource(ITypeSource typeSource) { _tyeSourceFactories.Add(new InstancedObjectFactory<ITypeSource>(typeSource)); return this; } /// <summary> /// Adds entities from the provided type of typesource /// </summary> /// <param name="type">Type of typesource, expected to be ITypeSource</param> /// <returns></returns> public AutoModelBuilder AddTypeSource(Type type) { _tyeSourceFactories.Add(new TypeBasedObjectFactory<ITypeSource>(type)); return this; } /// <summary> /// Adds entities from the provided type of typesource /// </summary> /// <typeparam name="TSource">Type of typesource, expected to be ITypeSource</typeparam> /// <returns></returns> public AutoModelBuilder AddTypeSource<TSource>() where TSource : ITypeSource => AddTypeSource(typeof(TSource)); /// <summary> /// Adds entities from the provided typesources /// </summary> /// <param name="typeSources">Typesources to add </param> /// <returns></returns> public AutoModelBuilder AddTypeSources(IEnumerable<ITypeSource> typeSources) { foreach (var source in typeSources) AddTypeSource(source); return this; } /// <summary> /// Adds entities from typesources found in given assembly /// </summary> /// <param name="assembly">Assembly to add typesources from</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder AddTypeSourcesFromAssembly(Assembly assembly) { var types = assembly.GetTypesImplementingInterface(typeof(ITypeSource)); foreach (var type in types) AddTypeSource(type); return this; } /// <summary> /// Adds entities from typesources found in given assemblies /// </summary> /// <param name="assemblies">Assemblies to add typesources from</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder AddTypeSourcesFromAssemblies(IEnumerable<Assembly> assemblies) { foreach (var assembly in assemblies) AddTypeSourcesFromAssembly(assembly); return this; } /// <summary> /// Adds entities from typesources found in the assembly containing the provided type /// </summary> /// <param name="type">Assembliy containing the provided type to add typesources from</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder AddTypeSourcesFromAssemblyOf(Type type) => AddTypeSourcesFromAssembly(type.GetTypeInfo().Assembly); /// <summary> /// Adds entities from typesources found in the assembly containing the provided type /// </summary> /// <typeparam name="T">Assembliy containing the provided type to add typesources from</typeparam> public AutoModelBuilder AddTypeSourcesFromAssemblyOf<T>() => AddTypeSourcesFromAssemblyOf(typeof(T)); #endregion #region Conventions /// <summary> /// Add a convention for the ModelBuilder /// </summary> /// <param name="modelBuilderConvention">Convention to add</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder UseConvention(IModelBuilderConvention modelBuilderConvention) { _conventionFactories.Add(new InstancedObjectFactory<IModelBuilderConvention>(modelBuilderConvention)); return this; } /// <summary> /// Add a convention for the ModelBuilder /// </summary> /// <typeparam name="TConvention">Type of IModelBuilderConvention</typeparam> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder UseConvention<TConvention>() where TConvention : IModelBuilderConvention => UseConvention(typeof(TConvention)); /// <summary> /// Add a convention for the ModelBuilder /// </summary> /// <param name="type">Type of to add. Expected to be IModelBuilderConvention</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder UseConvention(Type type) { _conventionFactories.Add(new TypeBasedObjectFactory<IModelBuilderConvention>(type)); return this; } /// <summary> /// Add conventions for the ModelBuilder /// </summary> /// <param name="modelBuilderConventions">Conventions to add</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder UseConventions(IEnumerable<IModelBuilderConvention> modelBuilderConventions) { foreach (var convention in modelBuilderConventions) _conventionFactories.Add(new InstancedObjectFactory<IModelBuilderConvention>(convention)); return this; } /// <summary> /// Add conventions from specified assembly /// </summary> /// <param name="assembly">Assembly to use</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder UseConventionsFromAssembly(Assembly assembly) { var types = assembly.GetTypesImplementingInterface(typeof(IModelBuilderConvention)); foreach(var type in types) _conventionFactories.Add(new TypeBasedObjectFactory<IModelBuilderConvention>(type)); return this; } /// <summary> /// Add conventions from specified assemblies /// </summary> /// <param name="assemblies">Assemblies to use</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder UseConventionsFromAssemblies(IEnumerable<Assembly> assemblies) { foreach (var assembly in assemblies) UseConventionsFromAssembly(assembly); return this; } /// <summary> /// Add conventions from assembly containing the specified type /// </summary> /// <param name="type">Type contained in the assembly to use</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder UseConventionsFromAssemblyOf(Type type) => UseConventionsFromAssembly(type.GetTypeInfo().Assembly); /// <summary> /// Add conventions from assembly containing the specified type /// </summary> /// <typeparam name="T">Type contained in the assembly to use</typeparam> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder UseConventionsFromAssemblyOf<T>() => UseConventionsFromAssemblyOf(typeof(T)); #endregion #region Overrides /// <summary> /// Add mapping overrides from specified assembly /// </summary> /// <param name="assembly">Assembly to use</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder UseOverridesFromAssembly(Assembly assembly) { var types = assembly.GetTypesImplementingInterface(typeof(IEntityTypeOverride<>)); foreach (var type in types) UseOverride(type); return this; } /// <summary> /// Add mapping overrides from specified assemblies /// </summary> /// <param name="assemblies">Assemblies to use</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder UseOverridesFromAssemblies(IEnumerable<Assembly> assemblies) { foreach (var assembly in assemblies) UseOverridesFromAssembly(assembly); return this; } /// <summary> /// Add mapping overrides defined in assembly of the provided type /// </summary> /// <param name="type">Type contained in the required assembly</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder UseOverridesFromAssemblyOf(Type type) => UseOverridesFromAssembly(type.GetTypeInfo().Assembly); /// <summary> /// Add mapping overrides defined in assembly of T /// </summary> /// <typeparam name="T">Type contained in required assembly</typeparam> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder UseOverridesFromAssemblyOf<T>() => UseOverridesFromAssemblyOf(typeof (T)); /// <summary> /// Adds an IEntityTypeOverride via reflection /// </summary> /// <param name="overrideType">Type of override, expected to be IEntityTypeOverride</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder UseOverride(Type overrideType) { var overrideMethod = typeof(AutoModelBuilder).GetTypeInfo().GetDeclaredMethod(nameof(OverrideHelper)); if (overrideMethod == null) return this; var overrideInterfaces = overrideType.GetTypeInfo().ImplementedInterfaces.Where(x => x.IsEntityTypeOverrideType()).ToList(); var overrideInstance = Activator.CreateInstance(overrideType); foreach (var overrideInterface in overrideInterfaces) { var entityType = overrideInterface.GetTypeInfo().GenericTypeArguments.First(); AddOverride(entityType, instance => { overrideMethod.MakeGenericMethod(entityType) .Invoke(this, new[] {instance, overrideInstance}); }); } return this; } /// <summary> /// Override the mapping of specific entity /// <remarks> /// Can also be used to add single entities that are not picked up via assembly scanning /// </remarks> /// </summary> /// <typeparam name="T">Type of entity to override</typeparam> /// <param name="builderAction">Action to perform override</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder Override<T>(Action<EntityTypeBuilder<T>> builderAction = null) where T : class { _inlineOverrides.Add(new InlineOverride(typeof (T), x => { var builder = x as EntityTypeBuilder<T>; if (builder != null) builderAction?.Invoke(builder); })); return this; } #endregion #region All /// <summary> /// Adds Alterations, Entities, Conventions, and Overrides (in this order) from specified assembly /// </summary> /// <param name="assembly">Assembly to add from</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder AddFromAssembly(Assembly assembly) { AddTypeSourcesFromAssembly(assembly); AddAlterationsFromAssembly(assembly); AddEntitiesFromAssembly(assembly); UseConventionsFromAssembly(assembly); UseOverridesFromAssembly(assembly); return this; } /// <summary> /// Adds Alterations, Entities, Conventions, and Overrides (in this order) from specified assemblies /// </summary> /// <param name="assemblies">Assemblies to add from</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder AddFromAssemblies(IEnumerable<Assembly> assemblies) { AddTypeSourcesFromAssemblies(assemblies); AddAlterationsFromAssemblies(assemblies); AddEntitiesFromAssemblies(assemblies); UseConventionsFromAssemblies(assemblies); UseOverridesFromAssemblies(assemblies); return this; } /// <summary> /// Adds Alterations, Entities, Conventions, and Overrides (in this order) from assembly containing the specified type /// </summary> /// <param name="type">Type contained in the assembly to add from</param> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder AddFromAssemblyOf(Type type) => AddFromAssembly(type.GetTypeInfo().Assembly); /// <summary> /// Adds Alterations, Entities, Conventions, and Overrides (in this order) from assembly containing the specified type /// </summary> /// <typeparam name="T">Type contained in the assembly to add from</typeparam> /// <returns>AutoModelBuilder</returns> public AutoModelBuilder AddFromAssemblyOf<T>() => AddFromAssemblyOf(typeof(T)); #endregion } }
using System; using System.Collections; using System.Collections.Generic; namespace Colyseus.Schema { /// <summary> /// A <see cref="Schema" /> array of <typeparamref name="T" /> type objects /// </summary> /// <typeparam name="T">The type of object in this array</typeparam> public class ArraySchema<T> : ISchemaCollection { /// <summary> /// Map of dynamic indices for quick access of <see cref="items" /> /// </summary> protected Dictionary<int, int> indexes = new Dictionary<int, int>(); /// <summary> /// The contents of the <see cref="ArraySchema{T}" /> /// </summary> public Dictionary<int, T> items; public ArraySchema() { items = new Dictionary<int, T>(); } public ArraySchema(Dictionary<int, T> items = null) { this.items = items ?? new Dictionary<int, T>(); } /// <summary> /// Accessor to get/set <see cref="items" /> by index /// </summary> public T this[int index] { get { return GetByVirtualIndex(index); } set { items[index] = value; } } /// <inheritdoc /> public int __refId { get; set; } /// <summary> /// Set the <see cref="indexes" /> value /// </summary> /// <param name="index">The field index</param> /// <param name="dynamicIndex">The new dynamic Index value, cast to <see cref="int" /></param> public void SetIndex(int index, object dynamicIndex) { indexes[index] = (int) dynamicIndex; } /// <summary> /// Set an Item by it's <paramref name="dynamicIndex" /> /// </summary> /// <param name="index">Unused, only here to satisfy <see cref="IRef" /> parameters</param> /// <param name="dynamicIndex"> /// The index, cast to <see cref="int" />, in <see cref="items" /> that will be set to /// <paramref name="value" /> /// </param> /// <param name="value">The new object to put into <see cref="items" /></param> public void SetByIndex(int index, object dynamicIndex, object value) { items[(int) dynamicIndex] = (T) value; } /// <summary> /// Get the dynamic index value from <see cref="indexes" /> /// </summary> /// <param name="index">The location of the dynamic index to return</param> /// <returns>The dynamic index from <see cref="indexes" />, if it exists. -1 if it does not</returns> public object GetIndex(int index) { return indexes.ContainsKey(index) ? indexes[index] : -1; } /// <summary> /// Get an item out of the <see cref="ArraySchema{T}" /> by it's index /// </summary> /// <param name="index">The index of the item</param> /// <returns>An object of type <typeparamref name="T" /> if it exists</returns> public object GetByIndex(int index) { int dynamicIndex = (int) GetIndex(index); if (dynamicIndex != -1) { T value; items.TryGetValue(dynamicIndex, out value); return value; } return null; } /// <summary> /// Remove an item and it's dynamic index reference /// </summary> /// <param name="index">The index of the item</param> public void DeleteByIndex(int index) { items.Remove((int) GetIndex(index)); indexes.Remove(index); } /// <summary> /// Clear all items and indices /// </summary> /// <param name="refs">Passed in for garbage collection, if needed</param> public void Clear(ColyseusReferenceTracker refs = null) { if (refs != null && HasSchemaChild) { foreach (IRef item in items.Values) { refs.Remove(item.__refId); } } indexes.Clear(); items.Clear(); } /// <summary> /// Clone this <see cref="ArraySchema{T}" /> /// </summary> /// <returns>A copy of this <see cref="ArraySchema{T}" /></returns> public ISchemaCollection Clone() { ArraySchema<T> clone = new ArraySchema<T>(items) { OnAdd = OnAdd, OnChange = OnChange, OnRemove = OnRemove }; return clone; } /// <summary> /// Determine what type of item this <see cref="ArraySchema{T}" /> contains /// </summary> /// <returns> /// <code>typeof(<typeparamref name="T" />);</code> /// </returns> public System.Type GetChildType() { return typeof(T); } /// <summary> /// Get the default value of <typeparamref name="T" /> /// </summary> /// <returns> /// <code>default(<typeparamref name="T" />);</code> /// </returns> public object GetTypeDefaultValue() { return default(T); } /// <summary> /// Determine if this <see cref="ArraySchema{T}" /> contains <paramref name="key" /> /// </summary> /// <param name="key">The key in <see cref="items" /> that will be cast to <see cref="int" /> and checked for</param> /// <returns>True if <see cref="items" /> contains the <paramref name="key" />, false if not</returns> public bool ContainsKey(object key) { return items.ContainsKey((int) key); } /// <summary> /// Getter for <see cref="HasSchemaChild" /> /// <para>This calls: <code>Schema.CheckSchemaChild(typeof(T))</code></para> /// </summary> public bool HasSchemaChild { get; } = Schema.CheckSchemaChild(typeof(T)); /// <summary> /// Getter/Setter of the <see cref="Type.ChildPrimitiveType" /> that this <see cref="ArraySchema{T}" /> /// contains /// </summary> public string ChildPrimitiveType { get; set; } /// <summary> /// Getter for the amount of <see cref="items" /> in this <see cref="ArraySchema{T}" /> /// </summary> public int Count { get { return items.Count; } } /// <summary> /// Accessor to get/set <see cref="items" /> with a <paramref name="key" /> /// </summary> /// <param name="key"></param> public object this[object key] { get { return this[(int) key]; } set { items[(int) key] = HasSchemaChild ? (T) value : (T) Convert.ChangeType(value, typeof(T)); } } /// <summary> /// Getter function to get all the <see cref="items" /> in this <see cref="ArraySchema{T}" /> /// </summary> /// <returns> /// <see cref="items" /> /// </returns> public IDictionary GetItems() { return items; } /// <summary> /// Setter function to cast and set <see cref="items" /> /// </summary> /// <param name="items"> /// The items to pass to the <see cref="ArraySchema{T}" />. Will be cast to Dictionary{int, /// <typeparamref name="T" />} /// </param> public void SetItems(object items) { this.items = (Dictionary<int, T>) items; } /// <summary> /// Invoke <see cref="OnAdd" /> on all <see cref="items" /> /// </summary> public void TriggerAll() { if (OnAdd == null) { return; } for (int i = 0; i < items.Count; i++) { OnAdd.Invoke(i, items[i]); } } /// <summary> /// Clone the Event Handlers from another <see cref="IRef" /> into this <see cref="ArraySchema{T}" /> /// </summary> /// <param name="previousInstance">The <see cref="IRef" /> with the EventHandlers to copy</param> public void MoveEventHandlers(IRef previousInstance) { OnAdd = ((ArraySchema<T>) previousInstance).OnAdd; OnChange = ((ArraySchema<T>) previousInstance).OnChange; OnRemove = ((ArraySchema<T>) previousInstance).OnRemove; } /// <summary> /// Trigger <see cref="OnAdd" /> with a specific <paramref name="item" /> at an <paramref name="index" /> /// </summary> /// <param name="item">The <typeparamref name="T" /> item to add</param> /// <param name="index">The index of the item</param> public void InvokeOnAdd(object item, object index) { OnAdd?.Invoke((int) index, (T)item); } /// <summary> /// Trigger <see cref="OnChange" /> with a specific <paramref name="item" /> at an <paramref name="index" /> /// </summary> /// <param name="item">The <typeparamref name="T" /> item to change</param> /// <param name="index">The index of the item</param> public void InvokeOnChange(object item, object index) { OnChange?.Invoke((int) index, (T)item); } /// <summary> /// Trigger <see cref="OnRemove" /> with a specific <paramref name="item" /> at an <paramref name="index" /> /// </summary> /// <param name="item">The <typeparamref name="T" /> item to remove</param> /// <param name="index">The index of the item</param> public void InvokeOnRemove(object item, object index) { OnRemove?.Invoke((int) index, (T)item); } /// <summary> /// Event that is invoked when something is added to the <see cref="ArraySchema{T}" /> /// </summary> public event KeyValueEventHandler<int, T> OnAdd; /// <summary> /// Event that is invoked when something is changed in the <see cref="ArraySchema{T}" /> /// </summary> public event KeyValueEventHandler<int, T> OnChange; /// <summary> /// Event that is invoked when something is removed from the <see cref="ArraySchema{T}" /> /// </summary> public event KeyValueEventHandler<int, T> OnRemove; /// <summary> /// Function to iterate over <see cref="items" /> and perform an <see cref="Action{T}" /> upon each entry /// </summary> /// <param name="action">The <see cref="Action" /> to perform</param> public void ForEach(Action<T> action) { foreach (KeyValuePair<int, T> item in items) { action(item.Value); } } /// <summary> /// Get an object by the dynamic index stored in <see cref="indexes" /> at <paramref name="index" /> /// </summary> /// <param name="index">The index of the object to get</param> /// <returns>The item at the dynamic index connected to the <paramref name="index" /> provided</returns> protected T GetByVirtualIndex(int index) { // // TODO: should be O(1) // List<int> keys = new List<int>(items.Keys); int dynamicIndex = index < keys.Count ? keys[index] : -1; T value; items.TryGetValue(dynamicIndex, out value); return value; } } }
/* Copyright 2015 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Phone.Media.Capture; using System.Windows.Media; using Microsoft.Xna.Framework.Media; using Windows.Foundation; using System.IO; using Microsoft.Phone.Tasks; using System.Diagnostics; using System.Net; using System.IO.IsolatedStorage; using System.Windows.Media.Imaging; using System.Reflection; using Windows.Storage; using WPCordovaClassLib.Cordova; using WPCordovaClassLib.Cordova.Commands; using WPCordovaClassLib.CordovaLib; using Windows.ApplicationModel; namespace Cordova.Extension.Commands { public class IntelXDKCamera : BaseCommand { #region Private Variables private bool busy = false; private CameraCaptureTask cameraCaptureTask; private PhotoChooserTask photoChooserTask; private const string PICTURES = "_pictures"; private PhotoCaptureDevice photoCaptureDevice { get; set; } #endregion #region Constructor /// <summary> /// Contructor /// </summary> public IntelXDKCamera() { cameraCaptureTask = new CameraCaptureTask(); cameraCaptureTask.Completed += new EventHandler<PhotoResult>(cameraCaptureTask_Completed); } #endregion #region appMobi.js public methods public void getInfo(string parameters) { GetStartupInfo(); } /// <summary> /// Takes the picture from camera task /// </summary> /// <param name="parameters"></param> public void takePicture(string parameters) { string[] args = WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize<string[]>(parameters); string js = ""; if (args.Length < 3) { js = (string.Format("javascript:var ev = document.createEvent('Events');" + "ev.initEvent('intel.xdk.camera.picture.add',true,true);ev.success=false;" + "ev.filename='{0}';ev.message='{1}';document.dispatchEvent(ev);", "", "Wrong number of parameters")); InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true); return; } string quality = args[0]; bool saveToLib = true; bool.TryParse(args[1], out saveToLib); string picType = args[2]; if (busy) { cameraBusy(); return; } this.busy = true; // Check to see if the camera is available on the device. if (PhotoCaptureDevice.AvailableSensorLocations.Contains(CameraSensorLocation.Back) || PhotoCaptureDevice.AvailableSensorLocations.Contains(CameraSensorLocation.Front)) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, "")); cameraCaptureTask.Show(); } else { // Write message. js = (string.Format("javascript:var ev = document.createEvent('Events');" + "ev.initEvent('intel.xdk.camera.picture.add',true,true);" + "ev.success=false;ev.message='{0}';document.dispatchEvent(ev);", "Camera is not available.")); InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true); } } /// <summary> /// Takes the picture from camera task /// </summary> /// <param name="parameters"></param> public void takeFrontPicture(string parameters) { string[] args = WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize<string[]>(parameters); if (args.Length < 3) { string js = (string.Format("javascript:var ev = document.createEvent('Events');" + "ev.initEvent('intel.xdk.camera.picture.add',true,true);ev.success=false;" + "ev.filename='{0}';document.dispatchEvent(ev);", "")); InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true); return; } string quality = args[0]; bool saveToLib = true; bool.TryParse(args[1], out saveToLib); string picType = args[2]; if (busy) { cameraBusy(); return; } this.busy = true; // Check to see if the camera is available on the device. if (PhotoCaptureDevice.AvailableSensorLocations.Contains(CameraSensorLocation.Front)) { cameraCaptureTask.Show(); } else { // Write message. string js = (string.Format("javascript:var ev = document.createEvent('Events');" + "ev.initEvent('intel.xdk.camera.picture.add',true,true);" + "ev.success=false;ev.message='{0}';document.dispatchEvent(ev);", "Front camera is not available.")); InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true); } } /// <summary> /// Imports picture from Library to isolated storage photo folder /// </summary> /// <param name="parameters"></param> public void importPicture(string parameters) { if (busy) { cameraBusy(); return; } this.busy = true; pickImage(); } /// <summary> /// Deletes picture from isolated storage photo folder /// </summary> /// <param name="parameters"></param> public void deletePicture(string parameters) { string[] args = WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize<string[]>(parameters); string url = HttpUtility.UrlDecode(args[0]); if (busy) { cameraBusy(); return; } this.busy = true; # if DEBUG Debug.WriteLine("AppMobiCamera.deletePicture: " + url); #endif bool removed = RemovePhoto(url); string js = ""; if (removed) { /* Update the dictionary. */ js = (string.Format("javascript:var ev = document.createEvent('Events');" + "ev.initEvent('intel.xdk.camera.internal.picture.remove',true,true);ev.success=true;" + "ev.filename='{0}';document.dispatchEvent(ev);" + "ev = document.createEvent('Events');" + "ev.initEvent('intel.xdk.camera.picture.remove',true,true);ev.success=true;" + "ev.filename='{0}';document.dispatchEvent(ev);", url)); } else { js = (string.Format("javascript:var ev = document.createEvent('Events');" + "ev.initEvent('intel.xdk.camera.picture.remove',true,true);ev.success=false;" + "ev.filename='{0}';document.dispatchEvent(ev);", url)); } InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true); this.busy = false; } /// <summary> /// Deletes all the pictures from isolated storage photo folder /// </summary> /// <param name="parameters"></param> public void clearPictures(string parameters) { string js = ""; if (RemoveAllAppPhotos()) { js = "javascript:var ev = document.createEvent('Events');" + "ev.initEvent('intel.xdk.camera.internal.picture.clear',true,true);" + "ev.success=true;document.dispatchEvent(ev);" + "ev = document.createEvent('Events');" + "ev.initEvent('intel.xdk.camera.picture.clear',true,true);" + "ev.success=true;document.dispatchEvent(ev);"; } else { js = (string.Format("javascript:var ev = document.createEvent('Events');" + "ev.initEvent('intel.xdk.camera.picture.clear',true,true);" + "ev.success=false;ev.message='{0}';document.dispatchEvent(ev);","Clearing images failed.")); } InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true); } public async Task GetStartupInfo() { string list = await GetPictureListJS(); StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder; string path = Path.Combine(local.Path, PICTURES).Replace(@"\",@"\\"); //Info info = new Info() { pictureLocation = PICTURES }; string info = "{\"pictureLocation\":\"" + path + "\", \"pictureList\":" + list + "}"; DispatchCommandResult(new PluginResult(PluginResult.Status.OK, info)); // Hack alert: needed to clean up the OnCustomScript object in BaseCommand. InvokeCustomScript(new ScriptCallback("eval", new string[] { "var temp = {};" }), true); } /// <summary> /// Gets All the pictures from the isolated storage photo folder /// </summary> /// <param name="parameters"></param> //public async Task GetPictures(string[] parameters) //{ // string list = await GetPictureListJS(); // string js = (string.Format("javascript:{0}; ev = document.createEvent('Events');" + // "ev.initEvent('intel.xdk.camera.picture.add',true,true);ev.success=true;" + // "document.dispatchEvent(ev);", list)); // InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true); //} #endregion #region chooser handlers /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void cameraCaptureTask_Completed(object sender, PhotoResult e) { busy = false; switch (e.TaskResult) { case TaskResult.Cancel: this.pictureCancelled(); break; case TaskResult.None: break; case TaskResult.OK: savePhoto(e); break; default: break; } } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void photoChooserTask_Completed(object sender, PhotoResult e) { busy = false; switch (e.TaskResult) { case TaskResult.Cancel: this.pictureCancelled(); break; case TaskResult.None: break; case TaskResult.OK: savePhoto(e); break; default: break; } } #endregion #region private methods public async Task<string> GetPictureListJS() { bool firstPic = true; try { StringBuilder js = new StringBuilder("["); StorageFolder storageFolder = await GetStorageFolder(PICTURES); foreach (StorageFile file in await storageFolder.GetFilesAsync()) { if (!firstPic) js.Append(", "); else firstPic = false; //js.Append(string.Format("'{0}'", PICTURES + "/" + file.Name)); js.Append(string.Format("\"{0}\"", file.Name)); } js.Append("]"); return js.ToString(); } catch (Exception ex) { return "[]"; } } /* * Show the photo gallery so the user can select a picture. */ private void pickImage() { photoChooserTask = new PhotoChooserTask(); photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed); photoChooserTask.Show(); } private void savePhoto(PhotoResult e) { String filePath = e.OriginalFileName; String fileName = Path.GetFileName(e.OriginalFileName); using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) { BitmapImage bitmap = new BitmapImage(); bitmap.SetSource(e.ChosenPhoto); //string folder = Package.Current.InstalledLocation.Path; string fullFilePath = Path.Combine( PICTURES, fileName); if (savePhotoToStorage(bitmap, fullFilePath)) { if (!filePath.Equals(string.Empty)) { //var js = string.Format("javascript:var ev = document.createEvent('Events');" + // "ev.initEvent('intel.xdk.camera.internal.picture.add',true,true);ev.success=true;" + // "ev.filename='{0}';document.dispatchEvent(ev);" + // "ev = document.createEvent('Events');" + // "ev.initEvent('intel.xdk.camera.picture.add',true,true);ev.success=true;" + // "ev.filename='{0}';document.dispatchEvent(ev);", fileName); //InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true); var js = "(function(name){var ev = document.createEvent('Events');" + "ev.initEvent('intel.xdk.camera.internal.picture.add',true,true);ev.success=true;" + "ev.filename=name;document.dispatchEvent(ev);" + "ev = document.createEvent('Events');" + "ev.initEvent('intel.xdk.camera.picture.add',true,true);ev.success=true;" + "ev.filename=name;document.dispatchEvent(ev);})('" + fileName + "')"; InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true); //var js = string.Format("javascript:var ev = document.createEvent('Events');" + // "ev.initEvent('intel.xdk.camera.internal.picture.add',true,true);ev.success=true;" + // "ev.filename='{0}';document.dispatchEvent(ev);", fileName); //InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), false); //js = string.Format("javascript:var ev = document.createEvent('Events');" + // "ev.initEvent('intel.xdk.camera.picture.add',true,true);ev.success=true;" + // "ev.filename='{0}';document.dispatchEvent(ev);", fileName); //InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true); } } else { string js = (string.Format("javascript:intel.xdk.picturelist.push('{0}');var ev = document.createEvent('Events');" + "ev.initEvent('intel.xdk.camera.picture.add',true,true);ev.success=false;" + "ev.message='Photo capture failed';ev.filename='{0}';document.dispatchEvent(ev);", fileName)); InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true); } } } //private void postAddError(String fileName) //{ // string js = (string.Format("javascript:var ev = document.createEvent('Events');" + // "ev.initEvent('intel.xdk.camera.picture.add',true,true);" + // "ev.success=false;ev.message='{0}';document.dispatchEvent(ev);", "Error taking photo.")); // InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true); //} private void cameraBusy() { string js = ("javascript:var e = document.createEvent('Events');" + "e.initEvent('intel.xdk.camera.picture.busy',true,true);" + "e.success=false;e.message='busy';document.dispatchEvent(e);"); InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true); } private void pictureCancelled() { busy = false; string js = ("javascript:var ev = document.createEvent('Events');" + "ev.initEvent('intel.xdk.camera.picture.cancel',true,true);" + "ev.success=false;document.dispatchEvent(ev);"); InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true); } private string getNextPictureFile(bool isPNG) { String baseName = null; int i = 0; //do //{ baseName = String.Format("picture_%1$03d.%2$s", i++, isPNG ? "png" : "jpg"); //} while (outFile.exists()); return baseName; } /// <summary> /// Removes a specific photo for the isolated storage photo directory /// </summary> /// <param name="fileName"></param> /// <returns></returns> private bool RemovePhoto(string fileName) { try { using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) { if (isolatedStorage.FileExists(Path.Combine(PICTURES, fileName))) { isolatedStorage.DeleteFile(Path.Combine(PICTURES, fileName)); } } } catch (Exception) { //throw; return false; } return true; } /// <summary> /// Removes all the photos from the isolated storage photo directory /// </summary> /// <returns></returns> public bool RemoveAllAppPhotos() { try { using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) { if (isolatedStorage.DirectoryExists(PICTURES)) { foreach (var file in isolatedStorage.GetFileNames(Path.Combine(PICTURES, "*.*"))) { isolatedStorage.DeleteFile(Path.Combine(Path.Combine(PICTURES, file))); } } } } catch (Exception) { //throw; return false; } return true; } public static async Task<StorageFolder> GetStorageFolder(string path) { StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder; //path = path.Replace(local.Path + "\\", ""); StorageFolder storageFolder = await StorageFolder.GetFolderFromPathAsync(Path.Combine(local.Path,path)); return storageFolder; } /// <summary> /// Saves the photo to the isolated storage photo directory /// </summary> /// <param name="bitmap"></param> /// <param name="fileName"></param> /// <returns></returns> public bool savePhotoToStorage(BitmapImage bitmap, string fileName) { try { using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) { string directoryPath = Path.GetDirectoryName(fileName); if (!isolatedStorage.DirectoryExists(directoryPath)) { Debug.WriteLine("INFO: Creating Directory : " + directoryPath); isolatedStorage.CreateDirectory(directoryPath); } if (isolatedStorage.FileExists(fileName)) isolatedStorage.DeleteFile(fileName); var fileStream = isolatedStorage.CreateFile(fileName); var wb = new WriteableBitmap(bitmap); wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 100); fileStream.Close(); } return true; } catch (Exception ex) { //throw; return false; } } #endregion } //[Serializable()] //public class Info //{ // public string pictureLocation { get; set; } // public string[] pictureList { get; set; } //} }
//------------------------------------------------------------------------------ // Copyright (c) 2014-2016 the original author or authors. All Rights Reserved. // // NOTICE: You are permitted to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. //------------------------------------------------------------------------------ using NUnit.Framework; using Robotlegs.Bender.Extensions.Matching.Support.A; using Robotlegs.Bender.Extensions.Matching.Support.C; using Robotlegs.Bender.Extensions.Matching.Support.B; using System; namespace Robotlegs.Bender.Extensions.Matching { public class NamespaceMatchingTest { /*============================================================================*/ /* Private Properties */ /*============================================================================*/ private NamespaceMatcher instance; private string PACKAGE_A = "Robotlegs.Bender.Extensions.Matching.Support.A"; private string PACKAGE_B = "Robotlegs.Bender.Extensions.Matching.Support.B"; private string PACKAGE_C = "Robotlegs.Bender.Extensions.Matching.Support.C"; private string PARENT_PACKAGE = "Robotlegs.Bender.Extensions.Matching.Support"; private string REQUIRE; private string REQUIRE_2; private string[] ANY_OF; private string[] ANY_OF_2; private string[] EMPTY_VECTOR = new string[0]; private string[] NONE_OF; private string[] NONE_OF_2; private PackagedTypeA ITEM_A = new PackagedTypeA(); private PackagedTypeB ITEM_B = new PackagedTypeB(); private PackagedTypeC ITEM_C = new PackagedTypeC(); /*============================================================================*/ /* Test Setup and Teardown */ /*============================================================================*/ [SetUp] public void setUp() { REQUIRE = PARENT_PACKAGE; REQUIRE_2 = PACKAGE_A; ANY_OF = new string[]{PACKAGE_A, PACKAGE_B}; ANY_OF_2 = new string[]{PACKAGE_B, PACKAGE_C}; NONE_OF = new string[]{PACKAGE_C}; NONE_OF_2 = new string[]{PACKAGE_B}; instance = new NamespaceMatcher(); } [TearDown] public void tearDown() { instance = null; } /*============================================================================*/ /* Tests */ /*============================================================================*/ [Test] public void can_be_instantiated() { Assert.That (instance, Is.InstanceOf<NamespaceMatcher> ()); } [Test] public void implements_ITypeMatcher() { Assert.That (instance, Is.InstanceOf<ITypeMatcher> ()); } [Test] public void matches_based_on_anyOf() { instance.AnyOf(ANY_OF); ITypeFilter typeFilter = instance.CreateTypeFilter(); Assert.That(typeFilter.Matches(ITEM_A), Is.True); } [Test] public void matches_based_on_noneOf() { instance.NoneOf(NONE_OF); ITypeFilter typeFilter = instance.CreateTypeFilter(); Assert.True(typeFilter.Matches(ITEM_B)); } [Test] public void doesnt_match_based_on_noneOf() { instance.NoneOf(NONE_OF); ITypeFilter typeFilter = instance.CreateTypeFilter(); Assert.False(typeFilter.Matches(ITEM_C)); } [Test] public void matches_based_on_noneOf_twice() { instance.NoneOf(NONE_OF); instance.NoneOf(NONE_OF_2); ITypeFilter typeFilter = instance.CreateTypeFilter(); Assert.False(typeFilter.Matches(ITEM_B)); Assert.False(typeFilter.Matches(ITEM_C)); } [Test] public void matches_based_on_anyOf_twice() { instance.AnyOf(ANY_OF); instance.AnyOf(ANY_OF_2); ITypeFilter typeFilter = instance.CreateTypeFilter(); Assert.True(typeFilter.Matches(ITEM_A)); Assert.True(typeFilter.Matches(ITEM_B)); Assert.True(typeFilter.Matches(ITEM_C)); } [Test] public void matches_subpackage_a_based_on_required() { instance.Require(REQUIRE); ITypeFilter typeFilter = instance.CreateTypeFilter(); Assert.True(typeFilter.Matches(ITEM_A)); } [Test] public void matches_subpackage_b_based_on_required() { instance.Require(REQUIRE); ITypeFilter typeFilter = instance.CreateTypeFilter(); Assert.True(typeFilter.Matches(ITEM_B)); } [Test] public void doesnt_match_subpackage_c_based_on_required_and_noneOf() { instance.Require(REQUIRE).NoneOf(NONE_OF); ITypeFilter typeFilter = instance.CreateTypeFilter(); Assert.False(typeFilter.Matches(ITEM_C)); } [Test] public void throws_IllegalOperationError_if_require_changed_after_filter_requested() { Assert.Throws(typeof(Exception), new TestDelegate(() => { instance.AnyOf(ANY_OF); instance.CreateTypeFilter(); instance.Require(REQUIRE); })); } [Test] public void throws_IllegalOperationError_if_require_changed_after_lock() { Assert.Throws(typeof(Exception), new TestDelegate(() => { instance.AnyOf(ANY_OF); instance.Lock(); instance.Require(REQUIRE); } )); } [Test] public void throws_IllegalOperationError_if_anyOf_changed_after_filter_requested() { Assert.Throws(typeof(Exception), new TestDelegate(() => { instance.NoneOf(NONE_OF); instance.CreateTypeFilter(); instance.AnyOf(ANY_OF); } )); } [Test] public void throws_IllegalOperationError_if_anyOf_changed_after_lock() { Assert.Throws(typeof(Exception), new TestDelegate(() => { instance.NoneOf(NONE_OF); instance.Lock(); instance.AnyOf(ANY_OF); } )); } [Test] public void throws_IllegalOperationError_if_noneOf_changed_after_filter_requested() { Assert.Throws(typeof(Exception), new TestDelegate(() => { instance.AnyOf(ANY_OF); instance.CreateTypeFilter(); instance.NoneOf(NONE_OF); } )); } [Test] public void throws_IllegalOperationError_if_noneOf_changed_after_lock() { Assert.Throws(typeof(Exception), new TestDelegate(() => { instance.AnyOf(ANY_OF); instance.Lock(); instance.NoneOf(NONE_OF); } )); } [Test] public void throws_IllegalOperationError_if_require_called_twice() { Assert.Throws(typeof(Exception), new TestDelegate(() => { instance.Require(REQUIRE); instance.Require(REQUIRE_2); } )); } [Test] public void throws_TypeMatcherError_if_conditions_empty_and_filter_requested() { Assert.Throws(typeof(TypeMatcherException), new TestDelegate(() => { NamespaceMatcher emptyInstance = new NamespaceMatcher(); emptyInstance.AnyOf(new string[0]).NoneOf(new string[0]); emptyInstance.CreateTypeFilter(); } )); } [Test] public void throws_TypeMatcherError_if_empty_and_filter_requested() { Assert.Throws(typeof(TypeMatcherException), new TestDelegate(() => { NamespaceMatcher emptyInstance = new NamespaceMatcher(); emptyInstance.CreateTypeFilter(); } )); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Diagnostics; //for [DebuggerNonUserCode] using System.Runtime.Remoting.Lifetime; using System.Threading; using System.Reflection; using System.Collections; using System.Collections.Generic; using OpenSim.Region.ScriptEngine.Interfaces; using OpenSim.Region.ScriptEngine.Shared.Api.Interfaces; using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat; using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger; using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list; using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion; using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3; namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase { public partial class ScriptBaseClass : MarshalByRefObject { public ILSL_Api m_LSL_Functions; public void ApiTypeLSL(IScriptApi api) { if (!(api is ILSL_Api)) return; m_LSL_Functions = (ILSL_Api)api; } public void state(string newState) { m_LSL_Functions.state(newState); } // // Script functions // public LSL_Integer llAbs(int i) { return m_LSL_Functions.llAbs(i); } public LSL_Float llAcos(double val) { return m_LSL_Functions.llAcos(val); } public void llAddToLandBanList(string avatar, double hours) { m_LSL_Functions.llAddToLandBanList(avatar, hours); } public void llAddToLandPassList(string avatar, double hours) { m_LSL_Functions.llAddToLandPassList(avatar, hours); } public void llAdjustSoundVolume(double volume) { m_LSL_Functions.llAdjustSoundVolume(volume); } public void llAllowInventoryDrop(int add) { m_LSL_Functions.llAllowInventoryDrop(add); } public LSL_Float llAngleBetween(LSL_Rotation a, LSL_Rotation b) { return m_LSL_Functions.llAngleBetween(a, b); } public void llApplyImpulse(LSL_Vector force, int local) { m_LSL_Functions.llApplyImpulse(force, local); } public void llApplyRotationalImpulse(LSL_Vector force, int local) { m_LSL_Functions.llApplyRotationalImpulse(force, local); } public LSL_Float llAsin(double val) { return m_LSL_Functions.llAsin(val); } public LSL_Float llAtan2(double x, double y) { return m_LSL_Functions.llAtan2(x, y); } public void llAttachToAvatar(int attachment) { m_LSL_Functions.llAttachToAvatar(attachment); } public LSL_Key llAvatarOnSitTarget() { return m_LSL_Functions.llAvatarOnSitTarget(); } public LSL_Key llAvatarOnLinkSitTarget(int linknum) { return m_LSL_Functions.llAvatarOnLinkSitTarget(linknum); } public LSL_Rotation llAxes2Rot(LSL_Vector fwd, LSL_Vector left, LSL_Vector up) { return m_LSL_Functions.llAxes2Rot(fwd, left, up); } public LSL_Rotation llAxisAngle2Rot(LSL_Vector axis, double angle) { return m_LSL_Functions.llAxisAngle2Rot(axis, angle); } public LSL_Integer llBase64ToInteger(string str) { return m_LSL_Functions.llBase64ToInteger(str); } public LSL_String llBase64ToString(string str) { return m_LSL_Functions.llBase64ToString(str); } public void llBreakAllLinks() { m_LSL_Functions.llBreakAllLinks(); } public void llBreakLink(int linknum) { m_LSL_Functions.llBreakLink(linknum); } public LSL_Integer llCeil(double f) { return m_LSL_Functions.llCeil(f); } public void llClearCameraParams() { m_LSL_Functions.llClearCameraParams(); } public void llCloseRemoteDataChannel(string channel) { m_LSL_Functions.llCloseRemoteDataChannel(channel); } public LSL_Float llCloud(LSL_Vector offset) { return m_LSL_Functions.llCloud(offset); } public void llCollisionFilter(string name, string id, int accept) { m_LSL_Functions.llCollisionFilter(name, id, accept); } public void llCollisionSound(string impact_sound, double impact_volume) { m_LSL_Functions.llCollisionSound(impact_sound, impact_volume); } public void llCollisionSprite(string impact_sprite) { m_LSL_Functions.llCollisionSprite(impact_sprite); } public LSL_Float llCos(double f) { return m_LSL_Functions.llCos(f); } public void llCreateLink(string target, int parent) { m_LSL_Functions.llCreateLink(target, parent); } public LSL_List llCSV2List(string src) { return m_LSL_Functions.llCSV2List(src); } public LSL_List llDeleteSubList(LSL_List src, int start, int end) { return m_LSL_Functions.llDeleteSubList(src, start, end); } public LSL_String llDeleteSubString(string src, int start, int end) { return m_LSL_Functions.llDeleteSubString(src, start, end); } public void llDetachFromAvatar() { m_LSL_Functions.llDetachFromAvatar(); } public LSL_Vector llDetectedGrab(int number) { return m_LSL_Functions.llDetectedGrab(number); } public LSL_Integer llDetectedGroup(int number) { return m_LSL_Functions.llDetectedGroup(number); } public LSL_Key llDetectedKey(int number) { return m_LSL_Functions.llDetectedKey(number); } public LSL_Integer llDetectedLinkNumber(int number) { return m_LSL_Functions.llDetectedLinkNumber(number); } public LSL_String llDetectedName(int number) { return m_LSL_Functions.llDetectedName(number); } public LSL_Key llDetectedOwner(int number) { return m_LSL_Functions.llDetectedOwner(number); } public LSL_Vector llDetectedPos(int number) { return m_LSL_Functions.llDetectedPos(number); } public LSL_Rotation llDetectedRot(int number) { return m_LSL_Functions.llDetectedRot(number); } public LSL_Integer llDetectedType(int number) { return m_LSL_Functions.llDetectedType(number); } public LSL_Vector llDetectedTouchBinormal(int index) { return m_LSL_Functions.llDetectedTouchBinormal(index); } public LSL_Integer llDetectedTouchFace(int index) { return m_LSL_Functions.llDetectedTouchFace(index); } public LSL_Vector llDetectedTouchNormal(int index) { return m_LSL_Functions.llDetectedTouchNormal(index); } public LSL_Vector llDetectedTouchPos(int index) { return m_LSL_Functions.llDetectedTouchPos(index); } public LSL_Vector llDetectedTouchST(int index) { return m_LSL_Functions.llDetectedTouchST(index); } public LSL_Vector llDetectedTouchUV(int index) { return m_LSL_Functions.llDetectedTouchUV(index); } public LSL_Vector llDetectedVel(int number) { return m_LSL_Functions.llDetectedVel(number); } public void llDialog(string avatar, string message, LSL_List buttons, int chat_channel) { m_LSL_Functions.llDialog(avatar, message, buttons, chat_channel); } [DebuggerNonUserCode] public void llDie() { m_LSL_Functions.llDie(); } public LSL_String llDumpList2String(LSL_List src, string seperator) { return m_LSL_Functions.llDumpList2String(src, seperator); } public LSL_Integer llEdgeOfWorld(LSL_Vector pos, LSL_Vector dir) { return m_LSL_Functions.llEdgeOfWorld(pos, dir); } public void llEjectFromLand(string pest) { m_LSL_Functions.llEjectFromLand(pest); } public void llEmail(string address, string subject, string message) { m_LSL_Functions.llEmail(address, subject, message); } public LSL_String llEscapeURL(string url) { return m_LSL_Functions.llEscapeURL(url); } public LSL_Rotation llEuler2Rot(LSL_Vector v) { return m_LSL_Functions.llEuler2Rot(v); } public LSL_Float llFabs(double f) { return m_LSL_Functions.llFabs(f); } public LSL_Integer llFloor(double f) { return m_LSL_Functions.llFloor(f); } public void llForceMouselook(int mouselook) { m_LSL_Functions.llForceMouselook(mouselook); } public LSL_Float llFrand(double mag) { return m_LSL_Functions.llFrand(mag); } public LSL_Key llGenerateKey() { return m_LSL_Functions.llGenerateKey(); } public LSL_Vector llGetAccel() { return m_LSL_Functions.llGetAccel(); } public LSL_Integer llGetAgentInfo(string id) { return m_LSL_Functions.llGetAgentInfo(id); } public LSL_String llGetAgentLanguage(string id) { return m_LSL_Functions.llGetAgentLanguage(id); } public LSL_List llGetAgentList(LSL_Integer scope, LSL_List options) { return m_LSL_Functions.llGetAgentList(scope, options); } public LSL_Vector llGetAgentSize(string id) { return m_LSL_Functions.llGetAgentSize(id); } public LSL_Float llGetAlpha(int face) { return m_LSL_Functions.llGetAlpha(face); } public LSL_Float llGetAndResetTime() { return m_LSL_Functions.llGetAndResetTime(); } public LSL_String llGetAnimation(string id) { return m_LSL_Functions.llGetAnimation(id); } public LSL_List llGetAnimationList(string id) { return m_LSL_Functions.llGetAnimationList(id); } public LSL_Integer llGetAttached() { return m_LSL_Functions.llGetAttached(); } public LSL_List llGetBoundingBox(string obj) { return m_LSL_Functions.llGetBoundingBox(obj); } public LSL_Vector llGetCameraPos() { return m_LSL_Functions.llGetCameraPos(); } public LSL_Rotation llGetCameraRot() { return m_LSL_Functions.llGetCameraRot(); } public LSL_Vector llGetCenterOfMass() { return m_LSL_Functions.llGetCenterOfMass(); } public LSL_Vector llGetColor(int face) { return m_LSL_Functions.llGetColor(face); } public LSL_String llGetCreator() { return m_LSL_Functions.llGetCreator(); } public LSL_String llGetDate() { return m_LSL_Functions.llGetDate(); } public LSL_Float llGetEnergy() { return m_LSL_Functions.llGetEnergy(); } public LSL_String llGetEnv(LSL_String name) { return m_LSL_Functions.llGetEnv(name); } public LSL_Vector llGetForce() { return m_LSL_Functions.llGetForce(); } public LSL_Integer llGetFreeMemory() { return m_LSL_Functions.llGetFreeMemory(); } public LSL_Integer llGetUsedMemory() { return m_LSL_Functions.llGetUsedMemory(); } public LSL_Integer llGetFreeURLs() { return m_LSL_Functions.llGetFreeURLs(); } public LSL_Vector llGetGeometricCenter() { return m_LSL_Functions.llGetGeometricCenter(); } public LSL_Float llGetGMTclock() { return m_LSL_Functions.llGetGMTclock(); } public LSL_String llGetHTTPHeader(LSL_Key request_id, string header) { return m_LSL_Functions.llGetHTTPHeader(request_id, header); } public LSL_Key llGetInventoryCreator(string item) { return m_LSL_Functions.llGetInventoryCreator(item); } public LSL_Key llGetInventoryKey(string name) { return m_LSL_Functions.llGetInventoryKey(name); } public LSL_String llGetInventoryName(int type, int number) { return m_LSL_Functions.llGetInventoryName(type, number); } public LSL_Integer llGetInventoryNumber(int type) { return m_LSL_Functions.llGetInventoryNumber(type); } public LSL_Integer llGetInventoryPermMask(string item, int mask) { return m_LSL_Functions.llGetInventoryPermMask(item, mask); } public LSL_Integer llGetInventoryType(string name) { return m_LSL_Functions.llGetInventoryType(name); } public LSL_Key llGetKey() { return m_LSL_Functions.llGetKey(); } public LSL_Key llGetLandOwnerAt(LSL_Vector pos) { return m_LSL_Functions.llGetLandOwnerAt(pos); } public LSL_Key llGetLinkKey(int linknum) { return m_LSL_Functions.llGetLinkKey(linknum); } public LSL_String llGetLinkName(int linknum) { return m_LSL_Functions.llGetLinkName(linknum); } public LSL_Integer llGetLinkNumber() { return m_LSL_Functions.llGetLinkNumber(); } public LSL_Integer llGetLinkNumberOfSides(int link) { return m_LSL_Functions.llGetLinkNumberOfSides(link); } public LSL_Integer llGetListEntryType(LSL_List src, int index) { return m_LSL_Functions.llGetListEntryType(src, index); } public LSL_Integer llGetListLength(LSL_List src) { return m_LSL_Functions.llGetListLength(src); } public LSL_Vector llGetLocalPos() { return m_LSL_Functions.llGetLocalPos(); } public LSL_Rotation llGetLocalRot() { return m_LSL_Functions.llGetLocalRot(); } public LSL_Float llGetMass() { return m_LSL_Functions.llGetMass(); } public LSL_Float llGetMassMKS() { return m_LSL_Functions.llGetMassMKS(); } public LSL_Integer llGetMemoryLimit() { return m_LSL_Functions.llGetMemoryLimit(); } public void llGetNextEmail(string address, string subject) { m_LSL_Functions.llGetNextEmail(address, subject); } public LSL_String llGetNotecardLine(string name, int line) { return m_LSL_Functions.llGetNotecardLine(name, line); } public LSL_Key llGetNumberOfNotecardLines(string name) { return m_LSL_Functions.llGetNumberOfNotecardLines(name); } public LSL_Integer llGetNumberOfPrims() { return m_LSL_Functions.llGetNumberOfPrims(); } public LSL_Integer llGetNumberOfSides() { return m_LSL_Functions.llGetNumberOfSides(); } public LSL_String llGetObjectDesc() { return m_LSL_Functions.llGetObjectDesc(); } public LSL_List llGetObjectDetails(string id, LSL_List args) { return m_LSL_Functions.llGetObjectDetails(id, args); } public LSL_Float llGetObjectMass(string id) { return m_LSL_Functions.llGetObjectMass(id); } public LSL_String llGetObjectName() { return m_LSL_Functions.llGetObjectName(); } public LSL_Integer llGetObjectPermMask(int mask) { return m_LSL_Functions.llGetObjectPermMask(mask); } public LSL_Integer llGetObjectPrimCount(string object_id) { return m_LSL_Functions.llGetObjectPrimCount(object_id); } public LSL_Vector llGetOmega() { return m_LSL_Functions.llGetOmega(); } public LSL_Key llGetOwner() { return m_LSL_Functions.llGetOwner(); } public LSL_Key llGetOwnerKey(string id) { return m_LSL_Functions.llGetOwnerKey(id); } public LSL_List llGetParcelDetails(LSL_Vector pos, LSL_List param) { return m_LSL_Functions.llGetParcelDetails(pos, param); } public LSL_Integer llGetParcelFlags(LSL_Vector pos) { return m_LSL_Functions.llGetParcelFlags(pos); } public LSL_Integer llGetParcelMaxPrims(LSL_Vector pos, int sim_wide) { return m_LSL_Functions.llGetParcelMaxPrims(pos, sim_wide); } public LSL_String llGetParcelMusicURL() { return m_LSL_Functions.llGetParcelMusicURL(); } public LSL_Integer llGetParcelPrimCount(LSL_Vector pos, int category, int sim_wide) { return m_LSL_Functions.llGetParcelPrimCount(pos, category, sim_wide); } public LSL_List llGetParcelPrimOwners(LSL_Vector pos) { return m_LSL_Functions.llGetParcelPrimOwners(pos); } public LSL_Integer llGetPermissions() { return m_LSL_Functions.llGetPermissions(); } public LSL_Key llGetPermissionsKey() { return m_LSL_Functions.llGetPermissionsKey(); } public LSL_Vector llGetPos() { return m_LSL_Functions.llGetPos(); } public LSL_List llGetPrimitiveParams(LSL_List rules) { return m_LSL_Functions.llGetPrimitiveParams(rules); } public LSL_List llGetLinkPrimitiveParams(int linknum, LSL_List rules) { return m_LSL_Functions.llGetLinkPrimitiveParams(linknum, rules); } public LSL_Integer llGetRegionAgentCount() { return m_LSL_Functions.llGetRegionAgentCount(); } public LSL_Vector llGetRegionCorner() { return m_LSL_Functions.llGetRegionCorner(); } public LSL_Integer llGetRegionFlags() { return m_LSL_Functions.llGetRegionFlags(); } public LSL_Float llGetRegionFPS() { return m_LSL_Functions.llGetRegionFPS(); } public LSL_String llGetRegionName() { return m_LSL_Functions.llGetRegionName(); } public LSL_Float llGetRegionTimeDilation() { return m_LSL_Functions.llGetRegionTimeDilation(); } public LSL_Vector llGetRootPosition() { return m_LSL_Functions.llGetRootPosition(); } public LSL_Rotation llGetRootRotation() { return m_LSL_Functions.llGetRootRotation(); } public LSL_Rotation llGetRot() { return m_LSL_Functions.llGetRot(); } public LSL_Vector llGetScale() { return m_LSL_Functions.llGetScale(); } public LSL_String llGetScriptName() { return m_LSL_Functions.llGetScriptName(); } public LSL_Integer llGetScriptState(string name) { return m_LSL_Functions.llGetScriptState(name); } public LSL_String llGetSimulatorHostname() { return m_LSL_Functions.llGetSimulatorHostname(); } public LSL_Integer llGetSPMaxMemory() { return m_LSL_Functions.llGetSPMaxMemory(); } public LSL_Integer llGetStartParameter() { return m_LSL_Functions.llGetStartParameter(); } public LSL_Integer llGetStatus(int status) { return m_LSL_Functions.llGetStatus(status); } public LSL_String llGetSubString(string src, int start, int end) { return m_LSL_Functions.llGetSubString(src, start, end); } public LSL_Vector llGetSunDirection() { return m_LSL_Functions.llGetSunDirection(); } public LSL_String llGetTexture(int face) { return m_LSL_Functions.llGetTexture(face); } public LSL_Vector llGetTextureOffset(int face) { return m_LSL_Functions.llGetTextureOffset(face); } public LSL_Float llGetTextureRot(int side) { return m_LSL_Functions.llGetTextureRot(side); } public LSL_Vector llGetTextureScale(int side) { return m_LSL_Functions.llGetTextureScale(side); } public LSL_Float llGetTime() { return m_LSL_Functions.llGetTime(); } public LSL_Float llGetTimeOfDay() { return m_LSL_Functions.llGetTimeOfDay(); } public LSL_String llGetTimestamp() { return m_LSL_Functions.llGetTimestamp(); } public LSL_Vector llGetTorque() { return m_LSL_Functions.llGetTorque(); } public LSL_Integer llGetUnixTime() { return m_LSL_Functions.llGetUnixTime(); } public LSL_Vector llGetVel() { return m_LSL_Functions.llGetVel(); } public LSL_Float llGetWallclock() { return m_LSL_Functions.llGetWallclock(); } public void llGiveInventory(string destination, string inventory) { m_LSL_Functions.llGiveInventory(destination, inventory); } public void llGiveInventoryList(string destination, string category, LSL_List inventory) { m_LSL_Functions.llGiveInventoryList(destination, category, inventory); } public LSL_Integer llGiveMoney(string destination, int amount) { return m_LSL_Functions.llGiveMoney(destination, amount); } public LSL_String llTransferLindenDollars(string destination, int amount) { return m_LSL_Functions.llTransferLindenDollars(destination, amount); } public void llGodLikeRezObject(string inventory, LSL_Vector pos) { m_LSL_Functions.llGodLikeRezObject(inventory, pos); } public LSL_Float llGround(LSL_Vector offset) { return m_LSL_Functions.llGround(offset); } public LSL_Vector llGroundContour(LSL_Vector offset) { return m_LSL_Functions.llGroundContour(offset); } public LSL_Vector llGroundNormal(LSL_Vector offset) { return m_LSL_Functions.llGroundNormal(offset); } public void llGroundRepel(double height, int water, double tau) { m_LSL_Functions.llGroundRepel(height, water, tau); } public LSL_Vector llGroundSlope(LSL_Vector offset) { return m_LSL_Functions.llGroundSlope(offset); } public LSL_String llHTTPRequest(string url, LSL_List parameters, string body) { return m_LSL_Functions.llHTTPRequest(url, parameters, body); } public void llHTTPResponse(LSL_Key id, int status, string body) { m_LSL_Functions.llHTTPResponse(id, status, body); } public LSL_String llInsertString(string dst, int position, string src) { return m_LSL_Functions.llInsertString(dst, position, src); } public void llInstantMessage(string user, string message) { m_LSL_Functions.llInstantMessage(user, message); } public LSL_String llIntegerToBase64(int number) { return m_LSL_Functions.llIntegerToBase64(number); } public LSL_String llKey2Name(string id) { return m_LSL_Functions.llKey2Name(id); } public LSL_String llGetUsername(string id) { return m_LSL_Functions.llGetUsername(id); } public LSL_String llRequestUsername(string id) { return m_LSL_Functions.llRequestUsername(id); } public LSL_String llGetDisplayName(string id) { return m_LSL_Functions.llGetDisplayName(id); } public LSL_String llRequestDisplayName(string id) { return m_LSL_Functions.llRequestDisplayName(id); } public LSL_List llCastRay(LSL_Vector start, LSL_Vector end, LSL_List options) { return m_LSL_Functions.llCastRay(start, end, options); } public void llLinkParticleSystem(int linknum, LSL_List rules) { m_LSL_Functions.llLinkParticleSystem(linknum, rules); } public LSL_String llList2CSV(LSL_List src) { return m_LSL_Functions.llList2CSV(src); } public LSL_Float llList2Float(LSL_List src, int index) { return m_LSL_Functions.llList2Float(src, index); } public LSL_Integer llList2Integer(LSL_List src, int index) { return m_LSL_Functions.llList2Integer(src, index); } public LSL_Key llList2Key(LSL_List src, int index) { return m_LSL_Functions.llList2Key(src, index); } public LSL_List llList2List(LSL_List src, int start, int end) { return m_LSL_Functions.llList2List(src, start, end); } public LSL_List llList2ListStrided(LSL_List src, int start, int end, int stride) { return m_LSL_Functions.llList2ListStrided(src, start, end, stride); } public LSL_Rotation llList2Rot(LSL_List src, int index) { return m_LSL_Functions.llList2Rot(src, index); } public LSL_String llList2String(LSL_List src, int index) { return m_LSL_Functions.llList2String(src, index); } public LSL_Vector llList2Vector(LSL_List src, int index) { return m_LSL_Functions.llList2Vector(src, index); } public LSL_Integer llListen(int channelID, string name, string ID, string msg) { return m_LSL_Functions.llListen(channelID, name, ID, msg); } public void llListenControl(int number, int active) { m_LSL_Functions.llListenControl(number, active); } public void llListenRemove(int number) { m_LSL_Functions.llListenRemove(number); } public LSL_Integer llListFindList(LSL_List src, LSL_List test) { return m_LSL_Functions.llListFindList(src, test); } public LSL_List llListInsertList(LSL_List dest, LSL_List src, int start) { return m_LSL_Functions.llListInsertList(dest, src, start); } public LSL_List llListRandomize(LSL_List src, int stride) { return m_LSL_Functions.llListRandomize(src, stride); } public LSL_List llListReplaceList(LSL_List dest, LSL_List src, int start, int end) { return m_LSL_Functions.llListReplaceList(dest, src, start, end); } public LSL_List llListSort(LSL_List src, int stride, int ascending) { return m_LSL_Functions.llListSort(src, stride, ascending); } public LSL_Float llListStatistics(int operation, LSL_List src) { return m_LSL_Functions.llListStatistics(operation, src); } public void llLoadURL(string avatar_id, string message, string url) { m_LSL_Functions.llLoadURL(avatar_id, message, url); } public LSL_Float llLog(double val) { return m_LSL_Functions.llLog(val); } public LSL_Float llLog10(double val) { return m_LSL_Functions.llLog10(val); } public void llLookAt(LSL_Vector target, double strength, double damping) { m_LSL_Functions.llLookAt(target, strength, damping); } public void llLoopSound(string sound, double volume) { m_LSL_Functions.llLoopSound(sound, volume); } public void llLoopSoundMaster(string sound, double volume) { m_LSL_Functions.llLoopSoundMaster(sound, volume); } public void llLoopSoundSlave(string sound, double volume) { m_LSL_Functions.llLoopSoundSlave(sound, volume); } public LSL_Integer llManageEstateAccess(int action, string avatar) { return m_LSL_Functions.llManageEstateAccess(action, avatar); } public void llMakeExplosion(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset) { m_LSL_Functions.llMakeExplosion(particles, scale, vel, lifetime, arc, texture, offset); } public void llMakeFire(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset) { m_LSL_Functions.llMakeFire(particles, scale, vel, lifetime, arc, texture, offset); } public void llMakeFountain(int particles, double scale, double vel, double lifetime, double arc, int bounce, string texture, LSL_Vector offset, double bounce_offset) { m_LSL_Functions.llMakeFountain(particles, scale, vel, lifetime, arc, bounce, texture, offset, bounce_offset); } public void llMakeSmoke(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset) { m_LSL_Functions.llMakeSmoke(particles, scale, vel, lifetime, arc, texture, offset); } public void llMapDestination(string simname, LSL_Vector pos, LSL_Vector look_at) { m_LSL_Functions.llMapDestination(simname, pos, look_at); } public LSL_String llMD5String(string src, int nonce) { return m_LSL_Functions.llMD5String(src, nonce); } public LSL_String llSHA1String(string src) { return m_LSL_Functions.llSHA1String(src); } public void llMessageLinked(int linknum, int num, string str, string id) { m_LSL_Functions.llMessageLinked(linknum, num, str, id); } public void llMinEventDelay(double delay) { m_LSL_Functions.llMinEventDelay(delay); } public void llModifyLand(int action, int brush) { m_LSL_Functions.llModifyLand(action, brush); } public LSL_Integer llModPow(int a, int b, int c) { return m_LSL_Functions.llModPow(a, b, c); } public void llMoveToTarget(LSL_Vector target, double tau) { m_LSL_Functions.llMoveToTarget(target, tau); } public void llOffsetTexture(double u, double v, int face) { m_LSL_Functions.llOffsetTexture(u, v, face); } public void llOpenRemoteDataChannel() { m_LSL_Functions.llOpenRemoteDataChannel(); } public LSL_Integer llOverMyLand(string id) { return m_LSL_Functions.llOverMyLand(id); } public void llOwnerSay(string msg) { m_LSL_Functions.llOwnerSay(msg); } public void llParcelMediaCommandList(LSL_List commandList) { m_LSL_Functions.llParcelMediaCommandList(commandList); } public LSL_List llParcelMediaQuery(LSL_List aList) { return m_LSL_Functions.llParcelMediaQuery(aList); } public LSL_List llParseString2List(string str, LSL_List separators, LSL_List spacers) { return m_LSL_Functions.llParseString2List(str, separators, spacers); } public LSL_List llParseStringKeepNulls(string src, LSL_List seperators, LSL_List spacers) { return m_LSL_Functions.llParseStringKeepNulls(src, seperators, spacers); } public void llParticleSystem(LSL_List rules) { m_LSL_Functions.llParticleSystem(rules); } public void llPassCollisions(int pass) { m_LSL_Functions.llPassCollisions(pass); } public void llPassTouches(int pass) { m_LSL_Functions.llPassTouches(pass); } public void llPlaySound(string sound, double volume) { m_LSL_Functions.llPlaySound(sound, volume); } public void llPlaySoundSlave(string sound, double volume) { m_LSL_Functions.llPlaySoundSlave(sound, volume); } public void llPointAt(LSL_Vector pos) { m_LSL_Functions.llPointAt(pos); } public LSL_Float llPow(double fbase, double fexponent) { return m_LSL_Functions.llPow(fbase, fexponent); } public void llPreloadSound(string sound) { m_LSL_Functions.llPreloadSound(sound); } public void llPushObject(string target, LSL_Vector impulse, LSL_Vector ang_impulse, int local) { m_LSL_Functions.llPushObject(target, impulse, ang_impulse, local); } public void llRefreshPrimURL() { m_LSL_Functions.llRefreshPrimURL(); } public void llRegionSay(int channelID, string text) { m_LSL_Functions.llRegionSay(channelID, text); } public void llRegionSayTo(string key, int channelID, string text) { m_LSL_Functions.llRegionSayTo(key, channelID, text); } public void llReleaseCamera(string avatar) { m_LSL_Functions.llReleaseCamera(avatar); } public void llReleaseURL(string url) { m_LSL_Functions.llReleaseURL(url); } public void llReleaseControls() { m_LSL_Functions.llReleaseControls(); } public void llRemoteDataReply(string channel, string message_id, string sdata, int idata) { m_LSL_Functions.llRemoteDataReply(channel, message_id, sdata, idata); } public void llRemoteDataSetRegion() { m_LSL_Functions.llRemoteDataSetRegion(); } public void llRemoteLoadScript(string target, string name, int running, int start_param) { m_LSL_Functions.llRemoteLoadScript(target, name, running, start_param); } public void llRemoteLoadScriptPin(string target, string name, int pin, int running, int start_param) { m_LSL_Functions.llRemoteLoadScriptPin(target, name, pin, running, start_param); } public void llRemoveFromLandBanList(string avatar) { m_LSL_Functions.llRemoveFromLandBanList(avatar); } public void llRemoveFromLandPassList(string avatar) { m_LSL_Functions.llRemoveFromLandPassList(avatar); } public void llRemoveInventory(string item) { m_LSL_Functions.llRemoveInventory(item); } public void llRemoveVehicleFlags(int flags) { m_LSL_Functions.llRemoveVehicleFlags(flags); } public LSL_Key llRequestAgentData(string id, int data) { return m_LSL_Functions.llRequestAgentData(id, data); } public LSL_Key llRequestInventoryData(string name) { return m_LSL_Functions.llRequestInventoryData(name); } public void llRequestPermissions(string agent, int perm) { m_LSL_Functions.llRequestPermissions(agent, perm); } public LSL_String llRequestSecureURL() { return m_LSL_Functions.llRequestSecureURL(); } public LSL_Key llRequestSimulatorData(string simulator, int data) { return m_LSL_Functions.llRequestSimulatorData(simulator, data); } public LSL_Key llRequestURL() { return m_LSL_Functions.llRequestURL(); } public void llResetLandBanList() { m_LSL_Functions.llResetLandBanList(); } public void llResetLandPassList() { m_LSL_Functions.llResetLandPassList(); } public void llResetOtherScript(string name) { m_LSL_Functions.llResetOtherScript(name); } public void llResetScript() { m_LSL_Functions.llResetScript(); } public void llResetTime() { m_LSL_Functions.llResetTime(); } public void llRezAtRoot(string inventory, LSL_Vector position, LSL_Vector velocity, LSL_Rotation rot, int param) { m_LSL_Functions.llRezAtRoot(inventory, position, velocity, rot, param); } public void llRezObject(string inventory, LSL_Vector pos, LSL_Vector vel, LSL_Rotation rot, int param) { m_LSL_Functions.llRezObject(inventory, pos, vel, rot, param); } public LSL_Float llRot2Angle(LSL_Rotation rot) { return m_LSL_Functions.llRot2Angle(rot); } public LSL_Vector llRot2Axis(LSL_Rotation rot) { return m_LSL_Functions.llRot2Axis(rot); } public LSL_Vector llRot2Euler(LSL_Rotation r) { return m_LSL_Functions.llRot2Euler(r); } public LSL_Vector llRot2Fwd(LSL_Rotation r) { return m_LSL_Functions.llRot2Fwd(r); } public LSL_Vector llRot2Left(LSL_Rotation r) { return m_LSL_Functions.llRot2Left(r); } public LSL_Vector llRot2Up(LSL_Rotation r) { return m_LSL_Functions.llRot2Up(r); } public void llRotateTexture(double rotation, int face) { m_LSL_Functions.llRotateTexture(rotation, face); } public LSL_Rotation llRotBetween(LSL_Vector start, LSL_Vector end) { return m_LSL_Functions.llRotBetween(start, end); } public void llRotLookAt(LSL_Rotation target, double strength, double damping) { m_LSL_Functions.llRotLookAt(target, strength, damping); } public LSL_Integer llRotTarget(LSL_Rotation rot, double error) { return m_LSL_Functions.llRotTarget(rot, error); } public void llRotTargetRemove(int number) { m_LSL_Functions.llRotTargetRemove(number); } public LSL_Integer llRound(double f) { return m_LSL_Functions.llRound(f); } public LSL_Integer llSameGroup(string agent) { return m_LSL_Functions.llSameGroup(agent); } public void llSay(int channelID, string text) { m_LSL_Functions.llSay(channelID, text); } public void llScaleTexture(double u, double v, int face) { m_LSL_Functions.llScaleTexture(u, v, face); } public LSL_Integer llScriptDanger(LSL_Vector pos) { return m_LSL_Functions.llScriptDanger(pos); } public void llScriptProfiler(LSL_Integer flags) { m_LSL_Functions.llScriptProfiler(flags); } public LSL_Key llSendRemoteData(string channel, string dest, int idata, string sdata) { return m_LSL_Functions.llSendRemoteData(channel, dest, idata, sdata); } public void llSensor(string name, string id, int type, double range, double arc) { m_LSL_Functions.llSensor(name, id, type, range, arc); } public void llSensorRemove() { m_LSL_Functions.llSensorRemove(); } public void llSensorRepeat(string name, string id, int type, double range, double arc, double rate) { m_LSL_Functions.llSensorRepeat(name, id, type, range, arc, rate); } public void llSetAlpha(double alpha, int face) { m_LSL_Functions.llSetAlpha(alpha, face); } public void llSetBuoyancy(double buoyancy) { m_LSL_Functions.llSetBuoyancy(buoyancy); } public void llSetCameraAtOffset(LSL_Vector offset) { m_LSL_Functions.llSetCameraAtOffset(offset); } public void llSetCameraEyeOffset(LSL_Vector offset) { m_LSL_Functions.llSetCameraEyeOffset(offset); } public void llSetLinkCamera(LSL_Integer link, LSL_Vector eye, LSL_Vector at) { m_LSL_Functions.llSetLinkCamera(link, eye, at); } public void llSetCameraParams(LSL_List rules) { m_LSL_Functions.llSetCameraParams(rules); } public void llSetClickAction(int action) { m_LSL_Functions.llSetClickAction(action); } public void llSetColor(LSL_Vector color, int face) { m_LSL_Functions.llSetColor(color, face); } public void llSetContentType(LSL_Key id, LSL_Integer type) { m_LSL_Functions.llSetContentType(id, type); } public void llSetDamage(double damage) { m_LSL_Functions.llSetDamage(damage); } public void llSetForce(LSL_Vector force, int local) { m_LSL_Functions.llSetForce(force, local); } public void llSetForceAndTorque(LSL_Vector force, LSL_Vector torque, int local) { m_LSL_Functions.llSetForceAndTorque(force, torque, local); } public void llSetVelocity(LSL_Vector force, int local) { m_LSL_Functions.llSetVelocity(force, local); } public void llSetAngularVelocity(LSL_Vector force, int local) { m_LSL_Functions.llSetAngularVelocity(force, local); } public void llSetHoverHeight(double height, int water, double tau) { m_LSL_Functions.llSetHoverHeight(height, water, tau); } public void llSetInventoryPermMask(string item, int mask, int value) { m_LSL_Functions.llSetInventoryPermMask(item, mask, value); } public void llSetLinkAlpha(int linknumber, double alpha, int face) { m_LSL_Functions.llSetLinkAlpha(linknumber, alpha, face); } public void llSetLinkColor(int linknumber, LSL_Vector color, int face) { m_LSL_Functions.llSetLinkColor(linknumber, color, face); } public void llSetLinkPrimitiveParams(int linknumber, LSL_List rules) { m_LSL_Functions.llSetLinkPrimitiveParams(linknumber, rules); } public void llSetLinkTexture(int linknumber, string texture, int face) { m_LSL_Functions.llSetLinkTexture(linknumber, texture, face); } public void llSetLinkTextureAnim(int linknum, int mode, int face, int sizex, int sizey, double start, double length, double rate) { m_LSL_Functions.llSetLinkTextureAnim(linknum, mode, face, sizex, sizey, start, length, rate); } public void llSetLocalRot(LSL_Rotation rot) { m_LSL_Functions.llSetLocalRot(rot); } public LSL_Integer llSetMemoryLimit(LSL_Integer limit) { return m_LSL_Functions.llSetMemoryLimit(limit); } public void llSetObjectDesc(string desc) { m_LSL_Functions.llSetObjectDesc(desc); } public void llSetObjectName(string name) { m_LSL_Functions.llSetObjectName(name); } public void llSetObjectPermMask(int mask, int value) { m_LSL_Functions.llSetObjectPermMask(mask, value); } public void llSetParcelMusicURL(string url) { m_LSL_Functions.llSetParcelMusicURL(url); } public void llSetPayPrice(int price, LSL_List quick_pay_buttons) { m_LSL_Functions.llSetPayPrice(price, quick_pay_buttons); } public void llSetPos(LSL_Vector pos) { m_LSL_Functions.llSetPos(pos); } public LSL_Integer llSetRegionPos(LSL_Vector pos) { return m_LSL_Functions.llSetRegionPos(pos); } public void llSetPrimitiveParams(LSL_List rules) { m_LSL_Functions.llSetPrimitiveParams(rules); } public void llSetLinkPrimitiveParamsFast(int linknum, LSL_List rules) { m_LSL_Functions.llSetLinkPrimitiveParamsFast(linknum, rules); } public void llSetPrimURL(string url) { m_LSL_Functions.llSetPrimURL(url); } public void llSetRemoteScriptAccessPin(int pin) { m_LSL_Functions.llSetRemoteScriptAccessPin(pin); } public void llSetRot(LSL_Rotation rot) { m_LSL_Functions.llSetRot(rot); } public void llSetScale(LSL_Vector scale) { m_LSL_Functions.llSetScale(scale); } public void llSetScriptState(string name, int run) { m_LSL_Functions.llSetScriptState(name, run); } public void llSetSitText(string text) { m_LSL_Functions.llSetSitText(text); } public void llSetSoundQueueing(int queue) { m_LSL_Functions.llSetSoundQueueing(queue); } public void llSetSoundRadius(double radius) { m_LSL_Functions.llSetSoundRadius(radius); } public void llSetStatus(int status, int value) { m_LSL_Functions.llSetStatus(status, value); } public void llSetText(string text, LSL_Vector color, double alpha) { m_LSL_Functions.llSetText(text, color, alpha); } public void llSetTexture(string texture, int face) { m_LSL_Functions.llSetTexture(texture, face); } public void llSetTextureAnim(int mode, int face, int sizex, int sizey, double start, double length, double rate) { m_LSL_Functions.llSetTextureAnim(mode, face, sizex, sizey, start, length, rate); } public void llSetTimerEvent(double sec) { m_LSL_Functions.llSetTimerEvent(sec); } public void llSetTorque(LSL_Vector torque, int local) { m_LSL_Functions.llSetTorque(torque, local); } public void llSetTouchText(string text) { m_LSL_Functions.llSetTouchText(text); } public void llSetVehicleFlags(int flags) { m_LSL_Functions.llSetVehicleFlags(flags); } public void llSetVehicleFloatParam(int param, LSL_Float value) { m_LSL_Functions.llSetVehicleFloatParam(param, value); } public void llSetVehicleRotationParam(int param, LSL_Rotation rot) { m_LSL_Functions.llSetVehicleRotationParam(param, rot); } public void llSetVehicleType(int type) { m_LSL_Functions.llSetVehicleType(type); } public void llSetVehicleVectorParam(int param, LSL_Vector vec) { m_LSL_Functions.llSetVehicleVectorParam(param, vec); } public void llShout(int channelID, string text) { m_LSL_Functions.llShout(channelID, text); } public LSL_Float llSin(double f) { return m_LSL_Functions.llSin(f); } public void llSitTarget(LSL_Vector offset, LSL_Rotation rot) { m_LSL_Functions.llSitTarget(offset, rot); } public void llLinkSitTarget(LSL_Integer link, LSL_Vector offset, LSL_Rotation rot) { m_LSL_Functions.llLinkSitTarget(link, offset, rot); } public void llSleep(double sec) { m_LSL_Functions.llSleep(sec); } public void llSound(string sound, double volume, int queue, int loop) { m_LSL_Functions.llSound(sound, volume, queue, loop); } public void llSoundPreload(string sound) { m_LSL_Functions.llSoundPreload(sound); } public LSL_Float llSqrt(double f) { return m_LSL_Functions.llSqrt(f); } public void llStartAnimation(string anim) { m_LSL_Functions.llStartAnimation(anim); } public void llStopAnimation(string anim) { m_LSL_Functions.llStopAnimation(anim); } public void llStopHover() { m_LSL_Functions.llStopHover(); } public void llStopLookAt() { m_LSL_Functions.llStopLookAt(); } public void llStopMoveToTarget() { m_LSL_Functions.llStopMoveToTarget(); } public void llStopPointAt() { m_LSL_Functions.llStopPointAt(); } public void llStopSound() { m_LSL_Functions.llStopSound(); } public LSL_Integer llStringLength(string str) { return m_LSL_Functions.llStringLength(str); } public LSL_String llStringToBase64(string str) { return m_LSL_Functions.llStringToBase64(str); } public LSL_String llStringTrim(string src, int type) { return m_LSL_Functions.llStringTrim(src, type); } public LSL_Integer llSubStringIndex(string source, string pattern) { return m_LSL_Functions.llSubStringIndex(source, pattern); } public void llTakeCamera(string avatar) { m_LSL_Functions.llTakeCamera(avatar); } public void llTakeControls(int controls, int accept, int pass_on) { m_LSL_Functions.llTakeControls(controls, accept, pass_on); } public LSL_Float llTan(double f) { return m_LSL_Functions.llTan(f); } public LSL_Integer llTarget(LSL_Vector position, double range) { return m_LSL_Functions.llTarget(position, range); } public void llTargetOmega(LSL_Vector axis, double spinrate, double gain) { m_LSL_Functions.llTargetOmega(axis, spinrate, gain); } public void llTargetRemove(int number) { m_LSL_Functions.llTargetRemove(number); } public void llTeleportAgent(string agent, string simname, LSL_Vector pos, LSL_Vector lookAt) { m_LSL_Functions.llTeleportAgent(agent, simname, pos, lookAt); } public void llTeleportAgentGlobalCoords(string agent, LSL_Vector global, LSL_Vector pos, LSL_Vector lookAt) { m_LSL_Functions.llTeleportAgentGlobalCoords(agent, global, pos, lookAt); } public void llTeleportAgentHome(string agent) { m_LSL_Functions.llTeleportAgentHome(agent); } public void llTextBox(string avatar, string message, int chat_channel) { m_LSL_Functions.llTextBox(avatar, message, chat_channel); } public LSL_String llToLower(string source) { return m_LSL_Functions.llToLower(source); } public LSL_String llToUpper(string source) { return m_LSL_Functions.llToUpper(source); } public void llTriggerSound(string sound, double volume) { m_LSL_Functions.llTriggerSound(sound, volume); } public void llTriggerSoundLimited(string sound, double volume, LSL_Vector top_north_east, LSL_Vector bottom_south_west) { m_LSL_Functions.llTriggerSoundLimited(sound, volume, top_north_east, bottom_south_west); } public LSL_String llUnescapeURL(string url) { return m_LSL_Functions.llUnescapeURL(url); } public void llUnSit(string id) { m_LSL_Functions.llUnSit(id); } public LSL_Float llVecDist(LSL_Vector a, LSL_Vector b) { return m_LSL_Functions.llVecDist(a, b); } public LSL_Float llVecMag(LSL_Vector v) { return m_LSL_Functions.llVecMag(v); } public LSL_Vector llVecNorm(LSL_Vector v) { return m_LSL_Functions.llVecNorm(v); } public void llVolumeDetect(int detect) { m_LSL_Functions.llVolumeDetect(detect); } public LSL_Float llWater(LSL_Vector offset) { return m_LSL_Functions.llWater(offset); } public void llWhisper(int channelID, string text) { m_LSL_Functions.llWhisper(channelID, text); } public LSL_Vector llWind(LSL_Vector offset) { return m_LSL_Functions.llWind(offset); } public LSL_String llXorBase64Strings(string str1, string str2) { return m_LSL_Functions.llXorBase64Strings(str1, str2); } public LSL_String llXorBase64StringsCorrect(string str1, string str2) { return m_LSL_Functions.llXorBase64StringsCorrect(str1, str2); } public LSL_List llGetPrimMediaParams(int face, LSL_List rules) { return m_LSL_Functions.llGetPrimMediaParams(face, rules); } public LSL_List llGetLinkMedia(LSL_Integer link, LSL_Integer face, LSL_List rules) { return m_LSL_Functions.llGetLinkMedia(link, face, rules); } public LSL_Integer llSetPrimMediaParams(int face, LSL_List rules) { return m_LSL_Functions.llSetPrimMediaParams(face, rules); } public LSL_Integer llSetLinkMedia(LSL_Integer link, LSL_Integer face, LSL_List rules) { return m_LSL_Functions.llSetLinkMedia(link, face, rules); } public LSL_Integer llClearPrimMedia(LSL_Integer face) { return m_LSL_Functions.llClearPrimMedia(face); } public LSL_Integer llClearLinkMedia(LSL_Integer link, LSL_Integer face) { return m_LSL_Functions.llClearLinkMedia(link, face); } public LSL_Integer llGetLinkNumberOfSides(LSL_Integer link) { return m_LSL_Functions.llGetLinkNumberOfSides(link); } public void llSetKeyframedMotion(LSL_List frames, LSL_List options) { m_LSL_Functions.llSetKeyframedMotion(frames, options); } public void llSetPhysicsMaterial(int material_bits, float material_gravity_modifier, float material_restitution, float material_friction, float material_density) { m_LSL_Functions.llSetPhysicsMaterial(material_bits, material_gravity_modifier, material_restitution, material_friction, material_density); } public LSL_List llGetPhysicsMaterial() { return m_LSL_Functions.llGetPhysicsMaterial(); } public void llSetAnimationOverride(LSL_String animState, LSL_String anim) { m_LSL_Functions.llSetAnimationOverride(animState, anim); } public void llResetAnimationOverride(LSL_String anim_state) { m_LSL_Functions.llResetAnimationOverride(anim_state); } public LSL_String llGetAnimationOverride(LSL_String anim_state) { return m_LSL_Functions.llGetAnimationOverride(anim_state); } public LSL_String llJsonGetValue(LSL_String json, LSL_List specifiers) { return m_LSL_Functions.llJsonGetValue(json, specifiers); } public LSL_List llJson2List(LSL_String json) { return m_LSL_Functions.llJson2List(json); } public LSL_String llList2Json(LSL_String type, LSL_List values) { return m_LSL_Functions.llList2Json(type, values); } public LSL_String llJsonSetValue(LSL_String json, LSL_List specifiers, LSL_String value) { return m_LSL_Functions.llJsonSetValue(json, specifiers, value); } public LSL_String llJsonValueType(LSL_String json, LSL_List specifiers) { return m_LSL_Functions.llJsonValueType(json, specifiers); } } }
using System; using System.Collections.Generic; using System.Numerics; namespace ProjectEuler { public struct FractionBig : IEquatable<FractionBig> { BigInteger _numerator; public BigInteger Numerator { get { return _numerator; } private set { _numerator = value; } } BigInteger _denominator; public BigInteger Denominator { get { return _denominator == 0 ? 1 : _denominator; } private set { if (value == 0) throw new InvalidOperationException("Denominator cannot be assigned a 0 Value."); _denominator = value; } } public FractionBig(BigInteger value) { _numerator = value; _denominator = 1; Reduce(); } public FractionBig(BigInteger numerator, BigInteger denominator) { if (denominator == 0) throw new InvalidOperationException("Denominator cannot be assigned a 0 Value."); _numerator = numerator; _denominator = denominator; Reduce(); } private void Reduce() { try { if (Numerator == 0) { Denominator = 1; return; } BigInteger iGCD = GCD(Numerator, Denominator); Numerator /= iGCD; Denominator /= iGCD; if (Denominator < 0) { Numerator *= -1; Denominator *= -1; } } catch (Exception exp) { throw new InvalidOperationException("Cannot reduce FractionBig: " + exp.Message); } } public bool Equals(FractionBig other) { if (other == null) return false; return (Numerator == other.Numerator && Denominator == other.Denominator); } public override bool Equals(object obj) { if (obj == null || !(obj is FractionBig)) return false; return Equals((FractionBig)obj); } public int CompareTo(FractionBig other) { if (other == null) return -1; return this == other ? 0 : this > other ? 1 : -1; } public int CompareTo(object obj) { if (obj == null || !(obj is FractionBig)) return -1; return CompareTo((FractionBig)obj); } public override int GetHashCode() { return Convert.ToInt32((Numerator ^ Denominator) & 0xFFFFFFFF); } public override string ToString() { if (this.Denominator == 1) return this.Numerator.ToString(); var sb = new System.Text.StringBuilder(); sb.Append(this.Numerator); sb.Append('/'); sb.Append(this.Denominator); return sb.ToString(); } public static FractionBig Parse(string strValue) { int i = strValue.IndexOf('/'); if (i == -1) return DecimalToFraction(Convert.ToDecimal(strValue)); BigInteger iNumerator = Convert.ToInt64(strValue.Substring(0, i)); BigInteger iDenominator = Convert.ToInt64(strValue.Substring(i + 1)); return new FractionBig(iNumerator, iDenominator); } public static bool TryParse(string strValue, out FractionBig FractionBig) { if (!string.IsNullOrWhiteSpace(strValue)) { try { int i = strValue.IndexOf('/'); if (i == -1) { decimal dValue; if (decimal.TryParse(strValue, out dValue)) { FractionBig = DecimalToFraction(dValue); return true; } } else { BigInteger iNumerator, iDenominator; if (BigInteger.TryParse(strValue.Substring(0, i), out iNumerator) && BigInteger.TryParse(strValue.Substring(i + 1), out iDenominator)) { FractionBig = new FractionBig(iNumerator, iDenominator); return true; } } } catch { } } FractionBig = new FractionBig(); return false; } private static FractionBig DoubleToFraction(double dValue) { char separator = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0]; try { checked { FractionBig frac; if (dValue % 1 == 0) // if whole number { frac = new FractionBig((BigInteger)dValue); } else { double dTemp = dValue; BigInteger iMultiple = 1; string strTemp = dValue.ToString(); while (strTemp.IndexOf("E") > 0) // if in the form like 12E-9 { dTemp *= 10; iMultiple *= 10; strTemp = dTemp.ToString(); } int i = 0; while (strTemp[i] != separator) i++; int iDigitsAfterDecimal = strTemp.Length - i - 1; while (iDigitsAfterDecimal > 0) { dTemp *= 10; iMultiple *= 10; iDigitsAfterDecimal--; } frac = new FractionBig((int)Math.Round(dTemp), iMultiple); } return frac; } } catch (OverflowException e) { throw new InvalidCastException("Conversion to FractionBig in no possible due to overflow.", e); } catch (Exception e) { throw new InvalidCastException("Conversion to FractionBig in not possible.", e); } } private static FractionBig DecimalToFraction(decimal dValue) { char separator = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0]; try { checked { FractionBig frac; if (dValue % 1 == 0) // if whole number { frac = new FractionBig((BigInteger)dValue); } else { decimal dTemp = dValue; BigInteger iMultiple = 1; string strTemp = dValue.ToString(); while (strTemp.IndexOf("E") > 0) // if in the form like 12E-9 { dTemp *= 10; iMultiple *= 10; strTemp = dTemp.ToString(); } int i = 0; while (strTemp[i] != separator) i++; int iDigitsAfterDecimal = strTemp.Length - i - 1; while (iDigitsAfterDecimal > 0) { dTemp *= 10; iMultiple *= 10; iDigitsAfterDecimal--; } frac = new FractionBig((int)Math.Round(dTemp), iMultiple); } return frac; } } catch (OverflowException e) { throw new InvalidCastException("Conversion to FractionBig in no possible due to overflow.", e); } catch (Exception e) { throw new InvalidCastException("Conversion to FractionBig in not possible.", e); } } private static FractionBig Inverse(FractionBig frac1) { if (frac1.Numerator == 0) throw new InvalidOperationException("Operation not possible (Denominator cannot be assigned a ZERO Value)"); BigInteger iNumerator = frac1.Denominator; BigInteger iDenominator = frac1.Numerator; return new FractionBig(iNumerator, iDenominator); } private static FractionBig Negate(FractionBig frac1) { BigInteger iNumerator = -frac1.Numerator; BigInteger iDenominator = frac1.Denominator; return new FractionBig(iNumerator, iDenominator); } private static FractionBig Add(FractionBig frac1, FractionBig frac2) { try { checked { BigInteger iNumerator = frac1.Numerator * frac2.Denominator + frac2.Numerator * frac1.Denominator; BigInteger iDenominator = frac1.Denominator * frac2.Denominator; return new FractionBig(iNumerator, iDenominator); } } catch (OverflowException e) { throw new OverflowException("Overflow occurred while performing arithemetic operation on FractionBig.", e); } catch (Exception e) { throw new Exception("An error occurred while performing arithemetic operation on FractionBig.", e); } } private static FractionBig Multiply(FractionBig frac1, FractionBig frac2) { try { checked { BigInteger iNumerator = frac1.Numerator * frac2.Numerator; BigInteger iDenominator = frac1.Denominator * frac2.Denominator; return new FractionBig(iNumerator, iDenominator); } } catch (OverflowException e) { throw new OverflowException("Overflow occurred while performing arithemetic operation on FractionBig.", e); } catch (Exception e) { throw new Exception("An error occurred while performing arithemetic operation on FractionBig.", e); } } private static BigInteger GCD(BigInteger iNo1, BigInteger iNo2) { if (iNo1 < 0) iNo1 = -iNo1; if (iNo2 < 0) iNo2 = -iNo2; do { if (iNo1 < iNo2) { BigInteger tmp = iNo1; iNo1 = iNo2; iNo2 = tmp; } iNo1 = iNo1 % iNo2; } while (iNo1 != 0); return iNo2; } public static FractionBig operator -(FractionBig frac1) { return (Negate(frac1)); } public static FractionBig operator +(FractionBig frac1, FractionBig frac2) { return (Add(frac1, frac2)); } public static FractionBig operator -(FractionBig frac1, FractionBig frac2) { return (Add(frac1, -frac2)); } public static FractionBig operator *(FractionBig frac1, FractionBig frac2) { return (Multiply(frac1, frac2)); } public static FractionBig operator /(FractionBig frac1, FractionBig frac2) { return (Multiply(frac1, Inverse(frac2))); } public static bool operator ==(FractionBig frac1, FractionBig frac2) { return frac1.Equals(frac2); } public static bool operator !=(FractionBig frac1, FractionBig frac2) { return (!frac1.Equals(frac2)); } public static bool operator <(FractionBig frac1, FractionBig frac2) { return frac1.Numerator * frac2.Denominator < frac2.Numerator * frac1.Denominator; } public static bool operator >(FractionBig frac1, FractionBig frac2) { return frac1.Numerator * frac2.Denominator > frac2.Numerator * frac1.Denominator; } public static bool operator <=(FractionBig frac1, FractionBig frac2) { return frac1.Numerator * frac2.Denominator <= frac2.Numerator * frac1.Denominator; } public static bool operator >=(FractionBig frac1, FractionBig frac2) { return frac1.Numerator * frac2.Denominator >= frac2.Numerator * frac1.Denominator; } public static implicit operator FractionBig(BigInteger value) { return new FractionBig(value); } public static implicit operator FractionBig(double value) { return DoubleToFraction(value); } public static implicit operator FractionBig(decimal value) { return DecimalToFraction(value); } public static explicit operator double(FractionBig frac) { return (double)(frac.Numerator / frac.Denominator); } public static explicit operator decimal(FractionBig frac) { return ((decimal)frac.Numerator / (decimal)frac.Denominator); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update { using Microsoft.Azure.Management.Compute.Fluent; using Microsoft.Azure.Management.Compute.Fluent.Models; using Microsoft.Azure.Management.Graph.RBAC.Fluent; using Microsoft.Azure.Management.Msi.Fluent; using Microsoft.Azure.Management.Network.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions; using Microsoft.Azure.Management.Storage.Fluent; /// <summary> /// The stage of the System Assigned (Local) Managed Service Identity enabled virtual machine scale set /// allowing to set access for the identity. /// </summary> public interface IWithSystemAssignedIdentityBasedAccessOrApply : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta, Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply { /// <summary> /// Specifies that virtual machine's system assigned (local) identity should have the given /// access (described by the role) on an ARM resource identified by the resource ID. /// Applications running on the scale set VM instance will have the same permission (role) /// on the ARM resource. /// </summary> /// <param name="resourceId">The ARM identifier of the resource.</param> /// <param name="role">Access role to assigned to the scale set local identity.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithSystemAssignedIdentityBasedAccessOrApply WithSystemAssignedIdentityBasedAccessTo(string resourceId, BuiltInRole role); /// <summary> /// Specifies that virtual machine scale set 's system assigned (local) identity should have the access /// (described by the role definition) on an ARM resource identified by the resource ID. Applications /// running on the scale set VM instance will have the same permission (role) on the ARM resource. /// </summary> /// <param name="resourceId">Scope of the access represented in ARM resource ID format.</param> /// <param name="roleDefinitionId">Access role definition to assigned to the scale set local identity.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithSystemAssignedIdentityBasedAccessOrApply WithSystemAssignedIdentityBasedAccessTo(string resourceId, string roleDefinitionId); /// <summary> /// Specifies that virtual machine scale set's system assigned (local) identity should have the given /// access (described by the role) on the resource group that virtual machine resides. Applications /// running on the scale set VM instance will have the same permission (role) on the resource group. /// </summary> /// <param name="role">Access role to assigned to the scale set local identity.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithSystemAssignedIdentityBasedAccessOrApply WithSystemAssignedIdentityBasedAccessToCurrentResourceGroup(BuiltInRole role); /// <summary> /// Specifies that virtual machine scale set's system assigned (local) identity should have the access /// (described by the role definition) on the resource group that virtual machine resides. Applications /// running on the scale set VM instance will have the same permission (role) on the resource group. /// </summary> /// <param name="roleDefinitionId">Access role definition to assigned to the scale set local identity.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithSystemAssignedIdentityBasedAccessOrApply WithSystemAssignedIdentityBasedAccessToCurrentResourceGroup(string roleDefinitionId); } /// <summary> /// The stage of the virtual machine definition allowing to specify extensions. /// </summary> public interface IWithExtension { /// <summary> /// Begins the definition of an extension reference to be attached to the virtual machines in the scale set. /// </summary> /// <param name="name">The reference name for an extension.</param> /// <return>The first stage of the extension reference definition.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSetExtension.UpdateDefinition.IBlank<Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply> DefineNewExtension(string name); /// <summary> /// Begins the description of an update of an existing extension assigned to the virtual machines in the scale set. /// </summary> /// <param name="name">The reference name for the extension.</param> /// <return>The first stage of the extension reference update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSetExtension.Update.IUpdate UpdateExtension(string name); /// <summary> /// Removes the extension with the specified name from the virtual machines in the scale set. /// </summary> /// <param name="name">The reference name of the extension to be removed/uninstalled.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithoutExtension(string name); } /// <summary> /// A stage of the virtual machine scale set update allowing to remove the associations between the primary network /// interface configuration and the specified inbound NAT pools of the load balancer. /// </summary> public interface IWithoutPrimaryLoadBalancerNatPool { /// <summary> /// Removes the associations between the primary network interface configuration and the specified inbound NAT pools /// of the internal load balancer. /// </summary> /// <param name="natPoolNames">The names of existing inbound NAT pools.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithoutPrimaryInternalLoadBalancerNatPools(params string[] natPoolNames); /// <summary> /// Removes the associations between the primary network interface configuration and the specified inbound NAT pools /// of an Internet-facing load balancer. /// </summary> /// <param name="natPoolNames">The names of existing inbound NAT pools.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithoutPrimaryInternetFacingLoadBalancerNatPools(params string[] natPoolNames); } /// <summary> /// The stage of a virtual machine scale set update allowing to specify an internal load balancer for /// the primary network interface of the scale set virtual machines. /// </summary> public interface IWithPrimaryInternalLoadBalancer : Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply { /// <summary> /// Specifies the load balancer to be used as the internal load balancer for the virtual machines in the /// scale set. /// This will replace the current internal load balancer associated with the virtual machines in the /// scale set (if any). /// By default all the backends and inbound NAT pools of the load balancer will be associated with the primary /// network interface of the virtual machines in the scale set unless subset of them is selected in the next stages. /// </p>. /// </summary> /// <param name="loadBalancer">The primary Internet-facing load balancer.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithPrimaryInternalLoadBalancerBackendOrNatPool WithExistingPrimaryInternalLoadBalancer(ILoadBalancer loadBalancer); } /// <summary> /// The stage of the virtual machine scale set update allowing to enable public ip /// for vm instances. /// </summary> public interface IWithVirtualMachinePublicIp : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Specify that virtual machines in the scale set should have public ip address. /// </summary> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithVirtualMachinePublicIp(); /// <summary> /// Specify that virtual machines in the scale set should have public ip address. /// </summary> /// <param name="leafDomainLabel">The domain name label.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithVirtualMachinePublicIp(string leafDomainLabel); /// <summary> /// Specify that virtual machines in the scale set should have public ip address. /// </summary> /// <param name="ipConfig">The public ip address configuration.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithVirtualMachinePublicIp(VirtualMachineScaleSetPublicIPAddressConfiguration ipConfig); } /// <summary> /// The stage of a virtual machine scale set update allowing to remove the association between the primary network /// interface configuration and a backend of a load balancer. /// </summary> public interface IWithoutPrimaryLoadBalancerBackend { /// <summary> /// Removes the associations between the primary network interface configuration and the specified backends /// of the internal load balancer. /// </summary> /// <param name="backendNames">Existing backend names.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithoutPrimaryInternalLoadBalancerBackends(params string[] backendNames); /// <summary> /// Removes the associations between the primary network interface configuration and the specfied backends /// of the Internet-facing load balancer. /// </summary> /// <param name="backendNames">Existing backend names.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithoutPrimaryInternetFacingLoadBalancerBackends(params string[] backendNames); } /// <summary> /// The stage of the virtual machine scale set update allowing to configure ip forwarding. /// </summary> public interface IWithIpForwarding : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Specify that ip forwarding should be enabled for the virtual machine scale set. /// </summary> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithIpForwarding(); /// <summary> /// Specify that ip forwarding should be disabled for the virtual machine scale set. /// </summary> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithoutIpForwarding(); } /// <summary> /// The stage of a virtual machine scale set update allowing to change the SKU for the virtual machines /// in the scale set. /// </summary> public interface IWithSku { /// <summary> /// Specifies the SKU for the virtual machines in the scale set. /// </summary> /// <param name="skuType">The SKU type.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithSku(VirtualMachineScaleSetSkuTypes skuType); /// <summary> /// Specifies the SKU for the virtual machines in the scale set. /// </summary> /// <param name="sku">A SKU from the list of available sizes for the virtual machines in this scale set.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithSku(IVirtualMachineScaleSetSku sku); } /// <summary> /// The stage of the virtual machine scale set update allowing to configure application security group. /// </summary> public interface IWithApplicationSecurityGroup : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Specifies that provided application security group should be associated with the virtual machine scale set. /// </summary> /// <param name="applicationSecurityGroup">The application security group.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithExistingApplicationSecurityGroup(IApplicationSecurityGroup applicationSecurityGroup); /// <summary> /// Specifies that provided application security group should be associated with the virtual machine scale set. /// </summary> /// <param name="applicationSecurityGroupId">The application security group id.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithExistingApplicationSecurityGroupId(string applicationSecurityGroupId); /// <summary> /// Specifies that provided application security group should be removed from the virtual machine scale set. /// </summary> /// <param name="applicationSecurityGroupId">The application security group id.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithoutApplicationSecurityGroup(string applicationSecurityGroupId); } /// <summary> /// The stage of a virtual machine scale set update allowing to remove the public and internal load balancer /// from the primary network interface configuration. /// </summary> public interface IWithoutPrimaryLoadBalancer { /// <summary> /// Removes the association between the internal load balancer and the primary network interface configuration. /// This removes the association between primary network interface configuration and all the backends and /// inbound NAT pools in the load balancer. /// </summary> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithoutPrimaryInternalLoadBalancer(); /// <summary> /// Removes the association between the Internet-facing load balancer and the primary network interface configuration. /// This removes the association between primary network interface configuration and all the backends and /// inbound NAT pools in the load balancer. /// </summary> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithoutPrimaryInternetFacingLoadBalancer(); } /// <summary> /// The stage of the virtual machine scale set update allowing to configure accelerated networking. /// </summary> public interface IWithAcceleratedNetworking : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Specify that accelerated networking should be enabled for the virtual machine scale set. /// </summary> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithAcceleratedNetworking(); /// <summary> /// Specify that accelerated networking should be disabled for the virtual machine scale set. /// </summary> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithoutAcceleratedNetworking(); } /// <summary> /// The stage of a virtual machine scale set definition allowing to specify the number of /// virtual machines in the scale set. /// </summary> public interface IWithCapacity { /// <summary> /// Specifies the new number of virtual machines in the scale set. /// </summary> /// <param name="capacity">The virtual machine capacity of the scale set.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithCapacity(int capacity); } /// <summary> /// The stage of a virtual machine scale set update allowing to specify load balancers for the primary /// network interface of the scale set virtual machines. /// </summary> public interface IWithPrimaryLoadBalancer : Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithPrimaryInternalLoadBalancer { /// <summary> /// Specifies the load balancer to be used as the Internet-facing load balancer for the virtual machines in the /// scale set. /// This will replace the current Internet-facing load balancer associated with the virtual machines in the /// scale set (if any). /// By default all the backend and inbound NAT pool of the load balancer will be associated with the primary /// network interface of the virtual machines unless a subset of them is selected in the next stages. /// </summary> /// <param name="loadBalancer">The primary Internet-facing load balancer.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithPrimaryInternetFacingLoadBalancerBackendOrNatPool WithExistingPrimaryInternetFacingLoadBalancer(ILoadBalancer loadBalancer); } /// <summary> /// The stage of the virtual machine scale set update allowing to configure single placement group. /// </summary> public interface IWithSinglePlacementGroup : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Specify that single placement group should be disabled for the virtual machine scale set. /// </summary> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithoutSinglePlacementGroup(); /// <summary> /// Specify that single placement group should be enabled for the virtual machine scale set. /// </summary> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithSinglePlacementGroup(); } /// <summary> /// The stage of a virtual machine scale set update containing inputs for the resource to be updated. /// </summary> public interface IWithApply : Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.IAppliable<Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineScaleSet>, Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Update.IUpdateWithTags<Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply>, Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithManagedDataDisk, Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithUnmanagedDataDisk, Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithSku, Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithCapacity, Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithExtension, Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithoutPrimaryLoadBalancer, Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithoutPrimaryLoadBalancerBackend, Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithoutPrimaryLoadBalancerNatPool, Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithSystemAssignedManagedServiceIdentity, Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithUserAssignedManagedServiceIdentity, Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithBootDiagnostics, Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithAvailabilityZone, Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithVirtualMachinePublicIp, Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithAcceleratedNetworking, Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithIpForwarding, Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithNetworkSecurityGroup, Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithSinglePlacementGroup, Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApplicationGateway, Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApplicationSecurityGroup { } /// <summary> /// The stage of a virtual machine scale set update allowing to associate backend pools and/or inbound NAT pools /// of the selected internal load balancer with the primary network interface of the scale set virtual machines. /// </summary> public interface IWithPrimaryInternalLoadBalancerBackendOrNatPool : Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithPrimaryInternalLoadBalancerNatPool { /// <summary> /// Associates the specified internal load balancer backends with the primary network interface of the /// virtual machines in the scale set. /// </summary> /// <param name="backendNames">The names of existing backends on the selected load balancer.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithPrimaryInternalLoadBalancerNatPool WithPrimaryInternalLoadBalancerBackends(params string[] backendNames); } /// <summary> /// The stage of a virtual machine scale set update allowing to associate inbound NAT pools of the selected internal /// load balancer with the primary network interface of the virtual machines in the scale set. /// </summary> public interface IWithPrimaryInternalLoadBalancerNatPool : Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply { /// <summary> /// Associates the specified internal load balancer inbound NAT pools with the the primary network interface of /// the virtual machines in the scale set. /// </summary> /// <param name="natPoolNames">The names of existing inbound NAT pools in the selected load balancer.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithPrimaryInternalLoadBalancerInboundNatPools(params string[] natPoolNames); } /// <summary> /// The stage of the virtual machine update allowing to add or remove User Assigned (External) /// Managed Service Identities. /// </summary> public interface IWithUserAssignedManagedServiceIdentity : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Specifies an existing user assigned identity to be associated with the virtual machine. /// </summary> /// <param name="identity">The identity.</param> /// <return>The next stage of the virtual machine scale set update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithExistingUserAssignedManagedServiceIdentity(IIdentity identity); /// <summary> /// Specifies the definition of a not-yet-created user assigned identity to be associated /// with the virtual machine. /// </summary> /// <param name="creatableIdentity">A creatable identity definition.</param> /// <return>The next stage of the virtual machine scale set update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithNewUserAssignedManagedServiceIdentity(ICreatable<Microsoft.Azure.Management.Msi.Fluent.IIdentity> creatableIdentity); /// <summary> /// Specifies that an user assigned identity associated with the virtual machine should be removed. /// </summary> /// <param name="identityId">ARM resource id of the identity.</param> /// <return>The next stage of the virtual machine scale set update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithoutUserAssignedManagedServiceIdentity(string identityId); } /// <summary> /// The stage of a virtual machine scale set update allowing to associate a backend pool and/or inbound NAT pool /// of the selected Internet-facing load balancer with the primary network interface of the virtual machines in /// the scale set. /// </summary> public interface IWithPrimaryInternetFacingLoadBalancerBackendOrNatPool : Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithPrimaryInternetFacingLoadBalancerNatPool { /// <summary> /// Associates the specified Internet-facing load balancer backends with the primary network interface of the /// virtual machines in the scale set. /// </summary> /// <param name="backendNames">The backend names.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithPrimaryInternetFacingLoadBalancerNatPool WithPrimaryInternetFacingLoadBalancerBackends(params string[] backendNames); } /// <summary> /// The entirety of the virtual machine scale set update. /// </summary> public interface IUpdate : Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithPrimaryLoadBalancer, Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithPrimaryInternetFacingLoadBalancerBackendOrNatPool, Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithPrimaryInternalLoadBalancerBackendOrNatPool { } /// <summary> /// The stage of the virtual machine scale set update allowing to configure application gateway. /// </summary> public interface IWithApplicationGateway : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Specify that an application gateway backend pool should be associated with virtual machine scale set. /// </summary> /// <param name="backendPoolId">An existing backend pool id of the gateway.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithExistingApplicationGatewayBackendPool(string backendPoolId); /// <summary> /// Specify an existing application gateway associated should be removed from the virtual machine scale set. /// </summary> /// <param name="backendPoolId">An existing backend pool id of the gateway.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithoutApplicationGatewayBackendPool(string backendPoolId); } /// <summary> /// The stage of a virtual machine scale set update allowing to specify managed data disks. /// </summary> public interface IWithManagedDataDisk { /// <summary> /// Specifies that a managed disk needs to be created implicitly with the given size. /// </summary> /// <param name="sizeInGB">The size of the managed disk.</param> /// <return>The next stage of virtual machine scale set update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithNewDataDisk(int sizeInGB); /// <summary> /// Specifies that a managed disk needs to be created implicitly with the given settings. /// </summary> /// <param name="sizeInGB">The size of the managed disk.</param> /// <param name="lun">The disk LUN.</param> /// <param name="cachingType">The caching type.</param> /// <return>The next stage of virtual machine scale set update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithNewDataDisk(int sizeInGB, int lun, CachingTypes cachingType); /// <summary> /// Specifies that a managed disk needs to be created implicitly with the given settings. /// </summary> /// <param name="sizeInGB">The size of the managed disk.</param> /// <param name="lun">The disk LUN.</param> /// <param name="cachingType">The caching type.</param> /// <param name="storageAccountType">The storage account type.</param> /// <return>The next stage of virtual machine scale set update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithNewDataDisk(int sizeInGB, int lun, CachingTypes cachingType, StorageAccountTypes storageAccountType); /// <summary> /// Detaches managed data disk with the given LUN from the virtual machine scale set instances. /// </summary> /// <param name="lun">The disk LUN.</param> /// <return>The next stage of virtual machine scale set update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithoutDataDisk(int lun); } /// <summary> /// The stage of the virtual machine scale set update allowing to specify availability zone. /// </summary> public interface IWithAvailabilityZone : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Specifies the availability zone for the virtual machine scale set. /// </summary> /// <param name="zoneId">The zone identifier.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithAvailabilityZone(AvailabilityZoneId zoneId); } /// <summary> /// The stage of the virtual machine scale set definition allowing to specify unmanaged data disk. /// </summary> public interface IWithUnmanagedDataDisk { } /// <summary> /// The stage of the virtual machine scale set definition allowing to enable boot diagnostics. /// </summary> public interface IWithBootDiagnostics : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Specifies that boot diagnostics needs to be enabled in the virtual machine scale set. /// </summary> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IUpdate WithBootDiagnostics(); /// <summary> /// Specifies that boot diagnostics needs to be enabled in the virtual machine scale set. /// </summary> /// <param name="creatable">The storage account to be created and used for store the boot diagnostics.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IUpdate WithBootDiagnostics(ICreatable<Microsoft.Azure.Management.Storage.Fluent.IStorageAccount> creatable); /// <summary> /// Specifies that boot diagnostics needs to be enabled in the virtual machine scale set. /// </summary> /// <param name="storageAccount">An existing storage account to be uses to store the boot diagnostics.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IUpdate WithBootDiagnostics(IStorageAccount storageAccount); /// <summary> /// Specifies that boot diagnostics needs to be enabled in the virtual machine scale set. /// </summary> /// <param name="storageAccountBlobEndpointUri">A storage account blob endpoint to store the boot diagnostics.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IUpdate WithBootDiagnostics(string storageAccountBlobEndpointUri); /// <summary> /// Specifies that boot diagnostics needs to be disabled in the virtual machine scale set. /// </summary> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IUpdate WithoutBootDiagnostics(); } /// <summary> /// The stage of a virtual machine scale set update allowing to associate an inbound NAT pool of the selected /// Internet-facing load balancer with the primary network interface of the virtual machines in the scale set. /// </summary> public interface IWithPrimaryInternetFacingLoadBalancerNatPool : Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithPrimaryInternalLoadBalancer { /// <summary> /// Associates inbound NAT pools of the selected Internet-facing load balancer with the primary network interface /// of the virtual machines in the scale set. /// </summary> /// <param name="natPoolNames">The names of existing inbound NAT pools on the selected load balancer.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithPrimaryInternalLoadBalancer WithPrimaryInternetFacingLoadBalancerInboundNatPools(params string[] natPoolNames); } /// <summary> /// The stage of the virtual machine scale set update allowing to configure network security group. /// </summary> public interface IWithNetworkSecurityGroup : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Specifies the network security group for the virtual machine scale set. /// </summary> /// <param name="networkSecurityGroup">The network security group to associate.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithExistingNetworkSecurityGroup(INetworkSecurityGroup networkSecurityGroup); /// <summary> /// Specifies the network security group for the virtual machine scale set. /// </summary> /// <param name="networkSecurityGroupId">The network security group to associate.</param> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithExistingNetworkSecurityGroupId(string networkSecurityGroupId); /// <summary> /// Specifies that network security group association should be removed if exists. /// </summary> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithApply WithoutNetworkSecurityGroup(); } /// <summary> /// The stage of the virtual machine scale set update allowing to enable System Assigned (Local) Managed Service Identity. /// </summary> public interface IWithSystemAssignedManagedServiceIdentity : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Specifies that System assigned (Local) Managed Service Identity needs to be disabled in the /// virtual machine scale set. /// </summary> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithSystemAssignedIdentityBasedAccessOrApply WithoutSystemAssignedManagedServiceIdentity(); /// <summary> /// Specifies that System assigned (Local) Managed Service Identity needs to be enabled in the /// virtual machine scale set. /// </summary> /// <return>The next stage of the update.</return> Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSet.Update.IWithSystemAssignedIdentityBasedAccessOrApply WithSystemAssignedManagedServiceIdentity(); } }
// 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.Net.Test.Common; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Sockets.Tests { public class AcceptAsync { private readonly ITestOutputHelper _log; public AcceptAsync(ITestOutputHelper output) { _log = TestLogging.GetInstance(); } public void OnAcceptCompleted(object sender, SocketAsyncEventArgs args) { _log.WriteLine("OnAcceptCompleted event handler"); EventWaitHandle handle = (EventWaitHandle)args.UserToken; handle.Set(); } public void OnConnectCompleted(object sender, SocketAsyncEventArgs args) { _log.WriteLine("OnConnectCompleted event handler"); EventWaitHandle handle = (EventWaitHandle)args.UserToken; handle.Set(); } [OuterLoop] // TODO: Issue #11345 [Fact] [Trait("IPv4", "true")] public void AcceptAsync_IpV4_Success() { Assert.True(Capability.IPv4Support()); AutoResetEvent completed = new AutoResetEvent(false); AutoResetEvent completedClient = new AutoResetEvent(false); using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = sock.BindToAnonymousPort(IPAddress.Loopback); sock.Listen(1); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.Completed += OnAcceptCompleted; args.UserToken = completed; Assert.True(sock.AcceptAsync(args)); _log.WriteLine("IPv4 Server: Waiting for clients."); using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { SocketAsyncEventArgs argsClient = new SocketAsyncEventArgs(); argsClient.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, port); argsClient.Completed += OnConnectCompleted; argsClient.UserToken = completedClient; client.ConnectAsync(argsClient); _log.WriteLine("IPv4 Client: Connecting."); Assert.True(completed.WaitOne(5000), "IPv4: Timed out while waiting for connection"); Assert.Equal<SocketError>(SocketError.Success, args.SocketError); Assert.NotNull(args.AcceptSocket); Assert.True(args.AcceptSocket.Connected, "IPv4 Accept Socket was not connected"); Assert.NotNull(args.AcceptSocket.RemoteEndPoint); Assert.Equal(client.LocalEndPoint, args.AcceptSocket.RemoteEndPoint); } } } [OuterLoop] // TODO: Issue #11345 [Fact] [Trait("IPv6", "true")] public void AcceptAsync_IPv6_Success() { Assert.True(Capability.IPv6Support()); AutoResetEvent completed = new AutoResetEvent(false); AutoResetEvent completedClient = new AutoResetEvent(false); using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { int port = sock.BindToAnonymousPort(IPAddress.IPv6Loopback); sock.Listen(1); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.Completed += OnAcceptCompleted; args.UserToken = completed; Assert.True(sock.AcceptAsync(args)); _log.WriteLine("IPv6 Server: Waiting for clients."); using (Socket client = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { SocketAsyncEventArgs argsClient = new SocketAsyncEventArgs(); argsClient.RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, port); argsClient.Completed += OnConnectCompleted; argsClient.UserToken = completedClient; client.ConnectAsync(argsClient); _log.WriteLine("IPv6 Client: Connecting."); Assert.True(completed.WaitOne(5000), "IPv6: Timed out while waiting for connection"); Assert.Equal<SocketError>(SocketError.Success, args.SocketError); Assert.NotNull(args.AcceptSocket); Assert.True(args.AcceptSocket.Connected, "IPv6 Accept Socket was not connected"); Assert.NotNull(args.AcceptSocket.RemoteEndPoint); Assert.Equal(client.LocalEndPoint, args.AcceptSocket.RemoteEndPoint); } } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(2)] [InlineData(5)] public async Task AcceptAsync_ConcurrentAcceptsBeforeConnects_Success(int numberAccepts) { using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(numberAccepts); var clients = new Socket[numberAccepts]; var servers = new Task<Socket>[numberAccepts]; try { for (int i = 0; i < numberAccepts; i++) { clients[i] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); servers[i] = listener.AcceptAsync(); } foreach (Socket client in clients) { client.Connect(listener.LocalEndPoint); } await Task.WhenAll(servers); Assert.All(servers, s => Assert.Equal(TaskStatus.RanToCompletion, s.Status)); Assert.All(servers, s => Assert.NotNull(s.Result)); Assert.All(servers, s => Assert.True(s.Result.Connected)); } finally { foreach (Socket client in clients) { client?.Dispose(); } foreach (Task<Socket> server in servers) { if (server?.Status == TaskStatus.RanToCompletion) { server.Result.Dispose(); } } } } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(2)] [InlineData(5)] public async Task AcceptAsync_ConcurrentAcceptsAfterConnects_Success(int numberAccepts) { using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(numberAccepts); var clients = new Socket[numberAccepts]; var clientConnects = new Task[numberAccepts]; var servers = new Task<Socket>[numberAccepts]; try { for (int i = 0; i < numberAccepts; i++) { clients[i] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); clientConnects[i] = clients[i].ConnectAsync(listener.LocalEndPoint); } for (int i = 0; i < numberAccepts; i++) { servers[i] = listener.AcceptAsync(); } await Task.WhenAll(clientConnects); Assert.All(clientConnects, c => Assert.Equal(TaskStatus.RanToCompletion, c.Status)); await Task.WhenAll(servers); Assert.All(servers, s => Assert.Equal(TaskStatus.RanToCompletion, s.Status)); Assert.All(servers, s => Assert.NotNull(s.Result)); Assert.All(servers, s => Assert.True(s.Result.Connected)); } finally { foreach (Socket client in clients) { client?.Dispose(); } foreach (Task<Socket> server in servers) { if (server?.Status == TaskStatus.RanToCompletion) { server.Result.Dispose(); } } } } } [OuterLoop] // TODO: Issue #11345 [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Unix platforms don't yet support receiving data with AcceptAsync. public void AcceptAsync_WithReceiveBuffer_Success() { Assert.True(Capability.IPv4Support()); AutoResetEvent accepted = new AutoResetEvent(false); using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = server.BindToAnonymousPort(IPAddress.Loopback); server.Listen(1); const int acceptBufferOverheadSize = 288; // see https://msdn.microsoft.com/en-us/library/system.net.sockets.socket.acceptasync(v=vs.110).aspx const int acceptBufferDataSize = 256; const int acceptBufferSize = acceptBufferOverheadSize + acceptBufferDataSize; byte[] sendBuffer = new byte[acceptBufferDataSize]; new Random().NextBytes(sendBuffer); SocketAsyncEventArgs acceptArgs = new SocketAsyncEventArgs(); acceptArgs.Completed += OnAcceptCompleted; acceptArgs.UserToken = accepted; acceptArgs.SetBuffer(new byte[acceptBufferSize], 0, acceptBufferSize); Assert.True(server.AcceptAsync(acceptArgs)); _log.WriteLine("IPv4 Server: Waiting for clients."); using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { client.Connect(IPAddress.Loopback, port); client.Send(sendBuffer); client.Shutdown(SocketShutdown.Both); } Assert.True( accepted.WaitOne(TestSettings.PassingTestTimeout), "Test completed in alotted time"); Assert.Equal( SocketError.Success, acceptArgs.SocketError); Assert.Equal( acceptBufferDataSize, acceptArgs.BytesTransferred); Assert.Equal( new ArraySegment<byte>(sendBuffer), new ArraySegment<byte>(acceptArgs.Buffer, 0, acceptArgs.BytesTransferred)); } } [OuterLoop] // TODO: Issue #11345 [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Unix platforms don't yet support receiving data with AcceptAsync. public void AcceptAsync_WithTooSmallReceiveBuffer_Failure() { using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = server.BindToAnonymousPort(IPAddress.Loopback); server.Listen(1); SocketAsyncEventArgs acceptArgs = new SocketAsyncEventArgs(); acceptArgs.Completed += OnAcceptCompleted; acceptArgs.UserToken = new ManualResetEvent(false); byte[] buffer = new byte[1]; acceptArgs.SetBuffer(buffer, 0, buffer.Length); Assert.Throws<ArgumentException>(() => server.AcceptAsync(acceptArgs)); } } [OuterLoop] // TODO: Issue #11345 [Fact] [ActiveIssue(17209, TestPlatforms.AnyUnix)] public void AcceptAsync_WithTargetSocket_Success() { using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = listener.BindToAnonymousPort(IPAddress.Loopback); listener.Listen(1); Task<Socket> acceptTask = listener.AcceptAsync(server); client.Connect(IPAddress.Loopback, port); Assert.Same(server, acceptTask.Result); } } [ActiveIssue(17209, TestPlatforms.AnyUnix)] [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(false)] [InlineData(true)] public void AcceptAsync_WithTargetSocket_ReuseAfterDisconnect_Success(bool reuseSocket) { using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var saea = new SocketAsyncEventArgs()) { int port = listener.BindToAnonymousPort(IPAddress.Loopback); listener.Listen(1); var are = new AutoResetEvent(false); saea.Completed += delegate { are.Set(); }; saea.AcceptSocket = server; using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { Assert.True(listener.AcceptAsync(saea)); client.Connect(IPAddress.Loopback, port); are.WaitOne(); Assert.Same(server, saea.AcceptSocket); Assert.True(server.Connected); } server.Disconnect(reuseSocket); Assert.False(server.Connected); if (reuseSocket) { using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { Assert.True(listener.AcceptAsync(saea)); client.Connect(IPAddress.Loopback, port); are.WaitOne(); Assert.Same(server, saea.AcceptSocket); Assert.True(server.Connected); } } else { if (listener.AcceptAsync(saea)) { are.WaitOne(); } Assert.Equal(SocketError.InvalidArgument, saea.SocketError); } } } [OuterLoop] // TODO: Issue #11345 [Fact] [ActiveIssue(17209, TestPlatforms.AnyUnix)] public void AcceptAsync_WithAlreadyBoundTargetSocket_Failed() { using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = listener.BindToAnonymousPort(IPAddress.Loopback); listener.Listen(1); server.BindToAnonymousPort(IPAddress.Loopback); Assert.Throws<InvalidOperationException>(() => { listener.AcceptAsync(server); }); } } [OuterLoop] // TODO: Issue #11345 [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Unix platforms don't yet support receiving data with AcceptAsync. public void AcceptAsync_WithReceiveBuffer_Failure() { // // Unix platforms don't yet support receiving data with AcceptAsync. // Assert.True(Capability.IPv4Support()); using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = server.BindToAnonymousPort(IPAddress.Loopback); server.Listen(1); SocketAsyncEventArgs acceptArgs = new SocketAsyncEventArgs(); acceptArgs.Completed += OnAcceptCompleted; acceptArgs.UserToken = new ManualResetEvent(false); byte[] buffer = new byte[1024]; acceptArgs.SetBuffer(buffer, 0, buffer.Length); Assert.Throws<PlatformNotSupportedException>(() => server.AcceptAsync(acceptArgs)); } } } }
#region Disclaimer/Info /////////////////////////////////////////////////////////////////////////////////////////////////// // Subtext WebLog // // Subtext is an open source weblog system that is a fork of the .TEXT // weblog system. // // For updated news and information please visit http://subtextproject.com/ // Subtext is hosted at Google Code at http://code.google.com/p/subtext/ // The development mailing list is at subtext@googlegroups.com // // This project is licensed under the BSD license. See the License.txt file for more information. /////////////////////////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Linq; using System.Threading; using MbUnit.Framework; using Moq; using Subtext.Extensibility; using Subtext.Framework; using Subtext.Framework.Components; using Subtext.Framework.Configuration; using Subtext.Framework.Providers; using Subtext.Framework.Web.HttpModules; namespace UnitTests.Subtext.Framework.Components.EntryTestsi { /// <summary> /// Tests the methods to obtain the previous and next entry to an entry. /// </summary> [TestFixture] public class PreviousNextTests { /// <summary> /// Test the case where we have a previous, but no next entry. /// </summary> [Test] [RollBack] public void GetPreviousAndNextEntriesReturnsPreviousWhenNoNextExists() { string hostname = UnitTestHelper.GenerateUniqueString(); Config.CreateBlog("", "username", "password", hostname, string.Empty); UnitTestHelper.SetHttpContextWithBlogRequest(hostname, string.Empty); BlogRequest.Current.Blog = Config.GetBlog(hostname, string.Empty); Entry previousEntry = UnitTestHelper.CreateEntryInstanceForSyndication("test", "test", "body", UnitTestHelper.GenerateUniqueString(), DateTime.Now.AddDays(-1)); Entry currentEntry = UnitTestHelper.CreateEntryInstanceForSyndication("test", "test", "body", UnitTestHelper.GenerateUniqueString(), DateTime.Now); int previousId = UnitTestHelper.Create(previousEntry); int currentId = UnitTestHelper.Create(currentEntry); var entries = ObjectProvider.Instance().GetPreviousAndNextEntries(currentId, PostType.BlogPost); Assert.AreEqual(1, entries.Count, "Since there is no next entry, should return only 1"); Assert.AreEqual(previousId, entries.First().Id, "The previous entry does not match expectations."); } /// <summary> /// Test the case where we have a next, but no previous entry. /// </summary> [Test] [RollBack] public void GetPreviousAndNextEntriesReturnsNextWhenNoPreviousExists() { string hostname = UnitTestHelper.GenerateUniqueString(); Config.CreateBlog("", "username", "password", hostname, string.Empty); UnitTestHelper.SetHttpContextWithBlogRequest(hostname, string.Empty); BlogRequest.Current.Blog = Config.GetBlog(hostname, string.Empty); Entry currentEntry = UnitTestHelper.CreateEntryInstanceForSyndication("test", "test", "body", UnitTestHelper.GenerateUniqueString(), DateTime.Now.AddDays(-1)); Entry nextEntry = UnitTestHelper.CreateEntryInstanceForSyndication("test", "test", "body", UnitTestHelper.GenerateUniqueString(), DateTime.Now); int currentId = UnitTestHelper.Create(currentEntry); int nextId = UnitTestHelper.Create(nextEntry); var entries = ObjectProvider.Instance().GetPreviousAndNextEntries(currentId, PostType.BlogPost); Assert.AreEqual(1, entries.Count, "Since there is no previous entry, should return only next"); Assert.AreEqual(nextId, entries.First().Id, "The next entry does not match expectations."); } /// <summary> /// Test the case where we have both a previous and next. /// </summary> [Test] [RollBack] public void GetPreviousAndNextEntriesReturnsBoth() { string hostname = UnitTestHelper.GenerateUniqueString(); Config.CreateBlog("", "username", "password", hostname, string.Empty); UnitTestHelper.SetHttpContextWithBlogRequest(hostname, string.Empty); BlogRequest.Current.Blog = Config.GetBlog(hostname, string.Empty); Entry previousEntry = UnitTestHelper.CreateEntryInstanceForSyndication("test", "test", "body", UnitTestHelper.GenerateUniqueString(), DateTime.Now.AddDays(-2)); Entry currentEntry = UnitTestHelper.CreateEntryInstanceForSyndication("test", "test", "body", UnitTestHelper.GenerateUniqueString(), DateTime.Now.AddDays(-1)); Entry nextEntry = UnitTestHelper.CreateEntryInstanceForSyndication("test", "test", "body", UnitTestHelper.GenerateUniqueString(), DateTime.Now); int previousId = UnitTestHelper.Create(previousEntry); Thread.Sleep(100); int currentId = UnitTestHelper.Create(currentEntry); Thread.Sleep(100); int nextId = UnitTestHelper.Create(nextEntry); var entries = ObjectProvider.Instance().GetPreviousAndNextEntries(currentId, PostType.BlogPost); Assert.AreEqual(2, entries.Count, "Expected both previous and next."); //The more recent one is next because of desceding sort. Assert.AreEqual(nextId, entries.First().Id, "The next entry does not match expectations."); Assert.AreEqual(previousId, entries.ElementAt(1).Id, "The previous entry does not match expectations."); } /// <summary> /// Test the case where we have more than three entries. /// </summary> [Test] [RollBack] public void GetPreviousAndNextEntriesReturnsCorrectEntries() { string hostname = UnitTestHelper.GenerateUniqueString(); Config.CreateBlog("", "username", "password", hostname, string.Empty); UnitTestHelper.SetHttpContextWithBlogRequest(hostname, string.Empty); BlogRequest.Current.Blog = Config.GetBlog(hostname, string.Empty); Entry firstEntry = UnitTestHelper.CreateEntryInstanceForSyndication("test", "test", "body", UnitTestHelper.GenerateUniqueString(), DateTime.Now.AddDays(-3)); Entry previousEntry = UnitTestHelper.CreateEntryInstanceForSyndication("test", "test", "body", UnitTestHelper.GenerateUniqueString(), DateTime.Now.AddDays(-2)); Entry currentEntry = UnitTestHelper.CreateEntryInstanceForSyndication("test", "test", "body", UnitTestHelper.GenerateUniqueString(), DateTime.Now.AddDays(-1)); Entry nextEntry = UnitTestHelper.CreateEntryInstanceForSyndication("test", "test", "body", UnitTestHelper.GenerateUniqueString(), DateTime.Now); Entry lastEntry = UnitTestHelper.CreateEntryInstanceForSyndication("test", "test", "body", UnitTestHelper.GenerateUniqueString(), DateTime.Now.AddDays(1)); Thread.Sleep(100); int previousId = UnitTestHelper.Create(previousEntry); Thread.Sleep(100); int currentId = UnitTestHelper.Create(currentEntry); Thread.Sleep(100); int nextId = UnitTestHelper.Create(nextEntry); Thread.Sleep(100); var entries = ObjectProvider.Instance().GetPreviousAndNextEntries(currentId, PostType.BlogPost); Assert.AreEqual(2, entries.Count, "Expected both previous and next."); //The more recent one is next because of desceding sort. Assert.AreEqual(nextId, entries.First().Id, "The next entry does not match expectations."); Assert.AreEqual(previousId, entries.ElementAt(1).Id, "The previous entry does not match expectations."); } /// <summary> /// Make sure that previous and next are based on syndication date and not entry id. /// </summary> [Test] [RollBack] public void GetPreviousAndNextBasedOnSyndicationDateNotEntryId() { string hostname = UnitTestHelper.GenerateUniqueString(); Config.CreateBlog("", "username", "password", hostname, string.Empty); UnitTestHelper.SetHttpContextWithBlogRequest(hostname, string.Empty); BlogRequest.Current.Blog = Config.GetBlog(hostname, string.Empty); Entry previousEntry = UnitTestHelper.CreateEntryInstanceForSyndication("test", "test", "body"); Entry currentEntry = UnitTestHelper.CreateEntryInstanceForSyndication("test", "test", "body"); Entry nextEntry = UnitTestHelper.CreateEntryInstanceForSyndication("test", "test", "body"); previousEntry.IsActive = false; currentEntry.IsActive = false; nextEntry.IsActive = false; //Create out of order. int currentId = UnitTestHelper.Create(currentEntry); int nextId = UnitTestHelper.Create(nextEntry); int previousId = UnitTestHelper.Create(previousEntry); //Now syndicate. previousEntry.IsActive = true; var subtextContext = new Mock<ISubtextContext>(); subtextContext.Setup(c => c.Blog).Returns(Config.CurrentBlog); subtextContext.Setup(c => c.Repository).Returns(ObjectProvider.Instance()); UnitTestHelper.Update(previousEntry, subtextContext.Object); Thread.Sleep(100); currentEntry.IsActive = true; UnitTestHelper.Update(currentEntry, subtextContext.Object); Thread.Sleep(100); nextEntry.IsActive = true; UnitTestHelper.Update(nextEntry, subtextContext.Object); Assert.IsTrue(previousId > currentId, "Ids are out of order."); var entries = ObjectProvider.Instance().GetPreviousAndNextEntries(currentId, PostType.BlogPost); Assert.AreEqual(2, entries.Count, "Expected both previous and next."); //The first should be next because of descending sort. Assert.AreEqual(nextId, entries.First().Id, "The next entry does not match expectations."); Assert.AreEqual(previousId, entries.ElementAt(1).Id, "The previous entry does not match expectations."); } } }
using System; using System.Collections.Generic; using System.Text; using ID3.ID3v2Frames; using System.IO; /* * This namespace contain Frames that is usefull for sending and recieving * mpeg files over streams. ex listening to audio from internet */ namespace ID3.ID3v2Frames.StreamFrames { /// <summary> /// A class for PositionSynchronised frame /// </summary> public class PositionSynchronisedFrame : Frame { private TimeStamps _TimeStamp; private long _Position; internal PositionSynchronisedFrame(string FrameID, FrameFlags Flags, FileStream Data, int Length) : base(FrameID, Flags) { _TimeStamp = (TimeStamps)Data.ReadByte(); if (!IsValidEnumValue(_TimeStamp, ValidatingErrorTypes.ID3Error)) { _MustDrop = true; return; } Length--; byte[] Long = new byte[8]; byte[] Buf = new byte[Length]; Data.Read(Buf, 0, Length); Buf.CopyTo(Long, 8 - Buf.Length); Array.Reverse(Long); _Position = BitConverter.ToInt64(Long, 0); } /// <summary> /// create new PositionSynchronised frame /// </summary> /// <param name="Flags">Flags of frame</param> /// <param name="TimeStamp">TimeStamp to use for frame</param> /// <param name="Position">Position of frame</param> public PositionSynchronisedFrame(FrameFlags Flags, TimeStamps TimeStamp, long Position) : base("POSS", Flags) { this.TimeStamp = TimeStamp; _Position = Position; } /// <summary> /// Gets or sets current frame TimeStamp /// </summary> public TimeStamps TimeStamp { get { return _TimeStamp; } set { if (!Enum.IsDefined(typeof(TimeStamps), value)) throw (new ArgumentException("This is not valid value for TimeStamp")); _TimeStamp = value; } } /// <summary> /// Gets or sets current frame Position /// </summary> public long Position { get { return _Position; } set { _Position = value; } } #region -> Override Method and properties <- /// <summary> /// Indicate is current frame information availabe or not /// </summary> public override bool IsAvailable { get { return true; } } /// <summary> /// Gets MemoryStream For saving this Frame /// </summary> /// <returns>MemoryStream to save this frame</returns> public override MemoryStream FrameStream(int MinorVersion) { MemoryStream ms = FrameHeader(MinorVersion); ms.WriteByte((byte)_TimeStamp); byte[] Buf; Buf = BitConverter.GetBytes(_Position); Array.Reverse(Buf); ms.Write(Buf, 0, 8); return ms; } /// <summary> /// Gets length of current frame /// </summary> public override int Length { get { return 9; } } #endregion } /// <summary> /// A class for RecomendedBufferSize Frame /// </summary> public class RecomendedBufferSizeFrame : Frame { protected uint _BufferSize; protected bool _EmbededInfoFlag; protected uint _OffsetToNextTag; /// <summary> /// Create new RecomendedBufferSize /// </summary> /// <param name="FrameID">Characters tag identifier</param> /// <param name="Flags">2 Bytes flags identifier</param> /// <param name="Data">Contain Data for this frame</param> /// <param name="Lenght">Length to read from FileStream</param> internal RecomendedBufferSizeFrame(string FrameID, FrameFlags Flags, FileStreamEx Data, int Length) : base(FrameID, Flags) { _BufferSize = Data.ReadUInt(3); _EmbededInfoFlag = Convert.ToBoolean(Data.ReadByte()); if (Length > 4) _OffsetToNextTag = Data.ReadUInt(4); } /// <summary> /// Create new RecomendedBufferSize /// </summary> /// <param name="Flags">Flags of frame</param> /// <param name="BufferSize">Recommended Buffer size</param> /// <param name="EmbededInfoFlag">EmbededInfoFlag</param> /// <param name="OffsetToNextTag">Offset to next tag</param> public RecomendedBufferSizeFrame(FrameFlags Flags, uint BufferSize, bool EmbededInfoFlag, uint OffsetToNextTag) : base("RBUF", Flags) { _BufferSize = BufferSize; _EmbededInfoFlag = EmbededInfoFlag; _OffsetToNextTag = OffsetToNextTag; } /// <summary> /// Gets or Sets Buffer size for current frame /// </summary> public uint BufferSize { get { return _BufferSize; } set { if (value > 0xFFFFFF) throw (new ArgumentException("Buffer size can't be greater 16,777,215(0xFFFFFF)")); _BufferSize = value; } } /// <summary> /// Gets or Sets current frame EmbeddedInfoFlag /// </summary> public bool EmbededInfoFlag { get { return _EmbededInfoFlag; } set { _EmbededInfoFlag = value; } } /// <summary> /// Gets or Sets Offset to next tag /// </summary> public uint OffsetToNextTag { get { return _OffsetToNextTag; } set { _OffsetToNextTag = value; } } #region -> Override Method and properties <- /// <summary> /// Gets length of current frame /// </summary> public override int Length { get { // 3: Buffer Size // 1: Info Flag // 4: Offset to next tag (if available) return 4 + (_OffsetToNextTag > 0 ? 4 : 0); } } /// <summary> /// Gets MemoryStream to saving this Frame /// </summary> /// <returns>MemoryStream to save this frame</returns> public override MemoryStream FrameStream(int MinorVersion) { byte[] Buf; int Len = Length; MemoryStream ms = FrameHeader(MinorVersion); Buf = BitConverter.GetBytes(_BufferSize); Array.Reverse(Buf); ms.Write(Buf, 0, Buf.Length); ms.WriteByte(Convert.ToByte(_EmbededInfoFlag)); if (_OffsetToNextTag > 0) { Buf = BitConverter.GetBytes(_OffsetToNextTag); Array.Reverse(Buf); ms.Write(Buf, 0, Buf.Length); } return ms; } /// <summary> /// Indicate if this frame is available /// </summary> public override bool IsAvailable { get { if (_BufferSize != 0) return true; else return false; } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Runtime.Serialization { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Xml; using System.Xml.Serialization; using System.Security; using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>; #if !NET_NATIVE using ExtensionDataObject = System.Object; #endif #if USE_REFEMIT || NET_NATIVE public class XmlObjectSerializerReadContext : XmlObjectSerializerContext #else internal class XmlObjectSerializerReadContext : XmlObjectSerializerContext #endif { internal Attributes attributes; private HybridObjectCache _deserializedObjects; private XmlSerializableReader _xmlSerializableReader; private object _getOnlyCollectionValue; private bool _isGetOnlyCollection; private HybridObjectCache DeserializedObjects { get { if (_deserializedObjects == null) _deserializedObjects = new HybridObjectCache(); return _deserializedObjects; } } internal override bool IsGetOnlyCollection { get { return _isGetOnlyCollection; } set { _isGetOnlyCollection = value; } } #if USE_REFEMIT public object GetCollectionMember() #else internal object GetCollectionMember() #endif { return _getOnlyCollectionValue; } #if USE_REFEMIT public void StoreCollectionMemberInfo(object collectionMember) #else internal void StoreCollectionMemberInfo(object collectionMember) #endif { _getOnlyCollectionValue = collectionMember; _isGetOnlyCollection = true; } #if USE_REFEMIT public static void ThrowNullValueReturnedForGetOnlyCollectionException(Type type) #else internal static void ThrowNullValueReturnedForGetOnlyCollectionException(Type type) #endif { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NullValueReturnedForGetOnlyCollection, DataContract.GetClrTypeFullName(type)))); } #if USE_REFEMIT public static void ThrowArrayExceededSizeException(int arraySize, Type type) #else internal static void ThrowArrayExceededSizeException(int arraySize, Type type) #endif { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayExceededSize, arraySize, DataContract.GetClrTypeFullName(type)))); } internal static XmlObjectSerializerReadContext CreateContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) { return (serializer.PreserveObjectReferences || serializer.SerializationSurrogateProvider != null) ? new XmlObjectSerializerReadContextComplex(serializer, rootTypeDataContract, dataContractResolver) : new XmlObjectSerializerReadContext(serializer, rootTypeDataContract, dataContractResolver); } internal XmlObjectSerializerReadContext(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject) : base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject) { } internal XmlObjectSerializerReadContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) : base(serializer, rootTypeDataContract, dataContractResolver) { this.attributes = new Attributes(); } #if USE_REFEMIT public virtual object InternalDeserialize(XmlReaderDelegator xmlReader, int id, RuntimeTypeHandle declaredTypeHandle, string name, string ns) #else internal virtual object InternalDeserialize(XmlReaderDelegator xmlReader, int id, RuntimeTypeHandle declaredTypeHandle, string name, string ns) #endif { DataContract dataContract = GetDataContract(id, declaredTypeHandle); return InternalDeserialize(xmlReader, name, ns, ref dataContract); } internal virtual object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, string name, string ns) { DataContract dataContract = GetDataContract(declaredType); return InternalDeserialize(xmlReader, name, ns, ref dataContract); } internal virtual object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, string name, string ns) { if (dataContract == null) GetDataContract(declaredType); return InternalDeserialize(xmlReader, name, ns, ref dataContract); } protected bool TryHandleNullOrRef(XmlReaderDelegator reader, Type declaredType, string name, string ns, ref object retObj) { ReadAttributes(reader); if (attributes.Ref != Globals.NewObjectId) { if (_isGetOnlyCollection) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ErrorDeserializing, SR.Format(SR.ErrorTypeInfo, DataContract.GetClrTypeFullName(declaredType)), SR.Format(SR.XmlStartElementExpected, Globals.RefLocalName)))); } else { retObj = GetExistingObject(attributes.Ref, declaredType, name, ns); reader.Skip(); return true; } } else if (attributes.XsiNil) { reader.Skip(); return true; } return false; } protected object InternalDeserialize(XmlReaderDelegator reader, string name, string ns, ref DataContract dataContract) { object retObj = null; if (TryHandleNullOrRef(reader, dataContract.UnderlyingType, name, ns, ref retObj)) return retObj; bool knownTypesAddedInCurrentScope = false; if (dataContract.KnownDataContracts != null) { scopedKnownTypes.Push(dataContract.KnownDataContracts); knownTypesAddedInCurrentScope = true; } if (attributes.XsiTypeName != null) { dataContract = ResolveDataContractFromKnownTypes(attributes.XsiTypeName, attributes.XsiTypeNamespace, dataContract); if (dataContract == null) { if (DataContractResolver == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(reader, SR.Format(SR.DcTypeNotFoundOnDeserialize, attributes.XsiTypeNamespace, attributes.XsiTypeName, reader.NamespaceURI, reader.LocalName)))); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(reader, SR.Format(SR.DcTypeNotResolvedOnDeserialize, attributes.XsiTypeNamespace, attributes.XsiTypeName, reader.NamespaceURI, reader.LocalName)))); } knownTypesAddedInCurrentScope = ReplaceScopedKnownTypesTop(dataContract.KnownDataContracts, knownTypesAddedInCurrentScope); } if (knownTypesAddedInCurrentScope) { object obj = ReadDataContractValue(dataContract, reader); scopedKnownTypes.Pop(); return obj; } else { return ReadDataContractValue(dataContract, reader); } } private bool ReplaceScopedKnownTypesTop(DataContractDictionary knownDataContracts, bool knownTypesAddedInCurrentScope) { if (knownTypesAddedInCurrentScope) { scopedKnownTypes.Pop(); knownTypesAddedInCurrentScope = false; } if (knownDataContracts != null) { scopedKnownTypes.Push(knownDataContracts); knownTypesAddedInCurrentScope = true; } return knownTypesAddedInCurrentScope; } #if USE_REFEMIT public static bool MoveToNextElement(XmlReaderDelegator xmlReader) #else internal static bool MoveToNextElement(XmlReaderDelegator xmlReader) #endif { return (xmlReader.MoveToContent() != XmlNodeType.EndElement); } #if USE_REFEMIT public int GetMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, ExtensionDataObject extensionData) #else internal int GetMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, ExtensionDataObject extensionData) #endif { for (int i = memberIndex + 1; i < memberNames.Length; i++) { if (xmlReader.IsStartElement(memberNames[i], memberNamespaces[i])) return i; } HandleMemberNotFound(xmlReader, extensionData, memberIndex); return memberNames.Length; } #if USE_REFEMIT public int GetMemberIndexWithRequiredMembers(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, int requiredIndex, ExtensionDataObject extensionData) #else internal int GetMemberIndexWithRequiredMembers(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, int requiredIndex, ExtensionDataObject extensionData) #endif { for (int i = memberIndex + 1; i < memberNames.Length; i++) { if (xmlReader.IsStartElement(memberNames[i], memberNamespaces[i])) { if (requiredIndex < i) ThrowRequiredMemberMissingException(xmlReader, memberIndex, requiredIndex, memberNames); return i; } } HandleMemberNotFound(xmlReader, extensionData, memberIndex); return memberNames.Length; } #if USE_REFEMIT public static void ThrowRequiredMemberMissingException(XmlReaderDelegator xmlReader, int memberIndex, int requiredIndex, XmlDictionaryString[] memberNames) #else internal static void ThrowRequiredMemberMissingException(XmlReaderDelegator xmlReader, int memberIndex, int requiredIndex, XmlDictionaryString[] memberNames) #endif { StringBuilder stringBuilder = new StringBuilder(); if (requiredIndex == memberNames.Length) requiredIndex--; for (int i = memberIndex + 1; i <= requiredIndex; i++) { if (stringBuilder.Length != 0) stringBuilder.Append(" | "); stringBuilder.Append(memberNames[i].Value); } throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.Format(SR.UnexpectedElementExpectingElements, xmlReader.NodeType, xmlReader.LocalName, xmlReader.NamespaceURI, stringBuilder.ToString())))); } #if NET_NATIVE public static void ThrowMissingRequiredMembers(object obj, XmlDictionaryString[] memberNames, byte[] expectedElements, byte[] requiredElements) { StringBuilder stringBuilder = new StringBuilder(); int missingMembersCount = 0; for (int i = 0; i < memberNames.Length; i++) { if (IsBitSet(expectedElements, i) && IsBitSet(requiredElements, i)) { if (stringBuilder.Length != 0) stringBuilder.Append(", "); stringBuilder.Append(memberNames[i]); missingMembersCount++; } } if (missingMembersCount == 1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.JsonOneRequiredMemberNotFound, DataContract.GetClrTypeFullName(obj.GetType()), stringBuilder.ToString()))); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.JsonRequiredMembersNotFound, DataContract.GetClrTypeFullName(obj.GetType()), stringBuilder.ToString()))); } } public static void ThrowDuplicateMemberException(object obj, XmlDictionaryString[] memberNames, int memberIndex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.JsonDuplicateMemberInInput, DataContract.GetClrTypeFullName(obj.GetType()), memberNames[memberIndex]))); } [SecuritySafeCritical] private static bool IsBitSet(byte[] bytes, int bitIndex) { throw new NotImplementedException(); //return BitFlagsGenerator.IsBitSet(bytes, bitIndex); } #endif protected void HandleMemberNotFound(XmlReaderDelegator xmlReader, ExtensionDataObject extensionData, int memberIndex) { xmlReader.MoveToContent(); if (xmlReader.NodeType != XmlNodeType.Element) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); if (IgnoreExtensionDataObject || extensionData == null) SkipUnknownElement(xmlReader); else HandleUnknownElement(xmlReader, extensionData, memberIndex); } internal void HandleUnknownElement(XmlReaderDelegator xmlReader, ExtensionDataObject extensionData, int memberIndex) { } #if USE_REFEMIT public void SkipUnknownElement(XmlReaderDelegator xmlReader) #else internal void SkipUnknownElement(XmlReaderDelegator xmlReader) #endif { ReadAttributes(xmlReader); xmlReader.Skip(); } #if USE_REFEMIT public string ReadIfNullOrRef(XmlReaderDelegator xmlReader, Type memberType, bool isMemberTypeSerializable) #else internal string ReadIfNullOrRef(XmlReaderDelegator xmlReader, Type memberType, bool isMemberTypeSerializable) #endif { if (attributes.Ref != Globals.NewObjectId) { CheckIfTypeSerializable(memberType, isMemberTypeSerializable); xmlReader.Skip(); return attributes.Ref; } else if (attributes.XsiNil) { CheckIfTypeSerializable(memberType, isMemberTypeSerializable); xmlReader.Skip(); return Globals.NullObjectId; } return Globals.NewObjectId; } #if USE_REFEMIT public virtual void ReadAttributes(XmlReaderDelegator xmlReader) #else internal virtual void ReadAttributes(XmlReaderDelegator xmlReader) #endif { if (attributes == null) attributes = new Attributes(); attributes.Read(xmlReader); } #if USE_REFEMIT public void ResetAttributes() #else internal void ResetAttributes() #endif { if (attributes != null) attributes.Reset(); } #if USE_REFEMIT public string GetObjectId() #else internal string GetObjectId() #endif { return attributes.Id; } #if USE_REFEMIT public virtual int GetArraySize() #else internal virtual int GetArraySize() #endif { return -1; } #if USE_REFEMIT public void AddNewObject(object obj) #else internal void AddNewObject(object obj) #endif { AddNewObjectWithId(attributes.Id, obj); } #if USE_REFEMIT public void AddNewObjectWithId(string id, object obj) #else internal void AddNewObjectWithId(string id, object obj) #endif { if (id != Globals.NewObjectId) DeserializedObjects.Add(id, obj); } public void ReplaceDeserializedObject(string id, object oldObj, object newObj) { if (object.ReferenceEquals(oldObj, newObj)) return; if (id != Globals.NewObjectId) { // In certain cases (IObjectReference, SerializationSurrogate or DataContractSurrogate), // an object can be replaced with a different object once it is deserialized. If the // object happens to be referenced from within itself, that reference needs to be updated // with the new instance. BinaryFormatter supports this by fixing up such references later. // These XmlObjectSerializer implementations do not currently support fix-ups. Hence we // throw in such cases to allow us add fix-up support in the future if we need to. if (DeserializedObjects.IsObjectReferenced(id)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.FactoryObjectContainsSelfReference, DataContract.GetClrTypeFullName(oldObj.GetType()), DataContract.GetClrTypeFullName(newObj.GetType()), id))); DeserializedObjects.Remove(id); DeserializedObjects.Add(id, newObj); } } #if USE_REFEMIT public object GetExistingObject(string id, Type type, string name, string ns) #else internal object GetExistingObject(string id, Type type, string name, string ns) #endif { object retObj = DeserializedObjects.GetObject(id); if (retObj == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DeserializedObjectWithIdNotFound, id))); return retObj; } #if USE_REFEMIT public static void Read(XmlReaderDelegator xmlReader) #else internal static void Read(XmlReaderDelegator xmlReader) #endif { if (!xmlReader.Read()) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.UnexpectedEndOfFile))); } internal static void ParseQualifiedName(string qname, XmlReaderDelegator xmlReader, out string name, out string ns, out string prefix) { int colon = qname.IndexOf(':'); prefix = ""; if (colon >= 0) prefix = qname.Substring(0, colon); name = qname.Substring(colon + 1); ns = xmlReader.LookupNamespace(prefix); } #if USE_REFEMIT public static T[] EnsureArraySize<T>(T[] array, int index) #else internal static T[] EnsureArraySize<T>(T[] array, int index) #endif { if (array.Length <= index) { if (index == Int32.MaxValue) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( XmlObjectSerializer.CreateSerializationException( SR.Format(SR.MaxArrayLengthExceeded, Int32.MaxValue, DataContract.GetClrTypeFullName(typeof(T))))); } int newSize = (index < Int32.MaxValue / 2) ? index * 2 : Int32.MaxValue; T[] newArray = new T[newSize]; Array.Copy(array, 0, newArray, 0, array.Length); array = newArray; } return array; } #if USE_REFEMIT public static T[] TrimArraySize<T>(T[] array, int size) #else internal static T[] TrimArraySize<T>(T[] array, int size) #endif { if (size != array.Length) { T[] newArray = new T[size]; Array.Copy(array, 0, newArray, 0, size); array = newArray; } return array; } #if USE_REFEMIT public void CheckEndOfArray(XmlReaderDelegator xmlReader, int arraySize, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) #else internal void CheckEndOfArray(XmlReaderDelegator xmlReader, int arraySize, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) #endif { if (xmlReader.NodeType == XmlNodeType.EndElement) return; while (xmlReader.IsStartElement()) { if (xmlReader.IsStartElement(itemName, itemNamespace)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayExceededSizeAttribute, arraySize, itemName.Value, itemNamespace.Value))); SkipUnknownElement(xmlReader); } if (xmlReader.NodeType != XmlNodeType.EndElement) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.EndElement, xmlReader)); } internal object ReadIXmlSerializable(XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType) { if (_xmlSerializableReader == null) _xmlSerializableReader = new XmlSerializableReader(); return ReadIXmlSerializable(_xmlSerializableReader, xmlReader, xmlDataContract, isMemberType); } internal static object ReadRootIXmlSerializable(XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType) { return ReadIXmlSerializable(new XmlSerializableReader(), xmlReader, xmlDataContract, isMemberType); } internal static object ReadIXmlSerializable(XmlSerializableReader xmlSerializableReader, XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType) { object obj = null; xmlSerializableReader.BeginRead(xmlReader); if (isMemberType && !xmlDataContract.HasRoot) { xmlReader.Read(); xmlReader.MoveToContent(); } if (xmlDataContract.UnderlyingType == Globals.TypeOfXmlElement) { if (!xmlReader.IsStartElement()) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); XmlDocument xmlDoc = new XmlDocument(); obj = (XmlElement)xmlDoc.ReadNode(xmlSerializableReader); } else if (xmlDataContract.UnderlyingType == Globals.TypeOfXmlNodeArray) { obj = XmlSerializableServices.ReadNodes(xmlSerializableReader); } else { IXmlSerializable xmlSerializable = xmlDataContract.CreateXmlSerializableDelegate(); xmlSerializable.ReadXml(xmlSerializableReader); obj = xmlSerializable; } xmlSerializableReader.EndRead(); return obj; } protected virtual DataContract ResolveDataContractFromTypeName() { return (attributes.XsiTypeName == null) ? null : ResolveDataContractFromKnownTypes(attributes.XsiTypeName, attributes.XsiTypeNamespace, null /*memberTypeContract*/); } #if USE_REFEMIT public static Exception CreateUnexpectedStateException(XmlNodeType expectedState, XmlReaderDelegator xmlReader) #else internal static Exception CreateUnexpectedStateException(XmlNodeType expectedState, XmlReaderDelegator xmlReader) #endif { return XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(SR.Format(SR.ExpectingState, expectedState), xmlReader); } //Silverlight only helper function to create SerializationException #if USE_REFEMIT public static Exception CreateSerializationException(string message) #else internal static Exception CreateSerializationException(string message) #endif { return XmlObjectSerializer.CreateSerializationException(message); } protected virtual object ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader) { return dataContract.ReadXmlValue(reader, this); } protected virtual XmlReaderDelegator CreateReaderDelegatorForReader(XmlReader xmlReader) { return new XmlReaderDelegator(xmlReader); } protected virtual bool IsReadingCollectionExtensionData(XmlReaderDelegator xmlReader) { return (attributes.ArraySZSize != -1); } protected virtual bool IsReadingClassExtensionData(XmlReaderDelegator xmlReader) { return false; } } }
// 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.Data; using System.Configuration; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using WebsitePanel.EnterpriseServer; using WebsitePanel.EnterpriseServer.Base.HostedSolution; namespace WebsitePanel.Portal { public partial class SpaceQuotas : WebsitePanelModuleBase { // private PackageContext cntx; // Brief quotas mapping hash // In case if you add new brief quota: just update this collection with quota & table row control ids // The code will do the rest... private readonly Dictionary<string, string> briefQuotaHash = new Dictionary<string, string> { // QUOTA CONTROL ID <=> TABLE ROW CONTROL ID { "quotaDiskspace", "pnlDiskspace" }, { "quotaBandwidth", "pnlBandwidth" }, { "quotaDomains", "pnlDomains" }, { "quotaSubDomains", "pnlSubDomains" }, //{ "quotaDomainPointers", "pnlDomainPointers" }, { "quotaOrganizations", "pnlOrganizations" }, { "quotaUserAccounts", "pnlUserAccounts" }, { "quotaDeletedUsers", "pnlDeletedUsers" }, { "quotaMailAccounts", "pnlMailAccounts" }, { "quotaExchangeAccounts", "pnlExchangeAccounts" }, { "quotaOCSUsers", "pnlOCSUsers" }, { "quotaLyncUsers", "pnlLyncUsers" }, { "quotaBlackBerryUsers", "pnlBlackBerryUsers" }, { "quotaSharepointSites", "pnlSharepointSites" }, { "quotaWebSites", "pnlWebSites" }, { "quotaDatabases", "pnlDatabases" }, { "quotaNumberOfVm", "pnlHyperVForPC" }, { "quotaFtpAccounts", "pnlFtpAccounts" }, { "quotaExchangeStorage", "pnlExchangeStorage" }, { "quotaNumberOfFolders", "pnlFolders" }, { "quotaEnterpriseStorage", "pnlEnterpriseStorage" }, { "quotaEnterpriseSharepointSites", "pnlEnterpriseSharepointSites"}, { "quotaRdsCollections", "pnlRdsCollections"}, { "quotaRdsServers", "pnlRdsServers"}, { "quotaRdsUsers", "pnlRdsUsers"} }; protected void Page_Load(object sender, EventArgs e) { // bind quotas BindQuotas(); UserInfo user = UsersHelper.GetUser(PanelSecurity.EffectiveUserId); if (user != null) { PackageContext cntx = PackagesHelper.GetCachedPackageContext(PanelSecurity.PackageId); if ((user.Role == UserRole.User) & (Utils.CheckQouta(Quotas.EXCHANGE2007_ISCONSUMER, cntx))) { btnViewQuotas.Visible = lnkViewDiskspaceDetails.Visible = false; } } } private void BindQuotas() { // load package context cntx = PackagesHelper.GetCachedPackageContext(PanelSecurity.PackageId); int packageId = ES.Services.Packages.GetPackage(PanelSecurity.PackageId).PackageId; lnkViewBandwidthDetails.NavigateUrl = GetNavigateBandwidthDetails(packageId); lnkViewDiskspaceDetails.NavigateUrl = GetNavigateDiskspaceDetails(packageId); } protected string GetNavigateBandwidthDetails(int packageId) { DateTime startDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1); DateTime endDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month)); return PortalUtils.NavigatePageURL("BandwidthReport", PortalUtils.SPACE_ID_PARAM, packageId.ToString(), "StartDate=" + startDate.Ticks.ToString(), "EndDate=" + endDate.Ticks.ToString(), "ctl=edit", "moduleDefId=BandwidthReport"); } protected string GetNavigateDiskspaceDetails(int packageId) { return PortalUtils.NavigatePageURL("DiskspaceReport", PortalUtils.SPACE_ID_PARAM, packageId.ToString(), "ctl=edit", "moduleDefId=DiskspaceReport"); } protected void btnViewQuotas_Click(object sender, EventArgs e) { Response.Redirect(EditUrl(PortalUtils.SPACE_ID_PARAM, PanelSecurity.PackageId.ToString(), "view_quotas")); } protected override void OnPreRender(EventArgs e) { // AddServiceLevelsQuotas(); // SetVisibilityStatus4BriefQuotasBlock(); // base.OnPreRender(e); } private void SetVisibilityStatus4BriefQuotasBlock() { foreach (KeyValuePair<string, string> kvp in briefQuotaHash) { // Lookup for quota control... Quota quotaCtl = FindControl(kvp.Key) as Quota; Control containerCtl = FindControl(kvp.Value); // Skip processing if quota or its container ctrl not found if (quotaCtl == null || containerCtl == null) continue; // Find out a quota value info within the package context QuotaValueInfo qvi = Array.Find<QuotaValueInfo>( cntx.QuotasArray, x => x.QuotaName == quotaCtl.QuotaName); // Skip processing if quota not defined in the package context if (qvi == null) continue; // Show or hide corresponding quotas' containers switch (qvi.QuotaTypeId) { case QuotaInfo.BooleanQuota: // 1: Quota is enabled; // 0: Quota is disabled; containerCtl.Visible = (qvi.QuotaAllocatedValue > 0); break; case QuotaInfo.NumericQuota: case QuotaInfo.MaximumValueQuota: // -1: Quota is unlimited // 0: Quota is disabled // xx: Quota is enabled containerCtl.Visible = (qvi.QuotaAllocatedValue != 0); break; } } } private void AddServiceLevelsQuotas() { var orgs = ES.Services.Organizations.GetOrganizations(PanelSecurity.PackageId, true); OrganizationStatistics stats = null; if (orgs != null && orgs.FirstOrDefault() != null) stats = ES.Services.Organizations.GetOrganizationStatistics(orgs.First().Id); foreach (var quota in Array.FindAll<QuotaValueInfo>( cntx.QuotasArray, x => x.QuotaName.Contains(Quotas.SERVICE_LEVELS))) { HtmlTableRow tr = new HtmlTableRow(); tr.ID = "pnl_" + quota.QuotaName.Replace(Quotas.SERVICE_LEVELS, "").Replace(" ", string.Empty).Trim(); HtmlTableCell col1 = new HtmlTableCell(); col1.Attributes["class"] = "SubHead"; col1.Attributes["nowrap"] = "nowrap"; Label lbl = new Label(); lbl.ID = "lbl_" + quota.QuotaName.Replace(Quotas.SERVICE_LEVELS, "").Replace(" ", string.Empty).Trim(); lbl.Text = quota.QuotaDescription + ":"; col1.Controls.Add(lbl); HtmlTableCell col2 = new HtmlTableCell(); col2.Attributes["class"] = "Normal"; Quota quotaControl = (Quota) LoadControl("UserControls/Quota.ascx"); quotaControl.ID = "quota_" + quota.QuotaName.Replace(Quotas.SERVICE_LEVELS, "").Replace(" ", string.Empty).Trim(); quotaControl.QuotaName = quota.QuotaName; quotaControl.DisplayGauge = true; col2.Controls.Add(quotaControl); tr.Controls.Add(col1); tr.Controls.Add(col2); tblQuotas.Controls.Add(tr); if (stats != null) { var serviceLevel = stats.ServiceLevels.FirstOrDefault(q => q.QuotaName == quota.QuotaName); if (serviceLevel != null) { quotaControl.QuotaAllocatedValue = serviceLevel.QuotaAllocatedValue; } } } } } }
// SPDX-License-Identifier: MIT // Copyright wtfsckgh@gmail.com // Copyright iced contributors #if ENCODER using System; using System.Collections.Generic; using Iced.Intel; using Iced.Intel.EncoderInternal; using Xunit; namespace Iced.UnitTests.Intel.EncoderTests { public sealed class MiscTests : EncoderTest { [Fact] void Encode_INVALID_Code_value_is_an_error() { Encoder encoder; var instruction = new Instruction { Code = Code.INVALID }; string errorMessage; bool result; uint instrLen; encoder = Encoder.Create(16, new CodeWriterImpl()); result = encoder.TryEncode(instruction, 0, out instrLen, out errorMessage); Assert.False(result); Assert.Equal(InvalidHandler.ERROR_MESSAGE, errorMessage); Assert.Equal(0U, instrLen); encoder = Encoder.Create(32, new CodeWriterImpl()); result = encoder.TryEncode(instruction, 0, out instrLen, out errorMessage); Assert.False(result); Assert.Equal(InvalidHandler.ERROR_MESSAGE, errorMessage); Assert.Equal(0U, instrLen); encoder = Encoder.Create(64, new CodeWriterImpl()); result = encoder.TryEncode(instruction, 0, out instrLen, out errorMessage); Assert.False(result); Assert.Equal(InvalidHandler.ERROR_MESSAGE, errorMessage); Assert.Equal(0U, instrLen); } [Fact] void Encode_throws() { var instruction = new Instruction { Code = Code.INVALID }; var encoder = Encoder.Create(64, new CodeWriterImpl()); Assert.Throws<EncoderException>(() => { var instrCopy = instruction; encoder.Encode(instrCopy, 0); }); } [Theory] [MemberData(nameof(DisplSize_eq_1_uses_long_form_if_it_does_not_fit_in_1_byte_Data))] void DisplSize_eq_1_uses_long_form_if_it_does_not_fit_in_1_byte(int bitness, string hexBytes, ulong rip, Instruction instruction) { var expectedBytes = HexUtils.ToByteArray(hexBytes); var codeWriter = new CodeWriterImpl(); var encoder = Encoder.Create(bitness, codeWriter); Assert.True(encoder.TryEncode(instruction, rip, out uint encodedLength, out string errorMessage), $"Could not encode {instruction}, error: {errorMessage}"); Assert.Equal(expectedBytes, codeWriter.ToArray()); Assert.Equal((uint)expectedBytes.Length, encodedLength); } public static IEnumerable<object[]> DisplSize_eq_1_uses_long_form_if_it_does_not_fit_in_1_byte_Data { get { const ulong rip = 0UL; var memory16 = new MemoryOperand(Register.SI, 0x1234, 1); var memory32 = new MemoryOperand(Register.ESI, 0x12345678, 1); var memory64 = new MemoryOperand(Register.R14, 0x12345678, 1); yield return new object[] { 16, "0F10 8C 3412", rip, Instruction.Create(Code.Movups_xmm_xmmm128, Register.XMM1, memory16) }; yield return new object[] { 32, "0F10 8E 78563412", rip, Instruction.Create(Code.Movups_xmm_xmmm128, Register.XMM1, memory32) }; yield return new object[] { 64, "41 0F10 8E 78563412", rip, Instruction.Create(Code.Movups_xmm_xmmm128, Register.XMM1, memory64) }; #if !NO_VEX yield return new object[] { 16, "C5F8 10 8C 3412", rip, Instruction.Create(Code.VEX_Vmovups_xmm_xmmm128, Register.XMM1, memory16) }; yield return new object[] { 32, "C5F8 10 8E 78563412", rip, Instruction.Create(Code.VEX_Vmovups_xmm_xmmm128, Register.XMM1, memory32) }; yield return new object[] { 64, "C4C178 10 8E 78563412", rip, Instruction.Create(Code.VEX_Vmovups_xmm_xmmm128, Register.XMM1, memory64) }; #endif #if !NO_EVEX yield return new object[] { 16, "62 F17C08 10 8C 3412", rip, Instruction.Create(Code.EVEX_Vmovups_xmm_k1z_xmmm128, Register.XMM1, memory16) }; yield return new object[] { 32, "62 F17C08 10 8E 78563412", rip, Instruction.Create(Code.EVEX_Vmovups_xmm_k1z_xmmm128, Register.XMM1, memory32) }; yield return new object[] { 64, "62 D17C08 10 8E 78563412", rip, Instruction.Create(Code.EVEX_Vmovups_xmm_k1z_xmmm128, Register.XMM1, memory64) }; #endif #if !NO_XOP yield return new object[] { 16, "8F E878C0 8C 3412 A5", rip, Instruction.Create(Code.XOP_Vprotb_xmm_xmmm128_imm8, Register.XMM1, memory16, 0xA5) }; yield return new object[] { 32, "8F E878C0 8E 78563412 A5", rip, Instruction.Create(Code.XOP_Vprotb_xmm_xmmm128_imm8, Register.XMM1, memory32, 0xA5) }; yield return new object[] { 64, "8F C878C0 8E 78563412 A5", rip, Instruction.Create(Code.XOP_Vprotb_xmm_xmmm128_imm8, Register.XMM1, memory64, 0xA5) }; #endif #if !NO_D3NOW yield return new object[] { 16, "0F0F 8C 3412 0C", rip, Instruction.Create(Code.D3NOW_Pi2fw_mm_mmm64, Register.MM1, memory16) }; yield return new object[] { 32, "0F0F 8E 78563412 0C", rip, Instruction.Create(Code.D3NOW_Pi2fw_mm_mmm64, Register.MM1, memory32) }; yield return new object[] { 64, "0F0F 8E 78563412 0C", rip, Instruction.Create(Code.D3NOW_Pi2fw_mm_mmm64, Register.MM1, memory64) }; #endif // If it fails, add more tests above (16-bit, 32-bit, and 64-bit test cases) Static.Assert(IcedConstants.EncodingKindEnumCount == 5 ? 0 : -1); } } [Fact] void Encode_BP_with_no_displ() { var writer = new CodeWriterImpl(); var encoder = Encoder.Create(16, writer); var instruction = Instruction.Create(Code.Mov_r16_rm16, Register.AX, new MemoryOperand(Register.BP)); uint len = encoder.Encode(instruction, 0); var expected = new byte[] { 0x8B, 0x46, 0x00 }; var actual = writer.ToArray(); Assert.Equal(actual.Length, (int)len); Assert.Equal(expected, actual); } [Fact] void Encode_EBP_with_no_displ() { var writer = new CodeWriterImpl(); var encoder = Encoder.Create(32, writer); var instruction = Instruction.Create(Code.Mov_r32_rm32, Register.EAX, new MemoryOperand(Register.EBP)); uint len = encoder.Encode(instruction, 0); var expected = new byte[] { 0x8B, 0x45, 0x00 }; var actual = writer.ToArray(); Assert.Equal(actual.Length, (int)len); Assert.Equal(expected, actual); } [Fact] void Encode_EBP_EDX_with_no_displ() { var writer = new CodeWriterImpl(); var encoder = Encoder.Create(32, writer); var instruction = Instruction.Create(Code.Mov_r32_rm32, Register.EAX, new MemoryOperand(Register.EBP, Register.EDX)); uint len = encoder.Encode(instruction, 0); var expected = new byte[] { 0x8B, 0x44, 0x15, 0x00 }; var actual = writer.ToArray(); Assert.Equal(actual.Length, (int)len); Assert.Equal(expected, actual); } [Fact] void Encode_R13D_with_no_displ() { var writer = new CodeWriterImpl(); var encoder = Encoder.Create(64, writer); var instruction = Instruction.Create(Code.Mov_r32_rm32, Register.EAX, new MemoryOperand(Register.R13D)); uint len = encoder.Encode(instruction, 0); var expected = new byte[] { 0x67, 0x41, 0x8B, 0x45, 0x00 }; var actual = writer.ToArray(); Assert.Equal(actual.Length, (int)len); Assert.Equal(expected, actual); } [Fact] void Encode_R13D_EDX_with_no_displ() { var writer = new CodeWriterImpl(); var encoder = Encoder.Create(64, writer); var instruction = Instruction.Create(Code.Mov_r32_rm32, Register.EAX, new MemoryOperand(Register.R13D, Register.EDX)); uint len = encoder.Encode(instruction, 0); var expected = new byte[] { 0x67, 0x41, 0x8B, 0x44, 0x15, 0x00 }; var actual = writer.ToArray(); Assert.Equal(actual.Length, (int)len); Assert.Equal(expected, actual); } [Fact] void Encode_RBP_with_no_displ() { var writer = new CodeWriterImpl(); var encoder = Encoder.Create(64, writer); var instruction = Instruction.Create(Code.Mov_r64_rm64, Register.RAX, new MemoryOperand(Register.RBP)); uint len = encoder.Encode(instruction, 0); var expected = new byte[] { 0x48, 0x8B, 0x45, 0x00 }; var actual = writer.ToArray(); Assert.Equal(actual.Length, (int)len); Assert.Equal(expected, actual); } [Fact] void Encode_RBP_RDX_with_no_displ() { var writer = new CodeWriterImpl(); var encoder = Encoder.Create(64, writer); var instruction = Instruction.Create(Code.Mov_r64_rm64, Register.RAX, new MemoryOperand(Register.RBP, Register.RDX)); uint len = encoder.Encode(instruction, 0); var expected = new byte[] { 0x48, 0x8B, 0x44, 0x15, 0x00 }; var actual = writer.ToArray(); Assert.Equal(actual.Length, (int)len); Assert.Equal(expected, actual); } [Fact] void Encode_R13_with_no_displ() { var writer = new CodeWriterImpl(); var encoder = Encoder.Create(64, writer); var instruction = Instruction.Create(Code.Mov_r64_rm64, Register.RAX, new MemoryOperand(Register.R13)); uint len = encoder.Encode(instruction, 0); var expected = new byte[] { 0x49, 0x8B, 0x45, 0x00 }; var actual = writer.ToArray(); Assert.Equal(actual.Length, (int)len); Assert.Equal(expected, actual); } [Fact] void Encode_R13_RDX_with_no_displ() { var writer = new CodeWriterImpl(); var encoder = Encoder.Create(64, writer); var instruction = Instruction.Create(Code.Mov_r64_rm64, Register.RAX, new MemoryOperand(Register.R13, Register.RDX)); uint len = encoder.Encode(instruction, 0); var expected = new byte[] { 0x49, 0x8B, 0x44, 0x15, 0x00 }; var actual = writer.ToArray(); Assert.Equal(actual.Length, (int)len); Assert.Equal(expected, actual); } [Theory] [InlineData(16)] [InlineData(32)] [InlineData(64)] void Verify_encoder_options(int bitness) { var encoder = Encoder.Create(bitness, new CodeWriterImpl()); Assert.False(encoder.PreventVEX2); Assert.Equal(0U, encoder.VEX_WIG); Assert.Equal(0U, encoder.VEX_LIG); Assert.Equal(0U, encoder.EVEX_WIG); Assert.Equal(0U, encoder.EVEX_LIG); } [Theory] [InlineData(16)] [InlineData(32)] [InlineData(64)] void GetSet_WIG_LIG_options(int bitness) { var encoder = Encoder.Create(bitness, new CodeWriterImpl()); encoder.VEX_LIG = 1; encoder.VEX_WIG = 0; Assert.Equal(0U, encoder.VEX_WIG); Assert.Equal(1U, encoder.VEX_LIG); encoder.VEX_WIG = 1; Assert.Equal(1U, encoder.VEX_WIG); Assert.Equal(1U, encoder.VEX_LIG); encoder.VEX_WIG = 0xFFFFFFFE; Assert.Equal(0U, encoder.VEX_WIG); Assert.Equal(1U, encoder.VEX_LIG); encoder.VEX_WIG = 0xFFFFFFFF; Assert.Equal(1U, encoder.VEX_WIG); Assert.Equal(1U, encoder.VEX_LIG); encoder.VEX_WIG = 1; encoder.VEX_LIG = 0; Assert.Equal(0U, encoder.VEX_LIG); Assert.Equal(1U, encoder.VEX_WIG); encoder.VEX_LIG = 1; Assert.Equal(1U, encoder.VEX_LIG); Assert.Equal(1U, encoder.VEX_WIG); encoder.VEX_LIG = 0xFFFFFFFE; Assert.Equal(0U, encoder.VEX_LIG); Assert.Equal(1U, encoder.VEX_WIG); encoder.VEX_LIG = 0xFFFFFFFF; Assert.Equal(1U, encoder.VEX_LIG); Assert.Equal(1U, encoder.VEX_WIG); encoder.EVEX_LIG = 3; encoder.EVEX_WIG = 0; Assert.Equal(0U, encoder.EVEX_WIG); Assert.Equal(3U, encoder.EVEX_LIG); encoder.EVEX_WIG = 1; Assert.Equal(1U, encoder.EVEX_WIG); Assert.Equal(3U, encoder.EVEX_LIG); encoder.EVEX_WIG = 0xFFFFFFFE; Assert.Equal(0U, encoder.EVEX_WIG); Assert.Equal(3U, encoder.EVEX_LIG); encoder.EVEX_WIG = 0xFFFFFFFF; Assert.Equal(1U, encoder.EVEX_WIG); Assert.Equal(3U, encoder.EVEX_LIG); encoder.EVEX_WIG = 1; encoder.EVEX_LIG = 0; Assert.Equal(0U, encoder.EVEX_LIG); Assert.Equal(1U, encoder.EVEX_WIG); encoder.EVEX_LIG = 1; Assert.Equal(1U, encoder.EVEX_LIG); Assert.Equal(1U, encoder.EVEX_WIG); encoder.EVEX_LIG = 2; Assert.Equal(2U, encoder.EVEX_LIG); Assert.Equal(1U, encoder.EVEX_WIG); encoder.EVEX_LIG = 3; Assert.Equal(3U, encoder.EVEX_LIG); Assert.Equal(1U, encoder.EVEX_WIG); encoder.EVEX_LIG = 0xFFFFFFFC; Assert.Equal(0U, encoder.EVEX_LIG); Assert.Equal(1U, encoder.EVEX_WIG); encoder.EVEX_LIG = 0xFFFFFFFD; Assert.Equal(1U, encoder.EVEX_LIG); Assert.Equal(1U, encoder.EVEX_WIG); encoder.EVEX_LIG = 0xFFFFFFFE; Assert.Equal(2U, encoder.EVEX_LIG); Assert.Equal(1U, encoder.EVEX_WIG); encoder.EVEX_LIG = 0xFFFFFFFF; Assert.Equal(3U, encoder.EVEX_LIG); Assert.Equal(1U, encoder.EVEX_WIG); } #if !NO_VEX [Theory] [InlineData("C5FC 10 10", "C4E17C 10 10", Code.VEX_Vmovups_ymm_ymmm256, true)] [InlineData("C5FC 10 10", "C5FC 10 10", Code.VEX_Vmovups_ymm_ymmm256, false)] void Prevent_VEX2_encoding(string hexBytes, string expectedBytes, Code code, bool preventVEX2) { var decoder = Decoder.Create(64, new ByteArrayCodeReader(hexBytes)); decoder.IP = DecoderConstants.DEFAULT_IP64; decoder.Decode(out var instruction); Assert.Equal(code, instruction.Code); var codeWriter = new CodeWriterImpl(); var encoder = Encoder.Create(decoder.Bitness, codeWriter); encoder.PreventVEX2 = preventVEX2; encoder.Encode(instruction, DecoderConstants.DEFAULT_IP64); var encodedBytes = codeWriter.ToArray(); var expectedBytesArray = HexUtils.ToByteArray(expectedBytes); Assert.Equal(expectedBytesArray, encodedBytes); } #endif #if !NO_VEX [Theory] [InlineData("C5CA 10 CD", "C5CA 10 CD", Code.VEX_Vmovss_xmm_xmm_xmm, 0, 0)] [InlineData("C5CA 10 CD", "C5CE 10 CD", Code.VEX_Vmovss_xmm_xmm_xmm, 0, 1)] [InlineData("C5CA 10 CD", "C5CA 10 CD", Code.VEX_Vmovss_xmm_xmm_xmm, 1, 0)] [InlineData("C5CA 10 CD", "C5CE 10 CD", Code.VEX_Vmovss_xmm_xmm_xmm, 1, 1)] [InlineData("C4414A 10 CD", "C4414A 10 CD", Code.VEX_Vmovss_xmm_xmm_xmm, 0, 0)] [InlineData("C4414A 10 CD", "C4414E 10 CD", Code.VEX_Vmovss_xmm_xmm_xmm, 0, 1)] [InlineData("C4414A 10 CD", "C441CA 10 CD", Code.VEX_Vmovss_xmm_xmm_xmm, 1, 0)] [InlineData("C4414A 10 CD", "C441CE 10 CD", Code.VEX_Vmovss_xmm_xmm_xmm, 1, 1)] [InlineData("C5F9 50 D3", "C5F9 50 D3", Code.VEX_Vmovmskpd_r32_xmm, 0, 0)] [InlineData("C5F9 50 D3", "C5F9 50 D3", Code.VEX_Vmovmskpd_r32_xmm, 0, 1)] [InlineData("C5F9 50 D3", "C5F9 50 D3", Code.VEX_Vmovmskpd_r32_xmm, 1, 0)] [InlineData("C5F9 50 D3", "C5F9 50 D3", Code.VEX_Vmovmskpd_r32_xmm, 1, 1)] [InlineData("C4C179 50 D3", "C4C179 50 D3", Code.VEX_Vmovmskpd_r32_xmm, 0, 0)] [InlineData("C4C179 50 D3", "C4C179 50 D3", Code.VEX_Vmovmskpd_r32_xmm, 0, 1)] [InlineData("C4C179 50 D3", "C4C179 50 D3", Code.VEX_Vmovmskpd_r32_xmm, 1, 0)] [InlineData("C4C179 50 D3", "C4C179 50 D3", Code.VEX_Vmovmskpd_r32_xmm, 1, 1)] void Test_VEX_WIG_LIG(string hexBytes, string expectedBytes, Code code, uint wig, uint lig) { var decoder = Decoder.Create(64, new ByteArrayCodeReader(hexBytes)); decoder.IP = DecoderConstants.DEFAULT_IP64; decoder.Decode(out var instruction); Assert.Equal(code, instruction.Code); var codeWriter = new CodeWriterImpl(); var encoder = Encoder.Create(decoder.Bitness, codeWriter); encoder.VEX_WIG = wig; encoder.VEX_LIG = lig; encoder.Encode(instruction, DecoderConstants.DEFAULT_IP64); var encodedBytes = codeWriter.ToArray(); var expectedBytesArray = HexUtils.ToByteArray(expectedBytes); Assert.Equal(expectedBytesArray, encodedBytes); } #endif #if !NO_EVEX [Theory] [InlineData("62 F14E08 10 D3", "62 F14E08 10 D3", Code.EVEX_Vmovss_xmm_k1z_xmm_xmm, 0, 0)] [InlineData("62 F14E08 10 D3", "62 F14E28 10 D3", Code.EVEX_Vmovss_xmm_k1z_xmm_xmm, 0, 1)] [InlineData("62 F14E08 10 D3", "62 F14E48 10 D3", Code.EVEX_Vmovss_xmm_k1z_xmm_xmm, 0, 2)] [InlineData("62 F14E08 10 D3", "62 F14E68 10 D3", Code.EVEX_Vmovss_xmm_k1z_xmm_xmm, 0, 3)] [InlineData("62 F14E08 10 D3", "62 F14E08 10 D3", Code.EVEX_Vmovss_xmm_k1z_xmm_xmm, 1, 0)] [InlineData("62 F14E08 10 D3", "62 F14E28 10 D3", Code.EVEX_Vmovss_xmm_k1z_xmm_xmm, 1, 1)] [InlineData("62 F14E08 10 D3", "62 F14E48 10 D3", Code.EVEX_Vmovss_xmm_k1z_xmm_xmm, 1, 2)] [InlineData("62 F14E08 10 D3", "62 F14E68 10 D3", Code.EVEX_Vmovss_xmm_k1z_xmm_xmm, 1, 3)] [InlineData("62 F14D0B 60 50 01", "62 F14D0B 60 50 01", Code.EVEX_Vpunpcklbw_xmm_k1z_xmm_xmmm128, 0, 0)] [InlineData("62 F14D0B 60 50 01", "62 F14D0B 60 50 01", Code.EVEX_Vpunpcklbw_xmm_k1z_xmm_xmmm128, 0, 1)] [InlineData("62 F14D0B 60 50 01", "62 F14D0B 60 50 01", Code.EVEX_Vpunpcklbw_xmm_k1z_xmm_xmmm128, 0, 2)] [InlineData("62 F14D0B 60 50 01", "62 F14D0B 60 50 01", Code.EVEX_Vpunpcklbw_xmm_k1z_xmm_xmmm128, 0, 3)] [InlineData("62 F14D0B 60 50 01", "62 F1CD0B 60 50 01", Code.EVEX_Vpunpcklbw_xmm_k1z_xmm_xmmm128, 1, 0)] [InlineData("62 F14D0B 60 50 01", "62 F1CD0B 60 50 01", Code.EVEX_Vpunpcklbw_xmm_k1z_xmm_xmmm128, 1, 1)] [InlineData("62 F14D0B 60 50 01", "62 F1CD0B 60 50 01", Code.EVEX_Vpunpcklbw_xmm_k1z_xmm_xmmm128, 1, 2)] [InlineData("62 F14D0B 60 50 01", "62 F1CD0B 60 50 01", Code.EVEX_Vpunpcklbw_xmm_k1z_xmm_xmmm128, 1, 3)] [InlineData("62 F17C0B 51 50 01", "62 F17C0B 51 50 01", Code.EVEX_Vsqrtps_xmm_k1z_xmmm128b32, 0, 0)] [InlineData("62 F17C0B 51 50 01", "62 F17C0B 51 50 01", Code.EVEX_Vsqrtps_xmm_k1z_xmmm128b32, 0, 1)] [InlineData("62 F17C0B 51 50 01", "62 F17C0B 51 50 01", Code.EVEX_Vsqrtps_xmm_k1z_xmmm128b32, 0, 2)] [InlineData("62 F17C0B 51 50 01", "62 F17C0B 51 50 01", Code.EVEX_Vsqrtps_xmm_k1z_xmmm128b32, 0, 3)] [InlineData("62 F17C0B 51 50 01", "62 F17C0B 51 50 01", Code.EVEX_Vsqrtps_xmm_k1z_xmmm128b32, 1, 0)] [InlineData("62 F17C0B 51 50 01", "62 F17C0B 51 50 01", Code.EVEX_Vsqrtps_xmm_k1z_xmmm128b32, 1, 1)] [InlineData("62 F17C0B 51 50 01", "62 F17C0B 51 50 01", Code.EVEX_Vsqrtps_xmm_k1z_xmmm128b32, 1, 2)] [InlineData("62 F17C0B 51 50 01", "62 F17C0B 51 50 01", Code.EVEX_Vsqrtps_xmm_k1z_xmmm128b32, 1, 3)] void Test_EVEX_WIG_LIG(string hexBytes, string expectedBytes, Code code, uint wig, uint lig) { var decoder = Decoder.Create(64, new ByteArrayCodeReader(hexBytes)); decoder.IP = DecoderConstants.DEFAULT_IP64; decoder.Decode(out var instruction); Assert.Equal(code, instruction.Code); var codeWriter = new CodeWriterImpl(); var encoder = Encoder.Create(decoder.Bitness, codeWriter); encoder.EVEX_WIG = wig; encoder.EVEX_LIG = lig; encoder.Encode(instruction, DecoderConstants.DEFAULT_IP64); var encodedBytes = codeWriter.ToArray(); var expectedBytesArray = HexUtils.ToByteArray(expectedBytes); Assert.Equal(expectedBytesArray, encodedBytes); } #endif [Fact] void Test_Encoder_Create_throws() { foreach (var bitness in BitnessUtils.GetInvalidBitnessValues()) Assert.Throws<ArgumentOutOfRangeException>(() => Encoder.Create(bitness, new CodeWriterImpl())); foreach (var bitness in new[] { 16, 32, 64 }) Assert.Throws<ArgumentNullException>(() => Encoder.Create(bitness, null)); } #if OPCODE_INFO [Fact] void ToOpCode_throws_if_input_is_invalid() { Assert.Throws<ArgumentOutOfRangeException>(() => ((Code)int.MinValue).ToOpCode()); Assert.Throws<ArgumentOutOfRangeException>(() => ((Code)(-1)).ToOpCode()); Assert.Throws<ArgumentOutOfRangeException>(() => ((Code)IcedConstants.CodeEnumCount).ToOpCode()); Assert.Throws<ArgumentOutOfRangeException>(() => ((Code)int.MaxValue).ToOpCode()); } #endif [Fact] void Verify_MemoryOperand_ctors() { { var op = new MemoryOperand(Register.RCX, Register.RSI, 4, -0x1234_5678_9ABC_DEF1, 8, true, Register.FS); Assert.Equal(Register.RCX, op.Base); Assert.Equal(Register.RSI, op.Index); Assert.Equal(4, op.Scale); Assert.Equal(-0x1234_5678_9ABC_DEF1, op.Displacement); Assert.Equal(8, op.DisplSize); Assert.True(op.IsBroadcast); Assert.Equal(Register.FS, op.SegmentPrefix); } { var op = new MemoryOperand(Register.RCX, Register.RSI, 4, true, Register.FS); Assert.Equal(Register.RCX, op.Base); Assert.Equal(Register.RSI, op.Index); Assert.Equal(4, op.Scale); Assert.Equal(0, op.Displacement); Assert.Equal(0, op.DisplSize); Assert.True(op.IsBroadcast); Assert.Equal(Register.FS, op.SegmentPrefix); } { var op = new MemoryOperand(Register.RCX, -0x1234_5678_9ABC_DEF1, 8, true, Register.FS); Assert.Equal(Register.RCX, op.Base); Assert.Equal(Register.None, op.Index); Assert.Equal(1, op.Scale); Assert.Equal(-0x1234_5678_9ABC_DEF1, op.Displacement); Assert.Equal(8, op.DisplSize); Assert.True(op.IsBroadcast); Assert.Equal(Register.FS, op.SegmentPrefix); } { var op = new MemoryOperand(Register.RSI, 4, -0x1234_5678_9ABC_DEF1, 8, true, Register.FS); Assert.Equal(Register.None, op.Base); Assert.Equal(Register.RSI, op.Index); Assert.Equal(4, op.Scale); Assert.Equal(-0x1234_5678_9ABC_DEF1, op.Displacement); Assert.Equal(8, op.DisplSize); Assert.True(op.IsBroadcast); Assert.Equal(Register.FS, op.SegmentPrefix); } { var op = new MemoryOperand(Register.RCX, -0x1234_5678_9ABC_DEF1, true, Register.FS); Assert.Equal(Register.RCX, op.Base); Assert.Equal(Register.None, op.Index); Assert.Equal(1, op.Scale); Assert.Equal(-0x1234_5678_9ABC_DEF1, op.Displacement); Assert.Equal(1, op.DisplSize); Assert.True(op.IsBroadcast); Assert.Equal(Register.FS, op.SegmentPrefix); } { var op = new MemoryOperand(Register.RCX, Register.RSI, 4, -0x1234_5678_9ABC_DEF1, 8); Assert.Equal(Register.RCX, op.Base); Assert.Equal(Register.RSI, op.Index); Assert.Equal(4, op.Scale); Assert.Equal(-0x1234_5678_9ABC_DEF1, op.Displacement); Assert.Equal(8, op.DisplSize); Assert.False(op.IsBroadcast); Assert.Equal(Register.None, op.SegmentPrefix); } { var op = new MemoryOperand(Register.RCX, Register.RSI, 4); Assert.Equal(Register.RCX, op.Base); Assert.Equal(Register.RSI, op.Index); Assert.Equal(4, op.Scale); Assert.Equal(0, op.Displacement); Assert.Equal(0, op.DisplSize); Assert.False(op.IsBroadcast); Assert.Equal(Register.None, op.SegmentPrefix); } { var op = new MemoryOperand(Register.RCX, Register.RSI); Assert.Equal(Register.RCX, op.Base); Assert.Equal(Register.RSI, op.Index); Assert.Equal(1, op.Scale); Assert.Equal(0, op.Displacement); Assert.Equal(0, op.DisplSize); Assert.False(op.IsBroadcast); Assert.Equal(Register.None, op.SegmentPrefix); } { var op = new MemoryOperand(Register.RCX, -0x1234_5678_9ABC_DEF1, 8); Assert.Equal(Register.RCX, op.Base); Assert.Equal(Register.None, op.Index); Assert.Equal(1, op.Scale); Assert.Equal(-0x1234_5678_9ABC_DEF1, op.Displacement); Assert.Equal(8, op.DisplSize); Assert.False(op.IsBroadcast); Assert.Equal(Register.None, op.SegmentPrefix); } { var op = new MemoryOperand(Register.RSI, 4, -0x1234_5678_9ABC_DEF1, 8); Assert.Equal(Register.None, op.Base); Assert.Equal(Register.RSI, op.Index); Assert.Equal(4, op.Scale); Assert.Equal(-0x1234_5678_9ABC_DEF1, op.Displacement); Assert.Equal(8, op.DisplSize); Assert.False(op.IsBroadcast); Assert.Equal(Register.None, op.SegmentPrefix); } { var op = new MemoryOperand(Register.RCX, -0x1234_5678_9ABC_DEF1); Assert.Equal(Register.RCX, op.Base); Assert.Equal(Register.None, op.Index); Assert.Equal(1, op.Scale); Assert.Equal(-0x1234_5678_9ABC_DEF1, op.Displacement); Assert.Equal(1, op.DisplSize); Assert.False(op.IsBroadcast); Assert.Equal(Register.None, op.SegmentPrefix); } { var op = new MemoryOperand(Register.RCX); Assert.Equal(Register.RCX, op.Base); Assert.Equal(Register.None, op.Index); Assert.Equal(1, op.Scale); Assert.Equal(0, op.Displacement); Assert.Equal(0, op.DisplSize); Assert.False(op.IsBroadcast); Assert.Equal(Register.None, op.SegmentPrefix); } } #if OPCODE_INFO [Fact] void OpCodeInfo_IsAvailableInMode_throws_if_invalid_bitness() { foreach (var bitness in BitnessUtils.GetInvalidBitnessValues()) Assert.Throws<ArgumentOutOfRangeException>(() => Code.Nopd.ToOpCode().IsAvailableInMode(bitness)); } #endif [Fact] void WriteByte_works() { var codeWriter = new CodeWriterImpl(); var encoder = Encoder.Create(64, codeWriter); var instruction = Instruction.Create(Code.Add_r64_rm64, Register.R8, Register.RBP); encoder.WriteByte(0x90); encoder.Encode(instruction, 0x55555555); encoder.WriteByte(0xCC); Assert.Equal(new byte[] { 0x90, 0x4C, 0x03, 0xC5, 0xCC }, codeWriter.ToArray()); } [Theory] [MemberData(nameof(EncodeInvalidRegOpSize_Data))] void EncodeInvalidRegOpSize(int bitness, Instruction instruction) { var encoder = Encoder.Create(bitness, new CodeWriterImpl()); bool b = encoder.TryEncode(instruction, 0, out _, out var errorMessage); Assert.False(b); Assert.NotNull(errorMessage); Assert.Contains("Register operand size must equal memory addressing mode (16/32/64)", errorMessage); } public static IEnumerable<object[]> EncodeInvalidRegOpSize_Data { get { yield return new object[] { 16, Instruction.Create(Code.Movdir64b_r16_m512, Register.CX, new MemoryOperand(Register.EBX)) }; yield return new object[] { 32, Instruction.Create(Code.Movdir64b_r16_m512, Register.CX, new MemoryOperand(Register.EBX)) }; yield return new object[] { 16, Instruction.Create(Code.Movdir64b_r32_m512, Register.ECX, new MemoryOperand(Register.BX)) }; yield return new object[] { 32, Instruction.Create(Code.Movdir64b_r32_m512, Register.ECX, new MemoryOperand(Register.BX)) }; yield return new object[] { 64, Instruction.Create(Code.Movdir64b_r32_m512, Register.ECX, new MemoryOperand(Register.RBX)) }; yield return new object[] { 64, Instruction.Create(Code.Movdir64b_r64_m512, Register.RCX, new MemoryOperand(Register.EBX)) }; yield return new object[] { 16, Instruction.Create(Code.Enqcmds_r16_m512, Register.CX, new MemoryOperand(Register.EBX)) }; yield return new object[] { 32, Instruction.Create(Code.Enqcmds_r16_m512, Register.CX, new MemoryOperand(Register.EBX)) }; yield return new object[] { 16, Instruction.Create(Code.Enqcmds_r32_m512, Register.ECX, new MemoryOperand(Register.BX)) }; yield return new object[] { 32, Instruction.Create(Code.Enqcmds_r32_m512, Register.ECX, new MemoryOperand(Register.BX)) }; yield return new object[] { 64, Instruction.Create(Code.Enqcmds_r32_m512, Register.ECX, new MemoryOperand(Register.RBX)) }; yield return new object[] { 64, Instruction.Create(Code.Enqcmds_r64_m512, Register.RCX, new MemoryOperand(Register.EBX)) }; yield return new object[] { 16, Instruction.Create(Code.Enqcmd_r16_m512, Register.CX, new MemoryOperand(Register.EBX)) }; yield return new object[] { 32, Instruction.Create(Code.Enqcmd_r16_m512, Register.CX, new MemoryOperand(Register.EBX)) }; yield return new object[] { 16, Instruction.Create(Code.Enqcmd_r32_m512, Register.ECX, new MemoryOperand(Register.BX)) }; yield return new object[] { 32, Instruction.Create(Code.Enqcmd_r32_m512, Register.ECX, new MemoryOperand(Register.BX)) }; yield return new object[] { 64, Instruction.Create(Code.Enqcmd_r32_m512, Register.ECX, new MemoryOperand(Register.RBX)) }; yield return new object[] { 64, Instruction.Create(Code.Enqcmd_r64_m512, Register.RCX, new MemoryOperand(Register.EBX)) }; } } } } #endif
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.Msagl.Core; using Microsoft.Msagl.Core.Geometry; using Microsoft.Msagl.Core.Layout; using Microsoft.Msagl.Core.Routing; using Microsoft.Msagl.Layout.Incremental; using Microsoft.Msagl.Layout.Layered; using Microsoft.Msagl.Layout.MDS; using Microsoft.Msagl.Routing; using Microsoft.Msagl.Routing.Rectilinear; using System.Threading.Tasks; #if TEST_MSAGL using Microsoft.Msagl.DebugHelpers; #endif namespace Microsoft.Msagl.Layout.Initial { /// <summary> /// Methods for obtaining an initial layout of a graph by arranging clusters bottom up using various means. /// </summary> public class InitialLayoutByCluster : AlgorithmBase { readonly GeometryGraph graph; readonly ICollection<Cluster> clusters; readonly Func<Cluster, LayoutAlgorithmSettings> clusterSettings; /// <summary> /// Recursively lay out the clusters of the given graph using the given settings. /// </summary> /// <param name="graph">The graph being operated on.</param> /// <param name="defaultSettings">Settings to use if none is provided for a particular cluster or its ancestors.</param> public InitialLayoutByCluster(GeometryGraph graph, LayoutAlgorithmSettings defaultSettings) : this(graph, anyCluster => defaultSettings) {} /// <summary> /// Recursively lay out the clusters of the given graph using the specified settings for each cluster, or if none is given for a particular /// cluster then inherit from the cluster's ancestor - or from the specifed defaultSettings. /// </summary> /// <param name="graph">The graph being operated on.</param> /// <param name="clusterSettings">Settings to use for each cluster and its descendents (if none provided for that descendent.</param> [SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public InitialLayoutByCluster(GeometryGraph graph, Func<Cluster, LayoutAlgorithmSettings> clusterSettings) : this(graph, new[] {graph.RootCluster}, clusterSettings) {} /// <summary> /// Recursively lay out the given clusters using the specified settings for each cluster, or if none is given for a particular /// cluster then inherit from the cluster's ancestor - or from the specifed defaultSettings. /// Clusters (other than the root) will be translated (together with their descendants) such that their /// bottom-left point of their new boundaries are the same as the bottom-left of their old boundaries /// (i.e. clusters are laid-out in place). /// </summary> /// <param name="graph">The graph being operated on.</param> /// <param name="clusters">The clusters to layout.</param> /// <param name="clusterSettings">Settings to use for each cluster and its descendents (if none provided for that descendent.</param> public InitialLayoutByCluster(GeometryGraph graph, IEnumerable<Cluster> clusters, Func<Cluster, LayoutAlgorithmSettings> clusterSettings) { ValidateArg.IsNotNull(graph, "graph"); ValidateArg.IsNotNull(clusters, "clusters"); ValidateArg.IsNotNull(clusterSettings, "clusterSettings"); #if TEST_MSAGL graph.SetDebugIds(); #endif this.graph = graph; this.clusters = clusters.ToList(); this.clusterSettings = clusterSettings; } ParallelOptions parallelOptions; #if SHARPKIT // no multithreading in JS bool runInParallel = false; #else bool runInParallel = true; #endif /// <summary> /// if set to true than parallel execution will b /// </summary> public bool RunInParallel { get { return runInParallel; } set { runInParallel = value; } } /// <summary> /// The actual layout process /// </summary> protected override void RunInternal() { if (runInParallel) { parallelOptions = new ParallelOptions(); #if PPC if (CancelToken != null) parallelOptions.CancellationToken = CancelToken.CancellationToken; #endif } #if DEBUG //CheckEdges(); #endif // This call isn't super cheap, so we shouldn't do this too often. //clusterCount = clusters.Sum(c => c.AllClustersDepthFirst().Count()); if (runInParallel && clusters.Count > 1) Parallel.ForEach(clusters, parallelOptions, ProcessCluster); else foreach (Cluster cluster in clusters) ProcessCluster(cluster); bool isRootCluster = clusters.Any(c => c == graph.RootCluster); if (isRootCluster) { // only want to do this when we are working solely with the root cluster. // expanding individual clusters will mean that the containment hierarchy is not valid // (until it's fixed up by the next incremental layout) RouteParentEdges(graph, clusterSettings(graph.RootCluster).EdgeRoutingSettings); } graph.UpdateBoundingBox(); if (isRootCluster) { Debug.Assert(clusters.Count() == 1, "Layout by cluster with a root cluster should not contain any other cluster."); // Zero the graph graph.Translate(-graph.BoundingBox.LeftBottom); //LayoutAlgorithmSettings.ShowGraph(graph); } ProgressComplete(); } void ProcessCluster(Cluster cluster) { if (cluster.IsCollapsed) return; Rectangle oldBounds = cluster.BoundingBox; cluster.UnsetInitialLayoutStateIncludingAncestors(); LayoutCluster(cluster); if (cluster != graph.RootCluster) { Rectangle newBounds = cluster.BoundingBox; cluster.DeepTranslation(oldBounds.Center - newBounds.Center, true); } #if DEBUG // ValidateLayout(cluster); #endif } internal static void RouteParentEdges(GeometryGraph graph, EdgeRoutingSettings edgeRoutingSettings) { var inParentEdges = new List<Edge>(); var outParentEdges = new List<Edge>(); RouteSimplHooksAndFillTheLists(graph.RootCluster, inParentEdges, outParentEdges, edgeRoutingSettings); if (inParentEdges.Count > 0 || outParentEdges.Count > 0) LabelParentEdgesAndMaybeRerouteThemNicely(graph, inParentEdges, outParentEdges, edgeRoutingSettings); } static void LabelParentEdgesAndMaybeRerouteThemNicely(GeometryGraph graph, List<Edge> inParentEdges, List<Edge> outParentEdges, EdgeRoutingSettings edgeRoutingSettings) { if (AllowedToRoute(inParentEdges, outParentEdges, edgeRoutingSettings)) { var shapeGroupRouter = new SplineRouter(graph, edgeRoutingSettings.Padding, edgeRoutingSettings.PolylinePadding, edgeRoutingSettings.RoutingToParentConeAngle, inParentEdges, outParentEdges); shapeGroupRouter.Run(); } var labeledEdges = outParentEdges.Concat(inParentEdges).Where(e => e.Labels.Any()); if (labeledEdges.Any()) { var elb = new EdgeLabelPlacement(graph.Nodes, labeledEdges); //consider adding more nodes here: some sibling clusters maybe elb.Run(); } /*//*************debug code start var parentEdges = inParentEdges.Concat(outParentEdges); var ll = new List<DebugCurve>(); var marked = new Microsoft.Msagl.Core.DataStructures.Set<Node>(); foreach (var e in parentEdges) { marked.Insert(e.Source); marked.Insert(e.Target); ll.Add(new DebugCurve(100, 1, "blue", e.Curve)); } foreach (var c in graph.RootCluster.AllClustersDepthFirst()) { var color = marked.Contains(c) ? "red" : "green"; ll.Add(new DebugCurve(100, 1, color, c.BoundaryCurve)); } foreach (var c in graph.Nodes) { var color = marked.Contains(c) ? "red" : "green"; ll.Add(new DebugCurve(100, 1, color, c.BoundaryCurve)); } LayoutAlgorithmSettings.ShowDebugCurvesEnumeration(ll); */ //*************debug code end } static bool AllowedToRoute(List<Edge> inParentEdges, List<Edge> outParentEdges, EdgeRoutingSettings edgeRoutingSettings) { return ShapeCreatorForRoutingToParents.NumberOfActiveNodesIsUnderThreshold(inParentEdges, outParentEdges, edgeRoutingSettings. SimpleSelfLoopsForParentEdgesThreshold); } static void RouteSimplHooksAndFillTheLists(Cluster rootCluster, List<Edge> inParentEdges, List<Edge> outParentEdges, EdgeRoutingSettings edgeRoutingSettings) { var padding = edgeRoutingSettings.Padding + edgeRoutingSettings.PolylinePadding; foreach (var cluster in rootCluster.AllClustersWidthFirstExcludingSelfAvoidingChildrenOfCollapsed().Where(c=>!c.IsCollapsed)) { RouteClusterParentInEdges(inParentEdges, edgeRoutingSettings, cluster, padding); RouteClusterParentOutEdges(outParentEdges, edgeRoutingSettings, cluster, padding); } } static void RouteClusterParentOutEdges(List<Edge> outParentEdges, EdgeRoutingSettings edgeRoutingSettings, Cluster cluster, double padding) { foreach (var e in cluster.OutEdges.Where(e => IsDescendant(e.Target, cluster))) { var ePadding = Math.Max(padding, 1.5*ArrowlengthAtSource(e)); var hookPort = e.SourcePort as HookUpAnywhereFromInsidePort; if (hookPort == null) e.SourcePort = hookPort = new HookUpAnywhereFromInsidePort(() => cluster.BoundaryCurve); hookPort.HookSize = ePadding; e.Curve = StraightLineEdges.CreateLoop(e.Target.BoundingBox, cluster.BoundingBox, ePadding, false); Arrowheads.TrimSplineAndCalculateArrowheads(e, e.Curve, false, edgeRoutingSettings.KeepOriginalSpline); outParentEdges.Add(e); } } static void RouteClusterParentInEdges(List<Edge> inParentEdges, EdgeRoutingSettings edgeRoutingSettings, Cluster cluster, double padding) { foreach (var e in cluster.InEdges.Where(e => IsDescendant(e.Source, cluster))) { double ePadding = Math.Max(padding, 1.5*ArrowlengthAtTarget(e)); var hookPort = e.TargetPort as HookUpAnywhereFromInsidePort; if (hookPort == null) e.TargetPort = hookPort = new HookUpAnywhereFromInsidePort(() => cluster.BoundaryCurve); hookPort.HookSize = ePadding; e.Curve = StraightLineEdges.CreateLoop(e.Source.BoundingBox, cluster.BoundingBox, ePadding, false); Arrowheads.TrimSplineAndCalculateArrowheads(e, e.Curve, false, edgeRoutingSettings.KeepOriginalSpline); inParentEdges.Add(e); } } static double ArrowlengthAtSource(Edge edge) { return edge.EdgeGeometry.SourceArrowhead == null ? 0 : edge.EdgeGeometry.SourceArrowhead.Length; } static double ArrowlengthAtTarget(Edge edge) { return edge.EdgeGeometry.TargetArrowhead == null ? 0 : edge.EdgeGeometry.TargetArrowhead.Length; } #if DEBUG // void CheckEdges() { // foreach (var edge in graph.Edges) // CheckEdge(edge); // } // // static void CheckEdge(Edge edge) { // var s = edge.Source; // var t = edge.Target; // var sParents = new Set<Node>(s.ClusterParents); // var tParents = new Set<Node>(t.ClusterParents); // if (sParents == tParents) // the edge is between of the nodes of the same cluster, in a simple case // return; // var cluster = t as Cluster; // if (cluster != null && IsDescendant(s, cluster)) // return; // cluster = s as Cluster; // if (cluster != null && IsDescendant(t, cluster)) // return; // Debug.Assert(false, "an edge can be flat or connecting with an ancestor"); // } /// <summary> /// Ensures that containment is preserved /// </summary> /// <param name="cluster">check is applied to specified cluster and below</param> static void ValidateLayout(Cluster cluster) { foreach (var c in cluster.AllClustersDepthFirst()) foreach (var v in c.nodes.Concat(c.Clusters.Cast<Node>())) Debug.Assert(c.BoundingBox.Contains(v.BoundingBox)); } #endif /// <summary> /// Apply the appropriate layout to the specified cluster and its children (bottom up) /// </summary> /// <param name="cluster">the root of the cluster hierarchy to lay out</param> /// <returns>list of edges external to the cluster</returns> void LayoutCluster(Cluster cluster) { if (cluster.IsCollapsed) return; LayoutAlgorithmSettings settings = clusterSettings(cluster); cluster.UnsetInitialLayoutState(); if (runInParallel && cluster.Clusters.Count() > 1) Parallel.ForEach(cluster.Clusters, parallelOptions, LayoutCluster); else foreach (var cl in cluster.Clusters) LayoutCluster(cl); List<GeometryGraph> components = (List<GeometryGraph>) GetComponents(cluster); //currentComponentFraction = (1.0 / clusterCount) / components.Count; // if (runInParallel) // Parallel.ForEach(components, parallelOptions, comp => LayoutComponent(settings, comp)); // else // debug!!!!!! components.ForEach(c => LayoutComponent(settings, c)); var bounds = MdsGraphLayout.PackGraphs(components, settings); foreach (var g in components) FixOriginalGraph(g, true); cluster.UpdateBoundary(bounds); cluster.SetInitialLayoutState(settings.ClusterMargin); cluster.RaiseLayoutDoneEvent(); // var l = new List<DebugCurve>(); // foreach (var node in cluster.Nodes) { // l.Add(new DebugCurve(node.BoundaryCurve)); // } // foreach (var cl in cluster.AllClustersDepthFirstExcludingSelf()) { // l.Add(new DebugCurve(cl.BoundaryCurve)); // l.AddRange(cl.Nodes.Select(n=>new DebugCurve(n.BoundaryCurve))); // } // LayoutAlgorithmSettings.ShowDebugCurves(l.ToArray()); } internal static void FixOriginalGraph(GeometryGraph graph, bool translateEdges) { foreach (var v in graph.Nodes) { var originalNode = (Node) v.UserData; var delta = v.BoundingBox.LeftBottom - originalNode.BoundingBox.LeftBottom; var cluster = originalNode as Cluster; if (cluster != null) { cluster.DeepTranslation(delta, translateEdges); } else originalNode.Center += delta; } if (translateEdges) { foreach (var e in graph.Edges) { var originalEdge = (Edge) e.UserData; if (e.Curve != null) originalEdge.Curve = e.Curve.Clone(); originalEdge.Length = e.Length; originalEdge.EdgeGeometry.SourcePort = e.SourcePort = null; // EdgeGeometry ports get clobbered by edge routing originalEdge.EdgeGeometry.TargetPort = e.TargetPort = null; foreach (var l in originalEdge.Labels) l.GeometryParent = originalEdge; } } } /// <summary> /// Check if root is an ancestor of node /// </summary> /// <param name="node"></param> /// <param name="root"></param> /// <returns>true if the node is a descendant of root</returns> static bool IsDescendant(Node node, Cluster root) { return Ancestor(node, root) != null; } /// <summary> /// Creates a shallow copy of the root cluster and divides into GeometryGraphs each of which is a connected component with /// respect to edges internal to root. /// </summary> /// <param name="cluster">cluster to break into components</param> /// <returns>GeometryGraphs that are each a connected component</returns> static IEnumerable<GeometryGraph> GetComponents(Cluster cluster) { Dictionary<Node, Node> originalToCopyNodeMap = ShallowNodeCopyDictionary(cluster); var copiedEdges = new List<Edge>(); foreach (var target in originalToCopyNodeMap.Keys) { foreach (var e in target.InEdges) { var sourceAncestorUnderRoot = Ancestor(e.Source, cluster); if (sourceAncestorUnderRoot == e.Source) //it is a flat edge and we are only interested in flat edges copiedEdges.Add(CopyEdge(originalToCopyNodeMap, e, sourceAncestorUnderRoot, target)); } copiedEdges.AddRange(target.SelfEdges.Select(e => CopyEdge(originalToCopyNodeMap, e))); } return GraphConnectedComponents.CreateComponents(originalToCopyNodeMap.Values.ToArray(), copiedEdges); } /// <summary> /// Create a copy of the edge using the specified original source and target, store the original in user data /// </summary> /// <param name="originalToCopyNodeMap">mapping from original nodes to their copies</param> /// <param name="originalEdge">edge to copy</param> /// <param name="originalSource">take this as the source node for the edge (e.g. an ancestor of the actual source)</param> /// <param name="originalTarget">take this as the target node for the edge (e.g. an ancestor of the actual target)</param> /// <returns></returns> internal static Edge CopyEdge(Dictionary<Node, Node> originalToCopyNodeMap, Edge originalEdge, Node originalSource, Node originalTarget) { var e = new Edge(originalToCopyNodeMap[originalSource], originalToCopyNodeMap[originalTarget]) { EdgeGeometry = originalEdge.EdgeGeometry, SourcePort = null, TargetPort = null, Length = originalEdge.Length, UserData = originalEdge }; foreach (var l in originalEdge.Labels) { e.Labels.Add(l); l.GeometryParent = e; } return e; } /// <summary> /// Copy the specified edge, use the given dictionary to find the copies of the edges source and target nodes /// </summary> /// <param name="originalToCopyNodeMap">mapping from original nodes to their copies</param> /// <param name="originalEdge"></param> /// <returns>Copy of edge</returns> internal static Edge CopyEdge(Dictionary<Node, Node> originalToCopyNodeMap, Edge originalEdge) { return CopyEdge(originalToCopyNodeMap, originalEdge, originalEdge.Source, originalEdge.Target); } /// <summary> /// Copy the cluster's child Nodes and Clusters as nodes and return a mapping of original to copy. /// The reverse mapping (copy to original) is available via the copy's UserData /// </summary> /// <param name="cluster">Cluster whose contents will be copied</param> /// <returns>the mapping from original to copy</returns> internal static Dictionary<Node, Node> ShallowNodeCopyDictionary(Cluster cluster) { var originalNodeToCopy = new Dictionary<Node, Node>(); foreach (var v in cluster.Nodes) originalNodeToCopy[v] = new Node(v.BoundaryCurve.Clone()) {UserData = v}; foreach (var cl in cluster.Clusters) { if (cl.IsCollapsed) originalNodeToCopy[cl] = new Node(cl.CollapsedBoundary.Clone()) {UserData = cl}; else { if (cl.BoundaryCurve == null) cl.BoundaryCurve = cl.RectangularBoundary.RectangularHull(); originalNodeToCopy[cl] = new Node(cl.BoundaryCurve.Clone()) {UserData = cl}; } } return originalNodeToCopy; } /// <summary> /// find ancestor of node that is immediate child of root, or node itself if node is a direct child of root /// null if none /// </summary> /// <param name="node"></param> /// <param name="root"></param> /// <returns>returns highest ancestor of node (or node itself) that is a direct child of root, null if not /// a descendent of root</returns> internal static Node Ancestor(Node node, Cluster root) { if (node.ClusterParents.Contains(root)) return node; var parents = new Queue<Cluster>(node.ClusterParents); while (parents.Count > 0) { Cluster parent = parents.Dequeue(); if (root.Clusters.Contains(parent)) return parent; foreach (Cluster grandParent in parent.ClusterParents) parents.Enqueue(grandParent); } return null; } internal void LayoutComponent(LayoutAlgorithmSettings settings, GeometryGraph component) { var fdSettings = settings as FastIncrementalLayoutSettings; var mdsSettings = settings as MdsLayoutSettings; var layeredSettings = settings as SugiyamaLayoutSettings; if (fdSettings != null) { ForceDirectedLayout(fdSettings, component); } else if (mdsSettings != null) { MDSLayout(mdsSettings, component); } else if (layeredSettings != null) { LayeredLayout(layeredSettings, component); } else { throw new NotImplementedException("Unknown type of layout settings!"); } //LayoutAlgorithmSettings.ShowGraph(component); } void ForceDirectedLayout(FastIncrementalLayoutSettings settings, GeometryGraph component) { LayoutAlgorithmHelpers.ComputeDesiredEdgeLengths(settings.IdealEdgeLength, component); var layout = new InitialLayout(component, settings) {SingleComponent = true}; layout.Run(this.CancelToken); InitialLayoutHelpers.RouteEdges(component, settings, this.CancelToken); InitialLayoutHelpers.PlaceLabels(component, this.CancelToken); InitialLayoutHelpers.FixBoundingBox(component, settings); } void MDSLayout(MdsLayoutSettings settings, GeometryGraph component) { LayoutAlgorithmHelpers.ComputeDesiredEdgeLengths(settings.IdealEdgeLength, component); var layout = new MdsGraphLayout(settings, component); layout.Run(this.CancelToken); InitialLayoutHelpers.RouteEdges(component, settings, this.CancelToken); InitialLayoutHelpers.PlaceLabels(component, this.CancelToken); InitialLayoutHelpers.FixBoundingBox(component, settings); } void LayeredLayout(SugiyamaLayoutSettings layeredSettings, GeometryGraph component) { var layeredLayout = new LayeredLayout(component, layeredSettings); layeredLayout.SetCancelToken(this.CancelToken); double aspectRatio = layeredLayout.EstimateAspectRatio(); double edgeDensity = (double) component.Edges.Count/component.Nodes.Count; // if the estimated aspect ratio is not in the range below then we fall back to force directed layout // with constraints which is both faster and usually returns a better aspect ratio for largish graphs var fallbackLayoutSettings = layeredSettings.FallbackLayoutSettings; if (fallbackLayoutSettings != null && (component.Nodes.Count > 50 && edgeDensity > 2 // too dense || component.Nodes.Count > 40 && edgeDensity > 3.0 // too dense || component.Nodes.Count > 30 && edgeDensity > 4.0 // too dense || component.Nodes.Count > 30 && aspectRatio > layeredSettings.MaxAspectRatioEccentricity // too wide || component.Nodes.Count > 30 && aspectRatio < 1d/layeredSettings.MaxAspectRatioEccentricity // too high )) { // for large graphs there's really no point trying to produce nice edge routes // the sugiyama edge routing can be quite circuitous on large graphs anyway var prevEdgeRouting = fallbackLayoutSettings.EdgeRoutingSettings.EdgeRoutingMode; if (component.Nodes.Count > 100 && edgeDensity > 2.0) fallbackLayoutSettings.EdgeRoutingSettings.EdgeRoutingMode = EdgeRoutingMode.StraightLine; LayoutComponent(fallbackLayoutSettings, component); fallbackLayoutSettings.EdgeRoutingSettings.EdgeRoutingMode = prevEdgeRouting; } else { var prevEdgeRouting = layeredSettings.EdgeRoutingSettings.EdgeRoutingMode; // for large graphs there's really no point trying to produce nice edge routes // the sugiyama edge routing can be quite circuitous on large graphs anyway if (component.Nodes.Count > 100 && edgeDensity > 2.0) { layeredSettings.EdgeRoutingSettings.EdgeRoutingMode = EdgeRoutingMode.StraightLine; } layeredLayout.Run(this.CancelToken); layeredSettings.EdgeRoutingSettings.EdgeRoutingMode = prevEdgeRouting; InitialLayoutHelpers.FixBoundingBox(component, layeredSettings); } //LayoutAlgorithmSettings.ShowGraph(component); } #if TEST_MSAGL_AND_HAVEGRAPHVIEWERGDI protected static void ShowGraphInDebugViewer(GeometryGraph graph) { if (graph == null) { return; } Microsoft.Msagl.GraphViewerGdi.DisplayGeometryGraph.SetShowFunctions(); //FixNullCurveEdges(graph.Edges); var debugCurves = graph.Nodes.Select(n => n.BoundaryCurve).Select(c => new DebugCurve("red", c)); debugCurves = debugCurves.Concat(graph.RootCluster.AllClustersDepthFirst().Select(c => c.BoundaryCurve).Select(c => new DebugCurve("green", c))); debugCurves = debugCurves.Concat(graph.Edges.Select(e => new DebugCurve(120, 1, "blue", e.Curve))); debugCurves = debugCurves.Concat(graph.Edges.Where(e => e.Label != null).Select(e => new DebugCurve("green", CurveFactory.CreateRectangle(e.LabelBBox)))); var arrowHeadsAtSource = from e in graph.Edges where e.Curve != null && e.EdgeGeometry.SourceArrowhead != null select new DebugCurve(120, 2, "black", new LineSegment(e.Curve.Start, e.EdgeGeometry.SourceArrowhead.TipPosition)); var arrowHeadsAtTarget = from e in graph.Edges where e.Curve != null && e.EdgeGeometry.TargetArrowhead != null select new DebugCurve(120, 2, "black", new LineSegment(e.Curve.End, e.EdgeGeometry.TargetArrowhead.TipPosition)); LayoutAlgorithmSettings.ShowDebugCurvesEnumeration(debugCurves.Concat(arrowHeadsAtSource).Concat(arrowHeadsAtTarget)); } #endif } }
/*************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. This code is licensed under the Visual Studio SDK license terms. THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. ***************************************************************************/ using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Text; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants; using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID; namespace Microsoft.VisualStudio.Project { [CLSCompliant(false), ComVisible(true)] public abstract class ReferenceNode : HierarchyNode { protected delegate void CannotAddReferenceErrorMessage(); #region ctors /// <summary> /// constructor for the ReferenceNode /// </summary> protected ReferenceNode(ProjectNode root, ProjectElement element) : base(root, element) { this.ExcludeNodeFromScc = true; } /// <summary> /// constructor for the ReferenceNode /// </summary> protected ReferenceNode(ProjectNode root) : base(root) { this.ExcludeNodeFromScc = true; } #endregion #region overridden properties public override int MenuCommandId { get { return VsMenus.IDM_VS_CTXT_REFERENCE; } } public override Guid ItemTypeGuid { get { return Guid.Empty; } } public override string Url { get { return String.Empty; } } public override string Caption { get { return String.Empty; } } #endregion #region overridden methods protected override NodeProperties CreatePropertiesObject() { return new ReferenceNodeProperties(this); } /// <summary> /// Get an instance of the automation object for ReferenceNode /// </summary> /// <returns>An instance of Automation.OAReferenceItem type if succeeded</returns> public override object GetAutomationObject() { if(this.ProjectMgr == null || this.ProjectMgr.IsClosed) { return null; } return new Automation.OAReferenceItem(this.ProjectMgr.GetAutomationObject() as Automation.OAProject, this); } /// <summary> /// Disable inline editing of Caption of a ReferendeNode /// </summary> /// <returns>null</returns> public override string GetEditLabel() { return null; } public override object GetIconHandle(bool open) { int offset = (this.CanShowDefaultIcon() ? (int)ProjectNode.ImageName.Reference : (int)ProjectNode.ImageName.DanglingReference); return this.ProjectMgr.ImageHandler.GetIconHandle(offset); } /// <summary> /// This method is called by the interface method GetMkDocument to specify the item moniker. /// </summary> /// <returns>The moniker for this item</returns> public override string GetMkDocument() { return this.Url; } /// <summary> /// Not supported. /// </summary> protected override int ExcludeFromProject() { return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED; } /// <summary> /// References node cannot be dragged. /// </summary> /// <returns>A stringbuilder.</returns> protected internal override StringBuilder PrepareSelectedNodesForClipBoard() { return null; } protected override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result) { if(cmdGroup == VsMenus.guidStandardCommandSet2K) { if((VsCommands2K)cmd == VsCommands2K.QUICKOBJECTSEARCH) { result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED; return VSConstants.S_OK; } } else { return (int)OleConstants.OLECMDERR_E_UNKNOWNGROUP; } return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result); } protected override int ExecCommandOnNode(Guid cmdGroup, uint cmd, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { if(cmdGroup == VsMenus.guidStandardCommandSet2K) { if((VsCommands2K)cmd == VsCommands2K.QUICKOBJECTSEARCH) { return this.ShowObjectBrowser(); } } return base.ExecCommandOnNode(cmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut); } #endregion #region methods /// <summary> /// Links a reference node to the project and hierarchy. /// </summary> public virtual void AddReference() { ReferenceContainerNode referencesFolder = this.ProjectMgr.FindChild(ReferenceContainerNode.ReferencesNodeVirtualName) as ReferenceContainerNode; Debug.Assert(referencesFolder != null, "Could not find the References node"); CannotAddReferenceErrorMessage referenceErrorMessageHandler = null; if(!this.CanAddReference(out referenceErrorMessageHandler)) { if(referenceErrorMessageHandler != null) { referenceErrorMessageHandler.DynamicInvoke(new object[] { }); } return; } // Link the node to the project file. this.BindReferenceData(); // At this point force the item to be refreshed this.ItemNode.RefreshProperties(); referencesFolder.AddChild(this); return; } /// <summary> /// Refreshes a reference by re-resolving it and redrawing the icon. /// </summary> internal virtual void RefreshReference() { this.ResolveReference(); this.ReDraw(UIHierarchyElement.Icon); } /// <summary> /// Resolves references. /// </summary> protected virtual void ResolveReference() { } /// <summary> /// Validates that a reference can be added. /// </summary> /// <param name="errorHandler">A CannotAddReferenceErrorMessage delegate to show the error message.</param> /// <returns>true if the reference can be added.</returns> protected virtual bool CanAddReference(out CannotAddReferenceErrorMessage errorHandler) { // When this method is called this refererence has not yet been added to the hierarchy, only instantiated. errorHandler = null; if(this.IsAlreadyAdded()) { return false; } return true; } /// <summary> /// Checks if a reference is already added. The method parses all references and compares the Url. /// </summary> /// <returns>true if the assembly has already been added.</returns> protected bool IsAlreadyAdded() { ReferenceNode existingReference; return IsAlreadyAdded(out existingReference); } /// <summary> /// Checks if a reference is already added. The method parses all references and compares the Url. /// </summary> /// <param name="existingEquivalentNode">The existing reference, if one is found.</param> /// <returns>true if the assembly has already been added.</returns> protected internal virtual bool IsAlreadyAdded(out ReferenceNode existingEquivalentNode) { ReferenceContainerNode referencesFolder = this.ProjectMgr.FindChild(ReferenceContainerNode.ReferencesNodeVirtualName) as ReferenceContainerNode; Debug.Assert(referencesFolder != null, "Could not find the References node"); for(HierarchyNode n = referencesFolder.FirstChild; n != null; n = n.NextSibling) { ReferenceNode referenceNode = n as ReferenceNode; if(null != referenceNode) { // We check if the Url of the assemblies is the same. if(NativeMethods.IsSamePath(referenceNode.Url, this.Url)) { existingEquivalentNode = referenceNode; return true; } } } existingEquivalentNode = null; return false; } /// <summary> /// Shows the Object Browser /// </summary> /// <returns></returns> protected virtual int ShowObjectBrowser() { if(String.IsNullOrEmpty(this.Url) || !File.Exists(this.Url)) { return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED; } // Request unmanaged code permission in order to be able to creaet the unmanaged memory representing the guid. new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); Guid guid = VSConstants.guidCOMPLUSLibrary; IntPtr ptr = System.Runtime.InteropServices.Marshal.AllocCoTaskMem(guid.ToByteArray().Length); System.Runtime.InteropServices.Marshal.StructureToPtr(guid, ptr, false); int returnValue = VSConstants.S_OK; try { VSOBJECTINFO[] objInfo = new VSOBJECTINFO[1]; objInfo[0].pguidLib = ptr; objInfo[0].pszLibName = this.Url; IVsObjBrowser objBrowser = this.ProjectMgr.Site.GetService(typeof(SVsObjBrowser)) as IVsObjBrowser; ErrorHandler.ThrowOnFailure(objBrowser.NavigateTo(objInfo, 0)); } catch(COMException e) { Trace.WriteLine("Exception" + e.ErrorCode); returnValue = e.ErrorCode; } finally { if(ptr != IntPtr.Zero) { System.Runtime.InteropServices.Marshal.FreeCoTaskMem(ptr); } } return returnValue; } protected override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation) { if(deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_RemoveFromProject) { return true; } return false; } protected abstract void BindReferenceData(); #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 System; using System.Collections.Generic; using System.Reflection; using System.IO; using System.Threading; using System.Xml; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenMetaverse.Packets; using OpenSim.Framework; using OpenSim.Region.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes.Serialization; namespace OpenSim.Region.CoreModules.Avatar.Attachments { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AttachmentsModule")] public class AttachmentsModule : IAttachmentsModule, INonSharedRegionModule { #region INonSharedRegionModule private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public int DebugLevel { get; set; } /// <summary> /// Period to sleep per 100 prims in order to avoid CPU spikes when an avatar with many attachments logs in/changes /// outfit or many avatars with a medium levels of attachments login/change outfit simultaneously. /// </summary> /// <remarks> /// A value of 0 will apply no pause. The pause is specified in milliseconds. /// </remarks> public int ThrottlePer100PrimsRezzed { get; set; } private Scene m_scene; private IInventoryAccessModule m_invAccessModule; /// <summary> /// Are attachments enabled? /// </summary> public bool Enabled { get; private set; } public string Name { get { return "Attachments Module"; } } public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource source) { IConfig config = source.Configs["Attachments"]; if (config != null) { Enabled = config.GetBoolean("Enabled", true); ThrottlePer100PrimsRezzed = config.GetInt("ThrottlePer100PrimsRezzed", 0); } else { Enabled = true; } } public void AddRegion(Scene scene) { m_scene = scene; if (Enabled) { // Only register module with scene if it is enabled. All callers check for a null attachments module. // Ideally, there should be a null attachments module for when this core attachments module has been // disabled. Registering only when enabled allows for other attachments module implementations. m_scene.RegisterModuleInterface<IAttachmentsModule>(this); m_scene.EventManager.OnNewClient += SubscribeToClientEvents; m_scene.EventManager.OnStartScript += (localID, itemID) => HandleScriptStateChange(localID, true); m_scene.EventManager.OnStopScript += (localID, itemID) => HandleScriptStateChange(localID, false); MainConsole.Instance.Commands.AddCommand( "Debug", false, "debug attachments log", "debug attachments log [0|1]", "Turn on attachments debug logging", " <= 0 - turns off debug logging\n" + " >= 1 - turns on attachment message debug logging", HandleDebugAttachmentsLog); MainConsole.Instance.Commands.AddCommand( "Debug", false, "debug attachments throttle", "debug attachments throttle <ms>", "Turn on attachments throttling.", "This requires a millisecond value. " + " == 0 - disable throttling.\n" + " > 0 - sleeps for this number of milliseconds per 100 prims rezzed.", HandleDebugAttachmentsThrottle); MainConsole.Instance.Commands.AddCommand( "Debug", false, "debug attachments status", "debug attachments status", "Show current attachments debug status", HandleDebugAttachmentsStatus); } // TODO: Should probably be subscribing to CloseClient too, but this doesn't yet give us IClientAPI } private void HandleDebugAttachmentsLog(string module, string[] args) { int debugLevel; if (!(args.Length == 4 && int.TryParse(args[3], out debugLevel))) { MainConsole.Instance.OutputFormat("Usage: debug attachments log [0|1]"); } else { DebugLevel = debugLevel; MainConsole.Instance.OutputFormat( "Set event queue debug level to {0} in {1}", DebugLevel, m_scene.Name); } } private void HandleDebugAttachmentsThrottle(string module, string[] args) { int ms; if (args.Length == 4 && int.TryParse(args[3], out ms)) { ThrottlePer100PrimsRezzed = ms; MainConsole.Instance.OutputFormat( "Attachments rez throttle per 100 prims is now {0} in {1}", ThrottlePer100PrimsRezzed, m_scene.Name); return; } MainConsole.Instance.OutputFormat("Usage: debug attachments throttle <ms>"); } private void HandleDebugAttachmentsStatus(string module, string[] args) { MainConsole.Instance.OutputFormat("Settings for {0}", m_scene.Name); MainConsole.Instance.OutputFormat("Debug logging level: {0}", DebugLevel); MainConsole.Instance.OutputFormat("Throttle per 100 prims: {0}ms", ThrottlePer100PrimsRezzed); } /// <summary> /// Listen for client triggered running state changes so that we can persist the script's object if necessary. /// </summary> /// <param name='localID'></param> /// <param name='itemID'></param> private void HandleScriptStateChange(uint localID, bool started) { SceneObjectGroup sog = m_scene.GetGroupByPrim(localID); if (sog != null && sog.IsAttachment) { if (!started) { // FIXME: This is a convoluted way for working out whether the script state has changed to stop // because it has been manually stopped or because the stop was called in UpdateDetachedObject() below // This needs to be handled in a less tangled way. ScenePresence sp = m_scene.GetScenePresence(sog.AttachedAvatar); if (sp.ControllingClient.IsActive) sog.HasGroupChanged = true; } else { sog.HasGroupChanged = true; } } } public void RemoveRegion(Scene scene) { m_scene.UnregisterModuleInterface<IAttachmentsModule>(this); if (Enabled) m_scene.EventManager.OnNewClient -= SubscribeToClientEvents; } public void RegionLoaded(Scene scene) { m_invAccessModule = m_scene.RequestModuleInterface<IInventoryAccessModule>(); } public void Close() { RemoveRegion(m_scene); } #endregion #region IAttachmentsModule public void CopyAttachments(IScenePresence sp, AgentData ad) { lock (sp.AttachmentsSyncLock) { // Attachment objects List<SceneObjectGroup> attachments = sp.GetAttachments(); if (attachments.Count > 0) { ad.AttachmentObjects = new List<ISceneObject>(); ad.AttachmentObjectStates = new List<string>(); // IScriptModule se = m_scene.RequestModuleInterface<IScriptModule>(); sp.InTransitScriptStates.Clear(); foreach (SceneObjectGroup sog in attachments) { // We need to make a copy and pass that copy // because of transfers withn the same sim ISceneObject clone = sog.CloneForNewScene(); // Attachment module assumes that GroupPosition holds the offsets...! ((SceneObjectGroup)clone).RootPart.GroupPosition = sog.RootPart.AttachedPos; ((SceneObjectGroup)clone).IsAttachment = false; ad.AttachmentObjects.Add(clone); string state = sog.GetStateSnapshot(); ad.AttachmentObjectStates.Add(state); sp.InTransitScriptStates.Add(state); // Let's remove the scripts of the original object here sog.RemoveScriptInstances(true); } } } } public void CopyAttachments(AgentData ad, IScenePresence sp) { if (ad.AttachmentObjects != null && ad.AttachmentObjects.Count > 0) { lock (sp.AttachmentsSyncLock) sp.ClearAttachments(); int i = 0; foreach (ISceneObject so in ad.AttachmentObjects) { ((SceneObjectGroup)so).LocalId = 0; ((SceneObjectGroup)so).RootPart.ClearUpdateSchedule(); so.SetState(ad.AttachmentObjectStates[i++], m_scene); m_scene.IncomingCreateObject(Vector3.Zero, so); } } } public void RezAttachments(IScenePresence sp) { if (!Enabled) return; if (null == sp.Appearance) { m_log.WarnFormat("[ATTACHMENTS MODULE]: Appearance has not been initialized for agent {0}", sp.UUID); return; } if (sp.GetAttachments().Count > 0) { if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Not doing simulator-side attachment rez for {0} in {1} as their viewer has already rezzed attachments", m_scene.Name, sp.Name); return; } if (DebugLevel > 0) m_log.DebugFormat("[ATTACHMENTS MODULE]: Rezzing any attachments for {0} from simulator-side", sp.Name); List<AvatarAttachment> attachments = sp.Appearance.GetAttachments(); foreach (AvatarAttachment attach in attachments) { uint attachmentPt = (uint)attach.AttachPoint; // m_log.DebugFormat( // "[ATTACHMENTS MODULE]: Doing initial rez of attachment with itemID {0}, assetID {1}, point {2} for {3} in {4}", // attach.ItemID, attach.AssetID, p, sp.Name, m_scene.RegionInfo.RegionName); // For some reason assetIDs are being written as Zero's in the DB -- need to track tat down // But they're not used anyway, the item is being looked up for now, so let's proceed. //if (UUID.Zero == assetID) //{ // m_log.DebugFormat("[ATTACHMENT]: Cannot rez attachment in point {0} with itemID {1}", p, itemID); // continue; //} try { // If we're an NPC then skip all the item checks and manipulations since we don't have an // inventory right now. RezSingleAttachmentFromInventoryInternal( sp, sp.PresenceType == PresenceType.Npc ? UUID.Zero : attach.ItemID, attach.AssetID, attachmentPt, true); } catch (Exception e) { UUID agentId = (sp.ControllingClient == null) ? (UUID)null : sp.ControllingClient.AgentId; m_log.ErrorFormat("[ATTACHMENTS MODULE]: Unable to rez attachment with itemID {0}, assetID {1}, point {2} for {3}: {4}\n{5}", attach.ItemID, attach.AssetID, attachmentPt, agentId, e.Message, e.StackTrace); } } } public void DeRezAttachments(IScenePresence sp) { if (!Enabled) return; if (DebugLevel > 0) m_log.DebugFormat("[ATTACHMENTS MODULE]: Saving changed attachments for {0}", sp.Name); List<SceneObjectGroup> attachments = sp.GetAttachments(); if (attachments.Count <= 0) return; Dictionary<SceneObjectGroup, string> scriptStates = new Dictionary<SceneObjectGroup, string>(); foreach (SceneObjectGroup so in attachments) { // Scripts MUST be snapshotted before the object is // removed from the scene because doing otherwise will // clobber the run flag // This must be done outside the sp.AttachmentSyncLock so that there is no risk of a deadlock from // scripts performing attachment operations at the same time. Getting object states stops the scripts. scriptStates[so] = PrepareScriptInstanceForSave(so, false); } lock (sp.AttachmentsSyncLock) { foreach (SceneObjectGroup so in attachments) UpdateDetachedObject(sp, so, scriptStates[so]); sp.ClearAttachments(); } } public void DeleteAttachmentsFromScene(IScenePresence sp, bool silent) { if (!Enabled) return; if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Deleting attachments from scene {0} for {1}, silent = {2}", m_scene.RegionInfo.RegionName, sp.Name, silent); foreach (SceneObjectGroup sop in sp.GetAttachments()) { sop.Scene.DeleteSceneObject(sop, silent); } sp.ClearAttachments(); } public bool AttachObject( IScenePresence sp, SceneObjectGroup group, uint attachmentPt, bool silent, bool addToInventory, bool append) { if (!Enabled) return false; return AttachObjectInternal(sp, group, attachmentPt, silent, addToInventory, false, append); } /// <summary> /// Internal method which actually does all the work for attaching an object. /// </summary> /// <returns>The object attached.</returns> /// <param name='sp'></param> /// <param name='group'>The object to attach.</param> /// <param name='attachmentPt'></param> /// <param name='silent'></param> /// <param name='addToInventory'>If true then add object to user inventory.</param> /// <param name='resumeScripts'>If true then scripts are resumed on the attached object.</param> /// <param name='append'>Append to attachment point rather than replace.</param> private bool AttachObjectInternal( IScenePresence sp, SceneObjectGroup group, uint attachmentPt, bool silent, bool addToInventory, bool resumeScripts, bool append) { if (group.GetSittingAvatarsCount() != 0) { if (DebugLevel > 0) m_log.WarnFormat( "[ATTACHMENTS MODULE]: Ignoring request to attach {0} {1} to {2} on {3} since {4} avatars are still sitting on it", group.Name, group.LocalId, sp.Name, attachmentPt, group.GetSittingAvatarsCount()); return false; } Vector3 attachPos = group.AbsolutePosition; // If the attachment point isn't the same as the one previously used // set it's offset position = 0 so that it appears on the attachment point // and not in a weird location somewhere unknown. if (attachmentPt != (uint)AttachmentPoint.Default && attachmentPt != group.AttachmentPoint) { attachPos = Vector3.Zero; } // AttachmentPt 0 means the client chose to 'wear' the attachment. if (attachmentPt == (uint)AttachmentPoint.Default) { // Check object for stored attachment point attachmentPt = group.AttachmentPoint; } // if we still didn't find a suitable attachment point....... if (attachmentPt == 0) { // Stick it on left hand with Zero Offset from the attachment point. attachmentPt = (uint)AttachmentPoint.LeftHand; attachPos = Vector3.Zero; } group.AttachmentPoint = attachmentPt; group.AbsolutePosition = attachPos; List<SceneObjectGroup> attachments = sp.GetAttachments(attachmentPt); if (attachments.Contains(group)) { if (DebugLevel > 0) m_log.WarnFormat( "[ATTACHMENTS MODULE]: Ignoring request to attach {0} {1} to {2} on {3} since it's already attached", group.Name, group.LocalId, sp.Name, attachmentPt); return false; } // If we already have 5, remove the oldest until only 4 are left. Skip over temp ones while (attachments.Count >= 5) { if (attachments[0].FromItemID != UUID.Zero) DetachSingleAttachmentToInv(sp, attachments[0]); attachments.RemoveAt(0); } // If we're not appending, remove the rest as well if (attachments.Count != 0 && !append) { foreach (SceneObjectGroup g in attachments) { if (g.FromItemID != UUID.Zero) DetachSingleAttachmentToInv(sp, g); } } lock (sp.AttachmentsSyncLock) { if (addToInventory && sp.PresenceType != PresenceType.Npc) UpdateUserInventoryWithAttachment(sp, group, attachmentPt, append); AttachToAgent(sp, group, attachmentPt, attachPos, silent); if (resumeScripts) { // Fire after attach, so we don't get messy perms dialogs // 4 == AttachedRez group.CreateScriptInstances(0, true, m_scene.DefaultScriptEngine, 4); group.ResumeScripts(); } // Do this last so that event listeners have access to all the effects of the attachment m_scene.EventManager.TriggerOnAttach(group.LocalId, group.FromItemID, sp.UUID); } return true; } private void UpdateUserInventoryWithAttachment(IScenePresence sp, SceneObjectGroup group, uint attachmentPt, bool append) { // Add the new attachment to inventory if we don't already have it. UUID newAttachmentItemID = group.FromItemID; if (newAttachmentItemID == UUID.Zero) newAttachmentItemID = AddSceneObjectAsNewAttachmentInInv(sp, group).ID; ShowAttachInUserInventory(sp, attachmentPt, newAttachmentItemID, group, append); } public SceneObjectGroup RezSingleAttachmentFromInventory(IScenePresence sp, UUID itemID, uint AttachmentPt) { if (!Enabled) return null; if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: RezSingleAttachmentFromInventory to point {0} from item {1} for {2} in {3}", (AttachmentPoint)AttachmentPt, itemID, sp.Name, m_scene.Name); // We check the attachments in the avatar appearance here rather than the objects attached to the // ScenePresence itself so that we can ignore calls by viewer 2/3 to attach objects on startup. We are // already doing this in ScenePresence.MakeRootAgent(). Simulator-side attaching needs to be done // because pre-outfit folder viewers (most version 1 viewers) require it. bool alreadyOn = false; List<AvatarAttachment> existingAttachments = sp.Appearance.GetAttachments(); foreach (AvatarAttachment existingAttachment in existingAttachments) { if (existingAttachment.ItemID == itemID) { alreadyOn = true; break; } } if (alreadyOn) { if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Ignoring request by {0} to wear item {1} at {2} since it is already worn", sp.Name, itemID, AttachmentPt); return null; } bool append = (AttachmentPt & 0x80) != 0; AttachmentPt &= 0x7f; return RezSingleAttachmentFromInventoryInternal(sp, itemID, UUID.Zero, AttachmentPt, append); } public void RezMultipleAttachmentsFromInventory(IScenePresence sp, List<KeyValuePair<UUID, uint>> rezlist) { if (!Enabled) return; if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Rezzing {0} attachments from inventory for {1} in {2}", rezlist.Count, sp.Name, m_scene.Name); foreach (KeyValuePair<UUID, uint> rez in rezlist) { RezSingleAttachmentFromInventory(sp, rez.Key, rez.Value); } } public void DetachSingleAttachmentToGround(IScenePresence sp, uint soLocalId) { DetachSingleAttachmentToGround(sp, soLocalId, sp.AbsolutePosition, Quaternion.Identity); } public void DetachSingleAttachmentToGround(IScenePresence sp, uint soLocalId, Vector3 absolutePos, Quaternion absoluteRot) { if (!Enabled) return; if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: DetachSingleAttachmentToGround() for {0}, object {1}", sp.UUID, soLocalId); SceneObjectGroup so = m_scene.GetGroupByPrim(soLocalId); if (so == null) return; if (so.AttachedAvatar != sp.UUID) return; UUID inventoryID = so.FromItemID; // As per Linden spec, drop is disabled for temp attachs if (inventoryID == UUID.Zero) return; if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: In DetachSingleAttachmentToGround(), object is {0} {1}, associated item is {2}", so.Name, so.LocalId, inventoryID); lock (sp.AttachmentsSyncLock) { if (!m_scene.Permissions.CanRezObject( so.PrimCount, sp.UUID, sp.AbsolutePosition)) return; bool changed = false; if (inventoryID != UUID.Zero) changed = sp.Appearance.DetachAttachment(inventoryID); if (changed && m_scene.AvatarFactory != null) m_scene.AvatarFactory.QueueAppearanceSave(sp.UUID); sp.RemoveAttachment(so); so.FromItemID = UUID.Zero; SceneObjectPart rootPart = so.RootPart; so.AbsolutePosition = absolutePos; if (absoluteRot != Quaternion.Identity) { so.UpdateGroupRotationR(absoluteRot); } so.AttachedAvatar = UUID.Zero; rootPart.SetParentLocalId(0); so.ClearPartAttachmentData(); rootPart.ApplyPhysics(rootPart.GetEffectiveObjectFlags(), rootPart.VolumeDetectActive); so.HasGroupChanged = true; rootPart.Rezzed = DateTime.Now; rootPart.RemFlag(PrimFlags.TemporaryOnRez); so.AttachToBackup(); m_scene.EventManager.TriggerParcelPrimCountTainted(); rootPart.ScheduleFullUpdate(); rootPart.ClearUndoState(); List<UUID> uuids = new List<UUID>(); uuids.Add(inventoryID); m_scene.InventoryService.DeleteItems(sp.UUID, uuids); sp.ControllingClient.SendRemoveInventoryItem(inventoryID); } m_scene.EventManager.TriggerOnAttach(so.LocalId, so.UUID, UUID.Zero); } public void DetachSingleAttachmentToInv(IScenePresence sp, SceneObjectGroup so) { if (so.AttachedAvatar != sp.UUID) { m_log.WarnFormat( "[ATTACHMENTS MODULE]: Tried to detach object {0} from {1} {2} but attached avatar id was {3} in {4}", so.Name, sp.Name, sp.UUID, so.AttachedAvatar, m_scene.RegionInfo.RegionName); return; } if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Detaching object {0} {1} (FromItemID {2}) for {3} in {4}", so.Name, so.LocalId, so.FromItemID, sp.Name, m_scene.Name); // Scripts MUST be snapshotted before the object is // removed from the scene because doing otherwise will // clobber the run flag // This must be done outside the sp.AttachmentSyncLock so that there is no risk of a deadlock from // scripts performing attachment operations at the same time. Getting object states stops the scripts. string scriptedState = PrepareScriptInstanceForSave(so, true); lock (sp.AttachmentsSyncLock) { // Save avatar attachment information // m_log.Debug("[ATTACHMENTS MODULE]: Detaching from UserID: " + sp.UUID + ", ItemID: " + itemID); bool changed = sp.Appearance.DetachAttachment(so.FromItemID); if (changed && m_scene.AvatarFactory != null) m_scene.AvatarFactory.QueueAppearanceSave(sp.UUID); sp.RemoveAttachment(so); UpdateDetachedObject(sp, so, scriptedState); } } public void UpdateAttachmentPosition(SceneObjectGroup sog, Vector3 pos) { if (!Enabled) return; sog.UpdateGroupPosition(pos); sog.HasGroupChanged = true; } #endregion #region AttachmentModule private methods // This is public but is not part of the IAttachmentsModule interface. // RegionCombiner module needs to poke at it to deliver client events. // This breaks the encapsulation of the module and should get fixed somehow. public void SubscribeToClientEvents(IClientAPI client) { client.OnRezSingleAttachmentFromInv += Client_OnRezSingleAttachmentFromInv; client.OnRezMultipleAttachmentsFromInv += Client_OnRezMultipleAttachmentsFromInv; client.OnObjectAttach += Client_OnObjectAttach; client.OnObjectDetach += Client_OnObjectDetach; client.OnDetachAttachmentIntoInv += Client_OnDetachAttachmentIntoInv; client.OnObjectDrop += Client_OnObjectDrop; } // This is public but is not part of the IAttachmentsModule interface. // RegionCombiner module needs to poke at it to deliver client events. // This breaks the encapsulation of the module and should get fixed somehow. public void UnsubscribeFromClientEvents(IClientAPI client) { client.OnRezSingleAttachmentFromInv -= Client_OnRezSingleAttachmentFromInv; client.OnRezMultipleAttachmentsFromInv -= Client_OnRezMultipleAttachmentsFromInv; client.OnObjectAttach -= Client_OnObjectAttach; client.OnObjectDetach -= Client_OnObjectDetach; client.OnDetachAttachmentIntoInv -= Client_OnDetachAttachmentIntoInv; client.OnObjectDrop -= Client_OnObjectDrop; } /// <summary> /// Update the attachment asset for the new sog details if they have changed. /// </summary> /// <remarks> /// This is essential for preserving attachment attributes such as permission. Unlike normal scene objects, /// these details are not stored on the region. /// </remarks> /// <param name="sp"></param> /// <param name="grp"></param> /// <param name="saveAllScripted"></param> private void UpdateKnownItem(IScenePresence sp, SceneObjectGroup grp, string scriptedState) { if (grp.FromItemID == UUID.Zero) { // We can't save temp attachments grp.HasGroupChanged = false; return; } // Saving attachments for NPCs messes them up for the real owner! INPCModule module = m_scene.RequestModuleInterface<INPCModule>(); if (module != null) { if (module.IsNPC(sp.UUID, m_scene)) return; } if (grp.HasGroupChanged) { m_log.DebugFormat( "[ATTACHMENTS MODULE]: Updating asset for attachment {0}, attachpoint {1}", grp.UUID, grp.AttachmentPoint); string sceneObjectXml = SceneObjectSerializer.ToOriginalXmlFormat(grp, scriptedState); InventoryItemBase item = new InventoryItemBase(grp.FromItemID, sp.UUID); item = m_scene.InventoryService.GetItem(item); if (item != null) { AssetBase asset = m_scene.CreateAsset( grp.GetPartName(grp.LocalId), grp.GetPartDescription(grp.LocalId), (sbyte)AssetType.Object, Utils.StringToBytes(sceneObjectXml), sp.UUID); m_scene.AssetService.Store(asset); item.AssetID = asset.FullID; item.Description = asset.Description; item.Name = asset.Name; item.AssetType = asset.Type; item.InvType = (int)InventoryType.Object; m_scene.InventoryService.UpdateItem(item); // If the name of the object has been changed whilst attached then we want to update the inventory // item in the viewer. if (sp.ControllingClient != null) sp.ControllingClient.SendInventoryItemCreateUpdate(item, 0); } grp.HasGroupChanged = false; // Prevent it being saved over and over } else if (DebugLevel > 0) { m_log.DebugFormat( "[ATTACHMENTS MODULE]: Don't need to update asset for unchanged attachment {0}, attachpoint {1}", grp.UUID, grp.AttachmentPoint); } } /// <summary> /// Attach this scene object to the given avatar. /// </summary> /// <remarks> /// This isn't publicly available since attachments should always perform the corresponding inventory /// operation (to show the attach in user inventory and update the asset with positional information). /// </remarks> /// <param name="sp"></param> /// <param name="so"></param> /// <param name="attachmentpoint"></param> /// <param name="attachOffset"></param> /// <param name="silent"></param> private void AttachToAgent( IScenePresence sp, SceneObjectGroup so, uint attachmentpoint, Vector3 attachOffset, bool silent) { if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Adding attachment {0} to avatar {1} in pt {2} pos {3} {4}", so.Name, sp.Name, attachmentpoint, attachOffset, so.RootPart.AttachedPos); so.DetachFromBackup(); // Remove from database and parcel prim count m_scene.DeleteFromStorage(so.UUID); m_scene.EventManager.TriggerParcelPrimCountTainted(); so.AttachedAvatar = sp.UUID; if (so.RootPart.PhysActor != null) so.RootPart.RemoveFromPhysics(); so.AbsolutePosition = attachOffset; so.RootPart.AttachedPos = attachOffset; so.IsAttachment = true; so.RootPart.SetParentLocalId(sp.LocalId); so.AttachmentPoint = attachmentpoint; sp.AddAttachment(so); if (!silent) { if (so.HasPrivateAttachmentPoint) { if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Killing private HUD {0} for avatars other than {1} at attachment point {2}", so.Name, sp.Name, so.AttachmentPoint); // As this scene object can now only be seen by the attaching avatar, tell everybody else in the // scene that it's no longer in their awareness. m_scene.ForEachClient( client => { if (client.AgentId != so.AttachedAvatar) client.SendKillObject(new List<uint>() { so.LocalId }); }); } // Fudge below is an extremely unhelpful comment. It's probably here so that the scheduled full update // will succeed, as that will not update if an attachment is selected. so.IsSelected = false; // fudge.... so.ScheduleGroupForFullUpdate(); } // In case it is later dropped again, don't let // it get cleaned up so.RootPart.RemFlag(PrimFlags.TemporaryOnRez); } /// <summary> /// Add a scene object as a new attachment in the user inventory. /// </summary> /// <param name="remoteClient"></param> /// <param name="grp"></param> /// <returns>The user inventory item created that holds the attachment.</returns> private InventoryItemBase AddSceneObjectAsNewAttachmentInInv(IScenePresence sp, SceneObjectGroup grp) { if (m_invAccessModule == null) return null; if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Called AddSceneObjectAsAttachment for object {0} {1} for {2}", grp.Name, grp.LocalId, sp.Name); InventoryItemBase newItem = m_invAccessModule.CopyToInventory( DeRezAction.TakeCopy, m_scene.InventoryService.GetFolderForType(sp.UUID, AssetType.Object).ID, new List<SceneObjectGroup> { grp }, sp.ControllingClient, true)[0]; // sets itemID so client can show item as 'attached' in inventory grp.FromItemID = newItem.ID; return newItem; } /// <summary> /// Prepares the script instance for save. /// </summary> /// <remarks> /// This involves triggering the detach event and getting the script state (which also stops the script) /// This MUST be done outside sp.AttachmentsSyncLock, since otherwise there is a chance of deadlock if a /// running script is performing attachment operations. /// </remarks> /// <returns> /// The script state ready for persistence. /// </returns> /// <param name='grp'> /// </param> /// <param name='fireDetachEvent'> /// If true, then fire the script event before we save its state. /// </param> private string PrepareScriptInstanceForSave(SceneObjectGroup grp, bool fireDetachEvent) { if (fireDetachEvent) m_scene.EventManager.TriggerOnAttach(grp.LocalId, grp.FromItemID, UUID.Zero); using (StringWriter sw = new StringWriter()) { using (XmlTextWriter writer = new XmlTextWriter(sw)) { grp.SaveScriptedState(writer); } return sw.ToString(); } } private void UpdateDetachedObject(IScenePresence sp, SceneObjectGroup so, string scriptedState) { // Don't save attachments for HG visitors, it // messes up their inventory. When a HG visitor logs // out on a foreign grid, their attachments will be // reloaded in the state they were in when they left // the home grid. This is best anyway as the visited // grid may use an incompatible script engine. bool saveChanged = sp.PresenceType != PresenceType.Npc && (m_scene.UserManagementModule == null || m_scene.UserManagementModule.IsLocalGridUser(sp.UUID)); // Remove the object from the scene so no more updates // are sent. Doing this before the below changes will ensure // updates can't cause "HUD artefacts" m_scene.DeleteSceneObject(so, false, false); // Prepare sog for storage so.AttachedAvatar = UUID.Zero; so.RootPart.SetParentLocalId(0); so.IsAttachment = false; if (saveChanged) { // We cannot use AbsolutePosition here because that would // attempt to cross the prim as it is detached so.ForEachPart(x => { x.GroupPosition = so.RootPart.AttachedPos; }); UpdateKnownItem(sp, so, scriptedState); } // Now, remove the scripts so.RemoveScriptInstances(true); } protected SceneObjectGroup RezSingleAttachmentFromInventoryInternal( IScenePresence sp, UUID itemID, UUID assetID, uint attachmentPt, bool append) { if (m_invAccessModule == null) return null; SceneObjectGroup objatt; if (itemID != UUID.Zero) objatt = m_invAccessModule.RezObject(sp.ControllingClient, itemID, Vector3.Zero, Vector3.Zero, UUID.Zero, (byte)1, true, false, false, sp.UUID, true); else objatt = m_invAccessModule.RezObject(sp.ControllingClient, null, assetID, Vector3.Zero, Vector3.Zero, UUID.Zero, (byte)1, true, false, false, sp.UUID, true); if (objatt == null) { m_log.WarnFormat( "[ATTACHMENTS MODULE]: Could not retrieve item {0} for attaching to avatar {1} at point {2}", itemID, sp.Name, attachmentPt); return null; } if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Rezzed single object {0} with {1} prims for attachment to {2} on point {3} in {4}", objatt.Name, objatt.PrimCount, sp.Name, attachmentPt, m_scene.Name); // HasGroupChanged is being set from within RezObject. Ideally it would be set by the caller. objatt.HasGroupChanged = false; bool tainted = false; if (attachmentPt != 0 && attachmentPt != objatt.AttachmentPoint) tainted = true; // FIXME: Detect whether it's really likely for AttachObject to throw an exception in the normal // course of events. If not, then it's probably not worth trying to recover the situation // since this is more likely to trigger further exceptions and confuse later debugging. If // exceptions can be thrown in expected error conditions (not NREs) then make this consistent // since other normal error conditions will simply return false instead. // This will throw if the attachment fails try { AttachObjectInternal(sp, objatt, attachmentPt, false, true, true, append); } catch (Exception e) { m_log.ErrorFormat( "[ATTACHMENTS MODULE]: Failed to attach {0} {1} for {2}, exception {3}{4}", objatt.Name, objatt.UUID, sp.Name, e.Message, e.StackTrace); // Make sure the object doesn't stick around and bail sp.RemoveAttachment(objatt); m_scene.DeleteSceneObject(objatt, false); return null; } if (tainted) objatt.HasGroupChanged = true; if (ThrottlePer100PrimsRezzed > 0) { int throttleMs = (int)Math.Round((float)objatt.PrimCount / 100 * ThrottlePer100PrimsRezzed); if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Throttling by {0}ms after rez of {1} with {2} prims for attachment to {3} on point {4} in {5}", throttleMs, objatt.Name, objatt.PrimCount, sp.Name, attachmentPt, m_scene.Name); Thread.Sleep(throttleMs); } return objatt; } /// <summary> /// Update the user inventory to reflect an attachment /// </summary> /// <param name="sp"></param> /// <param name="AttachmentPt"></param> /// <param name="itemID"></param> /// <param name="att"></param> private void ShowAttachInUserInventory(IScenePresence sp, uint AttachmentPt, UUID itemID, SceneObjectGroup att, bool append) { // m_log.DebugFormat( // "[USER INVENTORY]: Updating attachment {0} for {1} at {2} using item ID {3}", // att.Name, sp.Name, AttachmentPt, itemID); if (UUID.Zero == itemID) { m_log.Error("[ATTACHMENTS MODULE]: Unable to save attachment. Error inventory item ID."); return; } if (0 == AttachmentPt) { m_log.Error("[ATTACHMENTS MODULE]: Unable to save attachment. Error attachment point."); return; } InventoryItemBase item = new InventoryItemBase(itemID, sp.UUID); item = m_scene.InventoryService.GetItem(item); if (item == null) return; int attFlag = append ? 0x80 : 0; bool changed = sp.Appearance.SetAttachment((int)AttachmentPt | attFlag, itemID, item.AssetID); if (changed && m_scene.AvatarFactory != null) { if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Queueing appearance save for {0}, attachment {1} point {2} in ShowAttachInUserInventory()", sp.Name, att.Name, AttachmentPt); m_scene.AvatarFactory.QueueAppearanceSave(sp.UUID); } } #endregion #region Client Event Handlers private ISceneEntity Client_OnRezSingleAttachmentFromInv(IClientAPI remoteClient, UUID itemID, uint AttachmentPt) { if (!Enabled) return null; if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Rezzing attachment to point {0} from item {1} for {2}", (AttachmentPoint)AttachmentPt, itemID, remoteClient.Name); ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId); if (sp == null) { m_log.ErrorFormat( "[ATTACHMENTS MODULE]: Could not find presence for client {0} {1} in RezSingleAttachmentFromInventory()", remoteClient.Name, remoteClient.AgentId); return null; } return RezSingleAttachmentFromInventory(sp, itemID, AttachmentPt); } private void Client_OnRezMultipleAttachmentsFromInv(IClientAPI remoteClient, List<KeyValuePair<UUID, uint>> rezlist) { if (!Enabled) return; ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId); if (sp != null) RezMultipleAttachmentsFromInventory(sp, rezlist); else m_log.ErrorFormat( "[ATTACHMENTS MODULE]: Could not find presence for client {0} {1} in RezMultipleAttachmentsFromInventory()", remoteClient.Name, remoteClient.AgentId); } private void Client_OnObjectAttach(IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, bool silent) { if (DebugLevel > 0) m_log.DebugFormat( "[ATTACHMENTS MODULE]: Attaching object local id {0} to {1} point {2} from ground (silent = {3})", objectLocalID, remoteClient.Name, AttachmentPt, silent); if (!Enabled) return; try { ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId); if (sp == null) { m_log.ErrorFormat( "[ATTACHMENTS MODULE]: Could not find presence for client {0} {1}", remoteClient.Name, remoteClient.AgentId); return; } // If we can't take it, we can't attach it! SceneObjectPart part = m_scene.GetSceneObjectPart(objectLocalID); if (part == null) return; if (!m_scene.Permissions.CanTakeObject(part.UUID, remoteClient.AgentId)) { remoteClient.SendAgentAlertMessage( "You don't have sufficient permissions to attach this object", false); return; } bool append = (AttachmentPt & 0x80) != 0; AttachmentPt &= 0x7f; // Calls attach with a Zero position if (AttachObject(sp, part.ParentGroup, AttachmentPt, false, true, append)) { if (DebugLevel > 0) m_log.Debug( "[ATTACHMENTS MODULE]: Saving avatar attachment. AgentID: " + remoteClient.AgentId + ", AttachmentPoint: " + AttachmentPt); // Save avatar attachment information m_scene.EventManager.TriggerOnAttach(objectLocalID, part.ParentGroup.FromItemID, remoteClient.AgentId); } } catch (Exception e) { m_log.ErrorFormat("[ATTACHMENTS MODULE]: exception upon Attach Object {0}{1}", e.Message, e.StackTrace); } } private void Client_OnObjectDetach(uint objectLocalID, IClientAPI remoteClient) { if (!Enabled) return; ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId); SceneObjectGroup group = m_scene.GetGroupByPrim(objectLocalID); if (sp != null && group != null && group.FromItemID != UUID.Zero) DetachSingleAttachmentToInv(sp, group); } private void Client_OnDetachAttachmentIntoInv(UUID itemID, IClientAPI remoteClient) { if (!Enabled) return; ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId); if (sp != null) { List<SceneObjectGroup> attachments = sp.GetAttachments(); foreach (SceneObjectGroup group in attachments) { if (group.FromItemID == itemID && group.FromItemID != UUID.Zero) { DetachSingleAttachmentToInv(sp, group); return; } } } } private void Client_OnObjectDrop(uint soLocalId, IClientAPI remoteClient) { if (!Enabled) return; ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId); if (sp != null) DetachSingleAttachmentToGround(sp, soLocalId); } #endregion } }
using AjaxControlToolkit.Design; using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Web.UI; using System.Web.UI.WebControls; namespace AjaxControlToolkit { /// <summary> /// An extender class which adds collapse/expand behavior to an ASP.NET Panel control. /// The panel that is extended can then be collapsed or expanded by the user of the page, which is handy /// for doing things like showing or hiding content or maximizing available space. /// </summary> [Designer(typeof(CollapsiblePanelExtenderDesigner))] [ClientScriptResource("Sys.Extended.UI.CollapsiblePanelBehavior", Constants.CollapsiblePanelName)] [RequiredScript(typeof(CommonToolkitScripts))] [RequiredScript(typeof(AnimationScripts))] [TargetControlType(typeof(Panel))] [DefaultProperty("CollapseControlID")] [ToolboxBitmap(typeof(ToolboxIcons.Accessor), Constants.CollapsiblePanelName + Constants.IconPostfix)] public class CollapsiblePanelExtender : ExtenderControlBase { public CollapsiblePanelExtender() { ClientStateValuesLoaded += new EventHandler(CollapsiblePanelExtender_ClientStateValuesLoaded); EnableClientState = true; } /// <summary> /// The server ID of the control to initiate the collapse of the target panel. The panel will /// collapse when this control fires its client side "onclick" event /// </summary> /// <remarks> /// If this value is the same as the value for "ExpandControlID", the CollapsiblePanel will /// toggle when this control is clicked /// </remarks> [IDReferenceProperty(typeof(WebControl))] [DefaultValue("")] [ExtenderControlProperty] [ClientPropertyName("collapseControlID")] public string CollapseControlID { get { return GetPropertyValue("CollapseControlID", String.Empty); } set { SetPropertyValue("CollapseControlID", value); } } /// <summary> /// The server ID of the control to initiate the expansion of the target panel. The panel will /// opening when this control fires its client side "onclick" event /// </summary> /// <remarks> /// If this value is the same as the value for "CollapseControlID", the CollapsiblePanel will /// toggle when this control is clicked /// </remarks> [IDReferenceProperty(typeof(WebControl))] [DefaultValue("")] [ExtenderControlProperty] [ClientPropertyName("expandControlID")] public string ExpandControlID { get { return GetPropertyValue("ExpandControlID", String.Empty); } set { SetPropertyValue("ExpandControlID", value); } } /// <summary> /// If true, and the panel is in its 'expanded' state, the panel will /// automatically collapse when the mouse pointer moves off of the panel. /// The default is false /// </summary> [DefaultValue(false)] [ExtenderControlProperty] [ClientPropertyName("autoCollapse")] public bool AutoCollapse { get { return GetPropertyValue("AutoCollapse", false); } set { SetPropertyValue("AutoCollapse", value); } } /// <summary> /// If true, and the panel is in its 'collapsed' state, the panel will /// automatically expand when the mouse pointer moves into the panel. /// The default is false /// </summary> [DefaultValue(false)] [ExtenderControlProperty] [ClientPropertyName("autoExpand")] public bool AutoExpand { get { return GetPropertyValue("AutoExpand", false); } set { SetPropertyValue("AutoExpand", value); } } /// <summary> /// The size of the panel when it is in it's collapsed state. To avoid flicker when your page /// initializes, set the initial height (or width) of your Panel control to match this value, and set the Collapsed property /// to 'true' /// </summary> /// <remarks> /// The default value is -1, which indicates that the CollapsiblePanel should initialize the CollapsedSize based on the /// initial size of the object /// </remarks> [DefaultValue(-1)] [ExtenderControlProperty] [ClientPropertyName("collapsedSize")] public int CollapsedSize { get { return GetPropertyValue("CollapseHeight", -1); } set { SetPropertyValue("CollapseHeight", value); } } /// <summary> /// The size of the panel when it is in it's opened state. To avoid flicker when your page /// initializes, set the initial width of your Panel control to match this value, and set the Collapsed property /// to 'false' /// </summary> /// <remarks> /// The default value is -1, which indicates that the CollapsiblePanel should initialize the ExpandedSize based on the /// parent div offsetheight if aligned vertically and parentdiv offsetwidth if aligned horizonatally /// </remarks> [DefaultValue(-1)] [ExtenderControlProperty] public int ExpandedSize { get { return GetPropertyValue("ExpandedSize", -1); } set { SetPropertyValue("ExpandedSize", value); } } /// <summary> /// Determines whether the contents of the panel should be scrolled or clipped if they do not fit into /// the expanded size. /// The default is false /// </summary> [DefaultValue(false)] [ExtenderControlProperty] [ClientPropertyName("scrollContents")] public bool ScrollContents { get { return GetPropertyValue("ScrollContents", false); } set { SetPropertyValue("ScrollContents", value); } } /// <summary> /// Determines whether the CollapsiblePanelBehavior should suppress the click operations of the controls /// referenced in CollapseControlID and/or ExpandControlID. /// </summary> /// <remarks> /// By default, this value is false, except for anchor ("A") tags /// </remarks> [DefaultValue(false)] [ExtenderControlProperty] [ClientPropertyName("suppressPostBack")] public bool SuppressPostBack { get { return GetPropertyValue("SuppressPostBack", false); } set { SetPropertyValue("SuppressPostBack", value); } } /// <summary> /// Signals the initial collapsed state of the control. Note this will not cause /// an expanded control to collapse at initialization, but rather tells the extender /// what the initial state of the Panel control is. /// The default is false /// </summary> [DefaultValue(false)] [ExtenderControlProperty] [ClientPropertyName("collapsed")] public bool Collapsed { get { return GetPropertyValue("Collapsed", false); } set { SetPropertyValue("Collapsed", value); } } /// <summary> /// The text to display in the collapsed state. When the panel is collapsed, /// the internal contents (anything between the start and ending tags) of the control referenced by /// the TextLabelID property will be replaced with this text. This collapsed text is also used /// as the alternate text of the image if ImageControlID is set /// </summary> [DefaultValue("")] [ExtenderControlProperty] [ClientPropertyName("collapsedText")] public string CollapsedText { get { return GetPropertyValue("CollapsedText", String.Empty); } set { SetPropertyValue("CollapsedText", value); } } /// <summary> /// The text to display in the expanded state. When the panel is expanded, /// the internal contents (anything between the start and ending tags) of the control referenced by /// the TextLabelID property will be replaced with this text. This expanded text is also used /// as the alternate text of the image if ImageControlID is set /// </summary> [DefaultValue("")] [ExtenderControlProperty] [ClientPropertyName("expandedText")] public string ExpandedText { get { return GetPropertyValue("ExpandedText", String.Empty); } set { SetPropertyValue("ExpandedText", value); } } /// <summary> /// The ID of a label control to display the current state of the Panel. When the collapsed state of the /// panel changes, the entire HTML contents (anything between the start and ending tags of the label) will be replaced /// with the status text /// </summary> [IDReferenceProperty(typeof(Label))] [DefaultValue("")] [ExtenderControlProperty] [ClientPropertyName("textLabelID")] public string TextLabelID { get { return GetPropertyValue("TextLabelID", String.Empty); } set { SetPropertyValue("TextLabelID", value); } } /// <summary> /// Image to be displayed when the Panel is expanded and the ImageControlID is set /// </summary> [DefaultValue("")] [UrlProperty] [ExtenderControlProperty] [ClientPropertyName("expandedImage")] public string ExpandedImage { get { return GetPropertyValue("ExpandedImage", String.Empty); } set { SetPropertyValue("ExpandedImage", value); } } /// <summary> /// Image to be displayed when the Panel is collapsed and the ImageControlID is set /// </summary> [DefaultValue("")] [UrlProperty] [ExtenderControlProperty] [ClientPropertyName("collapsedImage")] public string CollapsedImage { get { return GetPropertyValue("CollapsedImage", String.Empty); } set { SetPropertyValue("CollapsedImage", value); } } /// <summary> /// The ID of an image control to display the current state of the Panel. When the collapsed state of the /// panel changes, the image source will be changed from the ExpandedImage to the CollapsedImage. We also /// use the ExpandedText and CollapsedText as the image's alternate text if they are provided /// </summary> [IDReferenceProperty(typeof(System.Web.UI.WebControls.Image))] [DefaultValue("")] [ExtenderControlProperty] [ClientPropertyName("imageControlID")] public string ImageControlID { get { return GetPropertyValue("ImageControlID", String.Empty); } set { SetPropertyValue("ImageControlID", value); } } /// <summary> /// The dimension to use for collapsing and expanding - vertical or horizontal /// </summary> [DefaultValue(CollapsiblePanelExpandDirection.Vertical)] [ExtenderControlProperty] [ClientPropertyName("expandDirection")] public CollapsiblePanelExpandDirection ExpandDirection { get { return GetPropertyValue("ExpandDirection", CollapsiblePanelExpandDirection.Vertical); } set { SetPropertyValue("ExpandDirection", value); } } [EditorBrowsable(EditorBrowsableState.Never)] public override void EnsureValid() { base.EnsureValid(); if((ExpandedText != null || CollapsedText != null) && TextLabelID == null) throw new ArgumentException("If CollapsedText or ExpandedText is set, TextLabelID must also be set."); } void CollapsiblePanelExtender_ClientStateValuesLoaded(object sender, EventArgs e) { var ctrl = this.FindControl(this.TargetControlID) as WebControl; if(ctrl != null) { if(!String.IsNullOrEmpty(base.ClientState)) { var collapsed = bool.Parse(base.ClientState); if(collapsed) ctrl.Style["display"] = "none"; else ctrl.Style["display"] = String.Empty; } } } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Configuration.Environment.Abstractions { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; using ZeligIR = Microsoft.Zelig.CodeGeneration.IR; public partial class ArmPlatform { [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARM_SetRegister" )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARM_SetRegisterFP32" )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARM_SetRegisterFP64" )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARM_SetSystemRegister" )] private void Handle_ProcessorARM_SetRegister( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ZeligIR.CallOperator op = nc.GetOperatorAndThrowIfNotCall(); ZeligIR.ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; uint encoding = nc.ExtractConstantUIntParameter( op, 1 ); var regDesc = nc.TypeSystem.PlatformAbstraction.GetRegisterForEncoding( encoding ); if(regDesc == null) { // // We cannot fail, because code for different processors could be mixed in the same assembly and we don't know until later. // //// throw TypeConsistencyErrorException.Create( "Attempt to set non-existing register: {0}", encoding ); op.Delete(); } else { var opNew = ZeligIR.SingleAssignmentOperator.New( op.DebugInfo, cfg.AllocatePhysicalRegister( regDesc ), op.ThirdArgument ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.Default ); opNew.AddAnnotation( ZeligIR.DontRemoveAnnotation.Create( nc.TypeSystem ) ); } nc.MarkAsModified(); } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARM_GetRegister" )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARM_GetRegisterFP32" )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARM_GetRegisterFP64" )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARM_GetSystemRegister" )] private void Handle_ProcessorARM_GetRegister( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ZeligIR.CallOperator op = nc.GetOperatorAndThrowIfNotCall(); ZeligIR.ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; uint encoding = nc.ExtractConstantUIntParameter( op, 1 ); var lhs = op.FirstResult; var regDesc = nc.TypeSystem.PlatformAbstraction.GetRegisterForEncoding( encoding ); if(regDesc == null) { // // We cannot fail, because code for different processors could be mixed in the same assembly and we don't know until later. // //// throw TypeConsistencyErrorException.Create( "Attempt to get non-existing register: {0}", encoding ); var opNew = ZeligIR.SingleAssignmentOperator.New( op.DebugInfo, lhs, nc.TypeSystem.CreateConstant( lhs.Type, 0 ) ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.Default ); } else { var reg = cfg.AllocatePhysicalRegister( regDesc ); ZeligIR.Operator opNew; // // The PC processor reads 8 bytes past the current value, let's adjust it. // if(regDesc.Encoding == TargetModel.ArmProcessor.EncodingDefinition.c_register_pc) { opNew = ZeligIR.BinaryOperator.New( op.DebugInfo, ZeligIR.BinaryOperator.ALU.SUB, false, false, lhs, reg, nc.TypeSystem.CreateConstant( TargetModel.ArmProcessor.EncodingDefinition.c_PC_offset ) ); } else { opNew = ZeligIR.SingleAssignmentOperator.New( op.DebugInfo, lhs, reg ); } op.AddAnnotation( ZeligIR.PreInvalidationAnnotation.Create( nc.TypeSystem, reg ) ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.Default ); } nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARM_SetStatusRegister" )] private void Handle_ProcessorARM_SetStatusRegister( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { Handle_ProcessorARM_SetStatusRegister( nc, false ); } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARM_SetSavedStatusRegister" )] private void Handle_ProcessorARM_SetSavedStatusRegister( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { Handle_ProcessorARM_SetStatusRegister( nc, true ); } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARM_GetStatusRegister" )] private void Handle_ProcessorARM_GetStatusRegister( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { Handle_ProcessorARM_GetStatusRegister( nc, false ); } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARM_GetSavedStatusRegister" )] private void Handle_ProcessorARM_GetSavedStatusRegister( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { Handle_ProcessorARM_GetStatusRegister( nc, true ); } private void Handle_ProcessorARM_SetStatusRegister( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc , bool fUseSPSR ) { ZeligIR.CallOperator op = nc.GetOperatorAndThrowIfNotCall(); ZeligIR.Expression exVal = op.ThirdArgument; uint fields = nc.ExtractConstantUIntParameter( op, 1 ); ZeligIR.Operator opNew = ARM.SetStatusRegisterOperator.New( op.DebugInfo, fUseSPSR, fields, exVal ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } private void Handle_ProcessorARM_GetStatusRegister( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc , bool fUseSPSR ) { ZeligIR.CallOperator op = nc.GetOperatorAndThrowIfNotCall(); ZeligIR.Operator opNew = ARM.GetStatusRegisterOperator.New( op.DebugInfo, fUseSPSR, op.FirstResult ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARM_MoveToCoprocessor" )] private void Handle_ProcessorARM_MoveToCoprocessor( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ZeligIR.CallOperator op = nc.GetOperatorAndThrowIfNotCall(); uint CpNum = nc.ExtractConstantUIntParameter( op, 1 ); uint Op1 = nc.ExtractConstantUIntParameter( op, 2 ); uint CRn = nc.ExtractConstantUIntParameter( op, 3 ); uint CRm = nc.ExtractConstantUIntParameter( op, 4 ); uint Op2 = nc.ExtractConstantUIntParameter( op, 5 ); ZeligIR.Operator opNew = ARM.MoveToCoprocessor.New( op.DebugInfo, CpNum, Op1, CRn, CRm, Op2, op.Arguments[6] ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARM_MoveFromCoprocessor" )] private void Handle_ProcessorARM_MoveFromCoprocessor( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ZeligIR.CallOperator op = nc.GetOperatorAndThrowIfNotCall(); uint CpNum = nc.ExtractConstantUIntParameter( op, 1 ); uint Op1 = nc.ExtractConstantUIntParameter( op, 2 ); uint CRn = nc.ExtractConstantUIntParameter( op, 3 ); uint CRm = nc.ExtractConstantUIntParameter( op, 4 ); uint Op2 = nc.ExtractConstantUIntParameter( op, 5 ); ZeligIR.Operator opNew = ARM.MoveFromCoprocessor.New( op.DebugInfo, CpNum, Op1, CRn, CRm, Op2, op.FirstResult ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARM_Breakpoint" )] //////[ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARMv6_Breakpoint" )] //////[ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "ProcessorARMv7_Breakpoint" )] private void Handle_ProcessorARM_Breakpoint( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ZeligIR.CallOperator op = nc.GetOperatorAndThrowIfNotCall(); uint Value = nc.ExtractConstantUIntParameter( op, 1 ); ZeligIR.Operator opNew = ARM.BreakpointOperator.New( op.DebugInfo, Value ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "Microsoft_Zelig_ProcessorARMv4_MethodWrapperHelpers_ScratchedRegisters" )] private void Handle_ProcessorARM_MethodWrapperHelpers_ScratchedRegisters( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ZeligIR.CallOperator op = nc.GetOperatorAndThrowIfNotCall(); var cc = nc.TypeSystem.CallingConvention; var pa = nc.TypeSystem.PlatformAbstraction; uint mask = 0; foreach(var reg in pa.GetRegisters()) { if(reg.InIntegerRegisterFile && cc.ShouldSaveRegister( reg ) == false) { mask |= 1u << (int)(reg.Encoding - EncodingDefinition.c_register_r0); } } var opNew = ZeligIR.SingleAssignmentOperator.New( op.DebugInfo, op.FirstResult, nc.TypeSystem.CreateConstant( mask ) ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "Microsoft_Zelig_ProcessorARMv4_MethodWrapperHelpers_PushRegisters" )] private void Handle_ProcessorARM_MethodWrapperHelpers_PushRegisters( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ZeligIR.CallOperator op = nc.GetOperatorAndThrowIfNotCall(); if(nc.IsParameterConstant( op, 1 ) && nc.IsParameterConstant( op, 2 ) && nc.IsParameterConstant( op, 3 ) && nc.IsParameterConstant( op, 4 ) ) { uint indexRegister = nc.ExtractConstantUIntParameter( op, 1 ); bool fWriteBackIndexRegister = nc.ExtractConstantBoolParameter( op, 2 ); bool fAddComputedRegisters = nc.ExtractConstantBoolParameter( op, 3 ); uint registerMask = nc.ExtractConstantUIntParameter( op, 4 ); var exReg = nc.GetVariableForRegisterEncoding( indexRegister ); var opNew = ARM.MoveIntegerRegistersOperator.New( op.DebugInfo, false, fWriteBackIndexRegister, fAddComputedRegisters, false, registerMask, exReg ); opNew.AddAnnotation( ZeligIR.PreInvalidationAnnotation.Create( nc.TypeSystem, exReg ) ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "Microsoft_Zelig_ProcessorARMv4_MethodWrapperHelpers_PopRegisters" )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "Microsoft_Zelig_ProcessorARMv7_MethodWrapperHelpers_PopRegisters" )] private void Handle_ProcessorARM_MethodWrapperHelpers_PopRegisters( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ZeligIR.CallOperator op = nc.GetOperatorAndThrowIfNotCall(); if(nc.IsParameterConstant( op, 1 ) && nc.IsParameterConstant( op, 2 ) && nc.IsParameterConstant( op, 3 ) && nc.IsParameterConstant( op, 4 ) && nc.IsParameterConstant( op, 5 ) ) { uint indexRegister = nc.ExtractConstantUIntParameter( op, 1 ); bool fWriteBackIndexRegister = nc.ExtractConstantBoolParameter( op, 2 ); bool fAddComputedRegisters = nc.ExtractConstantBoolParameter( op, 3 ); bool fRestoreSPSR = nc.ExtractConstantBoolParameter( op, 4 ); uint registerMask = nc.ExtractConstantUIntParameter( op, 5 ); var exReg = nc.GetVariableForRegisterEncoding( indexRegister ); var opNew = ARM.MoveIntegerRegistersOperator.New( op.DebugInfo, true, fWriteBackIndexRegister, fAddComputedRegisters, fRestoreSPSR, registerMask, exReg ); opNew.AddAnnotation( ZeligIR.PreInvalidationAnnotation.Create( nc.TypeSystem, exReg ) ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "Microsoft_Zelig_ProcessorARMv5_VFP_MethodWrapperHelpers_PushFpRegisters" )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "Microsoft_Zelig_ProcessorARMv7_VFP_MethodWrapperHelpers_PushFpRegisters" )] private void Handle_ProcessorARM_MethodWrapperHelpers_PushFpRegisters( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { Handle_ProcessorARM_MethodWrapperHelpers_MoveFpRegisters( nc, false ); } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "Microsoft_Zelig_ProcessorARMv5_VFP_MethodWrapperHelpers_PopFpRegisters" )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "Microsoft_Zelig_ProcessorARMv7_VFP_MethodWrapperHelpers_PopFpRegisters" )] private void Handle_ProcessorARM_MethodWrapperHelpers_PopFpRegisters( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { Handle_ProcessorARM_MethodWrapperHelpers_MoveFpRegisters( nc, true ); } private void Handle_ProcessorARM_MethodWrapperHelpers_MoveFpRegisters( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc , bool fLoad ) { ZeligIR.CallOperator op = nc.GetOperatorAndThrowIfNotCall(); if(nc.IsParameterConstant( op, 1 ) && nc.IsParameterConstant( op, 2 ) && nc.IsParameterConstant( op, 3 ) && nc.IsParameterConstant( op, 4 ) && nc.IsParameterConstant( op, 5 ) ) { uint indexRegister = nc.ExtractConstantUIntParameter( op, 1 ); bool fWriteBackIndexRegister = nc.ExtractConstantBoolParameter( op, 2 ); bool fAddComputedRegisters = nc.ExtractConstantBoolParameter( op, 3 ); uint registerLow = nc.ExtractConstantUIntParameter( op, 4 ); uint registerHigh = nc.ExtractConstantUIntParameter( op, 5 ); var exReg = nc.GetVariableForRegisterEncoding( indexRegister ); var opNew = ARM.MoveFloatingPointRegistersOperator.New( op.DebugInfo, fLoad, fWriteBackIndexRegister, fAddComputedRegisters, registerLow, registerHigh, exReg ); opNew.AddAnnotation( ZeligIR.PreInvalidationAnnotation.Create( nc.TypeSystem, exReg ) ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "Microsoft_Zelig_ProcessorARMv4_MethodWrapperHelpers_PushStackFrame" )] private void Handle_ProcessorARM_MethodWrapperHelpers_PushStackFrame( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { Handle_ProcessorARM_MethodWrapperHelpers_MoveStackFrame( nc, true ); } [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "Microsoft_Zelig_ProcessorARMv4_MethodWrapperHelpers_PopStackFrame" )] private void Handle_ProcessorARM_MethodWrapperHelpers_PopStackFrame( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { Handle_ProcessorARM_MethodWrapperHelpers_MoveStackFrame( nc, false ); } private void Handle_ProcessorARM_MethodWrapperHelpers_MoveStackFrame( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc , bool fPush ) { ZeligIR.CallOperator op = nc.GetOperatorAndThrowIfNotCall(); var opNew = ARM.MoveStackPointerOperator.New( op.DebugInfo, fPush ); op.SubstituteWithOperator( opNew, ZeligIR.Operator.SubstitutionFlags.Default ); nc.MarkAsModified(); } //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// [ZeligIR.CompilationSteps.PhaseFilter( typeof(ZeligIR.CompilationSteps.Phases.HighLevelTransformations) )] [ZeligIR.CompilationSteps.CallToWellKnownMethodHandler( "Solo_DSP_MatrixMultiply__MultiplyAndAccumulate" )] private void Handle_Solo_DSP_MatrixMultiply__MultiplyAndAccumulate( ZeligIR.CompilationSteps.PhaseExecution.NotificationContext nc ) { ZeligIR.CallOperator op = nc.GetOperatorAndThrowIfNotCall(); ZeligIR.ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG; ZeligIR.TypeSystemForCodeTransformation ts = nc.TypeSystem; ZeligIR.VariableExpression varRes = op.FirstResult; ZeligIR.Expression exAbase = op.SecondArgument; ZeligIR.Expression exBbase = op.ThirdArgument; ZeligIR.Expression exN = op.FourthArgument; int vectorSize = nc.ExtractConstantIntParameter( op, 4 ); if(vectorSize < 1 || vectorSize > 8) { throw TypeConsistencyErrorException.Create( "Invalid vector size for {0}: {1}", op, vectorSize ); } //--// var wkt = ts.WellKnownTypes; var tdValue = varRes.Type; var tdPtr = ts.CreateUnmanagedPointerToType( tdValue ); CHECKS.ASSERT( tdValue == wkt.System_Single, "Invalid result type, expecting 'float', got '{0}'", tdValue ); var debugInfo = op.DebugInfo; var pa = ts.PlatformAbstraction; ZeligIR.NormalBasicBlock bbEntry = new ZeligIR.NormalBasicBlock( cfg ); ZeligIR.NormalBasicBlock bbExit = new ZeligIR.NormalBasicBlock( cfg ); ZeligIR.NormalBasicBlock bbLoopHeader = new ZeligIR.NormalBasicBlock( cfg ); ZeligIR.NormalBasicBlock bbLoopBody = new ZeligIR.NormalBasicBlock( cfg ); ZeligIR.VariableExpression varAptr = cfg.AllocateTypedPhysicalRegister( tdPtr, pa.GetRegisterForEncoding( TargetModel.ArmProcessor.EncodingDefinition.c_register_r4 ), null, null, 0 ); ZeligIR.VariableExpression varBptr = cfg.AllocateTypedPhysicalRegister( tdPtr, pa.GetRegisterForEncoding( TargetModel.ArmProcessor.EncodingDefinition.c_register_r5 ), null, null, 0 ); ZeligIR.VariableExpression varAend = cfg.AllocateTypedPhysicalRegister( tdPtr, pa.GetRegisterForEncoding( TargetModel.ArmProcessor.EncodingDefinition.c_register_r6 ), null, null, 0 ); ZeligIR.VariableExpression varSize = cfg.AllocateTemporary ( wkt.System_Int32, null ); var regsLeftBankBase = GenerateVector( cfg, pa, vectorSize, TargetModel.ArmProcessor.EncodingDefinition_VFP.c_register_s8 ); var regsRightBankBase = GenerateVector( cfg, pa, vectorSize, TargetModel.ArmProcessor.EncodingDefinition_VFP.c_register_s16 ); var regsResultBankBase = GenerateVector( cfg, pa, vectorSize, TargetModel.ArmProcessor.EncodingDefinition_VFP.c_register_s24 ); //--// // // Entry: // float* Aptr = Abase; // float* Bptr = Bbase; // float* Aend = &Aptr[N]; // // <Initialize Vector Processor with vector length = VectorSize> // <Zero out the intermediate result registers> // // goto LoopHeader; // { var vecOp1 = ARM.VectorHack_Prepare.New( debugInfo, vectorSize, regsResultBankBase[0].RegisterDescriptor ); bbEntry.AddOperator( ZeligIR.SingleAssignmentOperator.New( debugInfo, varAptr, exAbase ) ); bbEntry.AddOperator( ZeligIR.SingleAssignmentOperator.New( debugInfo, varBptr, exBbase ) ); bbEntry.AddOperator( ZeligIR.BinaryOperator.New( debugInfo, ZeligIR.BinaryOperator.ALU.MUL, false, false, varSize, exN, ts.CreateConstant( (int)tdValue.SizeOfHoldingVariable ) ) ); bbEntry.AddOperator( ZeligIR.BinaryOperator.New( debugInfo, ZeligIR.BinaryOperator.ALU.ADD, false, false, varAend, varAptr, varSize ) ); bbEntry.AddOperator( ARM.VectorHack_Initialize.New( debugInfo, vectorSize ) ); bbEntry.AddOperator( vecOp1 ); AddSideEffects( ts, vecOp1, regsResultBankBase ); bbEntry.FlowControl = ZeligIR.UnconditionalControlOperator.New( debugInfo, bbLoopHeader ); } //--// // // LoopHeader: // if Aptr < Aend goto LoopBody else goto Exit; // { bbLoopHeader.FlowControl = ZeligIR.CompareConditionalControlOperator.New( debugInfo, ZeligIR.CompareAndSetOperator.ActionCondition.LT, false, varAptr, varAend, bbExit, bbLoopBody ); } //--// // // LoopBody: // <Load Left Data using R4> // <Load Right Data using R5> // <Multiply And Accumulate S24 = S8 * S12> // // goto LoopHeader; // { var vecOp1 = ARM.VectorHack_LoadData .New( debugInfo, vectorSize, regsLeftBankBase [0].RegisterDescriptor, varAptr, varAptr ); var vecOp2 = ARM.VectorHack_LoadData .New( debugInfo, vectorSize, regsRightBankBase[0].RegisterDescriptor, varBptr, varBptr ); var vecOp3 = ARM.VectorHack_MultiplyAndAccumulate.New( debugInfo, vectorSize, regsLeftBankBase [0].RegisterDescriptor, regsRightBankBase[0].RegisterDescriptor, regsResultBankBase[0].RegisterDescriptor ); bbLoopBody.AddOperator( vecOp1 ); AddSideEffects( ts, vecOp1, regsLeftBankBase ); bbLoopBody.AddOperator( vecOp2 ); AddSideEffects( ts, vecOp2, regsRightBankBase ); bbLoopBody.AddOperator( vecOp3 ); AddSideEffects( ts, vecOp3, regsLeftBankBase ); AddSideEffects( ts, vecOp3, regsRightBankBase ); AddSideEffects( ts, vecOp3, regsResultBankBase ); bbLoopBody.FlowControl = ZeligIR.UnconditionalControlOperator.New( debugInfo, bbLoopHeader ); } // // Exit: // <Finalize the vector sums into the result> // <Cleanup the Vector Processor> // { var vecOp1 = ARM.VectorHack_Finalize.New( debugInfo, vectorSize, regsResultBankBase[0].RegisterDescriptor, varRes ); bbExit.AddOperator( ARM.VectorHack_Cleanup.New( debugInfo, vectorSize ) ); bbExit.AddOperator( vecOp1 ); AddSideEffects( ts, vecOp1, regsResultBankBase ); } //--// op.SubstituteWithSubGraph( bbEntry, bbExit ); nc.MarkAsModified(); } private ZeligIR.PhysicalRegisterExpression[] GenerateVector( ZeligIR.ControlFlowGraphStateForCodeTransformation cfg , ZeligIR.Abstractions.Platform pa , int vectorSize , uint encoding ) { var res = new ZeligIR.PhysicalRegisterExpression[vectorSize]; for(int i = 0; i < vectorSize; i++) { res[i] = cfg.AllocatePhysicalRegister( pa.GetRegisterForEncoding( encoding++ ) ); } return res; } private void AddSideEffects( ZeligIR.TypeSystemForCodeTransformation ts , ZeligIR.Operator op , ZeligIR.PhysicalRegisterExpression[] regs ) { foreach(var reg in regs) { op.AddAnnotation( ZeligIR.PostInvalidationAnnotation.Create( ts, reg ) ); } } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Collections.Generic; using Dbg = System.Management.Automation.Diagnostics; using System.Management.Automation.Host; using System.Management.Automation.Internal; using System.Management.Automation.Remoting; using System.Collections.ObjectModel; namespace System.Management.Automation.Runspaces.Internal { /// <summary> /// PowerShell client side proxy base which handles invocation /// of powershell on a remote machine /// </summary> internal class ClientRemotePowerShell : IDisposable { #region Tracer [TraceSourceAttribute("CRPS", "ClientRemotePowerShell")] private static PSTraceSource s_tracer = PSTraceSource.GetTracer("CRPS", "ClientRemotePowerShellBase"); #endregion Tracer #region Constructors /// <summary> /// Constructor which creates a client remote powershell /// </summary> /// <param name="shell">powershell instance </param> /// <param name="runspacePool">The runspace pool associated with /// this shell</param> internal ClientRemotePowerShell(PowerShell shell, RemoteRunspacePoolInternal runspacePool) { this.shell = shell; clientRunspacePoolId = runspacePool.InstanceId; this.runspacePool = runspacePool; // retrieve the computer name from the runspacepool // information so that it can be used in adding // warning to host messages computerName = runspacePool.ConnectionInfo.ComputerName; } #endregion Constructors #region Internal Methods/Properties /// <summary> /// Instance Id associated with this /// client remote powershell /// </summary> internal Guid InstanceId { get { return PowerShell.InstanceId; } } /// <summary> /// PowerShell associated with this ClientRemotePowerShell /// </summary> internal PowerShell PowerShell { get { return shell; } } /// <summary> /// Set the state information of the client powershell /// </summary> /// <param name="stateInfo">state information to set</param> internal void SetStateInfo(PSInvocationStateInfo stateInfo) { shell.SetStateChanged(stateInfo); } /// <summary> /// whether input is available when this object is created /// </summary> internal bool NoInput { get { return noInput; } } /// <summary> /// Input stream associated with this object /// </summary> internal ObjectStreamBase InputStream { get { return inputstream; } set { inputstream = value; if (inputstream != null && (inputstream.IsOpen || inputstream.Count > 0)) { noInput = false; } else { noInput = true; } } } /// <summary> /// Output stream associated with this object /// </summary> internal ObjectStreamBase OutputStream { get { return outputstream; } set { outputstream = value; } } /// <summary> /// data structure handler object /// </summary> internal ClientPowerShellDataStructureHandler DataStructureHandler { get { return dataStructureHandler; } } /// <summary> /// Invocation settings associated with this /// ClientRemotePowerShell /// </summary> internal PSInvocationSettings Settings { get { return settings; } } /// <summary> /// Close the output, error and other collections /// associated with the shell, so that the /// enumerator does not block /// </summary> internal void UnblockCollections() { shell.ClearRemotePowerShell(); outputstream.Close(); errorstream.Close(); if (null != inputstream) { inputstream.Close(); } } /// <summary> /// Stop the remote powershell asynchronously /// </summary> /// <remarks>This method will be called from /// within the lock on PowerShell. Hence no need /// to lock</remarks> internal void StopAsync() { // If we are in robust connection retry mode then auto-disconnect this command // rather than try to stop it. PSConnectionRetryStatus retryStatus = _connectionRetryStatus; if ((retryStatus == PSConnectionRetryStatus.NetworkFailureDetected || retryStatus == PSConnectionRetryStatus.ConnectionRetryAttempt) && this.runspacePool.RunspacePoolStateInfo.State == RunspacePoolState.Opened) { // While in robust connection retry mode, this call forces robust connections // to abort retries and go directly to auto-disconnect. this.runspacePool.BeginDisconnect(null, null); return; } // powershell CoreStop would have handled cases // for NotStarted, Stopping and already Stopped // so at this point, there is no need to make any // check. The message simply needs to be sent // across to the server stopCalled = true; dataStructureHandler.SendStopPowerShellMessage(); } /// <summary> /// /// </summary> internal void SendInput() { dataStructureHandler.SendInput(this.inputstream); } /// <summary> /// This event is raised, when a host call is for a remote pipeline /// which this remote powershell wraps /// </summary> internal event EventHandler<RemoteDataEventArgs<RemoteHostCall>> HostCallReceived; /// <summary> /// Initialize the client remote powershell instance /// </summary> /// <param name="inputstream">input for execution</param> /// <param name="errorstream">error stream to which /// data needs to be written to</param> /// <param name="informationalBuffers">informational buffers /// which will hold debug, verbose and warning messages</param> /// <param name="settings">settings based on which this powershell /// needs to be executed</param> /// <param name="outputstream">output stream to which data /// needs to be written to</param> internal void Initialize( ObjectStreamBase inputstream, ObjectStreamBase outputstream, ObjectStreamBase errorstream, PSInformationalBuffers informationalBuffers, PSInvocationSettings settings) { initialized = true; this.informationalBuffers = informationalBuffers; InputStream = inputstream; this.errorstream = errorstream; this.outputstream = outputstream; this.settings = settings; if (settings == null || settings.Host == null) { hostToUse = runspacePool.Host; } else { hostToUse = settings.Host; } dataStructureHandler = runspacePool.DataStructureHandler.CreatePowerShellDataStructureHandler(this); // register for events from the data structure handler dataStructureHandler.InvocationStateInfoReceived += new EventHandler<RemoteDataEventArgs<PSInvocationStateInfo>>(HandleInvocationStateInfoReceived); dataStructureHandler.OutputReceived += new EventHandler<RemoteDataEventArgs<object>>(HandleOutputReceived); dataStructureHandler.ErrorReceived += new EventHandler<RemoteDataEventArgs<ErrorRecord>>(HandleErrorReceived); dataStructureHandler.InformationalMessageReceived += new EventHandler<RemoteDataEventArgs<InformationalMessage>>(HandleInformationalMessageReceived); dataStructureHandler.HostCallReceived += new EventHandler<RemoteDataEventArgs<RemoteHostCall>>(HandleHostCallReceived); dataStructureHandler.ClosedNotificationFromRunspacePool += new EventHandler<RemoteDataEventArgs<Exception>>(HandleCloseNotificationFromRunspacePool); dataStructureHandler.BrokenNotificationFromRunspacePool += new EventHandler<RemoteDataEventArgs<Exception>>(HandleBrokenNotificationFromRunspacePool); dataStructureHandler.ConnectCompleted += new EventHandler<RemoteDataEventArgs<Exception>>(HandleConnectCompleted); dataStructureHandler.ReconnectCompleted += new EventHandler<RemoteDataEventArgs<Exception>>(HandleConnectCompleted); dataStructureHandler.RobustConnectionNotification += new EventHandler<ConnectionStatusEventArgs>(HandleRobustConnectionNotification); dataStructureHandler.CloseCompleted += new EventHandler<EventArgs>(HandleCloseCompleted); } /// <summary> /// Do any clean up operation per initialization here /// </summary> internal void Clear() { initialized = false; } /// <summary> /// If this client remote powershell has been initialized /// </summary> internal bool Initialized { get { return initialized; } } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="eventArgs"></param> internal static void ExitHandler(object sender, RemoteDataEventArgs<RemoteHostCall> eventArgs) { RemoteHostCall hostcall = eventArgs.Data; if (hostcall.IsSetShouldExitOrPopRunspace) { return; } // use the method from the RemotePowerShell to indeed execute this call ClientRemotePowerShell remotePowerShell = (ClientRemotePowerShell)sender; remotePowerShell.ExecuteHostCall(hostcall); } /// <summary> /// Attempts to reconnect or connect to a running command on a remote server, /// which will resume events and data collection from the server. /// If connectCmdInfo parameter is null then a reconnection is attempted and /// it is assumed that the current client state is unchanged since disconnection. /// If connectCmdInfo parameter is non-null then a connection is attempted to /// the specified remote running command. /// This is an asynchronous call and results will be reported in the ReconnectCompleted /// or the ConnectCompleted call back as appropriate. /// </summary> /// <param name="connectCmdInfo">ConnectCommandInfo specifying remote command.</param> internal void ConnectAsync(ConnectCommandInfo connectCmdInfo) { if (connectCmdInfo == null) { // Attempt to do a reconnect with the current PSRP client state. this.dataStructureHandler.ReconnectAsync(); } else { // First add this command DS handler to the remote runspace pool list. Dbg.Assert(this.shell.RunspacePool != null, "Invalid runspace pool for this powershell object."); this.shell.RunspacePool.RemoteRunspacePoolInternal.AddRemotePowerShellDSHandler( this.InstanceId, this.dataStructureHandler); // Now do the asynchronous connect. this.dataStructureHandler.ConnectAsync(); } } /// <summary> /// This event is fired when this PowerShell object receives a robust connection /// notification from the transport. /// </summary> internal event EventHandler<PSConnectionRetryStatusEventArgs> RCConnectionNotification; /// <summary> /// Current remote connection retry status. /// </summary> internal PSConnectionRetryStatus ConnectionRetryStatus { get { return _connectionRetryStatus; } } #endregion Internal Methods/Properties #region Private Methods /// <summary> /// An error record is received from the powershell at the /// server side. It is added to the error collection of the /// client powershell /// </summary> /// <param name="sender">sender of this event, unused</param> /// <param name="eventArgs">arguments describing this event</param> private void HandleErrorReceived(object sender, RemoteDataEventArgs<ErrorRecord> eventArgs) { using (s_tracer.TraceEventHandlers()) { shell.SetHadErrors(true); errorstream.Write(eventArgs.Data); } } /// <summary> /// An output object is received from the powershell at the /// server side. It is added to the output collection of the /// client powershell /// </summary> /// <param name="sender">sender of this event, unused</param> /// <param name="eventArgs">arguments describing this event</param> private void HandleOutputReceived(object sender, RemoteDataEventArgs<object> eventArgs) { using (s_tracer.TraceEventHandlers()) { object data = eventArgs.Data; try { outputstream.Write(data); } catch (PSInvalidCastException e) { shell.SetStateChanged(new PSInvocationStateInfo(PSInvocationState.Failed, e)); } } } /// <summary> /// The invocation state of the server powershell has changed. /// The state of the client powershell is reflected accordingly /// </summary> /// <param name="sender">sender of this event, unused</param> /// <param name="eventArgs">arguments describing this event</param> private void HandleInvocationStateInfoReceived(object sender, RemoteDataEventArgs<PSInvocationStateInfo> eventArgs) { using (s_tracer.TraceEventHandlers()) { PSInvocationStateInfo stateInfo = eventArgs.Data; // we should not receive any transient state from // the server Dbg.Assert(!(stateInfo.State == PSInvocationState.Running || stateInfo.State == PSInvocationState.Stopping), "Transient states should not be received from the server"); if (stateInfo.State == PSInvocationState.Disconnected) { SetStateInfo(stateInfo); } else if (stateInfo.State == PSInvocationState.Stopped || stateInfo.State == PSInvocationState.Failed || stateInfo.State == PSInvocationState.Completed) { // Special case for failure error due to ErrorCode==-2144108453 (no ShellId found). // In this case terminate session since there is no longer a shell to communicate // with. bool terminateSession = false; if (stateInfo.State == PSInvocationState.Failed) { PSRemotingTransportException remotingTransportException = stateInfo.Reason as PSRemotingTransportException; terminateSession = (remotingTransportException != null) && (remotingTransportException.ErrorCode == System.Management.Automation.Remoting.Client.WSManNativeApi.ERROR_WSMAN_TARGETSESSION_DOESNOTEXIST); } // if state is completed or failed or stopped, // then the collections need to be closed as // well, else the enumerator will block UnblockCollections(); if (stopCalled || terminateSession) { // Reset stop called flag. stopCalled = false; // if a Stop method has been called, then powershell // would have already raised a Stopping event, after // which only a Stopped should be raised _stateInfoQueue.Enqueue(new PSInvocationStateInfo(PSInvocationState.Stopped, stateInfo.Reason)); // If the stop call failed due to network problems then close the runspace // since it is now unusable. CheckAndCloseRunspaceAfterStop(stateInfo.Reason); } else { _stateInfoQueue.Enqueue(stateInfo); } // calling close async only after making sure all the internal members are prepared // to handle close complete. dataStructureHandler.CloseConnectionAsync(null); } } } /// <summary> /// Helper method to check any error condition after a stop call /// and close the remote runspace/pool if the stop call failed due /// to network outage problems. /// </summary> /// <param name="ex">Exception</param> private void CheckAndCloseRunspaceAfterStop(Exception ex) { PSRemotingTransportException transportException = ex as PSRemotingTransportException; if (transportException != null && (transportException.ErrorCode == System.Management.Automation.Remoting.Client.WSManNativeApi.ERROR_WSMAN_SENDDATA_CANNOT_CONNECT || transportException.ErrorCode == System.Management.Automation.Remoting.Client.WSManNativeApi.ERROR_WSMAN_SENDDATA_CANNOT_COMPLETE || transportException.ErrorCode == System.Management.Automation.Remoting.Client.WSManNativeApi.ERROR_WSMAN_TARGETSESSION_DOESNOTEXIST)) { object rsObject = shell.GetRunspaceConnection(); if (rsObject is Runspace) { Runspace runspace = (Runspace)rsObject; if (runspace.RunspaceStateInfo.State == RunspaceState.Opened) { try { runspace.Close(); } catch (PSRemotingTransportException) { } } } else if (rsObject is RunspacePool) { RunspacePool runspacePool = (RunspacePool)rsObject; if (runspacePool.RunspacePoolStateInfo.State == RunspacePoolState.Opened) { try { runspacePool.Close(); } catch (PSRemotingTransportException) { } } } } } /// <summary> /// Handler for handling any informational message received /// from the server side. /// </summary> /// <param name="sender">sender of this event, unused</param> /// <param name="eventArgs">arguments describing this event</param> private void HandleInformationalMessageReceived(object sender, RemoteDataEventArgs<InformationalMessage> eventArgs) { using (s_tracer.TraceEventHandlers()) { InformationalMessage infoMessage = eventArgs.Data; switch (infoMessage.DataType) { case RemotingDataType.PowerShellDebug: { informationalBuffers.AddDebug((DebugRecord)infoMessage.Message); } break; case RemotingDataType.PowerShellVerbose: { informationalBuffers.AddVerbose((VerboseRecord)infoMessage.Message); } break; case RemotingDataType.PowerShellWarning: { informationalBuffers.AddWarning((WarningRecord)infoMessage.Message); } break; case RemotingDataType.PowerShellProgress: { ProgressRecord progress = (ProgressRecord)LanguagePrimitives.ConvertTo(infoMessage.Message, typeof(ProgressRecord), System.Globalization.CultureInfo.InvariantCulture); informationalBuffers.AddProgress(progress); } break; case RemotingDataType.PowerShellInformationStream: { informationalBuffers.AddInformation((InformationRecord)infoMessage.Message); } break; } } } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="eventArgs"></param> private void HandleHostCallReceived(object sender, RemoteDataEventArgs<RemoteHostCall> eventArgs) { using (s_tracer.TraceEventHandlers()) { Collection<RemoteHostCall> prerequisiteCalls = eventArgs.Data.PerformSecurityChecksOnHostMessage(computerName); if (HostCallReceived != null) { // raise events for all prerequisite calls if (prerequisiteCalls.Count > 0) { foreach (RemoteHostCall hostcall in prerequisiteCalls) { RemoteDataEventArgs<RemoteHostCall> args = new RemoteDataEventArgs<RemoteHostCall>(hostcall); HostCallReceived.SafeInvoke(this, args); } } HostCallReceived.SafeInvoke(this, eventArgs); } else { // execute any prerequisite calls before // executing this host call if (prerequisiteCalls.Count > 0) { foreach (RemoteHostCall hostcall in prerequisiteCalls) { ExecuteHostCall(hostcall); } } ExecuteHostCall(eventArgs.Data); } } } /// <summary> /// Handler for ConnectCompleted and ReconnectCompleted events from the /// PSRP layer. /// </summary> /// <param name="sender">Sender of this event, unused.</param> /// <param name="e">Event arguments.</param> private void HandleConnectCompleted(object sender, RemoteDataEventArgs<Exception> e) { // After initial connect/reconnect set state to "Running". Later events // will update state to appropriate command execution state. SetStateInfo(new PSInvocationStateInfo(PSInvocationState.Running, null)); } /// <summary> /// This is need for the state change events that resulted in closing the underlying /// datastructure handler. We cannot send the state back to the upper layers until /// close is completed from the datastructure/transport layer. We have to send /// the terminal state only when we know that underlying datastructure/transport /// is closed. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void HandleCloseCompleted(object sender, EventArgs args) { // if state is completed or failed or stopped, // then the collections need to be closed as // well, else the enumerator will block UnblockCollections(); // close the transport manager when CreateCloseAckPacket is received // otherwise may have race conditions in Server.OutOfProcessMediator dataStructureHandler.RaiseRemoveAssociationEvent(); if (_stateInfoQueue.Count == 0) { // If shell state is not finished on client side and queue is empty // then set state to stopped unless the current state is Disconnected // in which case transition state to failed. if (!IsFinished(shell.InvocationStateInfo.State)) { // If RemoteSessionStateEventArgs are provided then use them to set the // session close reason when setting finished state. RemoteSessionStateEventArgs sessionEventArgs = args as RemoteSessionStateEventArgs; Exception closeReason = (sessionEventArgs != null) ? sessionEventArgs.SessionStateInfo.Reason : null; PSInvocationState finishedState = (shell.InvocationStateInfo.State == PSInvocationState.Disconnected) ? PSInvocationState.Failed : PSInvocationState.Stopped; SetStateInfo(new PSInvocationStateInfo(finishedState, closeReason)); } } else { // Apply queued state changes. while (_stateInfoQueue.Count > 0) { PSInvocationStateInfo stateInfo = _stateInfoQueue.Dequeue(); SetStateInfo(stateInfo); } } } private bool IsFinished(PSInvocationState state) { return (state == PSInvocationState.Completed || state == PSInvocationState.Failed || state == PSInvocationState.Stopped); } /// <summary> /// Execute the specified host call /// </summary> /// <param name="hostcall">host call to execute</param> private void ExecuteHostCall(RemoteHostCall hostcall) { if (hostcall.IsVoidMethod) { if (hostcall.IsSetShouldExitOrPopRunspace) { this.shell.ClearRemotePowerShell(); } hostcall.ExecuteVoidMethod(hostToUse); } else { RemoteHostResponse remoteHostResponse = hostcall.ExecuteNonVoidMethod(hostToUse); dataStructureHandler.SendHostResponseToServer(remoteHostResponse); } } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="eventArgs"></param> private void HandleCloseNotificationFromRunspacePool(object sender, RemoteDataEventArgs<Exception> eventArgs) { // RunspacePool is closed...so going to set the state of PowerShell // to stopped here. // if state is completed or failed or stopped, // then the collections need to be closed as // well, else the enumerator will block UnblockCollections(); // Since this is a terminal state..close the transport manager. dataStructureHandler.RaiseRemoveAssociationEvent(); // RunspacePool is closed...so going to set the state of PowerShell // to stopped here. SetStateInfo(new PSInvocationStateInfo(PSInvocationState.Stopped, eventArgs.Data)); // Not calling dataStructureHandler.CloseConnection() as this must // have already been called by RunspacePool.Close() } /// <summary> /// Handles notification from RunspacePool indicating /// that the pool is broken. This sets the state of /// all the powershell objects associated with the /// runspace pool to Failed /// </summary> /// <param name="sender">sender of this information, unused</param> /// <param name="eventArgs">arguments describing this event /// contains information on the reason associated with the /// runspace pool entering a Broken state</param> private void HandleBrokenNotificationFromRunspacePool(object sender, RemoteDataEventArgs<Exception> eventArgs) { // RunspacePool is closed...so going to set the state of PowerShell // to stopped here. // if state is completed or failed or stopped, // then the collections need to be closed as // well, else the enumerator will block UnblockCollections(); // Since this is a terminal state..close the transport manager. dataStructureHandler.RaiseRemoveAssociationEvent(); if (stopCalled) { // Reset stop called flag. stopCalled = false; // if a Stop method has been called, then powershell // would have already raised a Stopping event, after // which only a Stopped should be raised SetStateInfo(new PSInvocationStateInfo(PSInvocationState.Stopped, eventArgs.Data)); } else { SetStateInfo(new PSInvocationStateInfo(PSInvocationState.Failed, eventArgs.Data)); } // Not calling dataStructureHandler.CloseConnection() as this must // have already been called by RunspacePool.Close() } /// <summary> /// Handles a robust connection layer notification from the transport /// manager. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void HandleRobustConnectionNotification( object sender, ConnectionStatusEventArgs e) { // Create event arguments and warnings/errors for this robust connection notification. PSConnectionRetryStatusEventArgs connectionRetryStatusArgs = null; WarningRecord warningRecord = null; ErrorRecord errorRecord = null; int maxRetryConnectionTimeMSecs = this.runspacePool.MaxRetryConnectionTime; int maxRetryConnectionTimeMinutes = maxRetryConnectionTimeMSecs / 60000; switch (e.Notification) { case ConnectionStatus.NetworkFailureDetected: warningRecord = new WarningRecord( PSConnectionRetryStatusEventArgs.FQIDNetworkFailureDetected, StringUtil.Format(RemotingErrorIdStrings.RCNetworkFailureDetected, this.computerName, maxRetryConnectionTimeMinutes)); connectionRetryStatusArgs = new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.NetworkFailureDetected, this.computerName, maxRetryConnectionTimeMSecs, warningRecord); break; case ConnectionStatus.ConnectionRetryAttempt: warningRecord = new WarningRecord( PSConnectionRetryStatusEventArgs.FQIDConnectionRetryAttempt, StringUtil.Format(RemotingErrorIdStrings.RCConnectionRetryAttempt, this.computerName)); connectionRetryStatusArgs = new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.ConnectionRetryAttempt, this.computerName, maxRetryConnectionTimeMSecs, warningRecord); break; case ConnectionStatus.ConnectionRetrySucceeded: warningRecord = new WarningRecord( PSConnectionRetryStatusEventArgs.FQIDConnectionRetrySucceeded, StringUtil.Format(RemotingErrorIdStrings.RCReconnectSucceeded, this.computerName)); connectionRetryStatusArgs = new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.ConnectionRetrySucceeded, this.computerName, maxRetryConnectionTimeMinutes, warningRecord); break; case ConnectionStatus.AutoDisconnectStarting: { warningRecord = new WarningRecord( PSConnectionRetryStatusEventArgs.FQIDAutoDisconnectStarting, StringUtil.Format(RemotingErrorIdStrings.RCAutoDisconnectingWarning, this.computerName)); connectionRetryStatusArgs = new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.AutoDisconnectStarting, this.computerName, maxRetryConnectionTimeMinutes, warningRecord); } break; case ConnectionStatus.AutoDisconnectSucceeded: warningRecord = new WarningRecord( PSConnectionRetryStatusEventArgs.FQIDAutoDisconnectSucceeded, StringUtil.Format(RemotingErrorIdStrings.RCAutoDisconnected, this.computerName)); connectionRetryStatusArgs = new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.AutoDisconnectSucceeded, this.computerName, maxRetryConnectionTimeMinutes, warningRecord); break; case ConnectionStatus.InternalErrorAbort: { string msg = StringUtil.Format(RemotingErrorIdStrings.RCInternalError, this.computerName); RuntimeException reason = new RuntimeException(msg); errorRecord = new ErrorRecord(reason, PSConnectionRetryStatusEventArgs.FQIDNetworkOrDisconnectFailed, ErrorCategory.InvalidOperation, this); connectionRetryStatusArgs = new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.InternalErrorAbort, this.computerName, maxRetryConnectionTimeMinutes, errorRecord); } break; } if (connectionRetryStatusArgs == null) { return; } // Update connection status. _connectionRetryStatus = connectionRetryStatusArgs.Notification; if (warningRecord != null) { RemotingWarningRecord remotingWarningRecord = new RemotingWarningRecord( warningRecord, new OriginInfo(this.computerName, this.InstanceId)); // Add warning record to information channel. HandleInformationalMessageReceived(this, new RemoteDataEventArgs<InformationalMessage>( new InformationalMessage(remotingWarningRecord, RemotingDataType.PowerShellWarning))); // Write warning to host. RemoteHostCall writeWarning = new RemoteHostCall( -100, RemoteHostMethodId.WriteWarningLine, new object[] { warningRecord.Message }); try { HandleHostCallReceived(this, new RemoteDataEventArgs<RemoteHostCall>(writeWarning)); } catch (PSNotImplementedException) { } } if (errorRecord != null) { RemotingErrorRecord remotingErrorRecord = new RemotingErrorRecord( errorRecord, new OriginInfo(this.computerName, this.InstanceId)); // Add error record to error channel, will also be written to host. HandleErrorReceived(this, new RemoteDataEventArgs<ErrorRecord>(remotingErrorRecord)); } // Raise event. RCConnectionNotification.SafeInvoke(this, connectionRetryStatusArgs); } #endregion Private Methods #region Protected Members protected ObjectStreamBase inputstream; protected ObjectStreamBase errorstream; protected PSInformationalBuffers informationalBuffers; protected PowerShell shell; protected Guid clientRunspacePoolId; protected bool noInput; protected PSInvocationSettings settings; protected ObjectStreamBase outputstream; protected string computerName; protected ClientPowerShellDataStructureHandler dataStructureHandler; protected bool stopCalled = false; protected PSHost hostToUse; protected RemoteRunspacePoolInternal runspacePool; protected const string WRITE_DEBUG_LINE = "WriteDebugLine"; protected const string WRITE_VERBOSE_LINE = "WriteVerboseLine"; protected const string WRITE_WARNING_LINE = "WriteWarningLine"; protected const string WRITE_PROGRESS = "WriteProgress"; protected bool initialized = false; /// <summary> /// This queue is for the state change events that resulted in closing the underlying /// datastructure handler. We cannot send the state back to the upper layers until /// close is completed from the datastructure/transport layer. /// </summary> private Queue<PSInvocationStateInfo> _stateInfoQueue = new Queue<PSInvocationStateInfo>(); private PSConnectionRetryStatus _connectionRetryStatus = PSConnectionRetryStatus.None; #endregion Protected Members #region IDisposable /// <summary> /// Public interface for dispose /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Release all resources /// </summary> /// <param name="disposing">if true, release all managed resources</param> protected void Dispose(bool disposing) { if (disposing) { //inputstream.Dispose(); //outputstream.Dispose(); //errorstream.Dispose(); } } #endregion IDisposable } #region PSConnectionRetryStatusEventArgs /// <summary> /// Robust Connection notifications. /// </summary> internal enum PSConnectionRetryStatus { None = 0, NetworkFailureDetected = 1, ConnectionRetryAttempt = 2, ConnectionRetrySucceeded = 3, AutoDisconnectStarting = 4, AutoDisconnectSucceeded = 5, InternalErrorAbort = 6 }; /// <summary> /// PSConnectionRetryStatusEventArgs /// </summary> internal sealed class PSConnectionRetryStatusEventArgs : EventArgs { internal const string FQIDNetworkFailureDetected = "PowerShellNetworkFailureDetected"; internal const string FQIDConnectionRetryAttempt = "PowerShellConnectionRetryAttempt"; internal const string FQIDConnectionRetrySucceeded = "PowerShellConnectionRetrySucceeded"; internal const string FQIDAutoDisconnectStarting = "PowerShellNetworkFailedStartDisconnect"; internal const string FQIDAutoDisconnectSucceeded = "PowerShellAutoDisconnectSucceeded"; internal const string FQIDNetworkOrDisconnectFailed = "PowerShellNetworkOrDisconnectFailed"; internal PSConnectionRetryStatusEventArgs( PSConnectionRetryStatus notification, string computerName, int maxRetryConnectionTime, object infoRecord) { Notification = notification; ComputerName = computerName; MaxRetryConnectionTime = maxRetryConnectionTime; InformationRecord = infoRecord; } internal PSConnectionRetryStatus Notification { get; } internal string ComputerName { get; } internal int MaxRetryConnectionTime { get; } internal object InformationRecord { get; } } #endregion }
using System.Linq; using Lucene.Net.Documents; using Lucene.Net.Index; using NUnit.Framework; using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Threading; namespace Lucene.Net.Analysis { /* * 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 Lucene.Net.Analysis.Tokenattributes; using Lucene.Net.Randomized.Generators; using Lucene.Net.Support; using System.Globalization; using System.IO; using Attribute = Lucene.Net.Util.Attribute; using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using Field = Field; using FieldType = FieldType; using IAttribute = Lucene.Net.Util.IAttribute; using IOUtils = Lucene.Net.Util.IOUtils; using LineFileDocs = Lucene.Net.Util.LineFileDocs; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using TestUtil = Lucene.Net.Util.TestUtil; using TextField = TextField; /// <summary> /// base class for all Lucene unit tests that use TokenStreams. /// <p> /// When writing unit tests for analysis components, its highly recommended /// to use the helper methods here (especially in conjunction with <seealso cref="MockAnalyzer"/> or /// <seealso cref="MockTokenizer"/>), as they contain many assertions and checks to /// catch bugs. /// </summary> /// <seealso cref= MockAnalyzer </seealso> /// <seealso cref= MockTokenizer </seealso> public abstract class BaseTokenStreamTestCase : LuceneTestCase { // some helpers to test Analyzers and TokenStreams: /// <summary> /// Attribute that records if it was cleared or not. this is used /// for testing that ClearAttributes() was called correctly. /// </summary> public interface ICheckClearAttributesAttribute : IAttribute { bool AndResetClearCalled { get; } } /// <summary> /// Attribute that records if it was cleared or not. this is used /// for testing that ClearAttributes() was called correctly. /// </summary> public sealed class CheckClearAttributesAttribute : Attribute, ICheckClearAttributesAttribute { internal bool ClearCalled = false; public bool AndResetClearCalled { get { bool old = ClearCalled; ClearCalled = false; return old; } } public override void Clear() { ClearCalled = true; } public override bool Equals(object other) { return (other is CheckClearAttributesAttribute && ((CheckClearAttributesAttribute)other).ClearCalled == this.ClearCalled); } public override int GetHashCode() { return 76137213 ^ Convert.ToBoolean(ClearCalled).GetHashCode(); } public override void CopyTo(Attribute target) { ((CheckClearAttributesAttribute)target).Clear(); } } // offsetsAreCorrect also validates: // - graph offsets are correct (all tokens leaving from // pos X have the same startOffset; all tokens // arriving to pos Y have the same endOffset) // - offsets only move forwards (startOffset >= // lastStartOffset) public static void AssertTokenStreamContents(TokenStream ts, string[] output, int[] startOffsets, int[] endOffsets, string[] types, int[] posIncrements, int[] posLengths, int? finalOffset, int? finalPosInc, bool[] keywordAtts, bool offsetsAreCorrect) { Assert.IsNotNull(output); var checkClearAtt = ts.AddAttribute<ICheckClearAttributesAttribute>(); ICharTermAttribute termAtt = null; if (output.Length > 0) { Assert.IsTrue(ts.HasAttribute<ICharTermAttribute>(), "has no CharTermAttribute"); termAtt = ts.GetAttribute<ICharTermAttribute>(); } IOffsetAttribute offsetAtt = null; if (startOffsets != null || endOffsets != null || finalOffset != null) { Assert.IsTrue(ts.HasAttribute<IOffsetAttribute>(), "has no OffsetAttribute"); offsetAtt = ts.GetAttribute<IOffsetAttribute>(); } ITypeAttribute typeAtt = null; if (types != null) { Assert.IsTrue(ts.HasAttribute<ITypeAttribute>(), "has no TypeAttribute"); typeAtt = ts.GetAttribute<ITypeAttribute>(); } IPositionIncrementAttribute posIncrAtt = null; if (posIncrements != null || finalPosInc != null) { Assert.IsTrue(ts.HasAttribute<IPositionIncrementAttribute>(), "has no PositionIncrementAttribute"); posIncrAtt = ts.GetAttribute<IPositionIncrementAttribute>(); } IPositionLengthAttribute posLengthAtt = null; if (posLengths != null) { Assert.IsTrue(ts.HasAttribute<IPositionLengthAttribute>(), "has no PositionLengthAttribute"); posLengthAtt = ts.GetAttribute<IPositionLengthAttribute>(); } IKeywordAttribute keywordAtt = null; if (keywordAtts != null) { Assert.IsTrue(ts.HasAttribute<IKeywordAttribute>(), "has no KeywordAttribute"); keywordAtt = ts.GetAttribute<IKeywordAttribute>(); } // Maps position to the start/end offset: IDictionary<int?, int?> posToStartOffset = new Dictionary<int?, int?>(); IDictionary<int?, int?> posToEndOffset = new Dictionary<int?, int?>(); ts.Reset(); int pos = -1; int lastStartOffset = 0; for (int i = 0; i < output.Length; i++) { // extra safety to enforce, that the state is not preserved and also assign bogus values ts.ClearAttributes(); termAtt.SetEmpty().Append("bogusTerm"); if (offsetAtt != null) { offsetAtt.SetOffset(14584724, 24683243); } if (typeAtt != null) { typeAtt.Type = "bogusType"; } if (posIncrAtt != null) { posIncrAtt.PositionIncrement = 45987657; } if (posLengthAtt != null) { posLengthAtt.PositionLength = 45987653; } if (keywordAtt != null) { keywordAtt.Keyword = (i & 1) == 0; } bool reset = checkClearAtt.AndResetClearCalled; // reset it, because we called clearAttribute() before Assert.IsTrue(ts.IncrementToken(), "token " + i + " does not exist"); Assert.IsTrue(reset, "ClearAttributes() was not called correctly in TokenStream chain"); Assert.AreEqual(output[i], termAtt.ToString(), "term " + i + ", output[i] = " + output[i] + ", termAtt = " + termAtt.ToString()); if (startOffsets != null) { Assert.AreEqual(startOffsets[i], offsetAtt.StartOffset(), "startOffset " + i); } if (endOffsets != null) { Assert.AreEqual(endOffsets[i], offsetAtt.EndOffset(), "endOffset " + i); } if (types != null) { Assert.AreEqual(types[i], typeAtt.Type, "type " + i); } if (posIncrements != null) { Assert.AreEqual(posIncrements[i], posIncrAtt.PositionIncrement, "posIncrement " + i); } if (posLengths != null) { Assert.AreEqual(posLengths[i], posLengthAtt.PositionLength, "posLength " + i); } if (keywordAtts != null) { Assert.AreEqual(keywordAtts[i], keywordAtt.Keyword, "keywordAtt " + i); } // we can enforce some basic things about a few attributes even if the caller doesn't check: if (offsetAtt != null) { int startOffset = offsetAtt.StartOffset(); int endOffset = offsetAtt.EndOffset(); if (finalOffset != null) { Assert.IsTrue(startOffset <= (int)finalOffset, "startOffset must be <= finalOffset"); Assert.IsTrue(endOffset <= (int)finalOffset, "endOffset must be <= finalOffset: got endOffset=" + endOffset + " vs finalOffset=" + (int)finalOffset); } if (offsetsAreCorrect) { Assert.IsTrue(offsetAtt.StartOffset() >= lastStartOffset, "offsets must not go backwards startOffset=" + startOffset + " is < lastStartOffset=" + lastStartOffset); lastStartOffset = offsetAtt.StartOffset(); } if (offsetsAreCorrect && posLengthAtt != null && posIncrAtt != null) { // Validate offset consistency in the graph, ie // all tokens leaving from a certain pos have the // same startOffset, and all tokens arriving to a // certain pos have the same endOffset: int posInc = posIncrAtt.PositionIncrement; pos += posInc; int posLength = posLengthAtt.PositionLength; if (!posToStartOffset.ContainsKey(pos)) { // First time we've seen a token leaving from this position: posToStartOffset[pos] = startOffset; //System.out.println(" + s " + pos + " -> " + startOffset); } else { // We've seen a token leaving from this position // before; verify the startOffset is the same: //System.out.println(" + vs " + pos + " -> " + startOffset); Assert.AreEqual((int)posToStartOffset[pos], startOffset, "pos=" + pos + " posLen=" + posLength + " token=" + termAtt); } int endPos = pos + posLength; if (!posToEndOffset.ContainsKey(endPos)) { // First time we've seen a token arriving to this position: posToEndOffset[endPos] = endOffset; //System.out.println(" + e " + endPos + " -> " + endOffset); } else { // We've seen a token arriving to this position // before; verify the endOffset is the same: //System.out.println(" + ve " + endPos + " -> " + endOffset); Assert.AreEqual((int)posToEndOffset[endPos], endOffset, "pos=" + pos + " posLen=" + posLength + " token=" + termAtt); } } } if (posIncrAtt != null) { if (i == 0) { Assert.IsTrue(posIncrAtt.PositionIncrement >= 1, "first posIncrement must be >= 1"); } else { Assert.IsTrue(posIncrAtt.PositionIncrement >= 0, "posIncrement must be >= 0"); } } if (posLengthAtt != null) { Assert.IsTrue(posLengthAtt.PositionLength >= 1, "posLength must be >= 1"); } } if (ts.IncrementToken()) { Assert.Fail("TokenStream has more tokens than expected (expected count=" + output.Length + "); extra token=" + termAtt); } // repeat our extra safety checks for End() ts.ClearAttributes(); if (termAtt != null) { termAtt.SetEmpty().Append("bogusTerm"); } if (offsetAtt != null) { offsetAtt.SetOffset(14584724, 24683243); } if (typeAtt != null) { typeAtt.Type = "bogusType"; } if (posIncrAtt != null) { posIncrAtt.PositionIncrement = 45987657; } if (posLengthAtt != null) { posLengthAtt.PositionLength = 45987653; } var reset_ = checkClearAtt.AndResetClearCalled; // reset it, because we called clearAttribute() before ts.End(); Assert.IsTrue(checkClearAtt.AndResetClearCalled, "super.End()/ClearAttributes() was not called correctly in End()"); if (finalOffset != null) { Assert.AreEqual((int)finalOffset, offsetAtt.EndOffset(), "finalOffset"); } if (offsetAtt != null) { Assert.IsTrue(offsetAtt.EndOffset() >= 0, "finalOffset must be >= 0"); } if (finalPosInc != null) { Assert.AreEqual((int)finalPosInc, posIncrAtt.PositionIncrement, "finalPosInc"); } ts.Dispose(); } public static void AssertTokenStreamContents(TokenStream ts, string[] output, int[] startOffsets, int[] endOffsets, string[] types, int[] posIncrements, int[] posLengths, int? finalOffset, bool[] keywordAtts, bool offsetsAreCorrect) { AssertTokenStreamContents(ts, output, startOffsets, endOffsets, types, posIncrements, posLengths, finalOffset, null, null, offsetsAreCorrect); } public static void AssertTokenStreamContents(TokenStream ts, string[] output, int[] startOffsets, int[] endOffsets, string[] types, int[] posIncrements, int[] posLengths, int? finalOffset, bool offsetsAreCorrect) { AssertTokenStreamContents(ts, output, startOffsets, endOffsets, types, posIncrements, posLengths, finalOffset, null, offsetsAreCorrect); } public static void AssertTokenStreamContents(TokenStream ts, string[] output, int[] startOffsets, int[] endOffsets, string[] types, int[] posIncrements, int[] posLengths, int? finalOffset) { AssertTokenStreamContents(ts, output, startOffsets, endOffsets, types, posIncrements, posLengths, finalOffset, true); } public static void AssertTokenStreamContents(TokenStream ts, string[] output, int[] startOffsets, int[] endOffsets, string[] types, int[] posIncrements, int? finalOffset) { AssertTokenStreamContents(ts, output, startOffsets, endOffsets, types, posIncrements, null, finalOffset); } public static void AssertTokenStreamContents(TokenStream ts, string[] output, int[] startOffsets, int[] endOffsets, string[] types, int[] posIncrements) { AssertTokenStreamContents(ts, output, startOffsets, endOffsets, types, posIncrements, null, null); } public static void AssertTokenStreamContents(TokenStream ts, string[] output) { AssertTokenStreamContents(ts, output, null, null, null, null, null, null); } public static void AssertTokenStreamContents(TokenStream ts, string[] output, string[] types) { AssertTokenStreamContents(ts, output, null, null, types, null, null, null); } public static void AssertTokenStreamContents(TokenStream ts, string[] output, int[] posIncrements) { AssertTokenStreamContents(ts, output, null, null, null, posIncrements, null, null); } public static void AssertTokenStreamContents(TokenStream ts, string[] output, int[] startOffsets, int[] endOffsets) { AssertTokenStreamContents(ts, output, startOffsets, endOffsets, null, null, null, null); } public static void AssertTokenStreamContents(TokenStream ts, string[] output, int[] startOffsets, int[] endOffsets, int? finalOffset) { AssertTokenStreamContents(ts, output, startOffsets, endOffsets, null, null, null, finalOffset); } public static void AssertTokenStreamContents(TokenStream ts, string[] output, int[] startOffsets, int[] endOffsets, int[] posIncrements) { AssertTokenStreamContents(ts, output, startOffsets, endOffsets, null, posIncrements, null, null); } public static void AssertTokenStreamContents(TokenStream ts, string[] output, int[] startOffsets, int[] endOffsets, int[] posIncrements, int? finalOffset) { AssertTokenStreamContents(ts, output, startOffsets, endOffsets, null, posIncrements, null, finalOffset); } public static void AssertTokenStreamContents(TokenStream ts, string[] output, int[] startOffsets, int[] endOffsets, int[] posIncrements, int[] posLengths, int? finalOffset) { AssertTokenStreamContents(ts, output, startOffsets, endOffsets, null, posIncrements, posLengths, finalOffset); } public static void AssertAnalyzesTo(Analyzer a, string input, string[] output, int[] startOffsets, int[] endOffsets, string[] types, int[] posIncrements) { CheckResetException(a, input); AssertTokenStreamContents(a.TokenStream("dummy", new StringReader(input)), output, startOffsets, endOffsets, types, posIncrements, null, input.Length); } public static void AssertAnalyzesTo(Analyzer a, string input, string[] output, int[] startOffsets, int[] endOffsets, string[] types, int[] posIncrements, int[] posLengths) { CheckResetException(a, input); AssertTokenStreamContents(a.TokenStream("dummy", new StringReader(input)), output, startOffsets, endOffsets, types, posIncrements, posLengths, input.Length); } public static void AssertAnalyzesTo(Analyzer a, string input, string[] output, int[] startOffsets, int[] endOffsets, string[] types, int[] posIncrements, int[] posLengths, bool offsetsAreCorrect) { CheckResetException(a, input); AssertTokenStreamContents(a.TokenStream("dummy", new StringReader(input)), output, startOffsets, endOffsets, types, posIncrements, posLengths, input.Length, offsetsAreCorrect); } public static void AssertAnalyzesTo(Analyzer a, string input, string[] output) { AssertAnalyzesTo(a, input, output, null, null, null, null, null); } public static void AssertAnalyzesTo(Analyzer a, string input, string[] output, string[] types) { AssertAnalyzesTo(a, input, output, null, null, types, null, null); } public static void AssertAnalyzesTo(Analyzer a, string input, string[] output, int[] posIncrements) { AssertAnalyzesTo(a, input, output, null, null, null, posIncrements, null); } public static void AssertAnalyzesToPositions(Analyzer a, string input, string[] output, int[] posIncrements, int[] posLengths) { AssertAnalyzesTo(a, input, output, null, null, null, posIncrements, posLengths); } public static void AssertAnalyzesTo(Analyzer a, string input, string[] output, int[] startOffsets, int[] endOffsets) { AssertAnalyzesTo(a, input, output, startOffsets, endOffsets, null, null, null); } public static void AssertAnalyzesTo(Analyzer a, string input, string[] output, int[] startOffsets, int[] endOffsets, int[] posIncrements) { AssertAnalyzesTo(a, input, output, startOffsets, endOffsets, null, posIncrements, null); } internal static void CheckResetException(Analyzer a, string input) { TokenStream ts = a.TokenStream("bogus", new StringReader(input)); try { if (ts.IncrementToken()) { ts.ReflectAsString(false); Assert.Fail("didn't get expected exception when reset() not called"); } } catch (InvalidOperationException expected) { //ok } catch (AssertionException expected) { // ok: MockTokenizer Assert.IsTrue(expected.Message != null && expected.Message.Contains("wrong state"), expected.Message); } catch (Exception unexpected) { //unexpected.printStackTrace(System.err); Console.Error.WriteLine(unexpected.StackTrace); Assert.Fail("got wrong exception when reset() not called: " + unexpected); } finally { // consume correctly ts.Reset(); while (ts.IncrementToken()) { } ts.End(); ts.Dispose(); } // check for a missing Close() ts = a.TokenStream("bogus", new StringReader(input)); ts.Reset(); while (ts.IncrementToken()) { } ts.End(); try { ts = a.TokenStream("bogus", new StringReader(input)); Assert.Fail("didn't get expected exception when Close() not called"); } catch (Exception) { // ok } finally { ts.Dispose(); } } // simple utility method for testing stemmers public static void CheckOneTerm(Analyzer a, string input, string expected) { AssertAnalyzesTo(a, input, new string[] { expected }); } /// <summary> /// utility method for blasting tokenstreams with data to make sure they don't do anything crazy </summary> public static void CheckRandomData(Random random, Analyzer a, int iterations) { CheckRandomData(random, a, iterations, 20, false, true); } /// <summary> /// utility method for blasting tokenstreams with data to make sure they don't do anything crazy </summary> public static void CheckRandomData(Random random, Analyzer a, int iterations, int maxWordLength) { CheckRandomData(random, a, iterations, maxWordLength, false, true); } /// <summary> /// utility method for blasting tokenstreams with data to make sure they don't do anything crazy </summary> /// <param name="simple"> true if only ascii strings will be used (try to avoid) </param> public static void CheckRandomData(Random random, Analyzer a, int iterations, bool simple) { CheckRandomData(random, a, iterations, 20, simple, true); } internal class AnalysisThread : ThreadClass { internal readonly int Iterations; internal readonly int MaxWordLength; internal readonly long Seed; internal readonly Analyzer a; internal readonly bool UseCharFilter; internal readonly bool Simple; internal readonly bool OffsetsAreCorrect; internal readonly RandomIndexWriter Iw; private readonly CountdownEvent _latch; // NOTE: not volatile because we don't want the tests to // add memory barriers (ie alter how threads // interact)... so this is just "best effort": public bool Failed; internal AnalysisThread(long seed, /*CountdownEvent latch,*/ Analyzer a, int iterations, int maxWordLength, bool useCharFilter, bool simple, bool offsetsAreCorrect, RandomIndexWriter iw) { this.Seed = seed; this.a = a; this.Iterations = iterations; this.MaxWordLength = maxWordLength; this.UseCharFilter = useCharFilter; this.Simple = simple; this.OffsetsAreCorrect = offsetsAreCorrect; this.Iw = iw; this._latch = null; } public override void Run() { bool success = false; try { if (_latch != null) _latch.Wait(); // see the part in checkRandomData where it replays the same text again // to verify reproducability/reuse: hopefully this would catch thread hazards. CheckRandomData(new Random((int)Seed), a, Iterations, MaxWordLength, UseCharFilter, Simple, OffsetsAreCorrect, Iw); success = true; } catch (Exception e) { Console.WriteLine("Exception in Thread: " + e); throw; } finally { Failed = !success; } } } public static void CheckRandomData(Random random, Analyzer a, int iterations, int maxWordLength, bool simple) { CheckRandomData(random, a, iterations, maxWordLength, simple, true); } public static void CheckRandomData(Random random, Analyzer a, int iterations, int maxWordLength, bool simple, bool offsetsAreCorrect) { CheckResetException(a, "best effort"); long seed = random.Next(); bool useCharFilter = random.NextBoolean(); Directory dir = null; RandomIndexWriter iw = null; string postingsFormat = TestUtil.GetPostingsFormat("dummy"); bool codecOk = iterations * maxWordLength < 100000 || !(postingsFormat.Equals("Memory") || postingsFormat.Equals("SimpleText")); if (Rarely(random) && codecOk) { dir = NewFSDirectory(CreateTempDir("bttc")); iw = new RandomIndexWriter(new Random((int)seed), dir, a); } bool success = false; try { CheckRandomData(new Random((int)seed), a, iterations, maxWordLength, useCharFilter, simple, offsetsAreCorrect, iw); // now test with multiple threads: note we do the EXACT same thing we did before in each thread, // so this should only really fail from another thread if its an actual thread problem int numThreads = TestUtil.NextInt(random, 2, 4); var startingGun = new CountdownEvent(1); var threads = new AnalysisThread[numThreads]; for (int i = 0; i < threads.Length; i++) { threads[i] = new AnalysisThread(seed, /*startingGun,*/ a, iterations, maxWordLength, useCharFilter, simple, offsetsAreCorrect, iw); } Array.ForEach(threads, thread => thread.Start()); startingGun.Signal(); foreach (var t in threads) { try { t.Join(); } catch (ThreadInterruptedException e) { Fail("Thread interrupted"); } } if (threads.Any(x => x.Failed)) Fail("Thread interrupted"); success = true; } finally { if (success) { IOUtils.Close(iw, dir); } else { IOUtils.CloseWhileHandlingException(iw, dir); // checkindex } } } private static void CheckRandomData(Random random, Analyzer a, int iterations, int maxWordLength, bool useCharFilter, bool simple, bool offsetsAreCorrect, RandomIndexWriter iw) { LineFileDocs docs = new LineFileDocs(random); Document doc = null; Field field = null, currentField = null; StringReader bogus = new StringReader(""); if (iw != null) { doc = new Document(); FieldType ft = new FieldType(TextField.TYPE_NOT_STORED); if (random.NextBoolean()) { ft.StoreTermVectors = true; ft.StoreTermVectorOffsets = random.NextBoolean(); ft.StoreTermVectorPositions = random.NextBoolean(); if (ft.StoreTermVectorPositions && !OLD_FORMAT_IMPERSONATION_IS_ACTIVE) { ft.StoreTermVectorPayloads = random.NextBoolean(); } } if (random.NextBoolean()) { ft.OmitNorms = true; } string pf = TestUtil.GetPostingsFormat("dummy"); bool supportsOffsets = !DoesntSupportOffsets.Contains(pf); switch (random.Next(4)) { case 0: ft.IndexOptions = FieldInfo.IndexOptions.DOCS_ONLY; break; case 1: ft.IndexOptions = FieldInfo.IndexOptions.DOCS_AND_FREQS; break; case 2: ft.IndexOptions = FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS; break; default: if (supportsOffsets && offsetsAreCorrect) { ft.IndexOptions = FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS; } else { ft.IndexOptions = FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS; } break; } currentField = field = new Field("dummy", bogus, ft); doc.Add(currentField); } try { for (int i = 0; i < iterations; i++) { string text; if (random.Next(10) == 7) { // real data from linedocs text = docs.NextDoc().Get("body"); if (text.Length > maxWordLength) { // Take a random slice from the text...: int startPos = random.Next(text.Length - maxWordLength); if (startPos > 0 && char.IsLowSurrogate(text[startPos])) { // Take care not to split up a surrogate pair: startPos--; Assert.True(char.IsHighSurrogate(text[startPos])); } int endPos = startPos + maxWordLength - 1; if (char.IsHighSurrogate(text[endPos])) { // Take care not to split up a surrogate pair: endPos--; } text = text.Substring(startPos, 1 + endPos - startPos); } } else { // synthetic text = TestUtil.RandomAnalysisString(random, maxWordLength, simple); } try { CheckAnalysisConsistency(random, a, useCharFilter, text, offsetsAreCorrect, currentField); if (iw != null) { if (random.Next(7) == 0) { // pile up a multivalued field var ft = (FieldType)field.FieldType(); currentField = new Field("dummy", bogus, ft); doc.Add(currentField); } else { iw.AddDocument(doc); if (doc.Fields.Count > 1) { // back to 1 field currentField = field; doc.RemoveFields("dummy"); doc.Add(currentField); } } } } catch (Exception t) { // TODO: really we should pass a random seed to // checkAnalysisConsistency then print it here too: Console.Error.WriteLine("TEST FAIL: useCharFilter=" + useCharFilter + " text='" + Escape(text) + "'"); throw; } } } finally { IOUtils.CloseWhileHandlingException(docs); } } public static string Escape(string s) { int charUpto = 0; StringBuilder sb = new StringBuilder(); while (charUpto < s.Length) { int c = s[charUpto]; if (c == 0xa) { // Strangely, you cannot put \ u000A into Java // sources (not in a comment nor a string // constant)...: sb.Append("\\n"); } else if (c == 0xd) { // ... nor \ u000D: sb.Append("\\r"); } else if (c == '"') { sb.Append("\\\""); } else if (c == '\\') { sb.Append("\\\\"); } else if (c >= 0x20 && c < 0x80) { sb.Append((char)c); } else { // TODO: we can make ascii easier to read if we // don't escape... sb.Append(string.Format(CultureInfo.InvariantCulture, "\\u%04x", c)); } charUpto++; } return sb.ToString(); } public static void CheckAnalysisConsistency(Random random, Analyzer a, bool useCharFilter, string text) { CheckAnalysisConsistency(random, a, useCharFilter, text, true); } public static void CheckAnalysisConsistency(Random random, Analyzer a, bool useCharFilter, string text, bool offsetsAreCorrect) { CheckAnalysisConsistency(random, a, useCharFilter, text, offsetsAreCorrect, null); } private static void CheckAnalysisConsistency(Random random, Analyzer a, bool useCharFilter, string text, bool offsetsAreCorrect, Field field) { if (VERBOSE) { Console.WriteLine(Thread.CurrentThread.Name + ": NOTE: baseTokenStreamTestCase: get first token stream now text=" + text); } ICharTermAttribute termAtt; IOffsetAttribute offsetAtt; IPositionIncrementAttribute posIncAtt; IPositionLengthAttribute posLengthAtt; ITypeAttribute typeAtt; IList<string> tokens = new List<string>(); IList<string> types = new List<string>(); IList<int> positions = new List<int>(); IList<int> positionLengths = new List<int>(); IList<int> startOffsets = new List<int>(); IList<int> endOffsets = new List<int>(); int remainder = random.Next(10); StringReader reader = new StringReader(text); TokenStream ts; using (ts = a.TokenStream("dummy", useCharFilter ? (TextReader) new MockCharFilter(reader, remainder) : reader)) { termAtt = ts.HasAttribute<ICharTermAttribute>() ? ts.GetAttribute<ICharTermAttribute>() : null; offsetAtt = ts.HasAttribute<IOffsetAttribute>() ? ts.GetAttribute<IOffsetAttribute>() : null; posIncAtt = ts.HasAttribute<IPositionIncrementAttribute>() ? ts.GetAttribute<IPositionIncrementAttribute>() : null; posLengthAtt = ts.HasAttribute<IPositionLengthAttribute>() ? ts.GetAttribute<IPositionLengthAttribute>() : null; typeAtt = ts.HasAttribute<ITypeAttribute>() ? ts.GetAttribute<ITypeAttribute>() : null; ts.Reset(); // First pass: save away "correct" tokens while (ts.IncrementToken()) { Assert.IsNotNull(termAtt, "has no CharTermAttribute"); tokens.Add(termAtt.ToString()); if (typeAtt != null) { types.Add(typeAtt.Type); } if (posIncAtt != null) { positions.Add(posIncAtt.PositionIncrement); } if (posLengthAtt != null) { positionLengths.Add(posLengthAtt.PositionLength); } if (offsetAtt != null) { startOffsets.Add(offsetAtt.StartOffset()); endOffsets.Add(offsetAtt.EndOffset()); } } ts.End(); } // verify reusing is "reproducable" and also get the normal tokenstream sanity checks if (tokens.Count > 0) { // KWTokenizer (for example) can produce a token // even when input is length 0: if (text.Length != 0) { // (Optional) second pass: do something evil: int evilness = random.Next(50); if (evilness == 17) { if (VERBOSE) { Console.WriteLine(Thread.CurrentThread.Name + ": NOTE: baseTokenStreamTestCase: re-run analysis w/ exception"); } // Throw an errant exception from the Reader: MockReaderWrapper evilReader = new MockReaderWrapper(random, text); evilReader.ThrowExcAfterChar(random.Next(text.Length)); reader = evilReader; try { // NOTE: some Tokenizers go and read characters // when you call .setReader(Reader), eg // PatternTokenizer. this is a bit // iffy... (really, they should only // pull from the Reader when you call // .incremenToken(), I think?), but we // currently allow it, so, we must call // a.TokenStream inside the try since we may // hit the exc on init: ts = a.TokenStream("dummy", useCharFilter ? (TextReader)new MockCharFilter(evilReader, remainder) : evilReader); ts.Reset(); while (ts.IncrementToken()) ; Assert.Fail("did not hit exception"); } catch (Exception re) { Assert.IsTrue(MockReaderWrapper.IsMyEvilException(re)); } try { ts.End(); } catch (InvalidOperationException ae) { // Catch & ignore MockTokenizer's // anger... if ("End() called before IncrementToken() returned false!".Equals(ae.Message)) { // OK } else { throw ae; } } finally { ts.Dispose(); } } else if (evilness == 7) { // Only consume a subset of the tokens: int numTokensToRead = random.Next(tokens.Count); if (VERBOSE) { Console.WriteLine(Thread.CurrentThread.Name + ": NOTE: baseTokenStreamTestCase: re-run analysis, only consuming " + numTokensToRead + " of " + tokens.Count + " tokens"); } reader = new StringReader(text); ts = a.TokenStream("dummy", useCharFilter ? (TextReader)new MockCharFilter(reader, remainder) : reader); ts.Reset(); for (int tokenCount = 0; tokenCount < numTokensToRead; tokenCount++) { Assert.IsTrue(ts.IncrementToken()); } try { ts.End(); } catch (InvalidOperationException ae) { // Catch & ignore MockTokenizer's // anger... if ("End() called before IncrementToken() returned false!".Equals(ae.Message)) { // OK } else { throw ae; } } finally { ts.Dispose(); } } } } // Final pass: verify clean tokenization matches // results from first pass: if (VERBOSE) { Console.WriteLine(Thread.CurrentThread.Name + ": NOTE: baseTokenStreamTestCase: re-run analysis; " + tokens.Count + " tokens"); } reader = new StringReader(text); long seed = random.Next(); random = new Random((int)seed); if (random.Next(30) == 7) { if (VERBOSE) { Console.WriteLine(Thread.CurrentThread.Name + ": NOTE: baseTokenStreamTestCase: using spoon-feed reader"); } reader = new MockReaderWrapper(random, text); } ts = a.TokenStream("dummy", useCharFilter ? (TextReader)new MockCharFilter(reader, remainder) : reader); if (typeAtt != null && posIncAtt != null && posLengthAtt != null && offsetAtt != null) { // offset + pos + posLength + type AssertTokenStreamContents(ts, tokens.ToArray(), ToIntArray(startOffsets), ToIntArray(endOffsets), types.ToArray(), ToIntArray(positions), ToIntArray(positionLengths), text.Length, offsetsAreCorrect); } else if (typeAtt != null && posIncAtt != null && offsetAtt != null) { // offset + pos + type AssertTokenStreamContents(ts, tokens.ToArray(), ToIntArray(startOffsets), ToIntArray(endOffsets), types.ToArray(), ToIntArray(positions), null, text.Length, offsetsAreCorrect); } else if (posIncAtt != null && posLengthAtt != null && offsetAtt != null) { // offset + pos + posLength AssertTokenStreamContents(ts, tokens.ToArray(), ToIntArray(startOffsets), ToIntArray(endOffsets), null, ToIntArray(positions), ToIntArray(positionLengths), text.Length, offsetsAreCorrect); } else if (posIncAtt != null && offsetAtt != null) { // offset + pos AssertTokenStreamContents(ts, tokens.ToArray(), ToIntArray(startOffsets), ToIntArray(endOffsets), null, ToIntArray(positions), null, text.Length, offsetsAreCorrect); } else if (offsetAtt != null) { // offset AssertTokenStreamContents(ts, tokens.ToArray(), ToIntArray(startOffsets), ToIntArray(endOffsets), null, null, null, text.Length, offsetsAreCorrect); } else { // terms only AssertTokenStreamContents(ts, tokens.ToArray()); } if (field != null) { reader = new StringReader(text); random = new Random((int)seed); if (random.Next(30) == 7) { if (VERBOSE) { Console.WriteLine(Thread.CurrentThread.Name + ": NOTE: baseTokenStreamTestCase: indexing using spoon-feed reader"); } reader = new MockReaderWrapper(random, text); } field.ReaderValue = useCharFilter ? (TextReader)new MockCharFilter(reader, remainder) : reader; } } protected internal virtual string ToDot(Analyzer a, string inputText) { StringWriter sw = new StringWriter(); TokenStream ts = a.TokenStream("field", new StringReader(inputText)); ts.Reset(); (new TokenStreamToDot(inputText, ts, /*new StreamWriter(*/(TextWriter)sw/*)*/)).ToDot(); return sw.ToString(); } protected internal virtual void ToDotFile(Analyzer a, string inputText, string localFileName) { StreamWriter w = new StreamWriter(new FileStream(localFileName, FileMode.Open), IOUtils.CHARSET_UTF_8); TokenStream ts = a.TokenStream("field", new StreamReader(inputText)); ts.Reset(); (new TokenStreamToDot(inputText, ts,/* new PrintWriter(*/w/*)*/)).ToDot(); w.Close(); } internal static int[] ToIntArray(IList<int> list) { int[] ret = new int[list.Count]; int offset = 0; foreach (int i in list) { ret[offset++] = i; } return ret; } } }
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Firebase.Sample.RemoteConfig { using Firebase.Extensions; using System; using System.Threading.Tasks; using UnityEngine; // Handler for UI buttons on the scene. Also performs some // necessary setup (initializing the firebase app, etc) on // startup. public class UIHandler : MonoBehaviour { public GUISkin fb_GUISkin; private Vector2 controlsScrollViewVector = Vector2.zero; private Vector2 scrollViewVector = Vector2.zero; bool UIEnabled = true; private string logText = ""; const int kMaxLogSize = 16382; Firebase.DependencyStatus dependencyStatus = Firebase.DependencyStatus.UnavailableOther; protected bool isFirebaseInitialized = false; // When the app starts, check to make sure that we have // the required dependencies to use Firebase, and if not, // add them if possible. protected virtual void Start() { Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task => { dependencyStatus = task.Result; if (dependencyStatus == Firebase.DependencyStatus.Available) { InitializeFirebase(); } else { Debug.LogError( "Could not resolve all Firebase dependencies: " + dependencyStatus); } }); } // Initialize remote config, and set the default values. void InitializeFirebase() { // [START set_defaults] System.Collections.Generic.Dictionary<string, object> defaults = new System.Collections.Generic.Dictionary<string, object>(); // These are the values that are used if we haven't fetched data from the // server // yet, or if we ask for values that the server doesn't have: defaults.Add("config_test_string", "default local string"); defaults.Add("config_test_int", 1); defaults.Add("config_test_float", 1.0); defaults.Add("config_test_bool", false); Firebase.RemoteConfig.FirebaseRemoteConfig.DefaultInstance.SetDefaultsAsync(defaults) .ContinueWithOnMainThread(task => { // [END set_defaults] DebugLog("RemoteConfig configured and ready!"); isFirebaseInitialized = true; }); } // Exit if escape (or back, on mobile) is pressed. protected virtual void Update() { if (Input.GetKeyDown(KeyCode.Escape)) { Application.Quit(); } } // Display the currently loaded data. If fetch has been called, this will be // the data fetched from the server. Otherwise, it will be the defaults. // Note: Firebase will cache this between sessions, so even if you haven't // called fetch yet, if it was called on a previous run of the program, you // will still have data from the last time it was run. public void DisplayData() { DebugLog("Current Data:"); DebugLog("config_test_string: " + Firebase.RemoteConfig.FirebaseRemoteConfig.DefaultInstance .GetValue("config_test_string").StringValue); DebugLog("config_test_int: " + Firebase.RemoteConfig.FirebaseRemoteConfig.DefaultInstance .GetValue("config_test_int").LongValue); DebugLog("config_test_float: " + Firebase.RemoteConfig.FirebaseRemoteConfig.DefaultInstance .GetValue("config_test_float").DoubleValue); DebugLog("config_test_bool: " + Firebase.RemoteConfig.FirebaseRemoteConfig.DefaultInstance .GetValue("config_test_bool").BooleanValue); } public void DisplayAllKeys() { DebugLog("Current Keys:"); System.Collections.Generic.IEnumerable<string> keys = Firebase.RemoteConfig.FirebaseRemoteConfig.DefaultInstance.Keys; foreach (string key in keys) { DebugLog(" " + key); } DebugLog("GetKeysByPrefix(\"config_test_s\"):"); keys = Firebase.RemoteConfig.FirebaseRemoteConfig.DefaultInstance.GetKeysByPrefix("config_test_s"); foreach (string key in keys) { DebugLog(" " + key); } } // [START fetch_async] // Start a fetch request. // FetchAsync only fetches new data if the current data is older than the provided // timespan. Otherwise it assumes the data is "recent enough", and does nothing. // By default the timespan is 12 hours, and for production apps, this is a good // number. For this example though, it's set to a timespan of zero, so that // changes in the console will always show up immediately. public Task FetchDataAsync() { DebugLog("Fetching data..."); System.Threading.Tasks.Task fetchTask = Firebase.RemoteConfig.FirebaseRemoteConfig.DefaultInstance.FetchAsync( TimeSpan.Zero); return fetchTask.ContinueWithOnMainThread(FetchComplete); } //[END fetch_async] void FetchComplete(Task fetchTask) { if (fetchTask.IsCanceled) { DebugLog("Fetch canceled."); } else if (fetchTask.IsFaulted) { DebugLog("Fetch encountered an error."); } else if (fetchTask.IsCompleted) { DebugLog("Fetch completed successfully!"); } var info = Firebase.RemoteConfig.FirebaseRemoteConfig.DefaultInstance.Info; switch (info.LastFetchStatus) { case Firebase.RemoteConfig.LastFetchStatus.Success: Firebase.RemoteConfig.FirebaseRemoteConfig.DefaultInstance.ActivateAsync() .ContinueWithOnMainThread(task => { DebugLog(String.Format("Remote data loaded and ready (last fetch time {0}).", info.FetchTime)); }); break; case Firebase.RemoteConfig.LastFetchStatus.Failure: switch (info.LastFetchFailureReason) { case Firebase.RemoteConfig.FetchFailureReason.Error: DebugLog("Fetch failed for unknown reason"); break; case Firebase.RemoteConfig.FetchFailureReason.Throttled: DebugLog("Fetch throttled until " + info.ThrottledEndTime); break; } break; case Firebase.RemoteConfig.LastFetchStatus.Pending: DebugLog("Latest Fetch call still pending."); break; } } // Output text to the debug log text field, as well as the console. public void DebugLog(string s) { print(s); logText += s + "\n"; while (logText.Length > kMaxLogSize) { int index = logText.IndexOf("\n"); logText = logText.Substring(index + 1); } scrollViewVector.y = int.MaxValue; } void DisableUI() { UIEnabled = false; } void EnableUI() { UIEnabled = true; } // Render the log output in a scroll view. void GUIDisplayLog() { scrollViewVector = GUILayout.BeginScrollView(scrollViewVector); GUILayout.Label(logText); GUILayout.EndScrollView(); } // Render the buttons and other controls. void GUIDisplayControls() { if (UIEnabled) { controlsScrollViewVector = GUILayout.BeginScrollView(controlsScrollViewVector); GUILayout.BeginVertical(); if (GUILayout.Button("Display Current Data")) { DisplayData(); } if (GUILayout.Button("Display All Keys")) { DisplayAllKeys(); } if (GUILayout.Button("Fetch Remote Data")) { FetchDataAsync(); } GUILayout.EndVertical(); GUILayout.EndScrollView(); } } // Render the GUI: void OnGUI() { GUI.skin = fb_GUISkin; if (dependencyStatus != Firebase.DependencyStatus.Available) { GUILayout.Label("One or more Firebase dependencies are not present."); GUILayout.Label("Current dependency status: " + dependencyStatus.ToString()); return; } Rect logArea, controlArea; if (Screen.width < Screen.height) { // Portrait mode controlArea = new Rect(0.0f, 0.0f, Screen.width, Screen.height * 0.5f); logArea = new Rect(0.0f, Screen.height * 0.5f, Screen.width, Screen.height * 0.5f); } else { // Landscape mode controlArea = new Rect(0.0f, 0.0f, Screen.width * 0.5f, Screen.height); logArea = new Rect(Screen.width * 0.5f, 0.0f, Screen.width * 0.5f, Screen.height); } GUILayout.BeginArea(logArea); GUIDisplayLog(); GUILayout.EndArea(); GUILayout.BeginArea(controlArea); GUIDisplayControls(); GUILayout.EndArea(); } } }
using System; using System.Collections.Immutable; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json.Linq; using OpenIddict.Abstractions; using OpenIddict.Core; using OrchardCore.OpenId.Abstractions.Descriptors; using OrchardCore.OpenId.Abstractions.Managers; using OrchardCore.OpenId.Abstractions.Stores; namespace OrchardCore.OpenId.Services.Managers { public class OpenIdApplicationManager<TApplication> : OpenIddictApplicationManager<TApplication>, IOpenIdApplicationManager where TApplication : class { public OpenIdApplicationManager( IOpenIddictApplicationCache<TApplication> cache, IOpenIddictApplicationStoreResolver resolver, ILogger<OpenIdApplicationManager<TApplication>> logger, IOptionsMonitor<OpenIddictCoreOptions> options) : base(cache, resolver, logger, options) { } /// <summary> /// Retrieves an application using its physical identifier. /// </summary> /// <param name="identifier">The unique identifier associated with the application.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <returns> /// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation, /// whose result returns the client application corresponding to the identifier. /// </returns> public virtual ValueTask<TApplication> FindByPhysicalIdAsync(string identifier, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(identifier)) { throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier)); } return new ValueTask<TApplication>(Store is IOpenIdApplicationStore<TApplication> store ? store.FindByPhysicalIdAsync(identifier, cancellationToken) : Store.FindByIdAsync(identifier, cancellationToken)); } /// <summary> /// Retrieves the physical identifier associated with an application. /// </summary> /// <param name="application">The application.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param> /// <returns> /// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation, /// whose result returns the physical identifier associated with the application. /// </returns> public virtual ValueTask<string> GetPhysicalIdAsync(TApplication application, CancellationToken cancellationToken = default) { if (application == null) { throw new ArgumentNullException(nameof(application)); } return Store is IOpenIdApplicationStore<TApplication> store ? store.GetPhysicalIdAsync(application, cancellationToken) : Store.GetIdAsync(application, cancellationToken); } public virtual async ValueTask<ImmutableArray<string>> GetRolesAsync( TApplication application, CancellationToken cancellationToken = default) { if (application == null) { throw new ArgumentNullException(nameof(application)); } if (Store is IOpenIdApplicationStore<TApplication> store) { return await store.GetRolesAsync(application, cancellationToken); } else { var properties = await Store.GetPropertiesAsync(application, cancellationToken); if (properties.TryGetValue(OpenIdConstants.Properties.Roles, StringComparison.OrdinalIgnoreCase, out JToken value)) { return value.ToObject<ImmutableArray<string>>(); } return ImmutableArray.Create<string>(); } } public virtual async ValueTask<ImmutableArray<TApplication>> ListInRoleAsync( string role, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(role)) { throw new ArgumentException("The role name cannot be null or empty.", nameof(role)); } if (Store is IOpenIdApplicationStore<TApplication> store) { return await store.ListInRoleAsync(role, cancellationToken); } var builder = ImmutableArray.CreateBuilder<TApplication>(); for (var offset = 0; ; offset += 1_000) { var applications = await Store.ListAsync(1_000, offset, cancellationToken); if (applications.Length == 0) { break; } foreach (var application in applications) { var roles = await GetRolesAsync(application, cancellationToken); if (roles.Contains(role, StringComparer.OrdinalIgnoreCase)) { builder.Add(application); } } } return builder.ToImmutable(); } public virtual async ValueTask SetRolesAsync(TApplication application, ImmutableArray<string> roles, CancellationToken cancellationToken = default) { if (application == null) { throw new ArgumentNullException(nameof(application)); } if (roles.Any(role => string.IsNullOrEmpty(role))) { throw new ArgumentException("Role names cannot be null or empty.", nameof(roles)); } if (Store is IOpenIdApplicationStore<TApplication> store) { await store.SetRolesAsync(application, roles, cancellationToken); } else { var properties = await Store.GetPropertiesAsync(application, cancellationToken); properties[OpenIdConstants.Properties.Roles] = JArray.FromObject(roles); await Store.SetPropertiesAsync(application, properties, cancellationToken); } await UpdateAsync(application, cancellationToken); } public override async Task PopulateAsync(TApplication application, OpenIddictApplicationDescriptor descriptor, CancellationToken cancellationToken = default) { if (application == null) { throw new ArgumentNullException(nameof(application)); } if (descriptor == null) { throw new ArgumentNullException(nameof(descriptor)); } if (descriptor is OpenIdApplicationDescriptor model) { if (Store is IOpenIdApplicationStore<TApplication> store) { await store.SetRolesAsync(application, model.Roles.ToImmutableArray(), cancellationToken); } else { var properties = await Store.GetPropertiesAsync(application, cancellationToken); properties[OpenIdConstants.Properties.Roles] = JArray.FromObject(model.Roles); await Store.SetPropertiesAsync(application, properties, cancellationToken); } } await base.PopulateAsync(application, descriptor, cancellationToken); } public override async Task PopulateAsync(OpenIddictApplicationDescriptor descriptor, TApplication application, CancellationToken cancellationToken = default) { if (descriptor == null) { throw new ArgumentNullException(nameof(descriptor)); } if (application == null) { throw new ArgumentNullException(nameof(application)); } if (descriptor is OpenIdApplicationDescriptor model) { model.Roles.UnionWith(await GetRolesAsync(application, cancellationToken)); } await base.PopulateAsync(descriptor, application, cancellationToken); } public override async Task<ImmutableArray<ValidationResult>> ValidateAsync( TApplication application, CancellationToken cancellationToken = default) { var results = ImmutableArray.CreateBuilder<ValidationResult>(); results.AddRange(await base.ValidateAsync(application, cancellationToken)); foreach (var role in await GetRolesAsync(application, cancellationToken)) { if (string.IsNullOrEmpty(role)) { results.Add(new ValidationResult("Roles cannot be null or empty.")); break; } } return results.ToImmutable(); } async ValueTask<object> IOpenIdApplicationManager.FindByPhysicalIdAsync(string identifier, CancellationToken cancellationToken) => await FindByPhysicalIdAsync(identifier, cancellationToken); ValueTask<string> IOpenIdApplicationManager.GetPhysicalIdAsync(object application, CancellationToken cancellationToken) => GetPhysicalIdAsync((TApplication)application, cancellationToken); ValueTask<ImmutableArray<string>> IOpenIdApplicationManager.GetRolesAsync(object application, CancellationToken cancellationToken) => GetRolesAsync((TApplication)application, cancellationToken); async ValueTask<ImmutableArray<object>> IOpenIdApplicationManager.ListInRoleAsync(string role, CancellationToken cancellationToken) => (await ListInRoleAsync(role, cancellationToken)).CastArray<object>(); ValueTask IOpenIdApplicationManager.SetRolesAsync(object application, ImmutableArray<string> roles, CancellationToken cancellationToken) => SetRolesAsync((TApplication)application, roles, cancellationToken); } }
using System.Linq; using System.Threading.Tasks; using Content.Server.Act; using Content.Server.Chat.Managers; using Content.Server.Chemistry.Components.SolutionManager; using Content.Server.Chemistry.EntitySystems; using Content.Server.Hands.Components; using Content.Server.Popups; using Content.Server.Power.Components; using Content.Server.Temperature.Components; using Content.Server.Temperature.Systems; using Content.Server.UserInterface; using Content.Shared.Acts; using Content.Shared.Body.Components; using Content.Shared.Body.Part; using Content.Shared.FixedPoint; using Content.Shared.Interaction; using Content.Shared.Item; using Content.Shared.Kitchen; using Content.Shared.Kitchen.Components; using Content.Shared.Popups; using Content.Shared.Power; using Content.Shared.Sound; using Content.Shared.Tag; using Robust.Server.GameObjects; using Robust.Shared.Audio; using Robust.Shared.Containers; using Robust.Shared.Player; namespace Content.Server.Kitchen.Components { [RegisterComponent] [ComponentReference(typeof(IActivate))] public sealed class MicrowaveComponent : SharedMicrowaveComponent, IActivate, IInteractUsing, ISuicideAct, IBreakAct { [Dependency] private readonly IEntityManager _entities = default!; [Dependency] private readonly RecipeManager _recipeManager = default!; #region YAMLSERIALIZE [DataField("cookTime")] private uint _cookTimeDefault = 5; [DataField("cookTimeMultiplier")] private int _cookTimeMultiplier = 1000; //For upgrades and stuff I guess? [DataField("failureResult")] private string _badRecipeName = "FoodBadRecipe"; [DataField("beginCookingSound")] private SoundSpecifier _startCookingSound = new SoundPathSpecifier("/Audio/Machines/microwave_start_beep.ogg"); [DataField("foodDoneSound")] private SoundSpecifier _cookingCompleteSound = new SoundPathSpecifier("/Audio/Machines/microwave_done_beep.ogg"); [DataField("clickSound")] private SoundSpecifier _clickSound = new SoundPathSpecifier("/Audio/Machines/machine_switch.ogg"); public SoundSpecifier ItemBreakSound = new SoundPathSpecifier("/Audio/Effects/clang.ogg"); #endregion YAMLSERIALIZE [ViewVariables] private bool _busy = false; private bool _broken; /// <summary> /// This is a fixed offset of 5. /// The cook times for all recipes should be divisible by 5,with a minimum of 1 second. /// For right now, I don't think any recipe cook time should be greater than 60 seconds. /// </summary> [ViewVariables] private uint _currentCookTimerTime = 1; /// <summary> /// The max temperature that this microwave can heat objects to. /// </summary> [DataField("temperatureUpperThreshold")] public float TemperatureUpperThreshold = 373.15f; private bool Powered => !_entities.TryGetComponent(Owner, out ApcPowerReceiverComponent? receiver) || receiver.Powered; private bool HasContents => _storage.ContainedEntities.Count > 0; private bool _uiDirty = true; private bool _lostPower; private int _currentCookTimeButtonIndex; public void DirtyUi() { _uiDirty = true; } private Container _storage = default!; [ViewVariables] private BoundUserInterface? UserInterface => Owner.GetUIOrNull(MicrowaveUiKey.Key); protected override void Initialize() { base.Initialize(); _currentCookTimerTime = _cookTimeDefault; _storage = ContainerHelpers.EnsureContainer<Container>(Owner, "microwave_entity_container", out _); if (UserInterface != null) { UserInterface.OnReceiveMessage += UserInterfaceOnReceiveMessage; } } private void UserInterfaceOnReceiveMessage(ServerBoundUserInterfaceMessage message) { if (!Powered || _busy) { return; } switch (message.Message) { case MicrowaveStartCookMessage: Wzhzhzh(); break; case MicrowaveEjectMessage: if (HasContents) { EjectSolids(); ClickSound(); _uiDirty = true; } break; case MicrowaveEjectSolidIndexedMessage msg: if (HasContents) { EjectSolid(msg.EntityID); ClickSound(); _uiDirty = true; } break; case MicrowaveSelectCookTimeMessage msg: _currentCookTimeButtonIndex = msg.ButtonIndex; _currentCookTimerTime = msg.NewCookTime; ClickSound(); _uiDirty = true; break; } } public void OnUpdate() { if (!Powered) { //TODO:If someone cuts power currently, microwave magically keeps going. FIX IT! SetAppearance(MicrowaveVisualState.Idle); } if (_busy && !Powered) { //we lost power while we were cooking/busy! _lostPower = true; EjectSolids(); _busy = false; _uiDirty = true; } if (_busy && _broken) { SetAppearance(MicrowaveVisualState.Broken); //we broke while we were cooking/busy! _lostPower = true; EjectSolids(); _busy = false; _uiDirty = true; } if (_uiDirty) { UserInterface?.SetState(new MicrowaveUpdateUserInterfaceState ( _storage.ContainedEntities.Select(item => item).ToArray(), _busy, _currentCookTimeButtonIndex, _currentCookTimerTime )); _uiDirty = false; } } private void SetAppearance(MicrowaveVisualState state) { var finalState = state; if (_broken) { finalState = MicrowaveVisualState.Broken; } if (_entities.TryGetComponent(Owner, out AppearanceComponent? appearance)) { appearance.SetData(PowerDeviceVisuals.VisualState, finalState); } } public void OnBreak(BreakageEventArgs eventArgs) { _broken = true; SetAppearance(MicrowaveVisualState.Broken); } void IActivate.Activate(ActivateEventArgs eventArgs) { if (!_entities.TryGetComponent(eventArgs.User, out ActorComponent? actor) || !Powered) { return; } _uiDirty = true; UserInterface?.Toggle(actor.PlayerSession); } async Task<bool> IInteractUsing.InteractUsing(InteractUsingEventArgs eventArgs) { if (!Powered) { Owner.PopupMessage(eventArgs.User, Loc.GetString("microwave-component-interact-using-no-power")); return false; } if (_broken) { Owner.PopupMessage(eventArgs.User, Loc.GetString("microwave-component-interact-using-broken")); return false; } if (_entities.GetComponent<HandsComponent>(eventArgs.User).GetActiveHandItem?.Owner is not {Valid: true} itemEntity) { eventArgs.User.PopupMessage(Loc.GetString("microwave-component-interact-using-no-active-hand")); return false; } if (!_entities.TryGetComponent(itemEntity, typeof(SharedItemComponent), out var food)) { Owner.PopupMessage(eventArgs.User, "microwave-component-interact-using-transfer-fail"); return false; } var ent = food.Owner; //Get the entity of the ItemComponent. _storage.Insert(ent); _uiDirty = true; return true; } // ReSharper disable once InconsistentNaming // ReSharper disable once IdentifierTypo private void Wzhzhzh() { if (!HasContents) { return; } _busy = true; // Convert storage into Dictionary of ingredients var solidsDict = new Dictionary<string, int>(); var reagentDict = new Dictionary<string, FixedPoint2>(); foreach (var item in _storage.ContainedEntities) { // special behavior when being microwaved ;) var ev = new BeingMicrowavedEvent(Owner); _entities.EventBus.RaiseLocalEvent(item, ev, false); if (ev.Handled) return; var tagSys = EntitySystem.Get<TagSystem>(); if (tagSys.HasTag(item, "MicrowaveMachineUnsafe") || tagSys.HasTag(item, "Metal")) { // destroy microwave _broken = true; SetAppearance(MicrowaveVisualState.Broken); SoundSystem.Play(Filter.Pvs(Owner), ItemBreakSound.GetSound(), Owner); return; } if (tagSys.HasTag(item, "MicrowaveSelfUnsafe") || tagSys.HasTag(item, "Plastic")) { _entities.SpawnEntity(_badRecipeName, _entities.GetComponent<TransformComponent>(Owner).Coordinates); _entities.QueueDeleteEntity(item); } var metaData = _entities.GetComponent<MetaDataComponent>(item); if (metaData.EntityPrototype == null) { continue; } if (solidsDict.ContainsKey(metaData.EntityPrototype.ID)) { solidsDict[metaData.EntityPrototype.ID]++; } else { solidsDict.Add(metaData.EntityPrototype.ID, 1); } if (!_entities.TryGetComponent<SolutionContainerManagerComponent>(item, out var solMan)) continue; foreach (var (_, solution) in solMan.Solutions) { foreach (var reagent in solution.Contents) { if (reagentDict.ContainsKey(reagent.ReagentId)) reagentDict[reagent.ReagentId] += reagent.Quantity; else reagentDict.Add(reagent.ReagentId, reagent.Quantity); } } } // Check recipes FoodRecipePrototype? recipeToCook = null; foreach (var r in _recipeManager.Recipes.Where(r => CanSatisfyRecipe(r, solidsDict, reagentDict))) { recipeToCook = r; } SetAppearance(MicrowaveVisualState.Cooking); var time = _currentCookTimerTime * _cookTimeMultiplier; SoundSystem.Play(Filter.Pvs(Owner), _startCookingSound.GetSound(), Owner, AudioParams.Default); Owner.SpawnTimer((int) (_currentCookTimerTime * _cookTimeMultiplier), () => { if (_lostPower) { return; } AddTemperature(time); if (recipeToCook != null) { SubtractContents(recipeToCook); _entities.SpawnEntity(recipeToCook.Result, _entities.GetComponent<TransformComponent>(Owner).Coordinates); } EjectSolids(); SoundSystem.Play(Filter.Pvs(Owner), _cookingCompleteSound.GetSound(), Owner, AudioParams.Default.WithVolume(-1f)); SetAppearance(MicrowaveVisualState.Idle); _busy = false; _uiDirty = true; }); _lostPower = false; _uiDirty = true; } /// <summary> /// Adds temperature to every item in the microwave, /// based on the time it took to microwave. /// </summary> /// <param name="time">The time on the microwave, in seconds.</param> public void AddTemperature(float time) { var solutionContainerSystem = EntitySystem.Get<SolutionContainerSystem>(); foreach (var entity in _storage.ContainedEntities) { if (_entities.TryGetComponent(entity, out TemperatureComponent? temp)) { EntitySystem.Get<TemperatureSystem>().ChangeHeat(entity, time / 10, false, temp); } if (_entities.TryGetComponent(entity, out SolutionContainerManagerComponent? solutions)) { foreach (var (_, solution) in solutions.Solutions) { if (solution.Temperature > TemperatureUpperThreshold) continue; solutionContainerSystem.AddThermalEnergy(entity, solution, time / 10); } } } } private void EjectSolids() { for (var i = _storage.ContainedEntities.Count - 1; i >= 0; i--) { _storage.Remove(_storage.ContainedEntities.ElementAt(i)); } } private void EjectSolid(EntityUid entityId) { if (_entities.EntityExists(entityId)) { _storage.Remove(entityId); } } private void SubtractContents(FoodRecipePrototype recipe) { var totalReagentsToRemove = new Dictionary<string, FixedPoint2>(recipe.IngredientsReagents); var solutionContainerSystem = EntitySystem.Get<SolutionContainerSystem>(); // this is spaghetti ngl foreach (var item in _storage.ContainedEntities) { if (!_entities.TryGetComponent<SolutionContainerManagerComponent>(item, out var solMan)) continue; // go over every solution foreach (var (_, solution) in solMan.Solutions) { foreach (var (reagent, _) in recipe.IngredientsReagents) { // removed everything if (!totalReagentsToRemove.ContainsKey(reagent)) continue; if (!solution.ContainsReagent(reagent)) continue; var quant = solution.GetReagentQuantity(reagent); if (quant >= totalReagentsToRemove[reagent]) { quant = totalReagentsToRemove[reagent]; totalReagentsToRemove.Remove(reagent); } else { totalReagentsToRemove[reagent] -= quant; } solutionContainerSystem.TryRemoveReagent(item, solution, reagent, quant); } } } foreach (var recipeSolid in recipe.IngredientsSolids) { for (var i = 0; i < recipeSolid.Value; i++) { foreach (var item in _storage.ContainedEntities) { var metaData = _entities.GetComponent<MetaDataComponent>(item); if (metaData.EntityPrototype == null) { continue; } if (metaData.EntityPrototype.ID == recipeSolid.Key) { _storage.Remove(item); _entities.DeleteEntity(item); break; } } } } } private bool CanSatisfyRecipe(FoodRecipePrototype recipe, Dictionary<string, int> solids, Dictionary<string, FixedPoint2> reagents) { if (_currentCookTimerTime != recipe.CookTime) { return false; } foreach (var solid in recipe.IngredientsSolids) { if (!solids.ContainsKey(solid.Key)) return false; if (solids[solid.Key] < solid.Value) return false; } foreach (var reagent in recipe.IngredientsReagents) { if (!reagents.ContainsKey(reagent.Key)) return false; if (reagents[reagent.Key] < reagent.Value) return false; } return true; } private void ClickSound() { SoundSystem.Play(Filter.Pvs(Owner), _clickSound.GetSound(), Owner, AudioParams.Default.WithVolume(-2f)); } SuicideKind ISuicideAct.Suicide(EntityUid victim, IChatManager chat) { var headCount = 0; if (_entities.TryGetComponent<SharedBodyComponent?>(victim, out var body)) { var headSlots = body.GetSlotsOfType(BodyPartType.Head); foreach (var slot in headSlots) { var part = slot.Part; if (part == null || !body.TryDropPart(slot, out var dropped)) { continue; } foreach (var droppedPart in dropped.Values) { if (droppedPart.PartType != BodyPartType.Head) { continue; } _storage.Insert(droppedPart.Owner); headCount++; } } } var othersMessage = headCount > 1 ? Loc.GetString("microwave-component-suicide-multi-head-others-message", ("victim", victim)) : Loc.GetString("microwave-component-suicide-others-message", ("victim", victim)); victim.PopupMessageOtherClients(othersMessage); var selfMessage = headCount > 1 ? Loc.GetString("microwave-component-suicide-multi-head-message") : Loc.GetString("microwave-component-suicide-message"); victim.PopupMessage(selfMessage); _currentCookTimerTime = 10; ClickSound(); _uiDirty = true; Wzhzhzh(); return SuicideKind.Heat; } } public sealed class BeingMicrowavedEvent : HandledEntityEventArgs { public EntityUid Microwave; public BeingMicrowavedEvent(EntityUid microwave) { Microwave = microwave; } } }
#region [License] /** Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: 1. You must give any other recipients of the Work or Derivative Works a copy of this License; and 2. You must cause any modified files to carry prominent notices stating that You changed the files; and 3. You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and 4. If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. */ #endregion using System; using System.Collections; using System.Collections.Generic; using Enyim.Caching; using Enyim.Caching.Memcached; using MemcachedProviders.Common; namespace MemcachedProviders.Cache { public class MemcachedCacheProvider:CacheProvider { #region Membership Variables private long _lDefaultExpireTime = 2000; // default Expire Time private string _strKeySuffix = string.Empty; private MemcachedClient _client = null; #endregion #region ProviderBase Methods public override string Name { get { return "MemcachedCacheProvider"; } } public override string Description { get { return "MemcachedCacheProvider"; } } public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config) { // Initialize values from Web.config. if(null == config) throw (new ArgumentNullException("config")); if(string.IsNullOrEmpty(name)) name = "MemcachedProviders.CacheProvider"; if(string.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "Memcached Cache Provider"); } // Call the base class implementation. base.Initialize(name, config); // Load configuration data. _lDefaultExpireTime = Convert.ToInt64(ConfigurationUtil.GetConfigValue(config["defaultExpireTime"], "2000")); _strKeySuffix = ConfigurationUtil.GetConfigValue(config["keySuffix"], string.Empty); this._client = MemcachedProviders.Common.MemcachedClientService.Instance.Client; } #endregion #region Cache Provider public override long DefaultExpireTime { get { return _lDefaultExpireTime; } set { _lDefaultExpireTime = value; } } public override bool Add(string strKey, object objValue, bool bDefaultExpire) { if(bDefaultExpire == true) { return this._client.Store(StoreMode.Add, _strKeySuffix + strKey, objValue, DateTime.Now.AddMilliseconds(this._lDefaultExpireTime)); } else { return this._client.Store(StoreMode.Set, _strKeySuffix + strKey, objValue); } } public override bool Add(string strKey, object objValue) { return this._client.Store(StoreMode.Set, _strKeySuffix + strKey, objValue); } public override bool Add(string strKey, object objValue, long lNumOfMilliSeconds) { return this._client.Store(StoreMode.Set, _strKeySuffix + strKey, objValue, DateTime.Now.AddMilliseconds(lNumOfMilliSeconds)); } public override bool Add(string strKey, object objValue, TimeSpan timeSpan) { return this._client.Store(StoreMode.Set, _strKeySuffix + strKey, objValue, timeSpan); } public override object Get(string strKey) { return this._client.Get(_strKeySuffix + strKey); } /// <summary> /// This method will work with memcached 1.2.4 and higher /// </summary> /// <param name="keys"></param> /// <returns></returns> public override IDictionary<string, object> Get(params string[] keys) { IList<string> keysList = new List<string>(); foreach(string str in keys) { keysList.Add(_strKeySuffix + str); } IDictionary<string, object> _ret = this._client.Get(keysList); IDictionary<string, object> _retVal = new Dictionary<string, object>(); foreach(string str in _ret.Keys) { _retVal.Add(str.Remove(0, _strKeySuffix.Length), _ret[str]); } return _retVal; } public override void RemoveAll() { this._client.FlushAll(); } public override bool Remove(string strKey) { return this._client.Remove(_strKeySuffix + strKey); } public override string KeySuffix { get { return this._strKeySuffix; } set { this._strKeySuffix = value; } } public override T Get<T>(string strKey) { return this._client.Get<T>(_strKeySuffix + strKey); } public override long Increment(string strKey, long lAmount) { return (long)this._client.Increment(_strKeySuffix + strKey, default(ulong), (ulong)lAmount); } public override long Decrement(string strKey, long lAmount) { return (long)this._client.Decrement(_strKeySuffix + strKey, default(ulong), (ulong)lAmount); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using System.Diagnostics; using System.Data.Common; using Res = System.SR; namespace System.Data.SqlTypes { public sealed class SqlChars : System.Data.SqlTypes.INullable { // -------------------------------------------------------------- // Data members // -------------------------------------------------------------- // SqlChars has five possible states // 1) SqlChars is Null // - m_stream must be null, m_lCuLen must be x_lNull // 2) SqlChars contains a valid buffer, // - m_rgchBuf must not be null, and m_stream must be null // 3) SqlChars contains a valid pointer // - m_rgchBuf could be null or not, // if not null, content is garbage, should never look into it. // - m_stream must be null. // 4) SqlChars contains a SqlStreamChars // - m_stream must not be null // - m_rgchBuf could be null or not. if not null, content is garbage, should never look into it. // - m_lCurLen must be x_lNull. // 5) SqlChars contains a Lazy Materialized Blob (ie, StorageState.Delayed) // internal char[] m_rgchBuf; // Data buffer private long _lCurLen; // Current data length internal SqlStreamChars m_stream; private SqlBytesCharsState _state; private char[] _rgchWorkBuf; // A 1-char work buffer. // The max data length that we support at this time. private const long x_lMaxLen = (long)System.Int32.MaxValue; private const long x_lNull = -1L; // -------------------------------------------------------------- // Constructor(s) // -------------------------------------------------------------- // Public default constructor used for XML serialization public SqlChars() { SetNull(); } // Create a SqlChars with an in-memory buffer public SqlChars(char[] buffer) { m_rgchBuf = buffer; m_stream = null; if (m_rgchBuf == null) { _state = SqlBytesCharsState.Null; _lCurLen = x_lNull; } else { _state = SqlBytesCharsState.Buffer; _lCurLen = (long)m_rgchBuf.Length; } _rgchWorkBuf = null; AssertValid(); } // Create a SqlChars from a SqlString public SqlChars(SqlString value) : this(value.IsNull ? (char[])null : value.Value.ToCharArray()) { } // Create a SqlChars from a SqlStreamChars internal SqlChars(SqlStreamChars s) { m_rgchBuf = null; _lCurLen = x_lNull; m_stream = s; _state = (s == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream; _rgchWorkBuf = null; AssertValid(); } // -------------------------------------------------------------- // Public properties // -------------------------------------------------------------- // INullable public bool IsNull { get { return _state == SqlBytesCharsState.Null; } } // Property: the in-memory buffer of SqlChars // Return Buffer even if SqlChars is Null. public char[] Buffer { get { if (FStream()) { CopyStreamToBuffer(); } return m_rgchBuf; } } // Property: the actual length of the data public long Length { get { switch (_state) { case SqlBytesCharsState.Null: throw new SqlNullValueException(); case SqlBytesCharsState.Stream: return m_stream.Length; default: return _lCurLen; } } } // Property: the max length of the data // Return MaxLength even if SqlChars is Null. // When the buffer is also null, return -1. // If containing a Stream, return -1. public long MaxLength { get { switch (_state) { case SqlBytesCharsState.Stream: return -1L; default: return (m_rgchBuf == null) ? -1L : (long)m_rgchBuf.Length; } } } // Property: get a copy of the data in a new char[] array. public char[] Value { get { char[] buffer; switch (_state) { case SqlBytesCharsState.Null: throw new SqlNullValueException(); case SqlBytesCharsState.Stream: if (m_stream.Length > x_lMaxLen) throw new SqlTypeException(Res.GetString(Res.SqlMisc_BufferInsufficientMessage)); buffer = new char[m_stream.Length]; if (m_stream.Position != 0) m_stream.Seek(0, SeekOrigin.Begin); m_stream.Read(buffer, 0, checked((int)m_stream.Length)); break; default: buffer = new char[_lCurLen]; Array.Copy(m_rgchBuf, buffer, (int)_lCurLen); break; } return buffer; } } // class indexer public char this[long offset] { get { if (offset < 0 || offset >= this.Length) throw new ArgumentOutOfRangeException("offset"); if (_rgchWorkBuf == null) _rgchWorkBuf = new char[1]; Read(offset, _rgchWorkBuf, 0, 1); return _rgchWorkBuf[0]; } set { if (_rgchWorkBuf == null) _rgchWorkBuf = new char[1]; _rgchWorkBuf[0] = value; Write(offset, _rgchWorkBuf, 0, 1); } } internal SqlStreamChars Stream { get { return FStream() ? m_stream : new StreamOnSqlChars(this); } set { _lCurLen = x_lNull; m_stream = value; _state = (value == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream; AssertValid(); } } public StorageState Storage { get { switch (_state) { case SqlBytesCharsState.Null: throw new SqlNullValueException(); case SqlBytesCharsState.Stream: return StorageState.Stream; case SqlBytesCharsState.Buffer: return StorageState.Buffer; default: return StorageState.UnmanagedBuffer; } } } // -------------------------------------------------------------- // Public methods // -------------------------------------------------------------- public void SetNull() { _lCurLen = x_lNull; m_stream = null; _state = SqlBytesCharsState.Null; AssertValid(); } // Set the current length of the data // If the SqlChars is Null, setLength will make it non-Null. public void SetLength(long value) { if (value < 0) throw new ArgumentOutOfRangeException("value"); if (FStream()) { m_stream.SetLength(value); } else { // If there is a buffer, even the value of SqlChars is Null, // still allow setting length to zero, which will make it not Null. // If the buffer is null, raise exception // if (null == m_rgchBuf) throw new SqlTypeException(Res.GetString(Res.SqlMisc_NoBufferMessage)); if (value > (long)m_rgchBuf.Length) throw new ArgumentOutOfRangeException("value"); else if (IsNull) // At this point we know that value is small enough // Go back in buffer mode _state = SqlBytesCharsState.Buffer; _lCurLen = value; } AssertValid(); } // Read data of specified length from specified offset into a buffer public long Read(long offset, char[] buffer, int offsetInBuffer, int count) { if (IsNull) throw new SqlNullValueException(); // Validate the arguments if (buffer == null) throw new ArgumentNullException("buffer"); if (offset > this.Length || offset < 0) throw new ArgumentOutOfRangeException("offset"); if (offsetInBuffer > buffer.Length || offsetInBuffer < 0) throw new ArgumentOutOfRangeException("offsetInBuffer"); if (count < 0 || count > buffer.Length - offsetInBuffer) throw new ArgumentOutOfRangeException("count"); // Adjust count based on data length if (count > this.Length - offset) count = (int)(this.Length - offset); if (count != 0) { switch (_state) { case SqlBytesCharsState.Stream: if (m_stream.Position != offset) m_stream.Seek(offset, SeekOrigin.Begin); m_stream.Read(buffer, offsetInBuffer, count); break; default: // ProjectK\Core doesn't support long-typed array indexers Debug.Assert(offset < int.MaxValue); Array.Copy(m_rgchBuf, checked((int)offset), buffer, offsetInBuffer, count); break; } } return count; } // Write data of specified length into the SqlChars from specified offset public void Write(long offset, char[] buffer, int offsetInBuffer, int count) { if (FStream()) { if (m_stream.Position != offset) m_stream.Seek(offset, SeekOrigin.Begin); m_stream.Write(buffer, offsetInBuffer, count); } else { // Validate the arguments if (buffer == null) throw new ArgumentNullException("buffer"); if (m_rgchBuf == null) throw new SqlTypeException(Res.GetString(Res.SqlMisc_NoBufferMessage)); if (offset < 0) throw new ArgumentOutOfRangeException("offset"); if (offset > m_rgchBuf.Length) throw new SqlTypeException(Res.GetString(Res.SqlMisc_BufferInsufficientMessage)); if (offsetInBuffer < 0 || offsetInBuffer > buffer.Length) throw new ArgumentOutOfRangeException("offsetInBuffer"); if (count < 0 || count > buffer.Length - offsetInBuffer) throw new ArgumentOutOfRangeException("count"); if (count > m_rgchBuf.Length - offset) throw new SqlTypeException(Res.GetString(Res.SqlMisc_BufferInsufficientMessage)); if (IsNull) { // If NULL and there is buffer inside, we only allow writing from // offset zero. // if (offset != 0) throw new SqlTypeException(Res.GetString(Res.SqlMisc_WriteNonZeroOffsetOnNullMessage)); // treat as if our current length is zero. // Note this has to be done after all inputs are validated, so that // we won't throw exception after this point. // _lCurLen = 0; _state = SqlBytesCharsState.Buffer; } else if (offset > _lCurLen) { // Don't allow writing from an offset that this larger than current length. // It would leave uninitialized data in the buffer. // throw new SqlTypeException(Res.GetString(Res.SqlMisc_WriteOffsetLargerThanLenMessage)); } if (count != 0) { // ProjectK\Core doesn't support long-typed array indexers Debug.Assert(offset < int.MaxValue); Array.Copy(buffer, offsetInBuffer, m_rgchBuf, checked((int)offset), count); // If the last position that has been written is after // the current data length, reset the length if (_lCurLen < offset + count) _lCurLen = offset + count; } } AssertValid(); } public SqlString ToSqlString() { return IsNull ? SqlString.Null : new String(Value); } // -------------------------------------------------------------- // Conversion operators // -------------------------------------------------------------- // Alternative method: ToSqlString() public static explicit operator SqlString(SqlChars value) { return value.ToSqlString(); } // Alternative method: constructor SqlChars(SqlString) public static explicit operator SqlChars(SqlString value) { return new SqlChars(value); } // -------------------------------------------------------------- // Private utility functions // -------------------------------------------------------------- [System.Diagnostics.Conditional("DEBUG")] private void AssertValid() { Debug.Assert(_state >= SqlBytesCharsState.Null && _state <= SqlBytesCharsState.Stream); if (IsNull) { } else { Debug.Assert((_lCurLen >= 0 && _lCurLen <= x_lMaxLen) || FStream()); Debug.Assert(FStream() || (m_rgchBuf != null && _lCurLen <= m_rgchBuf.Length)); Debug.Assert(!FStream() || (_lCurLen == x_lNull)); } Debug.Assert(_rgchWorkBuf == null || _rgchWorkBuf.Length == 1); } // whether the SqlChars contains a Stream internal bool FStream() { return _state == SqlBytesCharsState.Stream; } // Copy the data from the Stream to the array buffer. // If the SqlChars doesn't hold a buffer or the buffer // is not big enough, allocate new char array. private void CopyStreamToBuffer() { Debug.Assert(FStream()); long lStreamLen = m_stream.Length; if (lStreamLen >= x_lMaxLen) throw new SqlTypeException(Res.GetString(Res.SqlMisc_BufferInsufficientMessage)); if (m_rgchBuf == null || m_rgchBuf.Length < lStreamLen) m_rgchBuf = new char[lStreamLen]; if (m_stream.Position != 0) m_stream.Seek(0, SeekOrigin.Begin); m_stream.Read(m_rgchBuf, 0, (int)lStreamLen); m_stream = null; _lCurLen = lStreamLen; _state = SqlBytesCharsState.Buffer; AssertValid(); } // -------------------------------------------------------------- // Static fields, properties // -------------------------------------------------------------- // Get a Null instance. // Since SqlChars is mutable, have to be property and create a new one each time. public static SqlChars Null { get { return new SqlChars((char[])null); } } } // class SqlChars // StreamOnSqlChars is a stream build on top of SqlChars, and // provides the Stream interface. The purpose is to help users // to read/write SqlChars object. internal sealed class StreamOnSqlChars : SqlStreamChars { // -------------------------------------------------------------- // Data members // -------------------------------------------------------------- private SqlChars _sqlchars; // the SqlChars object private long _lPosition; // -------------------------------------------------------------- // Constructor(s) // -------------------------------------------------------------- internal StreamOnSqlChars(SqlChars s) { _sqlchars = s; _lPosition = 0; } // -------------------------------------------------------------- // Public properties // -------------------------------------------------------------- public override bool IsNull { get { return _sqlchars == null || _sqlchars.IsNull; } } // Always can read/write/seek, unless sb is null, // which means the stream has been closed. public override bool CanRead { get { return _sqlchars != null && !_sqlchars.IsNull; } } public override bool CanSeek { get { return _sqlchars != null; } } public override bool CanWrite { get { return _sqlchars != null && (!_sqlchars.IsNull || _sqlchars.m_rgchBuf != null); } } public override long Length { get { CheckIfStreamClosed("get_Length"); return _sqlchars.Length; } } public override long Position { get { CheckIfStreamClosed("get_Position"); return _lPosition; } set { CheckIfStreamClosed("set_Position"); if (value < 0 || value > _sqlchars.Length) throw new ArgumentOutOfRangeException("value"); else _lPosition = value; } } // -------------------------------------------------------------- // Public methods // -------------------------------------------------------------- public override long Seek(long offset, SeekOrigin origin) { CheckIfStreamClosed("Seek"); long lPosition = 0; switch (origin) { case SeekOrigin.Begin: if (offset < 0 || offset > _sqlchars.Length) throw ADP.ArgumentOutOfRange("offset"); _lPosition = offset; break; case SeekOrigin.Current: lPosition = _lPosition + offset; if (lPosition < 0 || lPosition > _sqlchars.Length) throw ADP.ArgumentOutOfRange("offset"); _lPosition = lPosition; break; case SeekOrigin.End: lPosition = _sqlchars.Length + offset; if (lPosition < 0 || lPosition > _sqlchars.Length) throw ADP.ArgumentOutOfRange("offset"); _lPosition = lPosition; break; default: throw ADP.ArgumentOutOfRange("offset"); ; } return _lPosition; } // The Read/Write/Readchar/Writechar simply delegates to SqlChars public override int Read(char[] buffer, int offset, int count) { CheckIfStreamClosed("Read"); if (buffer == null) throw new ArgumentNullException("buffer"); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException("offset"); if (count < 0 || count > buffer.Length - offset) throw new ArgumentOutOfRangeException("count"); int icharsRead = (int)_sqlchars.Read(_lPosition, buffer, offset, count); _lPosition += icharsRead; return icharsRead; } public override void Write(char[] buffer, int offset, int count) { CheckIfStreamClosed("Write"); if (buffer == null) throw new ArgumentNullException("buffer"); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException("offset"); if (count < 0 || count > buffer.Length - offset) throw new ArgumentOutOfRangeException("count"); _sqlchars.Write(_lPosition, buffer, offset, count); _lPosition += count; } public override int ReadChar() { CheckIfStreamClosed("ReadChar"); // If at the end of stream, return -1, rather than call SqlChars.Readchar, // which will throw exception. This is the behavior for Stream. // if (_lPosition >= _sqlchars.Length) return -1; int ret = _sqlchars[_lPosition]; _lPosition++; return ret; } public override void WriteChar(char value) { CheckIfStreamClosed("WriteChar"); _sqlchars[_lPosition] = value; _lPosition++; } public override void SetLength(long value) { CheckIfStreamClosed("SetLength"); _sqlchars.SetLength(value); if (_lPosition > value) _lPosition = value; } // Flush is a no-op if underlying SqlChars is not a stream on SqlChars public override void Flush() { if (_sqlchars.FStream()) _sqlchars.m_stream.Flush(); } protected override void Dispose(bool disposing) { // When m_sqlchars is null, it means the stream has been closed, and // any opearation in the future should fail. // This is the only case that m_sqlchars is null. _sqlchars = null; } // -------------------------------------------------------------- // Private utility functions // -------------------------------------------------------------- private bool FClosed() { return _sqlchars == null; } private void CheckIfStreamClosed(string methodname) { if (FClosed()) throw ADP.StreamClosed(methodname); } } // class StreamOnSqlChars } // namespace System.Data.SqlTypes
// // async.cs: Asynchronous functions // // Author: // Marek Safar (marek.safar@gmail.com) // // Dual licensed under the terms of the MIT X11 or GNU GPL // // Copyright 2011 Novell, Inc. // Copyright 2011-2012 Xamarin Inc. // using System; using System.Collections.Generic; using System.Linq; using System.Collections; #if STATIC using IKVM.Reflection; using IKVM.Reflection.Emit; #else using System.Reflection; using System.Reflection.Emit; #endif namespace Mono.CSharp { public class Await : ExpressionStatement { Expression expr; AwaitStatement stmt; public Await (Expression expr, Location loc) { this.expr = expr; this.loc = loc; } public Expression Expr { get { return expr; } } public AwaitStatement Statement { get { return stmt; } } protected override void CloneTo (CloneContext clonectx, Expression target) { var t = (Await) target; t.expr = expr.Clone (clonectx); } public override Expression CreateExpressionTree (ResolveContext ec) { throw new NotImplementedException ("ET"); } public override bool ContainsEmitWithAwait () { return true; } public override void FlowAnalysis (FlowAnalysisContext fc) { stmt.Expr.FlowAnalysis (fc); stmt.RegisterResumePoint (); } protected override Expression DoResolve (ResolveContext rc) { if (rc.HasSet (ResolveContext.Options.LockScope)) { rc.Report.Error (1996, loc, "The `await' operator cannot be used in the body of a lock statement"); } if (rc.IsUnsafe) { rc.Report.Error (4004, loc, "The `await' operator cannot be used in an unsafe context"); } var bc = (BlockContext) rc; stmt = new AwaitStatement (expr, loc); if (!stmt.Resolve (bc)) return null; if (rc.HasSet (ResolveContext.Options.FinallyScope) && rc.CurrentAnonymousMethod != null) { var ats = (AsyncTaskStorey)rc.CurrentAnonymousMethod.Storey; ats.HasAwaitInsideFinally = true; } type = stmt.ResultType; eclass = ExprClass.Variable; return this; } public override void Emit (EmitContext ec) { stmt.EmitPrologue (ec); using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) { stmt.Emit (ec); } } public override Expression EmitToField (EmitContext ec) { stmt.EmitPrologue (ec); return stmt.GetResultExpression (ec); } public void EmitAssign (EmitContext ec, FieldExpr field) { stmt.EmitPrologue (ec); field.InstanceExpression.Emit (ec); stmt.Emit (ec); } public override void EmitStatement (EmitContext ec) { stmt.EmitStatement (ec); } public override Reachability MarkReachable (Reachability rc) { return stmt.MarkReachable (rc); } public override object Accept (StructuralVisitor visitor) { return visitor.Visit (this); } } public class AwaitStatement : YieldStatement<AsyncInitializer> { public sealed class AwaitableMemberAccess : MemberAccess { public AwaitableMemberAccess (Expression expr) : base (expr, "GetAwaiter") { } public bool ProbingMode { get; set; } public override void Error_TypeDoesNotContainDefinition (ResolveContext rc, TypeSpec type, string name) { Error_OperatorCannotBeApplied (rc, type); } protected override void Error_OperatorCannotBeApplied (ResolveContext rc, TypeSpec type) { if (ProbingMode) return; var invocation = LeftExpression as Invocation; if (invocation != null && invocation.MethodGroup != null && (invocation.MethodGroup.BestCandidate.Modifiers & Modifiers.ASYNC) != 0) { rc.Report.Error (4008, loc, "Cannot await void method `{0}'. Consider changing method return type to `Task'", invocation.GetSignatureForError ()); } else if (type != InternalType.ErrorType) { rc.Report.Error (4001, loc, "Cannot await `{0}' expression", type.GetSignatureForError ()); } } } sealed class GetResultInvocation : Invocation { public GetResultInvocation (MethodGroupExpr mge, Arguments arguments) : base (null, arguments) { mg = mge; type = mg.BestCandidateReturnType; } public override Expression EmitToField (EmitContext ec) { return this; } } Field awaiter; AwaiterDefinition awaiter_definition; TypeSpec type; TypeSpec result_type; public AwaitStatement (Expression expr, Location loc) : base (expr, loc) { unwind_protect = true; } #region Properties bool IsDynamic { get { return awaiter_definition == null; } } public TypeSpec ResultType { get { return result_type; } } #endregion protected override void DoEmit (EmitContext ec) { using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) { GetResultExpression (ec).Emit (ec); } } public Expression GetResultExpression (EmitContext ec) { var fe_awaiter = new FieldExpr (awaiter, loc); fe_awaiter.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc); // // result = awaiter.GetResult (); // if (IsDynamic) { var rc = new ResolveContext (ec.MemberContext); return new Invocation (new MemberAccess (fe_awaiter, "GetResult"), new Arguments (0)).Resolve (rc); } var mg_result = MethodGroupExpr.CreatePredefined (awaiter_definition.GetResult, fe_awaiter.Type, loc); mg_result.InstanceExpression = fe_awaiter; return new GetResultInvocation (mg_result, new Arguments (0)); } public void EmitPrologue (EmitContext ec) { awaiter = ((AsyncTaskStorey) machine_initializer.Storey).AddAwaiter (expr.Type); var fe_awaiter = new FieldExpr (awaiter, loc); fe_awaiter.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc); Label skip_continuation = ec.DefineLabel (); using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) { // // awaiter = expr.GetAwaiter (); // fe_awaiter.EmitAssign (ec, expr, false, false); Expression completed_expr; if (IsDynamic) { var rc = new ResolveContext (ec.MemberContext); Arguments dargs = new Arguments (1); dargs.Add (new Argument (fe_awaiter)); completed_expr = new DynamicMemberBinder ("IsCompleted", dargs, loc).Resolve (rc); dargs = new Arguments (1); dargs.Add (new Argument (completed_expr)); completed_expr = new DynamicConversion (ec.Module.Compiler.BuiltinTypes.Bool, 0, dargs, loc).Resolve (rc); } else { var pe = PropertyExpr.CreatePredefined (awaiter_definition.IsCompleted, loc); pe.InstanceExpression = fe_awaiter; completed_expr = pe; } completed_expr.EmitBranchable (ec, skip_continuation, true); } base.DoEmit (ec); // // The stack has to be empty before calling await continuation. We handle this // by lifting values which would be left on stack into class fields. The process // is quite complicated and quite hard to test because any expression can possibly // leave a value on the stack. // // Following assert fails when some of expression called before is missing EmitToField // or parent expression fails to find await in children expressions // ec.AssertEmptyStack (); var storey = (AsyncTaskStorey) machine_initializer.Storey; if (IsDynamic) { storey.EmitAwaitOnCompletedDynamic (ec, fe_awaiter); } else { storey.EmitAwaitOnCompleted (ec, fe_awaiter); } // Return ok machine_initializer.EmitLeave (ec, unwind_protect); ec.MarkLabel (resume_point); ec.MarkLabel (skip_continuation); } public void EmitStatement (EmitContext ec) { EmitPrologue (ec); DoEmit (ec); awaiter.IsAvailableForReuse = true; if (ResultType.Kind != MemberKind.Void) ec.Emit (OpCodes.Pop); } void Error_WrongAwaiterPattern (ResolveContext rc, TypeSpec awaiter) { rc.Report.Error (4011, loc, "The awaiter type `{0}' must have suitable IsCompleted and GetResult members", awaiter.GetSignatureForError ()); } public override bool Resolve (BlockContext bc) { if (bc.CurrentBlock is Linq.QueryBlock) { bc.Report.Error (1995, loc, "The `await' operator may only be used in a query expression within the first collection expression of the initial `from' clause or within the collection expression of a `join' clause"); return false; } if (!base.Resolve (bc)) return false; type = expr.Type; Arguments args = new Arguments (0); // // The await expression is of dynamic type // if (type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) { result_type = type; expr = new Invocation (new MemberAccess (expr, "GetAwaiter"), args).Resolve (bc); return true; } // // Check whether the expression is awaitable // Expression ama = new AwaitableMemberAccess (expr).Resolve (bc); if (ama == null) return false; var errors_printer = new SessionReportPrinter (); var old = bc.Report.SetPrinter (errors_printer); // // The expression await t is classified the same way as the expression (t).GetAwaiter().GetResult(). // ama = new Invocation (new ParenthesizedExpression (ama, Location.Null), args).Resolve (bc); bc.Report.SetPrinter (old); if (errors_printer.ErrorsCount > 0 || !MemberAccess.IsValidDotExpression (ama.Type)) { bc.Report.Error (1986, expr.Location, "The `await' operand type `{0}' must have suitable GetAwaiter method", expr.Type.GetSignatureForError ()); return false; } var awaiter_type = ama.Type; awaiter_definition = bc.Module.GetAwaiter (awaiter_type); if (!awaiter_definition.IsValidPattern) { Error_WrongAwaiterPattern (bc, awaiter_type); return false; } if (!awaiter_definition.INotifyCompletion) { bc.Report.Error (4027, loc, "The awaiter type `{0}' must implement interface `{1}'", awaiter_type.GetSignatureForError (), bc.Module.PredefinedTypes.INotifyCompletion.GetSignatureForError ()); return false; } expr = ama; result_type = awaiter_definition.GetResult.ReturnType; return true; } } class AsyncInitializerStatement : StatementExpression { public AsyncInitializerStatement (AsyncInitializer expr) : base (expr) { } protected override bool DoFlowAnalysis (FlowAnalysisContext fc) { base.DoFlowAnalysis (fc); var init = (AsyncInitializer) Expr; var res = !init.Block.HasReachableClosingBrace; var storey = (AsyncTaskStorey) init.Storey; if (storey.ReturnType.IsGenericTask) return res; return true; } public override Reachability MarkReachable (Reachability rc) { if (!rc.IsUnreachable) reachable = true; var init = (AsyncInitializer) Expr; rc = init.Block.MarkReachable (rc); var storey = (AsyncTaskStorey) init.Storey; // // Explicit return is required for Task<T> state machine // if (storey.ReturnType != null && storey.ReturnType.IsGenericTask) return rc; return Reachability.CreateUnreachable (); } } public class AsyncInitializer : StateMachineInitializer { TypeInferenceContext return_inference; public AsyncInitializer (ParametersBlock block, TypeDefinition host, TypeSpec returnType) : base (block, host, returnType) { } #region Properties public override string ContainerType { get { return "async state machine block"; } } public TypeSpec DelegateType { get; set; } public StackFieldExpr HoistedReturnState { get; set; } public override bool IsIterator { get { return false; } } public TypeInferenceContext ReturnTypeInference { get { return return_inference; } } #endregion protected override BlockContext CreateBlockContext (BlockContext bc) { var ctx = base.CreateBlockContext (bc); var am = bc.CurrentAnonymousMethod as AnonymousMethodBody; if (am != null) return_inference = am.ReturnTypeInference; ctx.Set (ResolveContext.Options.TryScope); return ctx; } public override void Emit (EmitContext ec) { throw new NotImplementedException (); } public void EmitCatchBlock (EmitContext ec) { var catch_value = LocalVariable.CreateCompilerGenerated (ec.Module.Compiler.BuiltinTypes.Exception, block, Location); ec.BeginCatchBlock (catch_value.Type); catch_value.EmitAssign (ec); ec.EmitThis (); ec.EmitInt ((int) IteratorStorey.State.After); ec.Emit (OpCodes.Stfld, storey.PC.Spec); ((AsyncTaskStorey) Storey).EmitSetException (ec, new LocalVariableReference (catch_value, Location)); ec.Emit (OpCodes.Leave, move_next_ok); ec.EndExceptionBlock (); } protected override void EmitMoveNextEpilogue (EmitContext ec) { var storey = (AsyncTaskStorey) Storey; storey.EmitSetResult (ec); } public override void EmitStatement (EmitContext ec) { var storey = (AsyncTaskStorey) Storey; storey.EmitInitializer (ec); ec.Emit (OpCodes.Ret); } public override Reachability MarkReachable (Reachability rc) { // // Reachability has been done in AsyncInitializerStatement // return rc; } } class AsyncTaskStorey : StateMachine { int awaiters; Field builder; readonly TypeSpec return_type; MethodSpec set_result; MethodSpec set_exception; MethodSpec builder_factory; MethodSpec builder_start; PropertySpec task; int locals_captured; Dictionary<TypeSpec, List<Field>> stack_fields; Dictionary<TypeSpec, List<Field>> awaiter_fields; public AsyncTaskStorey (ParametersBlock block, IMemberContext context, AsyncInitializer initializer, TypeSpec type) : base (block, initializer.Host, context.CurrentMemberDefinition as MemberBase, context.CurrentTypeParameters, "async", MemberKind.Struct) { return_type = type; awaiter_fields = new Dictionary<TypeSpec, List<Field>> (); } #region Properties public bool HasAwaitInsideFinally { get; set; } public Expression HoistedReturnValue { get; set; } public TypeSpec ReturnType { get { return return_type; } } public PropertySpec Task { get { return task; } } protected override TypeAttributes TypeAttr { get { return base.TypeAttr & ~TypeAttributes.SequentialLayout; } } #endregion public Field AddAwaiter (TypeSpec type) { if (mutator != null) type = mutator.Mutate (type); List<Field> existing_fields; if (awaiter_fields.TryGetValue (type, out existing_fields)) { foreach (var f in existing_fields) { if (f.IsAvailableForReuse) { f.IsAvailableForReuse = false; return f; } } } var field = AddCompilerGeneratedField ("$awaiter" + awaiters++.ToString ("X"), new TypeExpression (type, Location), true); field.Define (); if (existing_fields == null) { existing_fields = new List<Field> (); awaiter_fields.Add (type, existing_fields); } existing_fields.Add (field); return field; } public Field AddCapturedLocalVariable (TypeSpec type, bool requiresUninitialized = false) { if (mutator != null) type = mutator.Mutate (type); List<Field> existing_fields = null; if (stack_fields == null) { stack_fields = new Dictionary<TypeSpec, List<Field>> (); } else if (stack_fields.TryGetValue (type, out existing_fields) && !requiresUninitialized) { foreach (var f in existing_fields) { if (f.IsAvailableForReuse) { f.IsAvailableForReuse = false; return f; } } } var field = AddCompilerGeneratedField ("$stack" + locals_captured++.ToString ("X"), new TypeExpression (type, Location), true); field.Define (); if (existing_fields == null) { existing_fields = new List<Field> (); stack_fields.Add (type, existing_fields); } existing_fields.Add (field); return field; } protected override bool DoDefineMembers () { PredefinedType builder_type; PredefinedMember<MethodSpec> bf; PredefinedMember<MethodSpec> bs; PredefinedMember<MethodSpec> sr; PredefinedMember<MethodSpec> se; PredefinedMember<MethodSpec> sm; bool has_task_return_type = false; var pred_members = Module.PredefinedMembers; if (return_type.Kind == MemberKind.Void) { builder_type = Module.PredefinedTypes.AsyncVoidMethodBuilder; bf = pred_members.AsyncVoidMethodBuilderCreate; bs = pred_members.AsyncVoidMethodBuilderStart; sr = pred_members.AsyncVoidMethodBuilderSetResult; se = pred_members.AsyncVoidMethodBuilderSetException; sm = pred_members.AsyncVoidMethodBuilderSetStateMachine; } else if (return_type == Module.PredefinedTypes.Task.TypeSpec) { builder_type = Module.PredefinedTypes.AsyncTaskMethodBuilder; bf = pred_members.AsyncTaskMethodBuilderCreate; bs = pred_members.AsyncTaskMethodBuilderStart; sr = pred_members.AsyncTaskMethodBuilderSetResult; se = pred_members.AsyncTaskMethodBuilderSetException; sm = pred_members.AsyncTaskMethodBuilderSetStateMachine; task = pred_members.AsyncTaskMethodBuilderTask.Get (); } else { builder_type = Module.PredefinedTypes.AsyncTaskMethodBuilderGeneric; bf = pred_members.AsyncTaskMethodBuilderGenericCreate; bs = pred_members.AsyncTaskMethodBuilderGenericStart; sr = pred_members.AsyncTaskMethodBuilderGenericSetResult; se = pred_members.AsyncTaskMethodBuilderGenericSetException; sm = pred_members.AsyncTaskMethodBuilderGenericSetStateMachine; task = pred_members.AsyncTaskMethodBuilderGenericTask.Get (); has_task_return_type = true; } set_result = sr.Get (); set_exception = se.Get (); builder_factory = bf.Get (); builder_start = bs.Get (); var istate_machine = Module.PredefinedTypes.IAsyncStateMachine; var set_statemachine = sm.Get (); if (!builder_type.Define () || !istate_machine.Define () || set_result == null || builder_factory == null || set_exception == null || set_statemachine == null || builder_start == null || !Module.PredefinedTypes.INotifyCompletion.Define ()) { Report.Error (1993, Location, "Cannot find compiler required types for asynchronous functions support. Are you targeting the wrong framework version?"); return base.DoDefineMembers (); } var bt = builder_type.TypeSpec; // // Inflate generic Task types // if (has_task_return_type) { var task_return_type = return_type.TypeArguments; if (mutator != null) task_return_type = mutator.Mutate (task_return_type); bt = bt.MakeGenericType (Module, task_return_type); set_result = MemberCache.GetMember (bt, set_result); set_exception = MemberCache.GetMember (bt, set_exception); set_statemachine = MemberCache.GetMember (bt, set_statemachine); if (task != null) task = MemberCache.GetMember (bt, task); } builder = AddCompilerGeneratedField ("$builder", new TypeExpression (bt, Location)); Field rfield; if (has_task_return_type && HasAwaitInsideFinally) { // // Special case async block with return value from finally clause. In such case // we rewrite all return expresison stores to stfld to $return. Instead of treating // returns outside of finally and inside of finally differently. // rfield = AddCompilerGeneratedField ("$return", new TypeExpression (bt.TypeArguments [0], Location)); } else { rfield = null; } var set_state_machine = new Method (this, new TypeExpression (Compiler.BuiltinTypes.Void, Location), Modifiers.COMPILER_GENERATED | Modifiers.DEBUGGER_HIDDEN | Modifiers.PUBLIC, new MemberName ("SetStateMachine"), ParametersCompiled.CreateFullyResolved ( new Parameter (new TypeExpression (istate_machine.TypeSpec, Location), "stateMachine", Parameter.Modifier.NONE, null, Location), istate_machine.TypeSpec), null); ToplevelBlock block = new ToplevelBlock (Compiler, set_state_machine.ParameterInfo, Location); block.IsCompilerGenerated = true; set_state_machine.Block = block; Members.Add (set_state_machine); if (!base.DoDefineMembers ()) return false; // // Fabricates SetStateMachine method // // public void SetStateMachine (IAsyncStateMachine stateMachine) // { // $builder.SetStateMachine (stateMachine); // } // var mg = MethodGroupExpr.CreatePredefined (set_statemachine, bt, Location); mg.InstanceExpression = new FieldExpr (builder, Location); var param_reference = block.GetParameterReference (0, Location); param_reference.Type = istate_machine.TypeSpec; param_reference.eclass = ExprClass.Variable; var args = new Arguments (1); args.Add (new Argument (param_reference)); set_state_machine.Block.AddStatement (new StatementExpression (new Invocation (mg, args))); if (has_task_return_type) { if (rfield != null) { HoistedReturnValue = new FieldExpr (rfield, Location) { InstanceExpression = new CompilerGeneratedThis (CurrentType, Location.Null) }; } else { HoistedReturnValue = TemporaryVariableReference.Create (bt.TypeArguments [0], StateMachineMethod.Block, Location); } } return true; } public void EmitAwaitOnCompletedDynamic (EmitContext ec, FieldExpr awaiter) { var critical = Module.PredefinedTypes.ICriticalNotifyCompletion; if (!critical.Define ()) { throw new NotImplementedException (); } var temp_critical = new LocalTemporary (critical.TypeSpec); var label_critical = ec.DefineLabel (); var label_end = ec.DefineLabel (); // // Special path for dynamic awaiters // // var awaiter = this.$awaiter as ICriticalNotifyCompletion; // if (awaiter == null) { // var completion = (INotifyCompletion) this.$awaiter; // this.$builder.AwaitOnCompleted (ref completion, ref this); // } else { // this.$builder.AwaitUnsafeOnCompleted (ref awaiter, ref this); // } // awaiter.Emit (ec); ec.Emit (OpCodes.Isinst, critical.TypeSpec); temp_critical.Store (ec); temp_critical.Emit (ec); ec.Emit (OpCodes.Brtrue_S, label_critical); var temp = new LocalTemporary (Module.PredefinedTypes.INotifyCompletion.TypeSpec); awaiter.Emit (ec); ec.Emit (OpCodes.Castclass, temp.Type); temp.Store (ec); EmitOnCompleted (ec, temp, false); temp.Release (ec); ec.Emit (OpCodes.Br_S, label_end); ec.MarkLabel (label_critical); EmitOnCompleted (ec, temp_critical, true); ec.MarkLabel (label_end); temp_critical.Release (ec); } public void EmitAwaitOnCompleted (EmitContext ec, FieldExpr awaiter) { bool unsafe_version = false; if (Module.PredefinedTypes.ICriticalNotifyCompletion.Define ()) { unsafe_version = awaiter.Type.ImplementsInterface (Module.PredefinedTypes.ICriticalNotifyCompletion.TypeSpec, false); } EmitOnCompleted (ec, awaiter, unsafe_version); } void EmitOnCompleted (EmitContext ec, Expression awaiter, bool unsafeVersion) { var pm = Module.PredefinedMembers; PredefinedMember<MethodSpec> predefined; bool has_task_return_type = false; if (return_type.Kind == MemberKind.Void) { predefined = unsafeVersion ? pm.AsyncVoidMethodBuilderOnCompletedUnsafe : pm.AsyncVoidMethodBuilderOnCompleted; } else if (return_type == Module.PredefinedTypes.Task.TypeSpec) { predefined = unsafeVersion ? pm.AsyncTaskMethodBuilderOnCompletedUnsafe : pm.AsyncTaskMethodBuilderOnCompleted; } else { predefined = unsafeVersion ? pm.AsyncTaskMethodBuilderGenericOnCompletedUnsafe : pm.AsyncTaskMethodBuilderGenericOnCompleted; has_task_return_type = true; } var on_completed = predefined.Resolve (Location); if (on_completed == null) return; if (has_task_return_type) on_completed = MemberCache.GetMember<MethodSpec> (set_result.DeclaringType, on_completed); on_completed = on_completed.MakeGenericMethod (this, awaiter.Type, ec.CurrentType); var mg = MethodGroupExpr.CreatePredefined (on_completed, on_completed.DeclaringType, Location); mg.InstanceExpression = new FieldExpr (builder, Location) { InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, Location) }; var args = new Arguments (2); args.Add (new Argument (awaiter, Argument.AType.Ref)); args.Add (new Argument (new CompilerGeneratedThis (CurrentType, Location), Argument.AType.Ref)); using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) { mg.EmitCall (ec, args, true); } } public void EmitInitializer (EmitContext ec) { // // Some predefined types are missing // if (builder == null) return; var instance = (TemporaryVariableReference) Instance; var builder_field = builder.Spec; if (MemberName.Arity > 0) { builder_field = MemberCache.GetMember (instance.Type, builder_field); } // // Inflated factory method when task is of generic type // if (builder_factory.DeclaringType.IsGeneric) { var task_return_type = return_type.TypeArguments; var bt = builder_factory.DeclaringType.MakeGenericType (Module, task_return_type); builder_factory = MemberCache.GetMember (bt, builder_factory); builder_start = MemberCache.GetMember (bt, builder_start); } // // stateMachine.$builder = AsyncTaskMethodBuilder<{task-type}>.Create(); // instance.AddressOf (ec, AddressOp.Store); ec.Emit (OpCodes.Call, builder_factory); ec.Emit (OpCodes.Stfld, builder_field); // // stateMachine.$builder.Start<{storey-type}>(ref stateMachine); // instance.AddressOf (ec, AddressOp.Store); ec.Emit (OpCodes.Ldflda, builder_field); if (Task != null) ec.Emit (OpCodes.Dup); instance.AddressOf (ec, AddressOp.Store); ec.Emit (OpCodes.Call, builder_start.MakeGenericMethod (Module, instance.Type)); // // Emits return stateMachine.$builder.Task; // if (Task != null) { var task_get = Task.Get; if (MemberName.Arity > 0) { task_get = MemberCache.GetMember (builder_field.MemberType, task_get); } var pe_task = new PropertyExpr (Task, Location) { InstanceExpression = EmptyExpression.Null, // Comes from the dup above Getter = task_get }; pe_task.Emit (ec); } } public void EmitSetException (EmitContext ec, LocalVariableReference exceptionVariable) { // // $builder.SetException (Exception) // var mg = MethodGroupExpr.CreatePredefined (set_exception, set_exception.DeclaringType, Location); mg.InstanceExpression = new FieldExpr (builder, Location) { InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, Location) }; Arguments args = new Arguments (1); args.Add (new Argument (exceptionVariable)); using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) { mg.EmitCall (ec, args, true); } } public void EmitSetResult (EmitContext ec) { // // $builder.SetResult (); // $builder.SetResult<return-type> (value); // var mg = MethodGroupExpr.CreatePredefined (set_result, set_result.DeclaringType, Location); mg.InstanceExpression = new FieldExpr (builder, Location) { InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, Location) }; Arguments args; if (HoistedReturnValue == null) { args = new Arguments (0); } else { args = new Arguments (1); args.Add (new Argument (HoistedReturnValue)); } using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) { mg.EmitCall (ec, args, true); } } protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class) { base_type = Compiler.BuiltinTypes.ValueType; base_class = null; var istate_machine = Module.PredefinedTypes.IAsyncStateMachine; if (istate_machine.Define ()) { return new[] { istate_machine.TypeSpec }; } return null; } } public class StackFieldExpr : FieldExpr, IExpressionCleanup { public StackFieldExpr (Field field) : base (field, Location.Null) { AutomaticallyReuse = true; } public bool AutomaticallyReuse { get; set; } public bool IsAvailableForReuse { get { var field = (Field) spec.MemberDefinition; return field.IsAvailableForReuse; } private set { var field = (Field) spec.MemberDefinition; field.IsAvailableForReuse = value; } } public override void AddressOf (EmitContext ec, AddressOp mode) { base.AddressOf (ec, mode); if (mode == AddressOp.Load && AutomaticallyReuse) { IsAvailableForReuse = true; } } public override void Emit (EmitContext ec) { base.Emit (ec); if (AutomaticallyReuse) PrepareCleanup (ec); } public void EmitLoad (EmitContext ec) { base.Emit (ec); } public void PrepareCleanup (EmitContext ec) { IsAvailableForReuse = true; // // Release any captured reference type stack variables // to imitate real stack behavour and help GC stuff early // if (TypeSpec.IsReferenceType (type)) { ec.AddStatementEpilog (this); } } void IExpressionCleanup.EmitCleanup (EmitContext ec) { EmitAssign (ec, new NullConstant (type, loc), false, false); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Web; using Funq; using NServiceKit.Common; using NServiceKit.Configuration; using NServiceKit.Html; using NServiceKit.IO; using NServiceKit.Logging; using NServiceKit.ServiceHost; using NServiceKit.WebHost.Endpoints.Extensions; namespace NServiceKit.WebHost.Endpoints { /// <summary> /// Inherit from this class if you want to host your web services inside an /// ASP.NET application. /// </summary> public abstract class AppHostBase : IFunqlet, IDisposable, IAppHost, IHasContainer { private readonly ILog log = LogManager.GetLogger(typeof(AppHostBase)); /// <summary>Gets the instance.</summary> /// /// <value>The instance.</value> public static AppHostBase Instance { get; protected set; } /// <summary>Initializes a new instance of the NServiceKit.WebHost.Endpoints.AppHostBase class.</summary> /// /// <param name="serviceName"> Name of the service.</param> /// <param name="assembliesWithServices">A variable-length parameters list containing assemblies with services.</param> protected AppHostBase(string serviceName, params Assembly[] assembliesWithServices) { EndpointHost.ConfigureHost(this, serviceName, CreateServiceManager(assembliesWithServices)); } /// <summary>Creates service manager.</summary> /// /// <param name="assembliesWithServices">A variable-length parameters list containing assemblies with services.</param> /// /// <returns>The new service manager.</returns> protected virtual ServiceManager CreateServiceManager(params Assembly[] assembliesWithServices) { return new ServiceManager(assembliesWithServices); //Alternative way to inject Container + Service Resolver strategy //return new ServiceManager(new Container(), // new ServiceController(() => assembliesWithServices.ToList().SelectMany(x => x.GetTypes()))); } /// <summary>Gets the service controller.</summary> /// /// <value>The service controller.</value> protected IServiceController ServiceController { get { return EndpointHost.Config.ServiceController; } } /// <summary>Register user-defined custom routes.</summary> /// /// <value>The routes.</value> public IServiceRoutes Routes { get { return EndpointHost.Config.ServiceController.Routes; } } /// <summary>Gets the container.</summary> /// /// <value>The container.</value> public Container Container { get { return EndpointHost.Config.ServiceManager != null ? EndpointHost.Config.ServiceManager.Container : null; } } /// <summary>Initialises this object.</summary> /// /// <exception cref="InvalidDataException">Thrown when an Invalid Data error condition occurs.</exception> public void Init() { if (Instance != null) { throw new InvalidDataException("AppHostBase.Instance has already been set"); } Instance = this; var serviceManager = EndpointHost.Config.ServiceManager; if (serviceManager != null) { serviceManager.Init(); Configure(EndpointHost.Config.ServiceManager.Container); } else { Configure(null); } EndpointHost.AfterInit(); } /// <summary>Configure the given container with the registrations provided by the funqlet.</summary> /// /// <param name="container">Container to register.</param> public abstract void Configure(Container container); /// <summary>Sets a configuration.</summary> /// /// <param name="config">The configuration.</param> public void SetConfig(EndpointHostConfig config) { if (config.ServiceName == null) config.ServiceName = EndpointHostConfig.Instance.ServiceName; if (config.ServiceManager == null) config.ServiceManager = EndpointHostConfig.Instance.ServiceManager; config.ServiceManager.ServiceController.EnableAccessRestrictions = config.EnableAccessRestrictions; EndpointHost.Config = config; } /// <summary>AutoWired Registration of an interface with a concrete type in AppHost IOC on Startup.</summary> /// /// <typeparam name="T"> .</typeparam> /// <typeparam name="TAs">.</typeparam> public void RegisterAs<T, TAs>() where T : TAs { this.Container.RegisterAutoWiredAs<T, TAs>(); } /// <summary>Allows the clean up for executed autowired services and filters. Calls directly after services and filters are executed.</summary> /// /// <param name="instance">.</param> public virtual void Release(object instance) { try { var iocAdapterReleases = Container.Adapter as IRelease; if (iocAdapterReleases != null) { iocAdapterReleases.Release(instance); } else { var disposable = instance as IDisposable; if (disposable != null) disposable.Dispose(); } } catch {/*ignore*/} } /// <summary>Called at the end of each request. Enables Request Scope.</summary> public virtual void OnEndRequest() { foreach (var item in HostContext.Instance.Items.Values) { Release(item); } HostContext.Instance.EndRequest(); } /// <summary>Register dependency in AppHost IOC on Startup.</summary> /// /// <typeparam name="T">.</typeparam> /// <param name="instance">.</param> public void Register<T>(T instance) { this.Container.Register(instance); } /// <summary>Try resolve.</summary> /// /// <typeparam name="T">Generic type parameter.</typeparam> /// /// <returns>A T.</returns> public T TryResolve<T>() { return this.Container.TryResolve<T>(); } /// <summary> /// Resolves from IoC container a specified type instance. /// </summary> /// <typeparam name="T">Type to be resolved.</typeparam> /// <returns>Instance of <typeparamref name="T"/>.</returns> public static T Resolve<T>() { if (Instance == null) throw new InvalidOperationException("AppHostBase is not initialized."); return Instance.Container.Resolve<T>(); } /// <summary> /// Resolves and auto-wires a NServiceKit Service /// </summary> /// <typeparam name="T">Type to be resolved.</typeparam> /// <returns>Instance of <typeparamref name="T"/>.</returns> public static T ResolveService<T>(HttpContext httpCtx) where T : class, IRequiresRequestContext { if (Instance == null) throw new InvalidOperationException("AppHostBase is not initialized."); var service = Instance.Container.Resolve<T>(); if (service == null) return null; service.RequestContext = httpCtx.ToRequestContext(); return service; } /// <summary>Provide a custom model minder for a specific Request DTO.</summary> /// /// <value>The request binders.</value> public Dictionary<Type, Func<IHttpRequest, object>> RequestBinders { get { return EndpointHost.ServiceManager.ServiceController.RequestTypeFactoryMap; } } /// <summary>Register custom ContentType serializers.</summary> /// /// <value>The content type filters.</value> public IContentTypeFilter ContentTypeFilters { get { return EndpointHost.ContentTypeFilter; } } /// <summary>Add Request Filters, to be applied before the dto is deserialized.</summary> /// /// <value>The pre request filters.</value> public List<Action<IHttpRequest, IHttpResponse>> PreRequestFilters { get { return EndpointHost.RawRequestFilters; } } /// <summary>Add Request Filters.</summary> /// /// <value>The request filters.</value> public List<Action<IHttpRequest, IHttpResponse, object>> RequestFilters { get { return EndpointHost.RequestFilters; } } /// <summary>Add Response Filters.</summary> /// /// <value>The response filters.</value> public List<Action<IHttpRequest, IHttpResponse, object>> ResponseFilters { get { return EndpointHost.ResponseFilters; } } /// <summary>Add alternative HTML View Engines.</summary> /// /// <value>The view engines.</value> public List<IViewEngine> ViewEngines { get { return EndpointHost.ViewEngines; } } /// <summary>Provide an exception handler for un-caught exceptions.</summary> /// /// <value>The exception handler.</value> public HandleUncaughtExceptionDelegate ExceptionHandler { get { return EndpointHost.ExceptionHandler; } set { EndpointHost.ExceptionHandler = value; } } /// <summary>Provide an exception handler for unhandled exceptions.</summary> /// /// <value>The service exception handler.</value> public HandleServiceExceptionDelegate ServiceExceptionHandler { get { return EndpointHost.ServiceExceptionHandler; } set { EndpointHost.ServiceExceptionHandler = value; } } /// <summary>Provide a catch-all handler that doesn't match any routes.</summary> /// /// <value>The catch all handlers.</value> public List<HttpHandlerResolverDelegate> CatchAllHandlers { get { return EndpointHost.CatchAllHandlers; } } /// <summary>The AppHost config.</summary> /// /// <value>The configuration.</value> public EndpointHostConfig Config { get { return EndpointHost.Config; } } /// <summary>List of pre-registered and user-defined plugins to be enabled in this AppHost.</summary> /// /// <value>The plugins.</value> public List<IPlugin> Plugins { get { return EndpointHost.Plugins; } } /// <summary>Virtual access to file resources.</summary> /// /// <value>The virtual path provider.</value> public IVirtualPathProvider VirtualPathProvider { get { return EndpointHost.VirtualPathProvider; } set { EndpointHost.VirtualPathProvider = value; } } /// <summary>Create a service runner for IService actions.</summary> /// /// <typeparam name="TRequest">Type of the request.</typeparam> /// <param name="actionContext">Context for the action.</param> /// /// <returns>The new service runner.</returns> public virtual IServiceRunner<TRequest> CreateServiceRunner<TRequest>(ActionContext actionContext) { //cached per service action return new ServiceRunner<TRequest>(this, actionContext); } /// <summary>Resolve the absolute url for this request.</summary> /// /// <param name="virtualPath">Full pathname of the virtual file.</param> /// <param name="httpReq"> The HTTP request.</param> /// /// <returns>A string.</returns> public virtual string ResolveAbsoluteUrl(string virtualPath, IHttpRequest httpReq) { return Config.WebHostUrl == null ? VirtualPathUtility.ToAbsolute(virtualPath) : httpReq.GetAbsoluteUrl(virtualPath); } /// <summary>Apply plugins to this AppHost.</summary> /// /// <param name="plugins">.</param> public virtual void LoadPlugin(params IPlugin[] plugins) { foreach (var plugin in plugins) { try { plugin.Register(this); } catch (Exception ex) { log.Warn("Error loading plugin " + plugin.GetType().Name, ex); } } } /// <summary>Executes the service operation.</summary> /// /// <param name="requestDto">The request dto.</param> /// /// <returns>An object.</returns> public virtual object ExecuteService(object requestDto) { return ExecuteService(requestDto, EndpointAttributes.None); } /// <summary>Executes the service operation.</summary> /// /// <param name="requestDto"> The request dto.</param> /// <param name="endpointAttributes">The endpoint attributes.</param> /// /// <returns>An object.</returns> public object ExecuteService(object requestDto, EndpointAttributes endpointAttributes) { return EndpointHost.Config.ServiceController.Execute(requestDto, new HttpRequestContext(requestDto, endpointAttributes)); } /// <summary>Register an Adhoc web service on Startup.</summary> /// /// <param name="serviceType">.</param> /// <param name="atRestPaths">.</param> public void RegisterService(Type serviceType, params string[] atRestPaths) { var genericService = EndpointHost.Config.ServiceManager.RegisterService(serviceType); if (genericService != null) { var requestType = genericService.GetGenericArguments()[0]; foreach (var atRestPath in atRestPaths) { this.Routes.Add(requestType, atRestPath, null); } } else { var reqAttr = serviceType.GetCustomAttributes(true).OfType<DefaultRequestAttribute>().FirstOrDefault(); if (reqAttr != null) { foreach (var atRestPath in atRestPaths) { this.Routes.Add(reqAttr.RequestType, atRestPath, null); } } } } /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary> public virtual void Dispose() { if (EndpointHost.Config.ServiceManager != null) { EndpointHost.Config.ServiceManager.Dispose(); } } } }
namespace System.Workflow.ComponentModel.Compiler { #region Imports using System; using System.Collections; using System.Collections.Specialized; using System.Collections.Generic; using System.CodeDom; using System.ComponentModel; using System.ComponentModel.Design; using System.CodeDom.Compiler; using System.Reflection; using System.ComponentModel.Design.Serialization; using System.Xml; using System.Globalization; using System.IO; using System.Text; using System.Diagnostics; using System.Text.RegularExpressions; using Microsoft.CSharp; using Microsoft.VisualBasic; using System.Workflow.ComponentModel.Design; using System.Workflow.ComponentModel.Serialization; using System.Security.Policy; using System.Runtime.Versioning; using System.Configuration; using System.Collections.ObjectModel; #endregion #region WorkflowMarkupSourceAttribute Class [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public sealed class WorkflowMarkupSourceAttribute : Attribute { private string fileName; private string md5Digest; public WorkflowMarkupSourceAttribute(string fileName, string md5Digest) { this.fileName = fileName; this.md5Digest = md5Digest; } public string FileName { get { return this.fileName; } } public string MD5Digest { get { return this.md5Digest; } } } #endregion #region Interface IWorkflowCompilerOptionsService [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public interface IWorkflowCompilerOptionsService { string RootNamespace { get; } string Language { get; } bool CheckTypes { get; } } [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public class WorkflowCompilerOptionsService : IWorkflowCompilerOptionsService { internal const string DefaultLanguage = "CSharp"; public virtual string RootNamespace { get { return string.Empty; } } public virtual string Language { get { return WorkflowCompilerOptionsService.DefaultLanguage; } } public virtual bool CheckTypes { get { return false; } } public virtual string TargetFrameworkMoniker { get { return string.Empty; } } } #endregion #region WorkflowCompilationContext [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public sealed class WorkflowCompilationContext { [ThreadStatic] static WorkflowCompilationContext current = null; ContextScope scope; ReadOnlyCollection<AuthorizedType> authorizedTypes; WorkflowCompilationContext(ContextScope scope) { this.scope = scope; } public static WorkflowCompilationContext Current { get { return WorkflowCompilationContext.current; } private set { WorkflowCompilationContext.current = value; } } public string RootNamespace { get { return this.scope.RootNamespace; } } public string Language { get { return this.scope.Language; } } public bool CheckTypes { get { return this.scope.CheckTypes; } } internal FrameworkName TargetFramework { get { return this.scope.TargetFramework; } } internal Version TargetFrameworkVersion { get { FrameworkName fx = this.scope.TargetFramework; if (fx != null) { return fx.Version; } else { return MultiTargetingInfo.DefaultTargetFramework; } } } internal IServiceProvider ServiceProvider { get { return this.scope; } } public static IDisposable CreateScope(IServiceProvider serviceProvider) { if (serviceProvider == null) { throw new ArgumentNullException("serviceProvider"); } IWorkflowCompilerOptionsService optionsService = serviceProvider.GetService(typeof(IWorkflowCompilerOptionsService)) as IWorkflowCompilerOptionsService; if (optionsService != null) { return CreateScope(serviceProvider, optionsService); } else { return new DefaultContextScope(serviceProvider); } } public IList<AuthorizedType> GetAuthorizedTypes() { if (this.authorizedTypes == null) { try { IList<AuthorizedType> authorizedTypes; IDictionary<string, IList<AuthorizedType>> authorizedTypesDictionary = ConfigurationManager.GetSection("System.Workflow.ComponentModel.WorkflowCompiler/authorizedTypes") as IDictionary<string, IList<AuthorizedType>>; Version targetVersion = null; FrameworkName framework = this.scope.TargetFramework; if (framework != null) { targetVersion = framework.Version; } else { targetVersion = MultiTargetingInfo.DefaultTargetFramework; } string normalizedVersionString = string.Format(CultureInfo.InvariantCulture, "v{0}.{1}", targetVersion.Major, targetVersion.Minor); if (authorizedTypesDictionary.TryGetValue(normalizedVersionString, out authorizedTypes)) { this.authorizedTypes = new ReadOnlyCollection<AuthorizedType>(authorizedTypes); } } catch { } } return this.authorizedTypes; } internal static IDisposable CreateScope(IServiceProvider serviceProvider, WorkflowCompilerParameters parameters) { return new ParametersContextScope(serviceProvider, parameters); } static IDisposable CreateScope(IServiceProvider serviceProvider, IWorkflowCompilerOptionsService optionsService) { WorkflowCompilerOptionsService standardService = optionsService as WorkflowCompilerOptionsService; if (standardService != null) { return new StandardContextScope(serviceProvider, standardService); } else { return new InterfaceContextScope(serviceProvider, optionsService); } } abstract class ContextScope : IDisposable, IServiceProvider { IServiceProvider serviceProvider; WorkflowCompilationContext currentContext; bool disposed; protected ContextScope(IServiceProvider serviceProvider) { this.serviceProvider = serviceProvider; this.currentContext = WorkflowCompilationContext.Current; WorkflowCompilationContext.Current = new WorkflowCompilationContext(this); } ~ContextScope() { DisposeImpl(); } public abstract string RootNamespace { get; } public abstract string Language { get; } public abstract bool CheckTypes { get; } public abstract FrameworkName TargetFramework { get; } public void Dispose() { DisposeImpl(); GC.SuppressFinalize(this); } public object GetService(Type serviceType) { return this.serviceProvider.GetService(serviceType); } void DisposeImpl() { if (!this.disposed) { WorkflowCompilationContext.Current = this.currentContext; this.disposed = true; } } } class InterfaceContextScope : ContextScope { IWorkflowCompilerOptionsService service; public InterfaceContextScope(IServiceProvider serviceProvider, IWorkflowCompilerOptionsService service) : base(serviceProvider) { this.service = service; } public override string RootNamespace { get { return this.service.RootNamespace; } } public override string Language { get { return this.service.Language; } } public override bool CheckTypes { get { return this.service.CheckTypes; } } public override FrameworkName TargetFramework { get { return null; } } } class StandardContextScope : ContextScope { WorkflowCompilerOptionsService service; FrameworkName fxName; public StandardContextScope(IServiceProvider serviceProvider, WorkflowCompilerOptionsService service) : base(serviceProvider) { this.service = service; } public override string RootNamespace { get { return this.service.RootNamespace; } } public override string Language { get { return this.service.Language; } } public override bool CheckTypes { get { return this.service.CheckTypes; } } public override FrameworkName TargetFramework { get { if (this.fxName == null) { string fxName = this.service.TargetFrameworkMoniker; if (!string.IsNullOrEmpty(fxName)) { this.fxName = new FrameworkName(fxName); } } return this.fxName; } } } class ParametersContextScope : ContextScope { WorkflowCompilerParameters parameters; public ParametersContextScope(IServiceProvider serviceProvider, WorkflowCompilerParameters parameters) : base(serviceProvider) { this.parameters = parameters; } public override string RootNamespace { get { return WorkflowCompilerParameters.ExtractRootNamespace(this.parameters); } } public override string Language { get { return this.parameters.LanguageToUse; } } public override bool CheckTypes { get { return this.parameters.CheckTypes; } } public override FrameworkName TargetFramework { get { if (this.parameters.MultiTargetingInformation != null) { return this.parameters.MultiTargetingInformation.TargetFramework; } else { return null; } } } } class DefaultContextScope : ContextScope { public DefaultContextScope(IServiceProvider serviceProvider) : base(serviceProvider) { } public override string RootNamespace { get { return string.Empty; } } public override string Language { get { return WorkflowCompilerOptionsService.DefaultLanguage; } } public override bool CheckTypes { get { return false; } } public override FrameworkName TargetFramework { get { return null; } } } } #endregion #region Class WorkflowCompiler [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public sealed class WorkflowCompiler { public WorkflowCompilerResults Compile(WorkflowCompilerParameters parameters, params string[] files) { if (parameters == null) throw new ArgumentNullException("parameters"); if (files == null) throw new ArgumentNullException("files"); AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation; setup.LoaderOptimization = LoaderOptimization.MultiDomainHost; AppDomain compilerDomain = AppDomain.CreateDomain("CompilerDomain", null, setup); bool generateInMemory = false; string originalOutputAssembly = parameters.OutputAssembly; try { if (parameters.GenerateInMemory) { generateInMemory = true; parameters.GenerateInMemory = false; if (string.IsNullOrEmpty(parameters.OutputAssembly)) parameters.OutputAssembly = Path.GetTempFileName() + ".dll"; else { while (true) { try { DirectoryInfo info = Directory.CreateDirectory(Path.GetTempPath() + "\\" + Guid.NewGuid()); parameters.OutputAssembly = info.FullName + "\\" + parameters.OutputAssembly; break; } catch { } } } } WorkflowCompilerInternal compiler = (WorkflowCompilerInternal)compilerDomain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(WorkflowCompilerInternal).FullName); WorkflowCompilerResults results = compiler.Compile(parameters, files); if (generateInMemory && !results.Errors.HasErrors) { results.CompiledAssembly = Assembly.Load(File.ReadAllBytes(results.PathToAssembly)); results.PathToAssembly = null; // Delete the file and directory. try { File.Delete(parameters.OutputAssembly); Directory.Delete(Path.GetDirectoryName(parameters.OutputAssembly), true); } catch { } } return results; } finally { string outputAssembly = parameters.OutputAssembly; if (generateInMemory) { parameters.GenerateInMemory = true; parameters.OutputAssembly = originalOutputAssembly; } AppDomain.Unload(compilerDomain); // The temp file must be deleted after the app domain is unloaded, or else it will // be "busy", causing the delete to throw an access exception. if (generateInMemory) { try { File.Delete(outputAssembly); Directory.Delete(Path.GetDirectoryName(outputAssembly), true); } catch { } } } } } #endregion #region Class WorkflowCompilerInternal internal sealed class WorkflowCompilerInternal : MarshalByRefObject { #region Lifetime service public override object InitializeLifetimeService() { return null; } #endregion #region File based compilation public WorkflowCompilerResults Compile(WorkflowCompilerParameters parameters, string[] allFiles) { WorkflowCompilerResults results = new WorkflowCompilerResults(parameters.TempFiles); // Split the xoml files from cs/vb files. StringCollection xomlFiles = new StringCollection(); StringCollection userCodeFiles = new StringCollection(); foreach (string file in allFiles) { if (file.EndsWith(".xoml", StringComparison.OrdinalIgnoreCase)) xomlFiles.Add(file); else userCodeFiles.Add(file); } string[] files = new string[xomlFiles.Count]; xomlFiles.CopyTo(files, 0); string[] codeFiles = new string[userCodeFiles.Count]; userCodeFiles.CopyTo(codeFiles, 0); string mscorlibPath = typeof(object).Assembly.Location; ServiceContainer serviceContainer = new ServiceContainer(); MultiTargetingInfo mtInfo = parameters.MultiTargetingInformation; if (mtInfo == null) { XomlCompilerHelper.FixReferencedAssemblies(parameters, results, parameters.LibraryPaths); } string mscorlibName = Path.GetFileName(mscorlibPath); // Add assembly resolver. ReferencedAssemblyResolver resolver = new ReferencedAssemblyResolver(parameters.ReferencedAssemblies, parameters.LocalAssembly); AppDomain.CurrentDomain.AssemblyResolve += resolver.ResolveEventHandler; // prepare service container TypeProvider typeProvider = new TypeProvider(new ServiceContainer()); int mscorlibIndex = -1; if ((parameters.ReferencedAssemblies != null) && (parameters.ReferencedAssemblies.Count > 0)) { for (int i = 0; i < parameters.ReferencedAssemblies.Count; i++) { string assemblyPath = parameters.ReferencedAssemblies[i]; if ((mscorlibIndex == -1) && (string.Compare(mscorlibName, Path.GetFileName(assemblyPath), StringComparison.OrdinalIgnoreCase) == 0)) { mscorlibIndex = i; mscorlibPath = assemblyPath; } typeProvider.AddAssemblyReference(assemblyPath); } } // a note about references to mscorlib: // If we found mscorlib in the list of reference assemblies, we should remove it prior to sending it to the CodeDOM compiler. // The CodeDOM compiler would add the right mscorlib [based on the version of the provider we use] and the duplication would // cause a compilation error. // If we didn't found a reference to mscorlib we need to add it to the type-provider, though, so we will support exposing // those known types. if (mscorlibIndex != -1) { parameters.ReferencedAssemblies.RemoveAt(mscorlibIndex); if (string.IsNullOrEmpty(parameters.CoreAssemblyFileName)) { parameters.CoreAssemblyFileName = mscorlibPath; } } else { typeProvider.AddAssemblyReference(mscorlibPath); } serviceContainer.AddService(typeof(ITypeProvider), typeProvider); TempFileCollection intermediateTempFiles = null; string localAssemblyPath = string.Empty; try { using (WorkflowCompilationContext.CreateScope(serviceContainer, parameters)) { parameters.LocalAssembly = GenerateLocalAssembly(files, codeFiles, parameters, results, out intermediateTempFiles, out localAssemblyPath); if (parameters.LocalAssembly != null) { // WinOE Bug 17591: we must set the local assembly here, // otherwise, the resolver won't be able to resolve custom types correctly. resolver.SetLocalAssembly(parameters.LocalAssembly); // Work around HERE!!! // prepare type provider typeProvider.SetLocalAssembly(parameters.LocalAssembly); typeProvider.AddAssembly(parameters.LocalAssembly); results.Errors.Clear(); XomlCompilerHelper.InternalCompileFromDomBatch(files, codeFiles, parameters, results, localAssemblyPath); } } } catch (Exception e) { results.Errors.Add(new WorkflowCompilerError(String.Empty, -1, -1, ErrorNumbers.Error_UnknownCompilerException.ToString(CultureInfo.InvariantCulture), SR.GetString(SR.Error_CompilationFailed, e.Message))); } finally { // Delate the temp files. if (intermediateTempFiles != null && parameters.TempFiles.KeepFiles == false) { string tempAssemblyDirectory = string.Empty; if (File.Exists(localAssemblyPath)) tempAssemblyDirectory = Path.GetDirectoryName(localAssemblyPath); foreach (string file in intermediateTempFiles) { try { System.IO.File.Delete(file); } catch { } } try { if (!string.IsNullOrEmpty(tempAssemblyDirectory)) Directory.Delete(tempAssemblyDirectory, true); } catch { } } } return results; } #endregion #region Code for Generating Local Assembly private static ValidationErrorCollection ValidateIdentifiers(IServiceProvider serviceProvider, Activity activity) { ValidationErrorCollection validationErrors = new ValidationErrorCollection(); Dictionary<string, int> names = new Dictionary<string, int>(); Walker walker = new Walker(); walker.FoundActivity += delegate(Walker walker2, WalkerEventArgs e) { Activity currentActivity = e.CurrentActivity; if (!currentActivity.Enabled) { e.Action = WalkerAction.Skip; return; } ValidationError identifierError = null; if (names.ContainsKey(currentActivity.QualifiedName)) { if (names[currentActivity.QualifiedName] != 1) { identifierError = new ValidationError(SR.GetString(SR.Error_DuplicatedActivityID, currentActivity.QualifiedName), ErrorNumbers.Error_DuplicatedActivityID, false, "Name"); identifierError.UserData[typeof(Activity)] = currentActivity; validationErrors.Add(identifierError); names[currentActivity.QualifiedName] = 1; } return; } // Undone: AkashS - remove this check when we allow root activities to not have a name. if (!string.IsNullOrEmpty(currentActivity.Name)) { names[currentActivity.Name] = 0; identifierError = ValidationHelpers.ValidateIdentifier("Name", serviceProvider, currentActivity.Name); if (identifierError != null) { identifierError.UserData[typeof(Activity)] = currentActivity; validationErrors.Add(identifierError); } } }; walker.Walk(activity as Activity); return validationErrors; } private Assembly GenerateLocalAssembly(string[] files, string[] codeFiles, WorkflowCompilerParameters parameters, WorkflowCompilerResults results, out TempFileCollection tempFiles2, out string localAssemblyPath) { localAssemblyPath = string.Empty; tempFiles2 = null; // Generate code for the markup files. CodeCompileUnit markupCompileUnit = GenerateCodeFromFileBatch(files, parameters, results); if (results.Errors.HasErrors) return null; SupportedLanguages language = CompilerHelpers.GetSupportedLanguage(parameters.LanguageToUse); // Convert all compile units to source files. CodeDomProvider codeDomProvider = CompilerHelpers.GetCodeDomProvider(language, parameters.CompilerVersion); // Clone the parameters. CompilerParameters clonedParams = XomlCompilerHelper.CloneCompilerParameters(parameters); clonedParams.TempFiles.KeepFiles = true; tempFiles2 = clonedParams.TempFiles; clonedParams.GenerateInMemory = true; if (string.IsNullOrEmpty(parameters.OutputAssembly)) localAssemblyPath = clonedParams.OutputAssembly = clonedParams.TempFiles.AddExtension("dll"); else { string tempAssemblyDirectory = clonedParams.TempFiles.BasePath; int postfix = 0; while (true) { try { Directory.CreateDirectory(tempAssemblyDirectory); break; } catch { tempAssemblyDirectory = clonedParams.TempFiles.BasePath + postfix++; } } localAssemblyPath = clonedParams.OutputAssembly = tempAssemblyDirectory + "\\" + Path.GetFileName(clonedParams.OutputAssembly); clonedParams.TempFiles.AddFile(localAssemblyPath, true); } // Explictily ignore warnings (in case the user set this property in the project options). clonedParams.TreatWarningsAsErrors = false; if (clonedParams.CompilerOptions != null && clonedParams.CompilerOptions.Length > 0) { // Need to remove /delaysign option together with the /keyfile or /keycontainer // the temp assembly should not be signed or we'll have problems loading it. // Custom splitting: need to take strings like '"one two"' into account // even though it has a space inside, it should not be split. string source = clonedParams.CompilerOptions; ArrayList optionsList = new ArrayList(); int begin = 0; int end = 0; bool insideString = false; while (end < source.Length) { int currentLength = end - begin; if (source[end] == '"') { insideString = !insideString; } else if (source[end] == ' ' && !insideString) { // Split only if not inside string like in "inside some string". // Split here. Ignore multiple spaces. if (begin == end) { begin++; // end will get incremented in the end of the loop. } else { string substring = source.Substring(begin, end - begin); optionsList.Add(substring); begin = end + 1; // end will get incremented in the end of the loop } } end++; } // The remaining sub-string. if (begin != end) { string substring = source.Substring(begin, end - begin); optionsList.Add(substring); } string[] options = optionsList.ToArray(typeof(string)) as string[]; clonedParams.CompilerOptions = string.Empty; foreach (string option in options) { if (option.Length > 0 && !option.StartsWith("/delaysign", StringComparison.OrdinalIgnoreCase) && !option.StartsWith("/keyfile", StringComparison.OrdinalIgnoreCase) && !option.StartsWith("/keycontainer", StringComparison.OrdinalIgnoreCase)) { clonedParams.CompilerOptions += " " + option; } } } // Disable compiler optimizations, but include debug information. clonedParams.CompilerOptions = (clonedParams.CompilerOptions == null) ? "/optimize-" : clonedParams.CompilerOptions + " /optimize-"; clonedParams.IncludeDebugInformation = true; if (language == SupportedLanguages.CSharp) clonedParams.CompilerOptions += " /unsafe"; // Add files. ArrayList ccus = new ArrayList((ICollection)parameters.UserCodeCompileUnits); ccus.Add(markupCompileUnit); ArrayList userCodeFiles = new ArrayList(); userCodeFiles.AddRange(codeFiles); userCodeFiles.AddRange(XomlCompilerHelper.GenerateFiles(codeDomProvider, clonedParams, (CodeCompileUnit[])ccus.ToArray(typeof(CodeCompileUnit)))); // Generate the temporary assembly. CompilerResults results2 = codeDomProvider.CompileAssemblyFromFile(clonedParams, (string[])userCodeFiles.ToArray(typeof(string))); if (results2.Errors.HasErrors) { results.AddCompilerErrorsFromCompilerResults(results2); return null; } return results2.CompiledAssembly; } internal static CodeCompileUnit GenerateCodeFromFileBatch(string[] files, WorkflowCompilerParameters parameters, WorkflowCompilerResults results) { WorkflowCompilationContext context = WorkflowCompilationContext.Current; if (context == null) throw new Exception(SR.GetString(SR.Error_MissingCompilationContext)); CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); foreach (string fileName in files) { Activity rootActivity = null; try { DesignerSerializationManager manager = new DesignerSerializationManager(context.ServiceProvider); using (manager.CreateSession()) { WorkflowMarkupSerializationManager xomlSerializationManager = new WorkflowMarkupSerializationManager(manager); xomlSerializationManager.WorkflowMarkupStack.Push(parameters); xomlSerializationManager.LocalAssembly = parameters.LocalAssembly; using (XmlReader reader = XmlReader.Create(fileName)) rootActivity = WorkflowMarkupSerializationHelpers.LoadXomlDocument(xomlSerializationManager, reader, fileName); if (parameters.LocalAssembly != null) { foreach (object error in manager.Errors) { if (error is WorkflowMarkupSerializationException) { results.Errors.Add(new WorkflowCompilerError(fileName, (WorkflowMarkupSerializationException)error)); } else { results.Errors.Add(new WorkflowCompilerError(fileName, -1, -1, ErrorNumbers.Error_SerializationError.ToString(CultureInfo.InvariantCulture), error.ToString())); } } } } } catch (WorkflowMarkupSerializationException xomlSerializationException) { results.Errors.Add(new WorkflowCompilerError(fileName, xomlSerializationException)); continue; } catch (Exception e) { results.Errors.Add(new WorkflowCompilerError(fileName, -1, -1, ErrorNumbers.Error_SerializationError.ToString(CultureInfo.InvariantCulture), SR.GetString(SR.Error_CompilationFailed, e.Message))); continue; } if (rootActivity == null) { results.Errors.Add(new WorkflowCompilerError(fileName, 1, 1, ErrorNumbers.Error_SerializationError.ToString(CultureInfo.InvariantCulture), SR.GetString(SR.Error_RootActivityTypeInvalid))); continue; } bool createNewClass = (!string.IsNullOrEmpty(rootActivity.GetValue(WorkflowMarkupSerializer.XClassProperty) as string)); if (!createNewClass) { results.Errors.Add(new WorkflowCompilerError(fileName, 1, 1, ErrorNumbers.Error_SerializationError.ToString(CultureInfo.InvariantCulture), SR.GetString(SR.Error_CannotCompile_No_XClass))); continue; } //NOTE: CompileWithNoCode is meaningless now. It means no x:Code in a XOML file. It exists until the FP migration is done //Ideally FP should just use XOML files w/o X:Class and run them w/o ever compiling them if ((parameters.CompileWithNoCode) && XomlCompilerHelper.HasCodeWithin(rootActivity)) { ValidationError error = new ValidationError(SR.GetString(SR.Error_CodeWithinNotAllowed), ErrorNumbers.Error_CodeWithinNotAllowed); error.UserData[typeof(Activity)] = rootActivity; results.Errors.Add(XomlCompilerHelper.CreateXomlCompilerError(error, parameters)); } ValidationErrorCollection errors = new ValidationErrorCollection(); errors = ValidateIdentifiers(context.ServiceProvider, rootActivity); foreach (ValidationError error in errors) results.Errors.Add(XomlCompilerHelper.CreateXomlCompilerError(error, parameters)); if (results.Errors.HasErrors) continue; codeCompileUnit.Namespaces.AddRange(WorkflowMarkupSerializationHelpers.GenerateCodeFromXomlDocument(rootActivity, fileName, context.RootNamespace, CompilerHelpers.GetSupportedLanguage(context.Language), context.ServiceProvider)); } WorkflowMarkupSerializationHelpers.FixStandardNamespacesAndRootNamespace(codeCompileUnit.Namespaces, context.RootNamespace, CompilerHelpers.GetSupportedLanguage(context.Language)); return codeCompileUnit; } #endregion } #endregion }
// Zlib.cs // ------------------------------------------------------------------ // // Copyright (c) 2009-2011 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: <2011-August-03 19:52:28> // // ------------------------------------------------------------------ // // This module defines classes for ZLIB compression and // decompression. This code is derived from the jzlib implementation of // zlib, but significantly modified. The object model is not the same, // and many of the behaviors are new or different. Nonetheless, in // keeping with the license for jzlib, the copyright to that code is // included below. // // ------------------------------------------------------------------ // // The following notice applies to jzlib: // // Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the distribution. // // 3. The names of the authors may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT, // INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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. // // ----------------------------------------------------------------------- // // jzlib is based on zlib-1.1.3. // // The following notice applies to zlib: // // ----------------------------------------------------------------------- // // Copyright (C) 1995-2004 Jean-loup Gailly and Mark Adler // // The ZLIB software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // // Jean-loup Gailly jloup@gzip.org // Mark Adler madler@alumni.caltech.edu // // ----------------------------------------------------------------------- using System; using Interop=System.Runtime.InteropServices; namespace Ionic.Zlib { /// <summary> /// Describes how to flush the current deflate operation. /// </summary> /// <remarks> /// The different FlushType values are useful when using a Deflate in a streaming application. /// </remarks> public enum FlushType { /// <summary>No flush at all.</summary> None = 0, /// <summary>Closes the current block, but doesn't flush it to /// the output. Used internally only in hypothetical /// scenarios. This was supposed to be removed by Zlib, but it is /// still in use in some edge cases. /// </summary> Partial, /// <summary> /// Use this during compression to specify that all pending output should be /// flushed to the output buffer and the output should be aligned on a byte /// boundary. You might use this in a streaming communication scenario, so that /// the decompressor can get all input data available so far. When using this /// with a ZlibCodec, <c>AvailableBytesIn</c> will be zero after the call if /// enough output space has been provided before the call. Flushing will /// degrade compression and so it should be used only when necessary. /// </summary> Sync, /// <summary> /// Use this during compression to specify that all output should be flushed, as /// with <c>FlushType.Sync</c>, but also, the compression state should be reset /// so that decompression can restart from this point if previous compressed /// data has been damaged or if random access is desired. Using /// <c>FlushType.Full</c> too often can significantly degrade the compression. /// </summary> Full, /// <summary>Signals the end of the compression/decompression stream.</summary> Finish, } /// <summary> /// The compression level to be used when using a DeflateStream or ZlibStream with CompressionMode.Compress. /// </summary> public enum CompressionLevel { /// <summary> /// None means that the data will be simply stored, with no change at all. /// If you are producing ZIPs for use on Mac OSX, be aware that archives produced with CompressionLevel.None /// cannot be opened with the default zip reader. Use a different CompressionLevel. /// </summary> None= 0, /// <summary> /// Same as None. /// </summary> Level0 = 0, /// <summary> /// The fastest but least effective compression. /// </summary> BestSpeed = 1, /// <summary> /// A synonym for BestSpeed. /// </summary> Level1 = 1, /// <summary> /// A little slower, but better, than level 1. /// </summary> Level2 = 2, /// <summary> /// A little slower, but better, than level 2. /// </summary> Level3 = 3, /// <summary> /// A little slower, but better, than level 3. /// </summary> Level4 = 4, /// <summary> /// A little slower than level 4, but with better compression. /// </summary> Level5 = 5, /// <summary> /// The default compression level, with a good balance of speed and compression efficiency. /// </summary> Default = 6, /// <summary> /// A synonym for Default. /// </summary> Level6 = 6, /// <summary> /// Pretty good compression! /// </summary> Level7 = 7, /// <summary> /// Better compression than Level7! /// </summary> Level8 = 8, /// <summary> /// The "best" compression, where best means greatest reduction in size of the input data stream. /// This is also the slowest compression. /// </summary> BestCompression = 9, /// <summary> /// A synonym for BestCompression. /// </summary> Level9 = 9, } /// <summary> /// Describes options for how the compression algorithm is executed. Different strategies /// work better on different sorts of data. The strategy parameter can affect the compression /// ratio and the speed of compression but not the correctness of the compresssion. /// </summary> public enum CompressionStrategy { /// <summary> /// The default strategy is probably the best for normal data. /// </summary> Default = 0, /// <summary> /// The <c>Filtered</c> strategy is intended to be used most effectively with data produced by a /// filter or predictor. By this definition, filtered data consists mostly of small /// values with a somewhat random distribution. In this case, the compression algorithm /// is tuned to compress them better. The effect of <c>Filtered</c> is to force more Huffman /// coding and less string matching; it is a half-step between <c>Default</c> and <c>HuffmanOnly</c>. /// </summary> Filtered = 1, /// <summary> /// Using <c>HuffmanOnly</c> will force the compressor to do Huffman encoding only, with no /// string matching. /// </summary> HuffmanOnly = 2, } /// <summary> /// An enum to specify the direction of transcoding - whether to compress or decompress. /// </summary> public enum CompressionMode { /// <summary> /// Used to specify that the stream should compress the data. /// </summary> Compress= 0, /// <summary> /// Used to specify that the stream should decompress the data. /// </summary> Decompress = 1, } /// <summary> /// A general purpose exception class for exceptions in the Zlib library. /// </summary> public class ZlibException : System.Exception { /// <summary> /// The ZlibException class captures exception information generated /// by the Zlib library. /// </summary> public ZlibException() : base() { } /// <summary> /// This ctor collects a message attached to the exception. /// </summary> /// <param name="s">the message for the exception.</param> public ZlibException(System.String s) : base(s) { } } internal class SharedUtils { /// <summary> /// Performs an unsigned bitwise right shift with the specified number /// </summary> /// <param name="number">Number to operate on</param> /// <param name="bits">Ammount of bits to shift</param> /// <returns>The resulting number from the shift operation</returns> public static int URShift(int number, int bits) { return (int)((uint)number >> bits); } #if NOT /// <summary> /// Performs an unsigned bitwise right shift with the specified number /// </summary> /// <param name="number">Number to operate on</param> /// <param name="bits">Ammount of bits to shift</param> /// <returns>The resulting number from the shift operation</returns> public static long URShift(long number, int bits) { return (long) ((UInt64)number >> bits); } #endif /// <summary> /// Reads a number of characters from the current source TextReader and writes /// the data to the target array at the specified index. /// </summary> /// /// <param name="sourceTextReader">The source TextReader to read from</param> /// <param name="target">Contains the array of characteres read from the source TextReader.</param> /// <param name="start">The starting index of the target array.</param> /// <param name="count">The maximum number of characters to read from the source TextReader.</param> /// /// <returns> /// The number of characters read. The number will be less than or equal to /// count depending on the data available in the source TextReader. Returns -1 /// if the end of the stream is reached. /// </returns> public static System.Int32 ReadInput(System.IO.TextReader sourceTextReader, byte[] target, int start, int count) { // Returns 0 bytes if not enough space in target if (target.Length == 0) return 0; char[] charArray = new char[target.Length]; int bytesRead = sourceTextReader.Read(charArray, start, count); // Returns -1 if EOF if (bytesRead == 0) return -1; for (int index = start; index < start + bytesRead; index++) target[index] = (byte)charArray[index]; return bytesRead; } internal static byte[] ToByteArray(System.String sourceString) { return System.Text.UTF8Encoding.UTF8.GetBytes(sourceString); } internal static char[] ToCharArray(byte[] byteArray) { return System.Text.UTF8Encoding.UTF8.GetChars(byteArray); } } internal static class InternalConstants { internal static readonly int MAX_BITS = 15; internal static readonly int BL_CODES = 19; internal static readonly int D_CODES = 30; internal static readonly int LITERALS = 256; internal static readonly int LENGTH_CODES = 29; internal static readonly int L_CODES = (LITERALS + 1 + LENGTH_CODES); // Bit length codes must not exceed MAX_BL_BITS bits internal static readonly int MAX_BL_BITS = 7; // repeat previous bit length 3-6 times (2 bits of repeat count) internal static readonly int REP_3_6 = 16; // repeat a zero length 3-10 times (3 bits of repeat count) internal static readonly int REPZ_3_10 = 17; // repeat a zero length 11-138 times (7 bits of repeat count) internal static readonly int REPZ_11_138 = 18; } internal sealed class StaticTree { internal static readonly short[] lengthAndLiteralsTreeCodes = new short[] { 12, 8, 140, 8, 76, 8, 204, 8, 44, 8, 172, 8, 108, 8, 236, 8, 28, 8, 156, 8, 92, 8, 220, 8, 60, 8, 188, 8, 124, 8, 252, 8, 2, 8, 130, 8, 66, 8, 194, 8, 34, 8, 162, 8, 98, 8, 226, 8, 18, 8, 146, 8, 82, 8, 210, 8, 50, 8, 178, 8, 114, 8, 242, 8, 10, 8, 138, 8, 74, 8, 202, 8, 42, 8, 170, 8, 106, 8, 234, 8, 26, 8, 154, 8, 90, 8, 218, 8, 58, 8, 186, 8, 122, 8, 250, 8, 6, 8, 134, 8, 70, 8, 198, 8, 38, 8, 166, 8, 102, 8, 230, 8, 22, 8, 150, 8, 86, 8, 214, 8, 54, 8, 182, 8, 118, 8, 246, 8, 14, 8, 142, 8, 78, 8, 206, 8, 46, 8, 174, 8, 110, 8, 238, 8, 30, 8, 158, 8, 94, 8, 222, 8, 62, 8, 190, 8, 126, 8, 254, 8, 1, 8, 129, 8, 65, 8, 193, 8, 33, 8, 161, 8, 97, 8, 225, 8, 17, 8, 145, 8, 81, 8, 209, 8, 49, 8, 177, 8, 113, 8, 241, 8, 9, 8, 137, 8, 73, 8, 201, 8, 41, 8, 169, 8, 105, 8, 233, 8, 25, 8, 153, 8, 89, 8, 217, 8, 57, 8, 185, 8, 121, 8, 249, 8, 5, 8, 133, 8, 69, 8, 197, 8, 37, 8, 165, 8, 101, 8, 229, 8, 21, 8, 149, 8, 85, 8, 213, 8, 53, 8, 181, 8, 117, 8, 245, 8, 13, 8, 141, 8, 77, 8, 205, 8, 45, 8, 173, 8, 109, 8, 237, 8, 29, 8, 157, 8, 93, 8, 221, 8, 61, 8, 189, 8, 125, 8, 253, 8, 19, 9, 275, 9, 147, 9, 403, 9, 83, 9, 339, 9, 211, 9, 467, 9, 51, 9, 307, 9, 179, 9, 435, 9, 115, 9, 371, 9, 243, 9, 499, 9, 11, 9, 267, 9, 139, 9, 395, 9, 75, 9, 331, 9, 203, 9, 459, 9, 43, 9, 299, 9, 171, 9, 427, 9, 107, 9, 363, 9, 235, 9, 491, 9, 27, 9, 283, 9, 155, 9, 411, 9, 91, 9, 347, 9, 219, 9, 475, 9, 59, 9, 315, 9, 187, 9, 443, 9, 123, 9, 379, 9, 251, 9, 507, 9, 7, 9, 263, 9, 135, 9, 391, 9, 71, 9, 327, 9, 199, 9, 455, 9, 39, 9, 295, 9, 167, 9, 423, 9, 103, 9, 359, 9, 231, 9, 487, 9, 23, 9, 279, 9, 151, 9, 407, 9, 87, 9, 343, 9, 215, 9, 471, 9, 55, 9, 311, 9, 183, 9, 439, 9, 119, 9, 375, 9, 247, 9, 503, 9, 15, 9, 271, 9, 143, 9, 399, 9, 79, 9, 335, 9, 207, 9, 463, 9, 47, 9, 303, 9, 175, 9, 431, 9, 111, 9, 367, 9, 239, 9, 495, 9, 31, 9, 287, 9, 159, 9, 415, 9, 95, 9, 351, 9, 223, 9, 479, 9, 63, 9, 319, 9, 191, 9, 447, 9, 127, 9, 383, 9, 255, 9, 511, 9, 0, 7, 64, 7, 32, 7, 96, 7, 16, 7, 80, 7, 48, 7, 112, 7, 8, 7, 72, 7, 40, 7, 104, 7, 24, 7, 88, 7, 56, 7, 120, 7, 4, 7, 68, 7, 36, 7, 100, 7, 20, 7, 84, 7, 52, 7, 116, 7, 3, 8, 131, 8, 67, 8, 195, 8, 35, 8, 163, 8, 99, 8, 227, 8 }; internal static readonly short[] distTreeCodes = new short[] { 0, 5, 16, 5, 8, 5, 24, 5, 4, 5, 20, 5, 12, 5, 28, 5, 2, 5, 18, 5, 10, 5, 26, 5, 6, 5, 22, 5, 14, 5, 30, 5, 1, 5, 17, 5, 9, 5, 25, 5, 5, 5, 21, 5, 13, 5, 29, 5, 3, 5, 19, 5, 11, 5, 27, 5, 7, 5, 23, 5 }; internal static readonly StaticTree Literals; internal static readonly StaticTree Distances; internal static readonly StaticTree BitLengths; internal short[] treeCodes; // static tree or null internal int[] extraBits; // extra bits for each code or null internal int extraBase; // base index for extra_bits internal int elems; // max number of elements in the tree internal int maxLength; // max bit length for the codes private StaticTree(short[] treeCodes, int[] extraBits, int extraBase, int elems, int maxLength) { this.treeCodes = treeCodes; this.extraBits = extraBits; this.extraBase = extraBase; this.elems = elems; this.maxLength = maxLength; } static StaticTree() { Literals = new StaticTree(lengthAndLiteralsTreeCodes, Tree.ExtraLengthBits, InternalConstants.LITERALS + 1, InternalConstants.L_CODES, InternalConstants.MAX_BITS); Distances = new StaticTree(distTreeCodes, Tree.ExtraDistanceBits, 0, InternalConstants.D_CODES, InternalConstants.MAX_BITS); BitLengths = new StaticTree(null, Tree.extra_blbits, 0, InternalConstants.BL_CODES, InternalConstants.MAX_BL_BITS); } } /// <summary> /// Computes an Adler-32 checksum. /// </summary> /// <remarks> /// The Adler checksum is similar to a CRC checksum, but faster to compute, though less /// reliable. It is used in producing RFC1950 compressed streams. The Adler checksum /// is a required part of the "ZLIB" standard. Applications will almost never need to /// use this class directly. /// </remarks> /// /// <exclude/> public sealed class Adler { // largest prime smaller than 65536 private static readonly uint BASE = 65521; // NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 private static readonly int NMAX = 5552; #pragma warning disable 3001 #pragma warning disable 3002 /// <summary> /// Calculates the Adler32 checksum. /// </summary> /// <remarks> /// <para> /// This is used within ZLIB. You probably don't need to use this directly. /// </para> /// </remarks> /// <example> /// To compute an Adler32 checksum on a byte array: /// <code> /// var adler = Adler.Adler32(0, null, 0, 0); /// adler = Adler.Adler32(adler, buffer, index, length); /// </code> /// </example> public static uint Adler32(uint adler, byte[] buf, int index, int len) { if (buf == null) return 1; uint s1 = (uint) (adler & 0xffff); uint s2 = (uint) ((adler >> 16) & 0xffff); while (len > 0) { int k = len < NMAX ? len : NMAX; len -= k; while (k >= 16) { //s1 += (buf[index++] & 0xff); s2 += s1; s1 += buf[index++]; s2 += s1; s1 += buf[index++]; s2 += s1; s1 += buf[index++]; s2 += s1; s1 += buf[index++]; s2 += s1; s1 += buf[index++]; s2 += s1; s1 += buf[index++]; s2 += s1; s1 += buf[index++]; s2 += s1; s1 += buf[index++]; s2 += s1; s1 += buf[index++]; s2 += s1; s1 += buf[index++]; s2 += s1; s1 += buf[index++]; s2 += s1; s1 += buf[index++]; s2 += s1; s1 += buf[index++]; s2 += s1; s1 += buf[index++]; s2 += s1; s1 += buf[index++]; s2 += s1; s1 += buf[index++]; s2 += s1; k -= 16; } if (k != 0) { do { s1 += buf[index++]; s2 += s1; } while (--k != 0); } s1 %= BASE; s2 %= BASE; } return (uint)((s2 << 16) | s1); } #pragma warning restore 3001 #pragma warning restore 3002 } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // AsynchronousOneToOneChannel.cs // // <OWNER>[....]</OWNER> // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Threading; using System.Diagnostics.Contracts; namespace System.Linq.Parallel { /// <summary> /// This is a bounded channel meant for single-producer/single-consumer scenarios. /// </summary> /// <typeparam name="T">Specifies the type of data in the channel.</typeparam> internal sealed class AsynchronousChannel<T> : IDisposable { // The producer will be blocked once the channel reaches a capacity, and unblocked // as soon as a consumer makes room. A consumer can block waiting until a producer // enqueues a new element. We use a chunking scheme to adjust the granularity and // frequency of synchronization, e.g. by enqueueing/dequeueing N elements at a time. // Because there is only ever a single producer and consumer, we are able to acheive // efficient and low-overhead synchronization. // // In general, the buffer has four logical states: // FULL <--> OPEN <--> EMPTY <--> DONE // // Here is a summary of the state transitions and what they mean: // * OPEN: // A buffer starts in the OPEN state. When the buffer is in the READY state, // a consumer and producer can dequeue and enqueue new elements. // * OPEN->FULL: // A producer transitions the buffer from OPEN->FULL when it enqueues a chunk // that causes the buffer to reach capacity; a producer can no longer enqueue // new chunks when this happens, causing it to block. // * FULL->OPEN: // When the consumer takes a chunk from a FULL buffer, it transitions back from // FULL->OPEN and the producer is woken up. // * OPEN->EMPTY: // When the consumer takes the last chunk from a buffer, the buffer is // transitioned from OPEN->EMPTY; a consumer can no longer take new chunks, // causing it to block. // * EMPTY->OPEN: // Lastly, when the producer enqueues an item into an EMPTY buffer, it // transitions to the OPEN state. This causes any waiting consumers to wake up. // * EMPTY->DONE: // If the buffer is empty, and the producer is done enqueueing new // items, the buffer is DONE. There will be no more consumption or production. // // Assumptions: // There is only ever one producer and one consumer operating on this channel // concurrently. The internal synchronization cannot handle anything else. // // ** WARNING ** WARNING ** WARNING ** WARNING ** WARNING ** WARNING ** WARNING ** // VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV // // There... got your attention now... just in case you didn't read the comments // very carefully above, this channel will deadlock, become corrupt, and generally // make you an unhappy camper if you try to use more than 1 producer or more than // 1 consumer thread to access this thing concurrently. It's been carefully designed // to avoid locking, but only because of this restriction... private T[][] m_buffer; // The buffer of chunks. private readonly int m_index; // Index of this channel private volatile int m_producerBufferIndex; // Producer's current index, i.e. where to put the next chunk. private volatile int m_consumerBufferIndex; // Consumer's current index, i.e. where to get the next chunk. private volatile bool m_done; // Set to true once the producer is done. private T[] m_producerChunk; // The temporary chunk being generated by the producer. private int m_producerChunkIndex; // A producer's index into its temporary chunk. private T[] m_consumerChunk; // The temporary chunk being enumerated by the consumer. private int m_consumerChunkIndex; // A consumer's index into its temporary chunk. private int m_chunkSize; // The number of elements that comprise a chunk. // These events are used to signal a waiting producer when the consumer dequeues, and to signal a // waiting consumer when the producer enqueues. private ManualResetEventSlim m_producerEvent; private IntValueEvent m_consumerEvent; // These two-valued ints track whether a producer or consumer _might_ be waiting. They are marked // volatile because they are used in synchronization critical regions of code (see usage below). private volatile int m_producerIsWaiting; private volatile int m_consumerIsWaiting; private CancellationToken m_cancellationToken; //----------------------------------------------------------------------------------- // Initializes a new channel with the specific capacity and chunk size. // // Arguments: // orderingHelper - the ordering helper to use for order preservation // capacity - the maximum number of elements before a producer blocks // chunkSize - the granularity of chunking on enqueue/dequeue. 0 means default size. // // Notes: // The capacity represents the maximum number of chunks a channel can hold. That // means producers will actually block after enqueueing capacity*chunkSize // individual elements. // internal AsynchronousChannel(int index, int chunkSize, CancellationToken cancellationToken, IntValueEvent consumerEvent) : this(index, Scheduling.DEFAULT_BOUNDED_BUFFER_CAPACITY, chunkSize, cancellationToken, consumerEvent) { } internal AsynchronousChannel(int index, int capacity, int chunkSize, CancellationToken cancellationToken, IntValueEvent consumerEvent) { if (chunkSize == 0) chunkSize = Scheduling.GetDefaultChunkSize<T>(); Contract.Assert(chunkSize > 0, "chunk size must be greater than 0"); Contract.Assert(capacity > 1, "this impl doesn't support capacity of 1 or 0"); // Initialize a buffer with enough space to hold 'capacity' elements. // We need one extra unused element as a sentinel to detect a full buffer, // thus we add one to the capacity requested. m_index = index; m_buffer = new T[capacity + 1][]; m_producerBufferIndex = 0; m_consumerBufferIndex = 0; m_producerEvent = new ManualResetEventSlim(); m_consumerEvent = consumerEvent; m_chunkSize = chunkSize; m_producerChunk = new T[chunkSize]; m_producerChunkIndex = 0; m_cancellationToken = cancellationToken; } //----------------------------------------------------------------------------------- // Checks whether the buffer is full. If the consumer is calling this, they can be // assured that a true value won't change before the consumer has a chance to dequeue // elements. That's because only one consumer can run at once. A producer might see // a true value, however, and then a consumer might transition to non-full, so it's // not stable for them. Lastly, it's of course possible to see a false value when // there really is a full queue, it's all dependent on small race conditions. // internal bool IsFull { get { // Read the fields once. One of these is always stable, since the only threads // that call this are the 1 producer/1 consumer threads. int producerIndex = m_producerBufferIndex; int consumerIndex = m_consumerBufferIndex; // Two cases: // 1) Is the producer index one less than the consumer? // 2) The producer is at the end of the buffer and the consumer at the beginning. return (producerIndex == consumerIndex - 1) || (consumerIndex == 0 && producerIndex == m_buffer.Length - 1); // Note to readers: you might have expected us to consider the case where // m_producerBufferIndex == m_buffer.Length && m_consumerBufferIndex == 1. // That is, a producer has gone off the end of the array, but is about to // wrap around to the 0th element again. We don't need this for a subtle // reason. It is SAFE for a consumer to think we are non-full when we // actually are full; it is NOT for a producer; but thankfully, there is // only one producer, and hence the producer will never see this seemingly // invalid state. Hence, we're fine producing a false negative. It's all // based on a race condition we have to deal with anyway. } } //----------------------------------------------------------------------------------- // Checks whether the buffer is empty. If the producer is calling this, they can be // assured that a true value won't change before the producer has a chance to enqueue // an item. That's because only one producer can run at once. A consumer might see // a true value, however, and then a producer might transition to non-empty. // internal bool IsChunkBufferEmpty { get { // The queue is empty when the producer and consumer are at the same index. return m_producerBufferIndex == m_consumerBufferIndex; } } //----------------------------------------------------------------------------------- // Checks whether the producer is done enqueueing new elements. // internal bool IsDone { get { return m_done; } } //----------------------------------------------------------------------------------- // Used by a producer to flush out any internal buffers that have been accumulating // data, but which hasn't yet been published to the consumer. internal void FlushBuffers() { TraceHelpers.TraceInfo("tid {0}: AsynchronousChannel<T>::FlushBuffers() called", Thread.CurrentThread.ManagedThreadId); // Ensure that a partially filled chunk is made available to the consumer. FlushCachedChunk(); } //----------------------------------------------------------------------------------- // Used by a producer to signal that it is done producing new elements. This will // also wake up any consumers that have gone to sleep. // internal void SetDone() { TraceHelpers.TraceInfo("tid {0}: AsynchronousChannel<T>::SetDone() called", Thread.CurrentThread.ManagedThreadId); // This is set with a volatile write to ensure that, after the consumer // sees done, they can re-read the enqueued chunks and see the last one we // enqueued just above. m_done = true; // We set the event to ensure consumers that may have waited or are // considering waiting will notice that the producer is done. This is done // after setting the done flag to facilitate a Dekker-style check/recheck. // // Because we can ---- with threads trying to Dispose of the event, we must // acquire a lock around our setting, and double-check that the event isn't null. // // Update 8/2/2011: Dispose() should never be called with SetDone() concurrently, // but in order to reduce churn late in the product cycle, we decided not to // remove the lock. lock (this) { if (m_consumerEvent != null) { m_consumerEvent.Set(m_index); } } } //----------------------------------------------------------------------------------- // Enqueues a new element to the buffer, possibly blocking in the process. // // Arguments: // item - the new element to enqueue // timeoutMilliseconds - a timeout (or -1 for no timeout) used in case the buffer // is full; we return false if it expires // // Notes: // This API will block until the buffer is non-full. This internally buffers // elements up into chunks, so elements are not immediately available to consumers. // internal void Enqueue(T item) { // Store the element into our current chunk. int producerChunkIndex = m_producerChunkIndex; m_producerChunk[producerChunkIndex] = item; // And lastly, if we have filled a chunk, make it visible to consumers. if (producerChunkIndex == m_chunkSize - 1) { EnqueueChunk(m_producerChunk); m_producerChunk = new T[m_chunkSize]; } m_producerChunkIndex = (producerChunkIndex + 1) % m_chunkSize; } //----------------------------------------------------------------------------------- // Internal helper to queue a real chunk, not just an element. // // Arguments: // chunk - the chunk to make visible to consumers // timeoutMilliseconds - an optional timeout; we return false if it expires // // Notes: // This API will block if the buffer is full. A chunk must contain only valid // elements; if the chunk wasn't filled, it should be trimmed to size before // enqueueing it for consumers to observe. // private void EnqueueChunk(T[] chunk) { Contract.Assert(chunk != null); Contract.Assert(!m_done, "can't continue producing after the production is over"); if (IsFull) WaitUntilNonFull(); Contract.Assert(!IsFull, "expected a non-full buffer"); // We can safely store into the current producer index because we know no consumers // will be reading from it concurrently. int bufferIndex = m_producerBufferIndex; m_buffer[bufferIndex] = chunk; // Increment the producer index, taking into count wrapping back to 0. This is a shared // write; the CLR 2.0 memory model ensures the write won't move before the write to the // corresponding element, so a consumer won't see the new index but the corresponding // element in the array as empty. #pragma warning disable 0420 Interlocked.Exchange(ref m_producerBufferIndex, (bufferIndex + 1) % m_buffer.Length); #pragma warning restore 0420 // (If there is a consumer waiting, we have to ensure to signal the event. Unfortunately, // this requires that we issue a memory barrier: We need to guarantee that the write to // our producer index doesn't pass the read of the consumer waiting flags; the CLR memory // model unfortunately permits this reordering. That is handled by using a CAS above.) if (m_consumerIsWaiting == 1 && !IsChunkBufferEmpty) { TraceHelpers.TraceInfo("AsynchronousChannel::EnqueueChunk - producer waking consumer"); m_consumerIsWaiting = 0; m_consumerEvent.Set(m_index); } } //----------------------------------------------------------------------------------- // Just waits until the queue is non-full. // private void WaitUntilNonFull() { // We must loop; sometimes the producer event will have been set // prematurely due to the way waiting flags are managed. By looping, // we will only return from this method when space is truly available. do { // If the queue is full, we have to wait for a consumer to make room. // Reset the event to unsignaled state before waiting. m_producerEvent.Reset(); // We have to handle the case where a producer and consumer are racing to // wait simultaneously. For instance, a producer might see a full queue (by // reading IsFull just above), but meanwhile a consumer might drain the queue // very quickly, suddenly seeing an empty queue. This would lead to deadlock // if we aren't careful. Therefore we check the empty/full state AGAIN after // setting our flag to see if a real wait is warranted. #pragma warning disable 0420 Interlocked.Exchange(ref m_producerIsWaiting, 1); #pragma warning restore 0420 // (We have to prevent the reads that go into determining whether the buffer // is full from moving before the write to the producer-wait flag. Hence the CAS.) // Because we might be racing with a consumer that is transitioning the // buffer from full to non-full, we must check that the queue is full once // more. Otherwise, we might decide to wait and never be woken up (since // we just reset the event). if (IsFull) { // Assuming a consumer didn't make room for us, we can wait on the event. TraceHelpers.TraceInfo("AsynchronousChannel::EnqueueChunk - producer waiting, buffer full"); m_producerEvent.Wait(m_cancellationToken); } else { // Reset the flags, we don't actually have to wait after all. m_producerIsWaiting = 0; } } while (IsFull); } //----------------------------------------------------------------------------------- // Flushes any built up elements that haven't been made available to a consumer yet. // Only safe to be called by a producer. // // Notes: // This API can block if the channel is currently full. // private void FlushCachedChunk() { // If the producer didn't fill their temporary working chunk, flushing forces an enqueue // so that a consumer will see the partially filled chunk of elements. if (m_producerChunk != null && m_producerChunkIndex != 0) { // Trim the partially-full chunk to an array just big enough to hold it. Contract.Assert(1 <= m_producerChunkIndex && m_producerChunkIndex <= m_chunkSize); T[] leftOverChunk = new T[m_producerChunkIndex]; Array.Copy(m_producerChunk, leftOverChunk, m_producerChunkIndex); // And enqueue the right-sized temporary chunk, possibly blocking if it's full. EnqueueChunk(leftOverChunk); m_producerChunk = null; } } //----------------------------------------------------------------------------------- // Dequeues the next element in the queue. // // Arguments: // item - a byref to the location into which we'll store the dequeued element // // Return Value: // True if an item was found, false otherwise. // internal bool TryDequeue(ref T item) { // Ensure we have a chunk to work with. if (m_consumerChunk == null) { if (!TryDequeueChunk(ref m_consumerChunk)) { Contract.Assert(m_consumerChunk == null); return false; } m_consumerChunkIndex = 0; } // Retrieve the current item in the chunk. Contract.Assert(m_consumerChunk != null, "consumer chunk is null"); Contract.Assert(0 <= m_consumerChunkIndex && m_consumerChunkIndex < m_consumerChunk.Length, "chunk index out of bounds"); item = m_consumerChunk[m_consumerChunkIndex]; // And lastly, if we have consumed the chunk, null it out so we'll get the // next one when dequeue is called again. ++m_consumerChunkIndex; if (m_consumerChunkIndex == m_consumerChunk.Length) { m_consumerChunk = null; } return true; } //----------------------------------------------------------------------------------- // Internal helper method to dequeue a whole chunk. // // Arguments: // chunk - a byref to the location into which we'll store the chunk // // Return Value: // True if a chunk was found, false otherwise. // private bool TryDequeueChunk(ref T[] chunk) { // This is the non-blocking version of dequeue. We first check to see // if the queue is empty. If the caller chooses to wait later, they can // call the overload with an event. if (IsChunkBufferEmpty) { return false; } chunk = InternalDequeueChunk(); return true; } //----------------------------------------------------------------------------------- // Blocking dequeue for the next element. This version of the API is used when the // caller will possibly wait for a new chunk to be enqueued. // // Arguments: // item - a byref for the returned element // waitEvent - a byref for the event used to signal blocked consumers // // Return Value: // True if an element was found, false otherwise. // // Notes: // If the return value is false, it doesn't always mean waitEvent will be non- // null. If the producer is done enqueueing, the return will be false and the // event will remain null. A caller must check for this condition. // // If the return value is false and an event is returned, there have been // side-effects on the channel. Namely, the flag telling producers a consumer // might be waiting will have been set. DequeueEndAfterWait _must_ be called // eventually regardless of whether the caller actually waits or not. // internal bool TryDequeue(ref T item, ref bool isDone) { isDone = false; // Ensure we have a buffer to work with. if (m_consumerChunk == null) { if (!TryDequeueChunk(ref m_consumerChunk, ref isDone)) { Contract.Assert(m_consumerChunk == null); return false; } m_consumerChunkIndex = 0; } // Retrieve the current item in the chunk. Contract.Assert(m_consumerChunk != null, "consumer chunk is null"); Contract.Assert(0 <= m_consumerChunkIndex && m_consumerChunkIndex < m_consumerChunk.Length, "chunk index out of bounds"); item = m_consumerChunk[m_consumerChunkIndex]; // And lastly, if we have consumed the chunk, null it out. ++m_consumerChunkIndex; if (m_consumerChunkIndex == m_consumerChunk.Length) { m_consumerChunk = null; } return true; } //----------------------------------------------------------------------------------- // Internal helper method to dequeue a whole chunk. This version of the API is used // when the caller will wait for a new chunk to be enqueued. // // Arguments: // chunk - a byref for the dequeued chunk // waitEvent - a byref for the event used to signal blocked consumers // // Return Value: // True if a chunk was found, false otherwise. // // Notes: // If the return value is false, it doesn't always mean waitEvent will be non- // null. If the producer is done enqueueing, the return will be false and the // event will remain null. A caller must check for this condition. // // If the return value is false and an event is returned, there have been // side-effects on the channel. Namely, the flag telling producers a consumer // might be waiting will have been set. DequeueEndAfterWait _must_ be called // eventually regardless of whether the caller actually waits or not. // private bool TryDequeueChunk(ref T[] chunk, ref bool isDone) { isDone = false; // We will register our interest in waiting, and then return an event // that the caller can use to wait. while (IsChunkBufferEmpty) { // If the producer is done and we've drained the queue, we can bail right away. if (IsDone) { // We have to see if the buffer is empty AFTER we've seen that it's done. // Otherwise, we would possibly miss the elements enqueued before the // producer signaled that it's done. This is done with a volatile load so // that the read of empty doesn't move before the read of done. if (IsChunkBufferEmpty) { // Return isDone=true so callers know not to wait isDone = true; return false; } } // We have to handle the case where a producer and consumer are racing to // wait simultaneously. For instance, a consumer might see an empty queue (by // reading IsChunkBufferEmpty just above), but meanwhile a producer might fill the queue // very quickly, suddenly seeing a full queue. This would lead to deadlock // if we aren't careful. Therefore we check the empty/full state AGAIN after // setting our flag to see if a real wait is warranted. #pragma warning disable 0420 Interlocked.Exchange(ref m_consumerIsWaiting, 1); #pragma warning restore 0420 // (We have to prevent the reads that go into determining whether the buffer // is full from moving before the write to the producer-wait flag. Hence the CAS.) // Because we might be racing with a producer that is transitioning the // buffer from empty to non-full, we must check that the queue is empty once // more. Similarly, if the queue has been marked as done, we must not wait // because we just reset the event, possibly losing as signal. In both cases, // we would otherwise decide to wait and never be woken up (i.e. deadlock). if (IsChunkBufferEmpty && !IsDone) { // Note that the caller must eventually call DequeueEndAfterWait to set the // flags back to a state where no consumer is waiting, whether they choose // to wait or not. TraceHelpers.TraceInfo("AsynchronousChannel::DequeueChunk - consumer possibly waiting"); return false; } else { // Reset the wait flags, we don't need to wait after all. We loop back around // and recheck that the queue isn't empty, done, etc. m_consumerIsWaiting = 0; } } Contract.Assert(!IsChunkBufferEmpty, "single-consumer should never witness an empty queue here"); chunk = InternalDequeueChunk(); return true; } //----------------------------------------------------------------------------------- // Internal helper method that dequeues a chunk after we've verified that there is // a chunk available to dequeue. // // Return Value: // The dequeued chunk. // // Assumptions: // The caller has verified that a chunk is available, i.e. the queue is non-empty. // private T[] InternalDequeueChunk() { Contract.Assert(!IsChunkBufferEmpty); // We can safely read from the consumer index because we know no producers // will write concurrently. int consumerBufferIndex = m_consumerBufferIndex; T[] chunk = m_buffer[consumerBufferIndex]; // Zero out contents to avoid holding on to memory for longer than necessary. This // ensures the entire chunk is eligible for GC sooner. (More important for big chunks.) m_buffer[consumerBufferIndex] = null; // Increment the consumer index, taking into count wrapping back to 0. This is a shared // write; the CLR 2.0 memory model ensures the write won't move before the write to the // corresponding element, so a consumer won't see the new index but the corresponding // element in the array as empty. #pragma warning disable 0420 Interlocked.Exchange(ref m_consumerBufferIndex, (consumerBufferIndex + 1) % m_buffer.Length); #pragma warning restore 0420 // (Unfortunately, this whole sequence requires a memory barrier: We need to guarantee // that the write to m_consumerBufferIndex doesn't pass the read of the wait-flags; the CLR memory // model sadly permits this reordering. Hence the CAS above.) if (m_producerIsWaiting == 1 && !IsFull) { TraceHelpers.TraceInfo("BoundedSingleLockFreeChannel::DequeueChunk - consumer waking producer"); m_producerIsWaiting = 0; m_producerEvent.Set(); } return chunk; } //----------------------------------------------------------------------------------- // Clears the flag set when a blocking Dequeue is called, letting producers know // the consumer is no longer waiting. // internal void DoneWithDequeueWait() { // On our way out, be sure to reset the flags. m_consumerIsWaiting = 0; } //----------------------------------------------------------------------------------- // Closes Win32 events possibly allocated during execution. // public void Dispose() { // We need to take a lock to deal with consumer threads racing to call Dispose // and producer threads racing inside of SetDone. // // Update 8/2/2011: Dispose() should never be called with SetDone() concurrently, // but in order to reduce churn late in the product cycle, we decided not to // remove the lock. lock (this) { Contract.Assert(m_done, "Expected channel to be done before disposing"); Contract.Assert(m_producerEvent != null); Contract.Assert(m_consumerEvent != null); m_producerEvent.Dispose(); m_producerEvent = null; m_consumerEvent = 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. /*============================================================================= ** ** Class: Stack ** ** Purpose: Represents a simple last-in-first-out (LIFO) ** non-generic collection of objects. ** ** =============================================================================*/ using System.Diagnostics; namespace System.Collections { // A simple stack of objects. Internally it is implemented as an array, // so Push can be O(n). Pop is O(1). [DebuggerTypeProxy(typeof(System.Collections.Stack.StackDebugView))] [DebuggerDisplay("Count = {Count}")] [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Stack : ICollection, ICloneable { private object?[] _array; // Storage for stack elements. Do not rename (binary serialization) private int _size; // Number of items in the stack. Do not rename (binary serialization) private int _version; // Used to keep enumerator in sync w/ collection. Do not rename (binary serialization) private const int _defaultCapacity = 10; public Stack() { _array = new object[_defaultCapacity]; _size = 0; _version = 0; } // Create a stack with a specific initial capacity. The initial capacity // must be a non-negative number. public Stack(int initialCapacity) { if (initialCapacity < 0) throw new ArgumentOutOfRangeException(nameof(initialCapacity), SR.ArgumentOutOfRange_NeedNonNegNum); if (initialCapacity < _defaultCapacity) initialCapacity = _defaultCapacity; // Simplify doubling logic in Push. _array = new object[initialCapacity]; _size = 0; _version = 0; } // Fills a Stack with the contents of a particular collection. The items are // pushed onto the stack in the same order they are read by the enumerator. // public Stack(ICollection col) : this((col == null ? 32 : col.Count)) { if (col == null) throw new ArgumentNullException(nameof(col)); IEnumerator en = col.GetEnumerator(); while (en.MoveNext()) Push(en.Current); } public virtual int Count { get { return _size; } } public virtual bool IsSynchronized { get { return false; } } public virtual object SyncRoot => this; // Removes all Objects from the Stack. public virtual void Clear() { Array.Clear(_array, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references. _size = 0; _version++; } public virtual object Clone() { Stack s = new Stack(_size); s._size = _size; Array.Copy(_array, 0, s._array, 0, _size); s._version = _version; return s; } public virtual bool Contains(object? obj) { int count = _size; while (count-- > 0) { if (obj == null) { if (_array[count] == null) return true; } else if (_array[count] != null && _array[count]!.Equals(obj)) { return true; } } return false; } // Copies the stack into an array. public virtual void CopyTo(Array array, int index) { if (array == null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - index < _size) throw new ArgumentException(SR.Argument_InvalidOffLen); int i = 0; object?[]? objArray = array as object[]; if (objArray != null) { while (i < _size) { objArray[i + index] = _array[_size - i - 1]; i++; } } else { while (i < _size) { array.SetValue(_array[_size - i - 1], i + index); i++; } } } // Returns an IEnumerator for this Stack. public virtual IEnumerator GetEnumerator() { return new StackEnumerator(this); } // Returns the top object on the stack without removing it. If the stack // is empty, Peek throws an InvalidOperationException. public virtual object? Peek() { if (_size == 0) throw new InvalidOperationException(SR.InvalidOperation_EmptyStack); return _array[_size - 1]; } // Pops an item from the top of the stack. If the stack is empty, Pop // throws an InvalidOperationException. public virtual object? Pop() { if (_size == 0) throw new InvalidOperationException(SR.InvalidOperation_EmptyStack); _version++; object? obj = _array[--_size]; _array[_size] = null; // Free memory quicker. return obj; } // Pushes an item to the top of the stack. // public virtual void Push(object? obj) { if (_size == _array.Length) { object[] newArray = new object[2 * _array.Length]; Array.Copy(_array, 0, newArray, 0, _size); _array = newArray; } _array[_size++] = obj; _version++; } // Returns a synchronized Stack. // public static Stack Synchronized(Stack stack) { if (stack == null) throw new ArgumentNullException(nameof(stack)); return new SyncStack(stack); } // Copies the Stack to an array, in the same order Pop would return the items. public virtual object?[] ToArray() { if (_size == 0) return Array.Empty<object>(); object?[] objArray = new object[_size]; int i = 0; while (i < _size) { objArray[i] = _array[_size - i - 1]; i++; } return objArray; } private class SyncStack : Stack { private readonly Stack _s; private readonly object _root; internal SyncStack(Stack stack) { _s = stack; _root = stack.SyncRoot; } public override bool IsSynchronized { get { return true; } } public override object SyncRoot { get { return _root; } } public override int Count { get { lock (_root) { return _s.Count; } } } public override bool Contains(object? obj) { lock (_root) { return _s.Contains(obj); } } public override object Clone() { lock (_root) { return new SyncStack((Stack)_s.Clone()); } } public override void Clear() { lock (_root) { _s.Clear(); } } public override void CopyTo(Array array, int arrayIndex) { lock (_root) { _s.CopyTo(array, arrayIndex); } } public override void Push(object? value) { lock (_root) { _s.Push(value); } } public override object? Pop() { lock (_root) { return _s.Pop(); } } public override IEnumerator GetEnumerator() { lock (_root) { return _s.GetEnumerator(); } } public override object? Peek() { lock (_root) { return _s.Peek(); } } public override object?[] ToArray() { lock (_root) { return _s.ToArray(); } } } private class StackEnumerator : IEnumerator, ICloneable { private readonly Stack _stack; private int _index; private readonly int _version; private object? _currentElement; internal StackEnumerator(Stack stack) { _stack = stack; _version = _stack._version; _index = -2; _currentElement = null; } public object Clone() => MemberwiseClone(); public virtual bool MoveNext() { bool retval; if (_version != _stack._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); if (_index == -2) { // First call to enumerator. _index = _stack._size - 1; retval = (_index >= 0); if (retval) _currentElement = _stack._array[_index]; return retval; } if (_index == -1) { // End of enumeration. return false; } retval = (--_index >= 0); if (retval) _currentElement = _stack._array[_index]; else _currentElement = null; return retval; } public virtual object? Current { get { if (_index == -2) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); if (_index == -1) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded); return _currentElement; } } public virtual void Reset() { if (_version != _stack._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); _index = -2; _currentElement = null; } } internal class StackDebugView { private readonly Stack _stack; public StackDebugView(Stack stack) { if (stack == null) throw new ArgumentNullException(nameof(stack)); _stack = stack; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public object?[] Items { get { return _stack.ToArray(); } } } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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 Gallio.Common.Xml.Diffing; using Gallio.Common.Xml.Paths; using Gallio.Model.Schema; using Gallio.Common.Reflection; using Gallio.Runner.Reports.Schema; using Gallio.Tests; using Gallio.Tests.Common.Xml.Diffing; using MbUnit.Framework; using Gallio.Common.Xml; using Gallio.Common; using System.Collections.Generic; using System; namespace Gallio.Tests.Common.Xml { [TestFixture] [TestsOn(typeof(NodeAttributeCollection))] public class NodeAttributeCollectionTest : DiffableTestBase { [Test] [ExpectedArgumentNullException] public void Constructs_with_null_initializer_should_throw_exception() { new NodeAttributeCollection(null); } [Test] public void Default_empty() { var collection = NodeAttributeCollection.Empty; Assert.IsEmpty(collection); Assert.Count(0, collection); } [Test] public void Constructs_ok() { var attribute1 = new Gallio.Common.Xml.NodeAttribute(123, "name1", "value1", 999); var attribute2 = new Gallio.Common.Xml.NodeAttribute(456, "name2", "value2", 999); var attribute3 = new Gallio.Common.Xml.NodeAttribute(789, "name3", "value3", 999); var array = new[] { attribute1, attribute2, attribute3 }; var collection = new NodeAttributeCollection(array); Assert.Count(3, collection); Assert.AreElementsSame(array, collection); } private static NodeAttributeCollection MakeStubCollection(params string[] namesValues) { var list = new List<Gallio.Common.Xml.NodeAttribute>(); for (int i = 0; i < namesValues.Length / 2; i++) { list.Add(new Gallio.Common.Xml.NodeAttribute(i, namesValues[2 * i], namesValues[2 * i + 1], namesValues.Length / 2)); } return new NodeAttributeCollection(list); } [Test] public void Contains_with_null_name_should_throw_exception() { var attributes = MakeStubCollection("name1", "value1", "name2", "value2", "name3", "value3"); Assert.Throws<ArgumentNullException>(() => attributes.Contains(null, null, Options.None)); } [Test] public void Contains_yes() { var attributes = MakeStubCollection("name1", "value1", "name2", "value2", "name3", "value3"); bool found = attributes.Contains("name2", null, Options.None); Assert.IsTrue(found); } [Test] public void Contains_case_insensitive_yes() { var attributes = MakeStubCollection("name1", "value1", "name2", "value2", "name3", "value3"); bool found = attributes.Contains("NAME2", null, Options.IgnoreAttributesNameCase); Assert.IsTrue(found); } [Test] public void Contains_no() { var attributes = MakeStubCollection("name1", "value1", "name2", "value2", "name3", "value3"); bool found = attributes.Contains("name123", null, Options.None); Assert.IsFalse(found); } [Test] public void Contains_case_senstive_no() { var attributes = MakeStubCollection("name1", "value1", "name2", "value2", "name3", "value3"); bool found = attributes.Contains("NAME123", null, Options.None); Assert.IsFalse(found); } [Test] public void Contains_with_case_sensitive_value_yes() { var attributes = MakeStubCollection("name1", "value1", "name2", "value2", "name3", "value3"); bool found = attributes.Contains("name2", "value2", Options.None); Assert.IsTrue(found); } [Test] public void Contains_with_case_insensitive_value_yes() { var attributes = MakeStubCollection("name1", "value1", "name2", "value2", "name3", "value3"); bool found = attributes.Contains("name2", "VALUE2", Options.IgnoreAttributesValueCase); Assert.IsTrue(found); } [Test] public void Contains_with_case_sensitive_value_no() { var attributes = MakeStubCollection("name1", "value1", "name2", "value2", "name3", "value3"); bool found = attributes.Contains("name2", "VALUE2", Options.None); Assert.IsFalse(found); } [Test] public void Contains_with_case_insensitive_value_no() { var attributes = MakeStubCollection("name1", "value1", "name2", "value2", "name3", "value3"); bool found = attributes.Contains("name2", "value3", Options.None); Assert.IsFalse(found); } [Test] public void Contains_value_among_several() { var attributes = MakeStubCollection("name", "value1", "name", "value2", "name", "value3"); bool found = attributes.Contains("name", "value3", Options.None); Assert.IsTrue(found); } [Test] [ExpectedArgumentNullException] public void Diff_with_null_expected_value_should_throw_exception() { var collection = NodeAttributeCollection.Empty; collection.Diff(null, XmlPathRoot.Strict.Empty, XmlPathRoot.Strict.Empty, XmlOptions.Strict.Value); } [Test] [ExpectedArgumentNullException] public void Diff_with_null_path_should_throw_exception() { var collection = NodeAttributeCollection.Empty; collection.Diff(NodeAttributeCollection.Empty, null, XmlPathRoot.Strict.Empty, XmlOptions.Strict.Value); } [Test] [ExpectedArgumentNullException] public void Diff_with_null_pathExpected_should_throw_exception() { var collection = NodeAttributeCollection.Empty; collection.Diff(NodeAttributeCollection.Empty, XmlPathRoot.Strict.Empty, null, XmlOptions.Strict.Value); } #region Diffing ordered attributes [Test] public void Diff_equal_collections() { var actual = MakeStubCollection("name1", "value1", "name2", "value2", "name3", "value3"); var expected = MakeStubCollection("name1", "value1", "name2", "value2", "name3", "value3"); DiffSet diffSet = actual.Diff(expected, XmlPathRoot.Strict.Element(0), XmlPathRoot.Strict.Element(0), XmlOptions.Strict.Value); Assert.IsEmpty(diffSet); } [Test] public void Diff_collections_with_missing_attribute_at_the_end() { var actual = MakeStubCollection("name1", "value1", "name2", "value2"); var expected = MakeStubCollection("name1", "value1", "name2", "value2", "name3", "value3"); DiffSet diffSet = actual.Diff(expected, XmlPathRoot.Strict.Element(0), XmlPathRoot.Strict.Element(0), XmlOptions.Strict.Value); AssertDiff(diffSet, new[] { new Diff(DiffType.MissingAttribute, XmlPathRoot.Strict.Element(0).Attribute(2), DiffTargets.Expected) }); } [Test] public void Diff_collections_with_missing_attribute_in_the_middle() { var actual = MakeStubCollection("name1", "value1", "name3", "value3"); var expected = MakeStubCollection("name1", "value1", "name2", "value2", "name3", "value3"); DiffSet diffSet = actual.Diff(expected, XmlPathRoot.Strict.Element(0), XmlPathRoot.Strict.Element(0), XmlOptions.Strict.Value); AssertDiff(diffSet, new[] { new Diff(DiffType.UnexpectedAttribute, XmlPathRoot.Strict.Element(0).Attribute(1), DiffTargets.Actual) }); } [Test] public void Diff_collections_with_exceeding_attribute_at_the_end() { var actual = MakeStubCollection("name1", "value1", "name2", "value2", "name3", "value3"); var expected = MakeStubCollection("name1", "value1", "name2", "value2"); DiffSet diffSet = actual.Diff(expected, XmlPathRoot.Strict.Element(0), XmlPathRoot.Strict.Element(0), XmlOptions.Strict.Value); AssertDiff(diffSet, new[] { new Diff(DiffType.UnexpectedAttribute, XmlPathRoot.Strict.Element(0).Attribute(2), DiffTargets.Actual) }); } [Test] public void Diff_collections_with_exceeding_attribute_in_the_middle() { var actual = MakeStubCollection("name1", "value1", "name2", "value2", "name3", "value3"); var expected = MakeStubCollection("name1", "value1", "name3", "value3"); DiffSet diffSet = actual.Diff(expected, XmlPathRoot.Strict.Element(0), XmlPathRoot.Strict.Element(0), XmlOptions.Strict.Value); AssertDiff(diffSet, new[] { new Diff(DiffType.UnexpectedAttribute, XmlPathRoot.Strict.Element(0).Attribute(1), DiffTargets.Actual) }); } [Test] public void Diff_collections_with_one_unexpected_value() { var actual = MakeStubCollection("name1", "value1", "name2", "ERROR!", "name3", "value3"); var expected = MakeStubCollection("name1", "value1", "name2", "value2", "name3", "value3"); DiffSet diffSet = actual.Diff(expected, XmlPathRoot.Strict.Element(0), XmlPathRoot.Strict.Element(0), XmlOptions.Strict.Value); AssertDiff(diffSet, new[] { new Diff(DiffType.MismatchedAttribute, XmlPathRoot.Strict.Element(0).Attribute(1), DiffTargets.Both) }); } [Test] public void Diff_collections_with_several_unexpected_values() { var actual = MakeStubCollection("name1", "ERROR1!", "name2", "value2", "name3", "ERROR3!"); var expected = MakeStubCollection("name1", "value1", "name2", "value2", "name3", "value3"); DiffSet diffSet = actual.Diff(expected, XmlPathRoot.Strict.Element(0), XmlPathRoot.Strict.Element(0), XmlOptions.Strict.Value); AssertDiff(diffSet, new[] { new Diff(DiffType.UnexpectedAttribute, XmlPathRoot.Strict.Element(0).Attribute(0), DiffTargets.Both), new Diff(DiffType.UnexpectedAttribute, XmlPathRoot.Strict.Element(0).Attribute(2), DiffTargets.Both) }); } #endregion #region Diffing unordered attributes [Test] public void Diff_equal_unordered_collections() { var actual = MakeStubCollection("name1", "value1", "name2", "value2", "name3", "value3"); var expected = MakeStubCollection("name2", "value2", "name3", "value3", "name1", "value1"); DiffSet diffSet = actual.Diff(expected, XmlPathRoot.Strict.Element(0), XmlPathRoot.Strict.Element(0), Options.IgnoreAttributesOrder); Assert.IsEmpty(diffSet); } [Test] public void Diff_equal_unordered_collections_with_missing_attribute() { var actual = MakeStubCollection("name1", "value1", "name3", "value3"); var expected = MakeStubCollection("name2", "value2", "name3", "value3", "name1", "value1"); DiffSet diffSet = actual.Diff(expected, XmlPathRoot.Strict.Element(0), XmlPathRoot.Strict.Element(0), Options.IgnoreAttributesOrder); AssertDiff(diffSet, new[] { new Diff(DiffType.MissingAttribute, XmlPathRoot.Strict.Element(0).Attribute(0), DiffTargets.Expected) }); } [Test] public void Diff_equal_unordered_collections_with_excess_attribute() { var actual = MakeStubCollection("name1", "value1", "name3", "value3", "name2", "value2"); var expected = MakeStubCollection("name2", "value2", "name1", "value1"); DiffSet diffSet = actual.Diff(expected, XmlPathRoot.Strict.Element(0), XmlPathRoot.Strict.Element(0), Options.IgnoreAttributesOrder); AssertDiff(diffSet, new[] { new Diff(DiffType.UnexpectedAttribute, XmlPathRoot.Strict.Element(0).Attribute(1), DiffTargets.Actual) }); } [Test] public void Diff_equal_unordered_collections_with_unexpected_attribute_value() { var actual = MakeStubCollection("name1", "value1", "name3", "ERROR!", "name2", "value2"); var expected = MakeStubCollection("name2", "value2", "name1", "value1", "name3", "value3"); DiffSet diffSet = actual.Diff(expected, XmlPathRoot.Strict.Element(0), XmlPathRoot.Strict.Element(0), Options.IgnoreAttributesOrder); AssertDiff(diffSet, new[] { new Diff(DiffType.MismatchedAttribute, XmlPathRoot.Strict.Element(0).Attribute(1), DiffTargets.Both) }); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics; using System.Net.Security; using System.Runtime.InteropServices; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography; using System.Text; using Microsoft.Win32.SafeHandles; internal static partial class Interop { internal static partial class Ssl { internal delegate int SslCtxSetVerifyCallback(int preverify_ok, IntPtr x509_ctx); [DllImport(Libraries.CryptoNative)] internal static extern void EnsureLibSslInitialized(); [DllImport(Libraries.CryptoNative)] internal static extern IntPtr SslV2_3Method(); [DllImport(Libraries.CryptoNative)] internal static extern IntPtr SslV3Method(); [DllImport(Libraries.CryptoNative)] internal static extern IntPtr TlsV1Method(); [DllImport(Libraries.CryptoNative)] internal static extern IntPtr TlsV1_1Method(); [DllImport(Libraries.CryptoNative)] internal static extern IntPtr TlsV1_2Method(); [DllImport(Libraries.CryptoNative)] internal static extern SafeSslHandle SslCreate(SafeSslContextHandle ctx); [DllImport(Libraries.CryptoNative)] internal static extern SslErrorCode SslGetError(SafeSslHandle ssl, int ret); [DllImport(Libraries.CryptoNative)] internal static extern SslErrorCode SslGetError(IntPtr ssl, int ret); [DllImport(Libraries.CryptoNative)] internal static extern void SslDestroy(IntPtr ssl); [DllImport(Libraries.CryptoNative)] internal static extern void SslSetConnectState(SafeSslHandle ssl); [DllImport(Libraries.CryptoNative)] internal static extern void SslSetAcceptState(SafeSslHandle ssl); [DllImport(Libraries.CryptoNative)] private static extern IntPtr SslGetVersion(SafeSslHandle ssl); internal static string GetProtocolVersion(SafeSslHandle ssl) { return Marshal.PtrToStringAnsi(SslGetVersion(ssl)); } [DllImport(Libraries.CryptoNative)] internal static extern bool GetSslConnectionInfo( SafeSslHandle ssl, out int dataCipherAlg, out int keyExchangeAlg, out int dataHashAlg, out int dataKeySize, out int hashKeySize); [DllImport(Libraries.CryptoNative)] internal static unsafe extern int SslWrite(SafeSslHandle ssl, byte* buf, int num); [DllImport(Libraries.CryptoNative)] internal static extern int SslRead(SafeSslHandle ssl, byte[] buf, int num); [DllImport(Libraries.CryptoNative)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool IsSslRenegotiatePending(SafeSslHandle ssl); [DllImport(Libraries.CryptoNative)] internal static extern int SslShutdown(IntPtr ssl); [DllImport(Libraries.CryptoNative)] internal static extern void SslSetBio(SafeSslHandle ssl, SafeBioHandle rbio, SafeBioHandle wbio); [DllImport(Libraries.CryptoNative)] internal static extern int SslDoHandshake(SafeSslHandle ssl); [DllImport(Libraries.CryptoNative)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool IsSslStateOK(SafeSslHandle ssl); // NOTE: this is just an (unsafe) overload to the BioWrite method from Interop.Bio.cs. [DllImport(Libraries.CryptoNative)] internal static unsafe extern int BioWrite(SafeBioHandle b, byte* data, int len); [DllImport(Libraries.CryptoNative)] internal static extern SafeX509Handle SslGetPeerCertificate(SafeSslHandle ssl); [DllImport(Libraries.CryptoNative)] internal static extern SafeSharedX509StackHandle SslGetPeerCertChain(SafeSslHandle ssl); [DllImport(Libraries.CryptoNative)] internal static extern void GetStreamSizes(out int header, out int trailer, out int maximumMessage); [DllImport(Libraries.CryptoNative)] internal static extern int SslGetPeerFinished(SafeSslHandle ssl, IntPtr buf, int count); [DllImport(Libraries.CryptoNative)] internal static extern int SslGetFinished(SafeSslHandle ssl, IntPtr buf, int count); [DllImport(Libraries.CryptoNative)] internal static extern bool SslSessionReused(SafeSslHandle ssl); [DllImport(Libraries.CryptoNative)] internal static extern bool SslAddExtraChainCert(SafeSslHandle ssl, SafeX509Handle x509); [DllImport(Libraries.CryptoNative, EntryPoint = "SslGetClientCAList")] private static extern SafeSharedX509NameStackHandle SslGetClientCAList_private(SafeSslHandle ssl); internal static SafeSharedX509NameStackHandle SslGetClientCAList(SafeSslHandle ssl) { Crypto.CheckValidOpenSslHandle(ssl); SafeSharedX509NameStackHandle handle = SslGetClientCAList_private(ssl); if (!handle.IsInvalid) { handle.SetParent(ssl); } return handle; } internal static class SslMethods { internal static readonly IntPtr TLSv1_method = TlsV1Method(); internal static readonly IntPtr TLSv1_1_method = TlsV1_1Method(); internal static readonly IntPtr TLSv1_2_method = TlsV1_2Method(); internal static readonly IntPtr SSLv3_method = SslV3Method(); internal static readonly IntPtr SSLv23_method = SslV2_3Method(); } internal enum SslErrorCode { SSL_ERROR_NONE = 0, SSL_ERROR_SSL = 1, SSL_ERROR_WANT_READ = 2, SSL_ERROR_WANT_WRITE = 3, SSL_ERROR_SYSCALL = 5, SSL_ERROR_ZERO_RETURN = 6, // NOTE: this SslErrorCode value doesn't exist in OpenSSL, but // we use it to distinguish when a renegotiation is pending. // Choosing an arbitrarily large value that shouldn't conflict // with any actual OpenSSL error codes SSL_ERROR_RENEGOTIATE = 29304 } } } namespace Microsoft.Win32.SafeHandles { internal sealed class SafeSslHandle : SafeHandle { private SafeBioHandle _readBio; private SafeBioHandle _writeBio; private bool _isServer; private bool _handshakeCompleted = false; public bool IsServer { get { return _isServer; } } public SafeBioHandle InputBio { get { return _readBio; } } public SafeBioHandle OutputBio { get { return _writeBio; } } internal void MarkHandshakeCompleted() { _handshakeCompleted = true; } public static SafeSslHandle Create(SafeSslContextHandle context, bool isServer) { SafeBioHandle readBio = Interop.Crypto.CreateMemoryBio(); if (readBio.IsInvalid) { return new SafeSslHandle(); } SafeBioHandle writeBio = Interop.Crypto.CreateMemoryBio(); if (writeBio.IsInvalid) { readBio.Dispose(); return new SafeSslHandle(); } SafeSslHandle handle = Interop.Ssl.SslCreate(context); if (handle.IsInvalid) { readBio.Dispose(); writeBio.Dispose(); return handle; } handle._isServer = isServer; // After SSL_set_bio, the BIO handles are owned by SSL pointer // and are automatically freed by SSL_free. To prevent a double // free, we need to keep the ref counts bumped up till SSL_free bool gotRef = false; readBio.DangerousAddRef(ref gotRef); try { bool ignore = false; writeBio.DangerousAddRef(ref ignore); } catch { if (gotRef) { readBio.DangerousRelease(); } throw; } Interop.Ssl.SslSetBio(handle, readBio, writeBio); handle._readBio = readBio; handle._writeBio = writeBio; if (isServer) { Interop.Ssl.SslSetAcceptState(handle); } else { Interop.Ssl.SslSetConnectState(handle); } return handle; } public override bool IsInvalid { get { return handle == IntPtr.Zero; } } protected override bool ReleaseHandle() { if (_handshakeCompleted) { Disconnect(); } Interop.Ssl.SslDestroy(handle); if (_readBio != null) { _readBio.SetHandleAsInvalid(); // BIO got freed in SslDestroy } if (_writeBio != null) { _writeBio.SetHandleAsInvalid(); // BIO got freed in SslDestroy } return true; } private void Disconnect() { Debug.Assert(!IsInvalid, "Expected a valid context in Disconnect"); int retVal = Interop.Ssl.SslShutdown(handle); if (retVal < 0) { //TODO (Issue #4031) check this error Interop.Ssl.SslGetError(handle, retVal); } } private SafeSslHandle() : base(IntPtr.Zero, true) { } internal SafeSslHandle(IntPtr validSslPointer, bool ownsHandle) : base(IntPtr.Zero, ownsHandle) { handle = validSslPointer; } } internal sealed class SafeChannelBindingHandle : SafeHandle { [StructLayout(LayoutKind.Sequential)] private struct SecChannelBindings { internal int InitiatorLength; internal int InitiatorOffset; internal int AcceptorAddrType; internal int AcceptorLength; internal int AcceptorOffset; internal int ApplicationDataLength; internal int ApplicationDataOffset; } private static readonly byte[] s_tlsServerEndPointByteArray = Encoding.UTF8.GetBytes("tls-server-end-point:"); private static readonly byte[] s_tlsUniqueByteArray = Encoding.UTF8.GetBytes("tls-unique:"); private static readonly int s_secChannelBindingSize = Marshal.SizeOf<SecChannelBindings>(); private readonly int _cbtPrefixByteArraySize; private const int CertHashMaxSize = 128; internal int Length { get; private set; } internal IntPtr CertHashPtr { get; private set; } internal void SetCertHash(byte[] certHashBytes) { Debug.Assert(certHashBytes != null, "check certHashBytes is not null"); int length = certHashBytes.Length; Marshal.Copy(certHashBytes, 0, CertHashPtr, length); SetCertHashLength(length); } private byte[] GetPrefixBytes(ChannelBindingKind kind) { if (kind == ChannelBindingKind.Endpoint) { return s_tlsServerEndPointByteArray; } else if (kind == ChannelBindingKind.Unique) { return s_tlsUniqueByteArray; } else { throw new NotSupportedException(); } } internal SafeChannelBindingHandle(ChannelBindingKind kind) : base(IntPtr.Zero, true) { byte[] cbtPrefix = GetPrefixBytes(kind); _cbtPrefixByteArraySize = cbtPrefix.Length; handle = Marshal.AllocHGlobal(s_secChannelBindingSize + _cbtPrefixByteArraySize + CertHashMaxSize); IntPtr cbtPrefixPtr = handle + s_secChannelBindingSize; Marshal.Copy(cbtPrefix, 0, cbtPrefixPtr, _cbtPrefixByteArraySize); CertHashPtr = cbtPrefixPtr + _cbtPrefixByteArraySize; Length = CertHashMaxSize; } internal void SetCertHashLength(int certHashLength) { int cbtLength = _cbtPrefixByteArraySize + certHashLength; Length = s_secChannelBindingSize + cbtLength; SecChannelBindings channelBindings = new SecChannelBindings() { ApplicationDataLength = cbtLength, ApplicationDataOffset = s_secChannelBindingSize }; Marshal.StructureToPtr(channelBindings, handle, true); } public override bool IsInvalid { get { return handle == IntPtr.Zero; } } protected override bool ReleaseHandle() { Marshal.FreeHGlobal(handle); SetHandle(IntPtr.Zero); return true; } } }
// // Copyright (C) 2012-2014 DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using Cassandra.IntegrationTests.TestBase; using Cassandra.IntegrationTests.TestClusterManagement; using Cassandra.Tests; using NUnit.Framework; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Cassandra.IntegrationTests.Core { [TestFixture, Category("long")] public class PoolTests : TestGlobals { protected TraceLevel OriginalTraceLevel; [OneTimeSetUp] public void OneTimeSetUp() { OriginalTraceLevel = Diagnostics.CassandraTraceSwitch.Level; Diagnostics.CassandraTraceSwitch.Level = TraceLevel.Info; } [OneTimeTearDown] public void TestFixtureTearDown() { Diagnostics.CassandraTraceSwitch.Level = OriginalTraceLevel; } /// <summary> /// Executes statements in parallel while killing nodes, validates that there are no issues failing over to remaining, available nodes /// </summary> [Test] public void FailoverTest() { var parallelOptions = new ParallelOptions(); parallelOptions.TaskScheduler = new ThreadPerTaskScheduler(); parallelOptions.MaxDegreeOfParallelism = 100; var policy = new ConstantReconnectionPolicy(int.MaxValue); var nonShareableTestCluster = TestClusterManager.GetNonShareableTestCluster(4, 1, true, false); using (var cluster = Cluster.Builder().AddContactPoint(nonShareableTestCluster.InitialContactPoint).WithReconnectionPolicy(policy).Build()) { var session = cluster.Connect(); // Check query to host distribution before killing nodes var queriedHosts = new List<string>(); DateTime futureDateTime = DateTime.Now.AddSeconds(120); while ((from singleHost in queriedHosts select singleHost).Distinct().Count() < 4 && DateTime.Now < futureDateTime) { var rs = session.Execute("SELECT * FROM system.local"); queriedHosts.Add(rs.Info.QueriedHost.ToString()); Thread.Sleep(50); } Assert.AreEqual(4, (from singleHost in queriedHosts select singleHost).Distinct().Count(), "All hosts should have been queried!"); // Create List of actions Action selectAction = () => { var rs = session.Execute("SELECT * FROM system.local"); Assert.Greater(rs.Count(), 0); }; var actions = new List<Action>(); for (var i = 0; i < 100; i++) { actions.Add(selectAction); } //kill some nodes. actions.Insert(20, () => nonShareableTestCluster.StopForce(1)); actions.Insert(20, () => nonShareableTestCluster.StopForce(2)); actions.Insert(80, () => nonShareableTestCluster.StopForce(3)); //Execute in parallel more than 100 actions Parallel.Invoke(parallelOptions, actions.ToArray()); // Wait for the nodes to be killed TestUtils.WaitForDown(nonShareableTestCluster.ClusterIpPrefix + "1", nonShareableTestCluster.Cluster, 20); TestUtils.WaitForDown(nonShareableTestCluster.ClusterIpPrefix + "2", nonShareableTestCluster.Cluster, 20); TestUtils.WaitForDown(nonShareableTestCluster.ClusterIpPrefix + "3", nonShareableTestCluster.Cluster, 20); // Execute some more SELECTs for (var i = 0; i < 250; i++) { var rowSet2 = session.Execute("SELECT * FROM system.local"); Assert.Greater(rowSet2.Count(), 0); StringAssert.StartsWith(nonShareableTestCluster.ClusterIpPrefix + "4", rowSet2.Info.QueriedHost.ToString()); } } } /// <summary> /// Executes statements in parallel while killing nodes, validates that there are no issues failing over to remaining, available nodes /// </summary> [Test] public void FailoverThenReconnect() { var parallelOptions = new ParallelOptions { TaskScheduler = new ThreadPerTaskScheduler(), MaxDegreeOfParallelism = 100 }; var policy = new ConstantReconnectionPolicy(500); var nonShareableTestCluster = TestClusterManager.GetNonShareableTestCluster(4, 1, true, false); using (var cluster = Cluster.Builder().AddContactPoint(nonShareableTestCluster.InitialContactPoint).WithReconnectionPolicy(policy).Build()) { var session = cluster.Connect(); // Check query to host distribution before killing nodes var queriedHosts = new List<string>(); DateTime futureDateTime = DateTime.Now.AddSeconds(120); while ((from singleHost in queriedHosts select singleHost).Distinct().Count() < 4 && DateTime.Now < futureDateTime) { var rs = session.Execute("SELECT * FROM system.local"); queriedHosts.Add(rs.Info.QueriedHost.ToString()); Thread.Sleep(50); } Assert.AreEqual(4, (from singleHost in queriedHosts select singleHost).Distinct().Count(), "All hosts should have been queried!"); // Create list of actions Action selectAction = () => { var rs = session.Execute("SELECT * FROM system.local"); Assert.Greater(rs.Count(), 0); }; var actions = new List<Action>(); for (var i = 0; i < 100; i++) { actions.Add(selectAction); //Check that the control connection is using first host StringAssert.StartsWith(nonShareableTestCluster.ClusterIpPrefix + "1", nonShareableTestCluster.Cluster.Metadata.ControlConnection.Address.ToString()); //Kill some nodes //Including the one used by the control connection actions.Insert(20, () => nonShareableTestCluster.Stop(1)); actions.Insert(20, () => nonShareableTestCluster.Stop(2)); actions.Insert(80, () => nonShareableTestCluster.Stop(3)); //Execute in parallel more than 100 actions Parallel.Invoke(parallelOptions, actions.ToArray()); //Wait for the nodes to be killed TestUtils.WaitForDown(nonShareableTestCluster.ClusterIpPrefix + "1", nonShareableTestCluster.Cluster, 20); TestUtils.WaitForDown(nonShareableTestCluster.ClusterIpPrefix + "2", nonShareableTestCluster.Cluster, 20); TestUtils.WaitForDown(nonShareableTestCluster.ClusterIpPrefix + "3", nonShareableTestCluster.Cluster, 20); actions = new List<Action>(); for (var j = 0; j < 100; j++) { actions.Add(selectAction); } //Check that the control connection is using first host //bring back some nodes actions.Insert(3, () => nonShareableTestCluster.Start(3)); actions.Insert(50, () => nonShareableTestCluster.Start(2)); actions.Insert(50, () => nonShareableTestCluster.Start(1)); //Execute in parallel more than 100 actions Trace.TraceInformation("Start invoking with restart nodes"); Parallel.Invoke(parallelOptions, actions.ToArray()); //Wait for the nodes to be restarted TestUtils.WaitForUp(nonShareableTestCluster.ClusterIpPrefix + "1", DefaultCassandraPort, 30); TestUtils.WaitForUp(nonShareableTestCluster.ClusterIpPrefix + "2", DefaultCassandraPort, 30); TestUtils.WaitForUp(nonShareableTestCluster.ClusterIpPrefix + "3", DefaultCassandraPort, 30); queriedHosts.Clear(); // keep querying hosts until they are all queried, or time runs out futureDateTime = DateTime.Now.AddSeconds(120); while ((from singleHost in queriedHosts select singleHost).Distinct().Count() < 4 && DateTime.Now < futureDateTime) { var rs = session.Execute("SELECT * FROM system.local"); queriedHosts.Add(rs.Info.QueriedHost.ToString()); Thread.Sleep(50); } //Check that one of the restarted nodes were queried Assert.Contains(nonShareableTestCluster.ClusterIpPrefix + "1:" + DefaultCassandraPort, queriedHosts); Assert.Contains(nonShareableTestCluster.ClusterIpPrefix + "2:" + DefaultCassandraPort, queriedHosts); Assert.Contains(nonShareableTestCluster.ClusterIpPrefix + "3:" + DefaultCassandraPort, queriedHosts); Assert.Contains(nonShareableTestCluster.ClusterIpPrefix + "4:" + DefaultCassandraPort, queriedHosts); //Check that the control connection is still using last host StringAssert.StartsWith(nonShareableTestCluster.ClusterIpPrefix + "4", nonShareableTestCluster.Cluster.Metadata.ControlConnection.Address.ToString()); } } } /// <summary> /// Tests that the reconnection attempt (on a dead node) is attempted only once per try (when allowed by the reconnection policy). /// </summary> [Test] [TestTimeout(120000)] public void ReconnectionAttemptedOnlyOnce() { const int reconnectionDelay = 5000; const int waitTime = reconnectionDelay * 3 + 4000; var nonShareableTestCluster = TestClusterManager.GetNonShareableTestCluster(2, DefaultMaxClusterCreateRetries, true, false); var cluster = Cluster.Builder() .AddContactPoint(nonShareableTestCluster.InitialContactPoint) .WithReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelay)) .Build(); var connectionAttempts = 0; cluster.Metadata.Hosts.Down += h => { //Every time there is a connection attempt, it is marked as down connectionAttempts++; Trace.TraceInformation("--Considered as down at " + DateTime.Now.ToString("hh:mm:ss.fff")); }; nonShareableTestCluster.Stop(2); var session = cluster.Connect(); TestHelper.Invoke(() => session.Execute("SELECT * FROM system.local"), 10); Assert.AreEqual(1, connectionAttempts); var watch = new Stopwatch(); watch.Start(); Action action = () => { if (watch.ElapsedMilliseconds < waitTime) { session.ExecuteAsync(new SimpleStatement("SELECT * FROM system.local")); } }; var waitHandle = new AutoResetEvent(false); var t = new Timer(s => { waitHandle.Set(); }, null, waitTime, Timeout.Infinite); var parallelOptions = new ParallelOptions() { MaxDegreeOfParallelism = 50 }; while (watch.ElapsedMilliseconds < waitTime) { Trace.TraceInformation("Executing multiple times"); Parallel.Invoke(parallelOptions, Enumerable.Repeat(action, 20).ToArray()); Thread.Sleep(500); } Assert.True(waitHandle.WaitOne(waitTime), "Wait time passed but it was not signaled"); t.Dispose(); Assert.AreEqual(4, connectionAttempts); } #if !NO_MOCKS /// <summary> /// Tests that when a peer is added or set as down, the address translator is invoked /// </summary> [Test] public void AddressTranslatorIsCalledPerEachPeer() { var invokedEndPoints = new List<IPEndPoint>(); var translatorMock = new Moq.Mock<IAddressTranslator>(Moq.MockBehavior.Strict); translatorMock .Setup(t => t.Translate(Moq.It.IsAny<IPEndPoint>())) .Callback<IPEndPoint>(invokedEndPoints.Add) .Returns<IPEndPoint>(e => e); var testCluster = TestClusterManager.GetNonShareableTestCluster(3); var cluster = Cluster.Builder() .AddContactPoint(testCluster.InitialContactPoint) .WithReconnectionPolicy(new ConstantReconnectionPolicy(int.MaxValue)) .WithAddressTranslator(translatorMock.Object) .Build(); cluster.Connect(); //2 peers translated Assert.AreEqual(2, invokedEndPoints.Count); Assert.True(cluster.AllHosts().All(h => h.IsUp)); testCluster.Stop(3); //Wait for the C* event to notify the control connection Thread.Sleep(30000); //Should be down Assert.False(cluster.AllHosts().First(h => TestHelper.GetLastAddressByte(h) == 3).IsUp); //Should have been translated Assert.AreEqual(3, invokedEndPoints.Count); //The recently translated should be the host #3 Assert.AreEqual(3, TestHelper.GetLastAddressByte(invokedEndPoints.Last())); cluster.Dispose(); } #endif /// <summary> /// Tests that a node is down and the schema is not the same, it waits until the max wait time is reached /// </summary> [Test] public void ClusterWaitsForSchemaChangesUntilMaxWaitTimeIsReached() { ITestCluster nonShareableTestCluster = TestClusterManager.GetNonShareableTestCluster(2, 0, true, false); nonShareableTestCluster.Stop(2); using (var cluster = Cluster.Builder() .AddContactPoint(nonShareableTestCluster.InitialContactPoint) .Build()) { var session = cluster.Connect(); //Will wait for all the nodes to have the same schema session.Execute("CREATE KEYSPACE ks1 WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3}"); } } /// <summary> /// Tests that a node is down and the schema is not the same, it waits until the max wait time is reached /// </summary> [Test] public void ClusterWaitsForSchemaChangesUntilMaxWaitTimeIsReachedMultiple() { var index = 0; ITestCluster nonShareableTestCluster = TestClusterManager.GetNonShareableTestCluster(2, 0, true, false); nonShareableTestCluster.Stop(2); using (var cluster = Cluster.Builder() .AddContactPoint(nonShareableTestCluster.InitialContactPoint) .Build()) { var session = cluster.Connect(); //Will wait for all the nodes to have the same schema session.Execute("CREATE KEYSPACE ks1 WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3}"); session.ChangeKeyspace("ks1"); TestHelper.ParallelInvoke(() => { session.Execute("CREATE TABLE tbl1" + Interlocked.Increment(ref index) + " (id uuid primary key)"); }, 10); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Text; namespace Orleans.Storage { internal class HierarchicalKeyStore : MarshalByRefObject, ILocalDataStore { public string Etag { get; private set; } private const string KEY_VALUE_PAIR_SEPERATOR = "+"; private const string KEY_VALUE_SEPERATOR = "="; private long lastETagCounter = 1; [NonSerialized] private readonly IDictionary<string, IDictionary<string, object>> dataTable; private readonly int numKeyLayers; private readonly object lockable = new object(); public HierarchicalKeyStore(int keyLayers) { numKeyLayers = keyLayers; dataTable = new Dictionary<string, IDictionary<string, object>>(); } public string WriteRow(IList<Tuple<string, string>> keys, IDictionary<string, object> data, string eTag) { if (keys.Count > numKeyLayers) { var error = string.Format("Wrong number of keys supplied -- Expected count = {0} Received = {1}", numKeyLayers, keys.Count); Trace.TraceError(error); throw new ArgumentOutOfRangeException("keys", keys.Count, error); } lock (lockable) { var storedData = GetDataStore(keys); foreach (var kv in data) storedData[kv.Key] = kv.Value; Etag = NewEtag(); #if DEBUG var storeContents = DumpData(false); Trace.TraceInformation("WriteRow: Keys={0} Data={1} Store contents after = {2} New Etag = {3}", StorageProviderUtils.PrintKeys(keys), StorageProviderUtils.PrintData(data), storeContents, Etag); #endif return Etag; } } public IDictionary<string, object> ReadRow(IList<Tuple<string, string>> keys) { if (keys.Count > numKeyLayers) { var error = string.Format("Not enough keys supplied -- Expected count = {0} Received = {1}", numKeyLayers, keys.Count); Trace.TraceError(error); throw new ArgumentOutOfRangeException("keys", keys.Count, error); } lock (lockable) { IDictionary<string, object> data = GetDataStore(keys); #if DEBUG Trace.TraceInformation("ReadMultiRow: Keys={0} returning Data={1}", StorageProviderUtils.PrintKeys(keys), StorageProviderUtils.PrintData(data)); #endif return data; } } public IList<IDictionary<string, object>> ReadMultiRow(IList<Tuple<string, string>> keys) { if (keys.Count > numKeyLayers) { throw new ArgumentOutOfRangeException("keys", keys.Count, string.Format("Too many key supplied -- Expected count = {0} Received = {1}", numKeyLayers, keys.Count)); } lock (lockable) { IList<IDictionary<string, object>> results = FindDataStores(keys); #if DEBUG Trace.TraceInformation("ReadMultiRow: Keys={0} returning Results={1}", StorageProviderUtils.PrintKeys(keys), StorageProviderUtils.PrintResults(results)); #endif return results; } } public bool DeleteRow(IList<Tuple<string, string>> keys, string eTag) { if (keys.Count > numKeyLayers) { throw new ArgumentOutOfRangeException("keys", keys.Count, string.Format("Not enough keys supplied -- Expected count = {0} Received = {1}", numKeyLayers, keys.Count)); } string keyStr = MakeStoreKey(keys); bool removedEntry = false; lock (lockable) { IDictionary<string, object> data; if (dataTable.TryGetValue(keyStr, out data)) { var kv = new KeyValuePair<string, IDictionary<string, object>>(keyStr, data); dataTable.Remove(kv); removedEntry = true; } // No change to Etag #if DEBUG Trace.TraceInformation("DeleteRow: Keys={0} Removed={1} Data={2} Etag={3}", StorageProviderUtils.PrintKeys(keys), StorageProviderUtils.PrintData(data), removedEntry, Etag); #endif return removedEntry; } } public void Clear() { #if DEBUG Trace.TraceInformation("Clear Table"); #endif lock (lockable) { dataTable.Clear(); } } public string DumpData(bool printDump = true) { var sb = new StringBuilder(); lock (lockable) { string[] keys = dataTable.Keys.ToArray(); foreach (var key in keys) { var data = dataTable[key]; sb.AppendFormat("{0} => {1}", key, StorageProviderUtils.PrintData(data)).AppendLine(); } } #if !DEBUG if (printDump) #endif { Trace.TraceInformation("Dump {0} Etag={1} Data= {2}", GetType(), Etag, sb); } return sb.ToString(); } private IDictionary<string, object> GetDataStore(IList<Tuple<string, string>> keys) { string keyStr = MakeStoreKey(keys); lock (lockable) { IDictionary<string, object> data; if (dataTable.ContainsKey(keyStr)) { data = dataTable[keyStr]; } else { data = new Dictionary<string, object>(); // Empty data set dataTable[keyStr] = data; } #if DEBUG Trace.TraceInformation("Read: {0}", StorageProviderUtils.PrintOneWrite(keys, data, null)); #endif return data; } } private IList<IDictionary<string, object>> FindDataStores(IList<Tuple<string, string>> keys) { var results = new List<IDictionary<string, object>>(); if (numKeyLayers == keys.Count) { results.Add(GetDataStore(keys)); } else { string keyStr = MakeStoreKey(keys); lock (lockable) { foreach (var key in dataTable.Keys) if (key.StartsWith(keyStr)) results.Add(dataTable[key]); } } return results; } internal static string MakeStoreKey(IEnumerable<Tuple<string, string>> keys) { var sb = new StringBuilder(); bool first = true; foreach (var keyPair in keys) { if (first) first = false; else sb.Append(KEY_VALUE_PAIR_SEPERATOR); sb.Append(keyPair.Item1 + KEY_VALUE_SEPERATOR + keyPair.Item2); } return sb.ToString(); } private string NewEtag() { return lastETagCounter++.ToString(CultureInfo.InvariantCulture); } } }
#region License /* * All content copyright Terracotta, Inc., unless otherwise indicated. 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. * */ #endregion using System; using NUnit.Framework; using Quartz.Impl.Calendar; using Quartz.Util; namespace Quartz.Tests.Unit.Impl.Calendar { /// <author>Marko Lahma (.NET)</author> [TestFixture] public class AnnualCalendarTest : SerializationTestSupport { private AnnualCalendar cal; private static readonly string[] Versions = new string[] {"0.6.0"}; [SetUp] public void Setup() { cal = new AnnualCalendar(); } [Test] public void TestDayExclusion() { // we're local by default DateTime d = new DateTime(2005, 1, 1); cal.SetDayExcluded(d, true); Assert.IsFalse(cal.IsTimeIncluded(d.ToUniversalTime()), "Time was included when it was supposed not to be"); Assert.IsTrue(cal.IsDayExcluded(d), "Day was not excluded when it was supposed to be excluded"); Assert.AreEqual(1, cal.DaysExcluded.Count); Assert.AreEqual(d.Day, cal.DaysExcluded[0].Day); Assert.AreEqual(d.Month, cal.DaysExcluded[0].Month); } [Test] public void TestDayInclusionAfterExclusion() { DateTime d = new DateTime(2005, 1, 1); cal.SetDayExcluded(d, true); cal.SetDayExcluded(d, false); cal.SetDayExcluded(d, false); Assert.IsTrue(cal.IsTimeIncluded(d), "Time was not included when it was supposed to be"); Assert.IsFalse(cal.IsDayExcluded(d), "Day was excluded when it was supposed to be included"); } [Test] public void TestDayExclusionDifferentYears() { string errMessage = "Day was not excluded when it was supposed to be excluded"; DateTime d = new DateTime(2005, 1, 1); cal.SetDayExcluded(d, true); Assert.IsTrue(cal.IsDayExcluded(d), errMessage); Assert.IsTrue(cal.IsDayExcluded(d.AddYears(-2)), errMessage); Assert.IsTrue(cal.IsDayExcluded(d.AddYears(2)), errMessage); Assert.IsTrue(cal.IsDayExcluded(d.AddYears(100)), errMessage); } [Test] public void TestExclusionAndNextIncludedTime() { cal.DaysExcluded = null; DateTimeOffset test = DateTimeOffset.UtcNow.Date; Assert.AreEqual(test, cal.GetNextIncludedTimeUtc(test), "Did not get today as date when nothing was excluded"); cal.SetDayExcluded(test, true); Assert.AreEqual(test.AddDays(1), cal.GetNextIncludedTimeUtc(test), "Did not get next day when current day excluded"); } /// <summary> /// QUARTZ-679 Test if the annualCalendar works over years. /// </summary> [Test] public void TestDaysExcludedOverTime() { AnnualCalendar annualCalendar = new AnnualCalendar(); DateTime day = new DateTime(2005, 6, 23); annualCalendar.SetDayExcluded(day, true); day = new DateTime(2008, 2, 1); annualCalendar.SetDayExcluded(day, true); Assert.IsTrue(annualCalendar.IsDayExcluded(day), "The day 1 February is expected to be excluded but it is not"); } /// <summary> /// Part 2 of the tests of QUARTZ-679 /// </summary> [Test] public void TestRemoveInTheFuture() { AnnualCalendar annualCalendar = new AnnualCalendar(); DateTime day = new DateTime(2005, 6, 23); annualCalendar.SetDayExcluded(day, true); // Trying to remove the 23th of June day = new DateTime(2008, 6, 23); annualCalendar.SetDayExcluded(day, false); Assert.IsFalse(annualCalendar.IsDayExcluded(day), "The day 23 June is not expected to be excluded but it is"); } [Test] public void TestAnnualCalendarTimeZone() { TimeZoneInfo tz = TimeZoneUtil.FindTimeZoneById("Eastern Standard Time"); AnnualCalendar c = new AnnualCalendar(); c.TimeZone = tz; DateTimeOffset excludedDay = new DateTimeOffset(2012, 11, 4, 0, 0, 0, TimeSpan.Zero); c.SetDayExcluded(excludedDay, true); // 11/5/2012 12:00:00 AM -04:00 translate into 11/4/2012 11:00:00 PM -05:00 (EST) DateTimeOffset date = new DateTimeOffset(2012, 11, 5, 0, 0, 0, TimeSpan.FromHours(-4)); Assert.IsFalse(c.IsTimeIncluded(date), "date was expected to not be included."); Assert.IsTrue(c.IsTimeIncluded(date.AddDays(1))); DateTimeOffset expectedNextAvailable = new DateTimeOffset(2012, 11, 5, 0, 0, 0, TimeSpan.FromHours(-5)); DateTimeOffset actualNextAvailable = c.GetNextIncludedTimeUtc(date); Assert.AreEqual(expectedNextAvailable, actualNextAvailable); } [Test] public void BaseCalendarShouldNotAffectSettingInternalDataStructures() { var dayToExclude = new DateTime(2015, 1, 1); AnnualCalendar a = new AnnualCalendar(); a.SetDayExcluded(dayToExclude, true); AnnualCalendar b = new AnnualCalendar(a); b.SetDayExcluded(dayToExclude, true); b.CalendarBase = null; Assert.That(b.IsDayExcluded(dayToExclude), "day was no longer excluded after base calendar was detached"); } /// <summary> /// Get the object to serialize when generating serialized file for future /// tests, and against which to validate deserialized object. /// </summary> /// <returns></returns> protected override object GetTargetObject() { AnnualCalendar c = new AnnualCalendar(); c.Description = "description"; DateTime date = new DateTime(2005, 1, 20, 10, 5, 15); c.SetDayExcluded(date, true); return c; } /// <summary> /// Get the Quartz versions for which we should verify /// serialization backwards compatibility. /// </summary> /// <returns></returns> protected override string[] GetVersions() { return Versions; } /// <summary> /// Verify that the target object and the object we just deserialized /// match. /// </summary> /// <param name="target"></param> /// <param name="deserialized"></param> protected override void VerifyMatch(object target, object deserialized) { AnnualCalendar targetCalendar = (AnnualCalendar) target; AnnualCalendar deserializedCalendar = (AnnualCalendar) deserialized; Assert.IsNotNull(deserializedCalendar); Assert.AreEqual(targetCalendar.Description, deserializedCalendar.Description); Assert.AreEqual(targetCalendar.DaysExcluded, deserializedCalendar.DaysExcluded); //Assert.IsNull(deserializedCalendar.getTimeZone()); } } }
//--------------------------------------------------------------------------- // <copyright file="PageContentAsyncResult.cs" company="Microsoft"> // Copyright (C) 2004 by Microsoft Corporation. All rights reserved. // </copyright> // // Description: // Implements the PageContentAsyncResult // // History: // 02/25/2004 - Zhenbin Xu (ZhenbinX) - Created. // // //--------------------------------------------------------------------------- namespace System.Windows.Documents { using System; using System.Diagnostics; using System.IO; using System.Windows.Threading; using System.Threading; using MS.Internal; using MS.Internal.AppModel; using MS.Internal.Utility; using MS.Internal.Navigation; using MS.Utility; using System.Reflection; using System.Windows.Controls; using System.Windows.Markup; using System.Net; using System.IO.Packaging; /// <summary> /// IAsyncResult for GetPageAsync. This item is passed around and queued up during various /// phase of async call. /// </summary> internal sealed class PageContentAsyncResult : IAsyncResult { //-------------------------------------------------------------------- // // Internal enum // //--------------------------------------------------------------------- internal enum GetPageStatus { Loading, Cancelled, Finished } //-------------------------------------------------------------------- // // Ctor // //--------------------------------------------------------------------- #region Ctor internal PageContentAsyncResult(AsyncCallback callback, object state, Dispatcher dispatcher, Uri baseUri, Uri source, FixedPage child) { this._dispatcher = dispatcher; this._isCompleted = false; this._completedSynchronously = false; this._callback = callback; this._asyncState = state; this._getpageStatus = GetPageStatus.Loading; this._child = child; this._baseUri = baseUri; Debug.Assert(source == null || source.IsAbsoluteUri); this._source = source; } #endregion Ctor //-------------------------------------------------------------------- // // Public Methods // //--------------------------------------------------------------------- //-------------------------------------------------------------------- // // Public Properties // //--------------------------------------------------------------------- #region IAsyncResult //--------------------------------------------------------------------- /// <summary> /// Gets a user-defined object that contains information about /// this GetPageAsync call /// </summary> public object AsyncState { get { return _asyncState; } } //--------------------------------------------------------------------- /// <summary> /// Gets a WaitHandle that is used to wait for the asynchrounus /// GetPageAsync to complete. We are not providing WaitHandle /// since this can be called on the main UIThread. /// </summary> public WaitHandle AsyncWaitHandle { get { Debug.Assert(false); return null; } } //--------------------------------------------------------------------- /// <summary> /// Gets an indication of whether the asynchronous GetPage /// completed synchronously. /// </summary> public bool CompletedSynchronously { get { return _completedSynchronously; } } //--------------------------------------------------------------------- /// <summary> /// Gets an indication whether the asynchronous GetPage has finished /// </summary> public bool IsCompleted { get { return _isCompleted; } } #endregion IAsyncResult //-------------------------------------------------------------------- // // Internal Methods // //--------------------------------------------------------------------- #region DispatcherOperationCallback //--------------------------------------------------------------------- internal object Dispatch(object arg) { if (this._exception != null) { // force finish if there was any exception this._getpageStatus = GetPageStatus.Finished; } switch (this._getpageStatus) { case GetPageStatus.Loading: try { if (this._child != null) { this._completedSynchronously = true; this._result = this._child; _getpageStatus = GetPageStatus.Finished; goto case GetPageStatus.Finished; } // // Note if _source == null, exception will // be thrown. // Stream responseStream; PageContent._LoadPageImpl(this._baseUri, this._source, out _result, out responseStream); if (_result == null || _result.IsInitialized) { responseStream.Close(); } else { _pendingStream = responseStream; _result.Initialized += new EventHandler(_OnPaserFinished); } _getpageStatus = GetPageStatus.Finished; } catch (ApplicationException e) { this._exception = e; } goto case GetPageStatus.Finished; case GetPageStatus.Cancelled: // do nothing goto case GetPageStatus.Finished; case GetPageStatus.Finished: _isCompleted = true; if (_callback != null) { _callback(this); } break; } return null; } #endregion DispatcherOperationCallback //----------------------------------------------------------------- internal void Cancel() { _getpageStatus = GetPageStatus.Cancelled; // } internal void Wait() { _dispatcherOperation.Wait(); } //-------------------------------------------------------------------- // // Internal Properties // //--------------------------------------------------------------------- #region Internal Properties //--------------------------------------------------------------------- internal Exception Exception { get { return _exception; } } //----------------------------------------------------------------- internal bool IsCancelled { get { return _getpageStatus == GetPageStatus.Cancelled; } } internal DispatcherOperation DispatcherOperation { set { _dispatcherOperation = value; } } //----------------------------------------------------------------- internal FixedPage Result { get { return _result; } } #endregion Internal Properties //-------------------------------------------------------------------- // // Private Methods // //--------------------------------------------------------------------- #region Private Methods private void _OnPaserFinished(object sender, EventArgs args) { if (_pendingStream != null) { _pendingStream.Close(); _pendingStream = null; } } #endregion Private Methods //-------------------------------------------------------------------- // // Private Fields // //--------------------------------------------------------------------- #region Private private object _asyncState; private bool _isCompleted; private bool _completedSynchronously; private AsyncCallback _callback; private Exception _exception; private GetPageStatus _getpageStatus; private Uri _baseUri; private Uri _source; private FixedPage _child; private Dispatcher _dispatcher; private FixedPage _result; private Stream _pendingStream; private DispatcherOperation _dispatcherOperation; #endregion Private } }
// 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.IO; using System.Linq; using System.Net.Security; using System.Net.Sockets; using System.Security.Authentication; using System.Text; using System.Threading.Tasks; using Xunit; namespace System.Net.Test.Common { public sealed partial class LoopbackServer : IDisposable { private Socket _listenSocket; private Options _options; private Uri _uri; // Use CreateServerAsync or similar to create private LoopbackServer(Socket listenSocket, Options options) { _listenSocket = listenSocket; _options = options; var localEndPoint = (IPEndPoint)listenSocket.LocalEndPoint; string host = options.Address.AddressFamily == AddressFamily.InterNetworkV6 ? $"[{localEndPoint.Address}]" : localEndPoint.Address.ToString(); string scheme = options.UseSsl ? "https" : "http"; if (options.WebSocketEndpoint) { scheme = options.UseSsl ? "wss" : "ws"; } _uri = new Uri($"{scheme}://{host}:{localEndPoint.Port}/"); } public void Dispose() { if (_listenSocket != null) { _listenSocket.Dispose(); _listenSocket = null; } } public Socket ListenSocket => _listenSocket; public Uri Uri => _uri; public static async Task CreateServerAsync(Func<LoopbackServer, Task> funcAsync, Options options = null) { options = options ?? new Options(); using (var listenSocket = new Socket(options.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { listenSocket.Bind(new IPEndPoint(options.Address, 0)); listenSocket.Listen(options.ListenBacklog); using (var server = new LoopbackServer(listenSocket, options)) { await funcAsync(server); } } } public static Task CreateServerAsync(Func<LoopbackServer, Uri, Task> funcAsync, Options options = null) { return CreateServerAsync(server => funcAsync(server, server.Uri), options); } public static Task CreateClientAndServerAsync(Func<Uri, Task> clientFunc, Func<LoopbackServer, Task> serverFunc, Options options = null) { return CreateServerAsync(async server => { Task clientTask = clientFunc(server.Uri); Task serverTask = serverFunc(server); await new Task[] { clientTask, serverTask }.WhenAllOrAnyFailed(); }, options); } public async Task AcceptConnectionAsync(Func<Connection, Task> funcAsync) { using (Socket s = await _listenSocket.AcceptAsync().ConfigureAwait(false)) { s.NoDelay = true; Stream stream = new NetworkStream(s, ownsSocket: false); if (_options.UseSsl) { var sslStream = new SslStream(stream, false, delegate { return true; }); using (var cert = Configuration.Certificates.GetServerCertificate()) { await sslStream.AuthenticateAsServerAsync( cert, clientCertificateRequired: true, // allowed but not required enabledSslProtocols: _options.SslProtocols, checkCertificateRevocation: false).ConfigureAwait(false); } stream = sslStream; } if (_options.StreamWrapper != null) { stream = _options.StreamWrapper(stream); } using (var connection = new Connection(s, stream)) { await funcAsync(connection); } } } public async Task<List<string>> AcceptConnectionSendCustomResponseAndCloseAsync(string response) { List<string> lines = null; // Note, we assume there's no request body. // We'll close the connection after reading the request header and sending the response. await AcceptConnectionAsync(async connection => { lines = await connection.ReadRequestHeaderAndSendCustomResponseAsync(response); }); return lines; } public async Task<List<string>> AcceptConnectionSendResponseAndCloseAsync(HttpStatusCode statusCode = HttpStatusCode.OK, string additionalHeaders = null, string content = null) { List<string> lines = null; // Note, we assume there's no request body. // We'll close the connection after reading the request header and sending the response. await AcceptConnectionAsync(async connection => { lines = await connection.ReadRequestHeaderAndSendResponseAsync(statusCode, additionalHeaders + "Connection: close\r\n", content); }); return lines; } public static string GetRequestHeaderValue(List<string> headers, string name) { var sep = new char[] { ':' }; foreach (string line in headers) { string[] tokens = line.Split(sep , 2); if (name.Equals(tokens[0], StringComparison.InvariantCultureIgnoreCase)) { return tokens[1].Trim(); } } return null; } public static string GetRequestMethod(List<string> headers) { if (headers != null && headers.Count > 1) { return headers[0].Split()[1].Trim(); } return null; } // Stolen from HttpStatusDescription code in the product code private static string GetStatusDescription(HttpStatusCode code) { switch ((int)code) { case 100: return "Continue"; case 101: return "Switching Protocols"; case 102: return "Processing"; case 200: return "OK"; case 201: return "Created"; case 202: return "Accepted"; case 203: return "Non-Authoritative Information"; case 204: return "No Content"; case 205: return "Reset Content"; case 206: return "Partial Content"; case 207: return "Multi-Status"; case 300: return "Multiple Choices"; case 301: return "Moved Permanently"; case 302: return "Found"; case 303: return "See Other"; case 304: return "Not Modified"; case 305: return "Use Proxy"; case 307: return "Temporary Redirect"; case 400: return "Bad Request"; case 401: return "Unauthorized"; case 402: return "Payment Required"; case 403: return "Forbidden"; case 404: return "Not Found"; case 405: return "Method Not Allowed"; case 406: return "Not Acceptable"; case 407: return "Proxy Authentication Required"; case 408: return "Request Timeout"; case 409: return "Conflict"; case 410: return "Gone"; case 411: return "Length Required"; case 412: return "Precondition Failed"; case 413: return "Request Entity Too Large"; case 414: return "Request-Uri Too Long"; case 415: return "Unsupported Media Type"; case 416: return "Requested Range Not Satisfiable"; case 417: return "Expectation Failed"; case 422: return "Unprocessable Entity"; case 423: return "Locked"; case 424: return "Failed Dependency"; case 426: return "Upgrade Required"; // RFC 2817 case 500: return "Internal Server Error"; case 501: return "Not Implemented"; case 502: return "Bad Gateway"; case 503: return "Service Unavailable"; case 504: return "Gateway Timeout"; case 505: return "Http Version Not Supported"; case 507: return "Insufficient Storage"; } return null; } public enum ContentMode { ContentLength, SingleChunk, BytePerChunk, ConnectionClose } public static string GetContentModeResponse(ContentMode mode, string content, bool connectionClose = false) { switch (mode) { case ContentMode.ContentLength: return GetHttpResponse(content: content, connectionClose: connectionClose); case ContentMode.SingleChunk: return GetSingleChunkHttpResponse(content: content, connectionClose: connectionClose); case ContentMode.BytePerChunk: return GetBytePerChunkHttpResponse(content: content, connectionClose: connectionClose); case ContentMode.ConnectionClose: Assert.True(connectionClose); return GetConnectionCloseResponse(content: content); default: Assert.True(false, $"Unknown content mode: {mode}"); return null; } } public static string GetHttpResponse(HttpStatusCode statusCode = HttpStatusCode.OK, string additionalHeaders = null, string content = null, bool connectionClose = false) => $"HTTP/1.1 {(int)statusCode} {GetStatusDescription(statusCode)}\r\n" + (connectionClose ? "Connection: close\r\n" : "") + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + $"Content-Length: {(content == null ? 0 : content.Length)}\r\n" + additionalHeaders + "\r\n" + content; public static string GetSingleChunkHttpResponse(HttpStatusCode statusCode = HttpStatusCode.OK, string additionalHeaders = null, string content = null, bool connectionClose = false) => $"HTTP/1.1 {(int)statusCode} {GetStatusDescription(statusCode)}\r\n" + (connectionClose ? "Connection: close\r\n" : "") + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + "Transfer-Encoding: chunked\r\n" + additionalHeaders + "\r\n" + (string.IsNullOrEmpty(content) ? "" : $"{content.Length:X}\r\n" + $"{content}\r\n") + $"0\r\n" + $"\r\n"; public static string GetBytePerChunkHttpResponse(HttpStatusCode statusCode = HttpStatusCode.OK, string additionalHeaders = null, string content = null, bool connectionClose = false) => $"HTTP/1.1 {(int)statusCode} {GetStatusDescription(statusCode)}\r\n" + (connectionClose ? "Connection: close\r\n" : "") + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + "Transfer-Encoding: chunked\r\n" + additionalHeaders + "\r\n" + (string.IsNullOrEmpty(content) ? "" : string.Concat(content.Select(c => $"1\r\n{c}\r\n"))) + $"0\r\n" + $"\r\n"; public static string GetConnectionCloseResponse(HttpStatusCode statusCode = HttpStatusCode.OK, string additionalHeaders = null, string content = null) => $"HTTP/1.1 {(int)statusCode} {GetStatusDescription(statusCode)}\r\n" + "Connection: close\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + additionalHeaders + "\r\n" + content; public class Options { public IPAddress Address { get; set; } = IPAddress.Loopback; public int ListenBacklog { get; set; } = 1; public bool UseSsl { get; set; } = false; public SslProtocols SslProtocols { get; set; } = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12; public bool WebSocketEndpoint { get; set; } = false; public Func<Stream, Stream> StreamWrapper { get; set; } public string Username { get; set; } public string Domain { get; set; } public string Password { get; set; } public bool IsProxy { get; set; } = false; } public sealed class Connection : IDisposable { private Socket _socket; private Stream _stream; private StreamReader _reader; private StreamWriter _writer; public Connection(Socket socket, Stream stream) { _socket = socket; _stream = stream; _reader = new StreamReader(stream, Encoding.ASCII); _writer = new StreamWriter(stream, Encoding.ASCII) { AutoFlush = true }; } public Socket Socket => _socket; public Stream Stream => _stream; public StreamReader Reader => _reader; public StreamWriter Writer => _writer; public void Dispose() { try { // Try to shutdown the send side of the socket. // This seems to help avoid connection reset issues caused by buffered data // that has not been sent/acked when the graceful shutdown timeout expires. // This may throw if the socket was already closed, so eat any exception. _socket.Shutdown(SocketShutdown.Send); } catch (Exception) { } _reader.Dispose(); _writer.Dispose(); _stream.Dispose(); _socket.Dispose(); } public async Task<List<string>> ReadRequestHeaderAsync() { var lines = new List<string>(); string line; while (!string.IsNullOrEmpty(line = await _reader.ReadLineAsync().ConfigureAwait(false))) { lines.Add(line); } if (line == null) { throw new Exception("Unexpected EOF trying to read request header"); } return lines; } public async Task SendResponseAsync(HttpStatusCode statusCode = HttpStatusCode.OK, string additionalHeaders = null, string content = null) { await _writer.WriteAsync(GetHttpResponse(statusCode, additionalHeaders, content)); } public async Task<List<string>> ReadRequestHeaderAndSendCustomResponseAsync(string response) { List<string> lines = await ReadRequestHeaderAsync().ConfigureAwait(false); await _writer.WriteAsync(response); return lines; } public async Task<List<string>> ReadRequestHeaderAndSendResponseAsync(HttpStatusCode statusCode = HttpStatusCode.OK, string additionalHeaders = null, string content = null) { List<string> lines = await ReadRequestHeaderAsync().ConfigureAwait(false); await SendResponseAsync(statusCode, additionalHeaders, content); return lines; } } } }
using System; using System.Windows.Forms; using System.Drawing; using PrimerProForms; using PrimerProObjects; using GenLib; namespace PrimerProSearch { public class MinPairsSearch : Search { //Search parameters private string m_Grapheme1; //first grapheme for Minimal Pairs private string m_Grapheme2; //second grapheme for Minimal Pairs private bool m_AllPairs; //All Minimal Pairs for first grapheme private bool m_RootsOnly; //use roots only private bool m_IgnoreTone; //Ignore Tone private bool m_AllowVowelHarmony; //Allow Harmony private SearchOptions m_SearchOptions; //search options filter private string m_Title; //search title private Settings m_Settings; //Application settings private PSTable m_PSTable; //Parts of Speech private GraphemeInventory m_GI; //Grapheme Inventory private Font m_DefaultFont; //Default Font //Search Definition tags private const string kTarget1 = "target1"; private const string kTarget2 = "target2"; private const string kAll = "AllPairs"; private const string kRoots = "RootsOnly"; private const string kTone = "IgnoreTone"; private const string kHarmony = "AllowForVowelHarmony"; //private const string kTitle = "Minimal Pairs Search"; //private const string kSearch = "Processing Minimal Pairs Search"; public MinPairsSearch(int number, Settings s) : base(number, SearchDefinition.kMinPairs) { m_Grapheme1 = ""; m_Grapheme2 = ""; m_AllPairs = false; m_RootsOnly = false; m_IgnoreTone = false; m_SearchOptions = null; m_Settings = s; m_Title = m_Settings.LocalizationTable.GetMessage("MinPairsSearchT"); if (m_Title == "") m_Title = "Minimal Pairs Search"; m_PSTable = m_Settings.PSTable; m_GI = m_Settings.GraphemeInventory; m_DefaultFont = m_Settings.OptionSettings.GetDefaultFont(); } public string Grapheme1 { get { return m_Grapheme1; } set { m_Grapheme1 = value; } } public string Grapheme2 { get { return m_Grapheme2; } set { m_Grapheme2 = value; } } public bool AllPairs { get { return m_AllPairs; } set { m_AllPairs = value; } } public bool RootsOnly { get { return m_RootsOnly; } set { m_RootsOnly = value; } } public bool IgnoreTone { get { return m_IgnoreTone; } set { m_IgnoreTone = value; } } public bool AllowVowelHarmony { get { return m_AllowVowelHarmony; } set { m_AllowVowelHarmony = value; } } public SearchOptions SearchOptions { get {return m_SearchOptions;} set {m_SearchOptions = value;} } public string Title { get {return m_Title;} } public PSTable PSTable { get {return m_PSTable;} } public GraphemeInventory GI { get {return m_GI;} } public Font DefaultFont { get { return m_DefaultFont; } } public bool SetupSearch() { bool flag = false; string strMsg = ""; FormMinPairs form = new FormMinPairs(m_Settings, m_Settings.LocalizationTable); DialogResult dr; dr = form.ShowDialog(); if (dr == DialogResult.OK) { this.Grapheme1 = form.Grapheme1; this.Grapheme2 = form.Grapheme2; this.AllPairs = form.AllPairs; this.RootsOnly = form.RootsOnly; this.IgnoreTone = form.IgnoreTone; this.AllowVowelHarmony = form.AllowVowelHarmony; this.SearchOptions = form.SearchOptions; SearchDefinition sd = new SearchDefinition(SearchDefinition.kMinPairs); SearchDefinitionParm sdp = null; this.SearchDefinition = sd; if (this.AllPairs) { if ((this.Grapheme1 != "")) { if (this.GI.IsInInventory(this.Grapheme1)) { sdp = new SearchDefinitionParm(MinPairsSearch.kTarget1, this.Grapheme1); sd.AddSearchParm(sdp); sdp = new SearchDefinitionParm(MinPairsSearch.kAll); sd.AddSearchParm(sdp); if (this.RootsOnly) { sdp = new SearchDefinitionParm(MinPairsSearch.kRoots); sd.AddSearchParm(sdp); } if (this.IgnoreTone) { sdp = new SearchDefinitionParm(MinPairsSearch.kTone); sd.AddSearchParm(sdp); } if (this.AllowVowelHarmony) { sdp = new SearchDefinitionParm(MinPairsSearch.kHarmony); sd.AddSearchParm(sdp); } m_Title = m_Title + " - [" + this.Grapheme1 + "]"; if (m_SearchOptions != null) sd.AddSearchOptions(m_SearchOptions); this.SearchDefinition = sd; flag = true; } //else MessageBox.Show("First grapheme is not in the grapheme inventory"); else { strMsg = m_Settings.LocalizationTable.GetMessage("MinPairsSearch3"); if (strMsg == "") strMsg = "First grapheme is not in the grapheme inventory"; MessageBox.Show(strMsg); } } //else MessageBox.Show("First Grapheme must be specified"); else { strMsg = m_Settings.LocalizationTable.GetMessage("MinPairsSearch4"); if (strMsg == "") strMsg = "First Grapheme must be specified"; MessageBox.Show(strMsg); } } else { if ((this.Grapheme1 != "") && (this.Grapheme2 != "")) { if (this.GI.IsInInventory(this.Grapheme1)) { if (this.GI.IsInInventory(this.Grapheme2)) { if (this.Grapheme1 != this.Grapheme2) { sdp = new SearchDefinitionParm(MinPairsSearch.kTarget1, this.Grapheme1); sd.AddSearchParm(sdp); sdp = new SearchDefinitionParm(MinPairsSearch.kTarget2, this.Grapheme2); sd.AddSearchParm(sdp); if (this.RootsOnly) { sdp = new SearchDefinitionParm(MinPairsSearch.kRoots); sd.AddSearchParm(sdp); } if (this.IgnoreTone) { sdp = new SearchDefinitionParm(MinPairsSearch.kTone); sd.AddSearchParm(sdp); } if (this.AllowVowelHarmony) { sdp = new SearchDefinitionParm(MinPairsSearch.kHarmony); sd.AddSearchParm(sdp); } m_Title = m_Title + " - [" + this.Grapheme1 + "] [" + this.Grapheme2 + "]"; if (m_SearchOptions != null) sd.AddSearchOptions(m_SearchOptions); this.SearchDefinition = sd; flag = true; } //else MessageBox.Show("Graphemes can not be the same"); else { strMsg = m_Settings.LocalizationTable.GetMessage("MinPairsSearch1"); if (strMsg == "") strMsg = "Graphemes can not be the same"; MessageBox.Show(strMsg); } } //else MessageBox.Show("Second grapheme is not in Inventory"); else { strMsg = m_Settings.LocalizationTable.GetMessage("MinPairsSearch2"); if (strMsg == "") strMsg = "Second grapheme is not in Inventory"; MessageBox.Show(strMsg); } } //else MessageBox.Show("First Grapheme is not in Inventory"); else { strMsg = m_Settings.LocalizationTable.GetMessage("MinPairsSearch3"); if (strMsg == "") strMsg = "First grapheme is not in Inventory"; MessageBox.Show(strMsg); } } //else MessageBox.Show("First and Second Graphemes must be specified"); else { strMsg = m_Settings.LocalizationTable.GetMessage("MinPairsSearch4"); if (strMsg == "") strMsg = "First and Second Graphemes must be specified"; MessageBox.Show(strMsg); } } } return flag; } public bool SetupSearch(SearchDefinition sd) { bool flag = false; SearchOptions so = new SearchOptions(m_PSTable); string strTag = ""; for (int i = 0; i < sd.SearchParmsCount(); i++) { strTag = sd.GetSearchParmAt(i).GetTag(); if (strTag == MinPairsSearch.kTarget1) this.Grapheme1 = sd.GetSearchParmContent(strTag); if (strTag == MinPairsSearch.kTarget2) this.Grapheme2 = sd.GetSearchParmContent(strTag); if (strTag == MinPairsSearch.kAll) this.AllPairs = true; if (strTag == MinPairsSearch.kRoots) this.RootsOnly = true; if (strTag == MinPairsSearch.kTone) this.IgnoreTone = true; if (strTag == MinPairsSearch.kHarmony) this.AllowVowelHarmony = true; } if (this.AllPairs) m_Title = m_Title + " - [" + this.Grapheme1 + "]"; else m_Title = m_Title + " - [" + this.Grapheme1 + "] [" + this.Grapheme2 + "]"; this.SearchOptions = sd.MakeSearchOptions(so); this.SearchDefinition = sd; return flag; } public string BuildResults() { string strText = ""; string strSN = ""; string str = ""; if (this.SearchNumber > 0) { strSN = Search.TagSN + this.SearchNumber.ToString().Trim(); strText += Search.TagOpener + strSN + Search.TagCloser + Environment.NewLine; } strText += this.Title + Environment.NewLine + Environment.NewLine; strText += this.SearchResults; strText += Environment.NewLine; //strText += this.SearchCount.ToString() + " entries found" + Environment.NewLine; str = m_Settings.LocalizationTable.GetMessage("Search2"); if (str == "") str = "entries found"; strText += this.SearchCount.ToString() + Constants.Space + str + Environment.NewLine; if (this.SearchNumber > 0) strText += Search.TagOpener + Search.TagForwardSlash + strSN + Search.TagCloser; return strText; } public MinPairsSearch ExecuteMinPairsSearch(WordList wl) { GraphemeInventory gi = m_Settings.GraphemeInventory; this.SearchResults = wl.GetDisplayHeadings() + Environment.NewLine; if (this.AllPairs) { Grapheme grf1 = gi.GetGrapheme(this.Grapheme1); //ExecuteMinPairsSearchAll(wl, grf1, gi); } else { Grapheme grf1 = gi.GetGrapheme(this.Grapheme1); Grapheme grf2 = gi.GetGrapheme(this.Grapheme2); ExecuteMinPairsSearch2(wl, grf1, grf2); } if (this.SearchCount == 0) { //this.SearchResults = "***No Results***"; this.SearchResults += m_Settings.LocalizationTable.GetMessage("Search1"); if (this.SearchResults == "") this.SearchResults = "***No Results***"; } return this; } private void ExecuteMinPairsSearch2(WordList wl, Grapheme grf1, Grapheme grf2) { int nCount = 0; string strResult = ""; Word wrd1 = null; Word wrd2 = null; int nWord = wl.WordCount(); bool fMinPair = false; //SearchOptions so = this.SearchOptions; string str = m_Settings.LocalizationTable.GetMessage("MinPairsSearch5"); if (str == "") str = "Processing Minimal Pairs Search"; FormProgressBar form = new FormProgressBar(str); form.PB_Init(1, nWord); for (int i = 0; i < nWord; i++) { wrd1 = wl.GetWord(i); //Get first word for comparison form.PB_Update(i + 1); //for (int j = i + 1; j < nWord; j++) for (int j = 0; j < nWord; j++) { wrd2 = wl.GetWord(j); //get second word for comparsion fMinPair = IsMinPair(wrd1, wrd2, grf1, grf2); if (fMinPair) { strResult += wl.GetDisplayLineForWord(i) + Environment.NewLine; strResult += wl.GetDisplayLineForWord(j) + Environment.NewLine; strResult += Environment.NewLine; nCount++; } } } form.Close(); if (nCount > 0) { this.SearchResults += strResult; this.SearchCount += nCount; } return; } //private void ExecuteMinPairsSearchAll(WordList wl, Grapheme grf1, GraphemeInventory gi) //{ // int nCount = 0; // string strResult = ""; // Word wrd1 = null; // Word wrd2 = null; // Grapheme grf2 = null; // int nWord = wl.WordCount(); // bool fMinPair = false; // string str = m_Settings.LocalizationTable.GetMessage("MinPairsSearch5"); // FormProgressBar form = new FormProgressBar(str); // form.PB_Init(1, nWord); // for (int i = 0; i < nWord; i++) // { // wrd1 = wl.GetWord(i); //Get first word for comparison // form.PB_Update(i + 1); // for (int j = 0; j < nWord; j++) // { // wrd2 = wl.GetWord(j); //get second word for comparsion // for (int k = 0; k < gi.ConsonantCount(); k++) // { // grf2 = (Grapheme) gi.GetConsonant(k); // //fMinPair = IsMinPair(wrd1, wrd2, grf1, grf2); // if (fMinPair) // { // strResult += wl.GetDisplayLineForWord(i) + Environment.NewLine; // strResult += wl.GetDisplayLineForWord(j) + Environment.NewLine; // strResult += Environment.NewLine; // nCount++; // } // } // for (int k = 0; k < gi.VowelCount(); k++) // { // grf2 = (Grapheme)gi.GetVowel(k); // //fMinPair = IsMinPair(wrd1, wrd2, grf1, grf2); // if (fMinPair) // { // strResult += wl.GetDisplayLineForWord(i) + Environment.NewLine; // strResult += wl.GetDisplayLineForWord(j) + Environment.NewLine; // strResult += Environment.NewLine; // nCount++; // } // } // for (int k = 0; k < gi.ToneCount(); k++) // { // grf2 = (Grapheme) gi.GetTone(k); // //fMinPair = IsMinPair(wrd1, wrd2, grf1, grf2); // if (fMinPair) // { // strResult += wl.GetDisplayLineForWord(i) + Environment.NewLine; // strResult += wl.GetDisplayLineForWord(j) + Environment.NewLine; // strResult += Environment.NewLine; // nCount++; // } // } // } // } // form.Close(); // if (nCount > 0) // { // this.SearchResults += strResult; // this.SearchCount += nCount; // } // return; //} private bool IsMinPair(Word wrd1, Word wrd2, Grapheme grf1, Grapheme grf2) { bool fReturn = false; if (this.SearchOptions == null) //no search options { if (this.RootsOnly) //doing roots { if (!wrd1.Root.IsSame(wrd2.Root)) { if (this.AllowVowelHarmony && grf1.IsVowel && grf2.IsVowel) fReturn = wrd1.Root.IsMinimalPairHarmony(wrd2.Root, this.IgnoreTone, grf1, grf2); else fReturn = wrd1.Root.IsMinimalPair(wrd2.Root, this.IgnoreTone, grf1, grf2); } } else //doing words { if (!wrd1.IsSame(wrd2)) { if (this.AllowVowelHarmony && grf1.IsVowel && grf2.IsVowel) fReturn = wrd1.IsMinimalPairHarmony(wrd2, this.IgnoreTone, grf1, grf2); else fReturn = wrd1.IsMinimalPair(wrd2, this.IgnoreTone, grf1, grf2); } } } else //have search options { if ((this.SearchOptions.MatchesWord(wrd1)) && (this.SearchOptions.MatchesWord(wrd2))) { if (this.RootsOnly) //doing roots { if (!wrd1.Root.IsSame(wrd2.Root)) { if (this.AllowVowelHarmony && grf1.IsVowel && grf2.IsVowel) fReturn = wrd1.Root.IsMinimalPairHarmony(wrd2.Root, this.IgnoreTone, grf1, grf2); else fReturn = wrd1.Root.IsMinimalPair(wrd2.Root, this.IgnoreTone, grf1, grf2); } } else //doing words { if (!wrd1.IsSame(wrd2)) { if (this.AllowVowelHarmony && grf1.IsVowel && grf2.IsVowel) fReturn = wrd1.IsMinimalPairHarmony(wrd2, this.IgnoreTone, grf1, grf2); else fReturn = wrd1.IsMinimalPair(wrd2, this.IgnoreTone, grf1, grf2); } } } } return fReturn; } } }
// 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.Threading; using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; using System.Diagnostics; namespace System.IO { public partial class FileStream : Stream { private const FileShare DefaultShare = FileShare.Read; private const bool DefaultIsAsync = false; internal const int DefaultBufferSize = 4096; private byte[] _buffer; private int _bufferLength; private readonly SafeFileHandle _fileHandle; /// <summary>Whether the file is opened for reading, writing, or both.</summary> private readonly FileAccess _access; /// <summary>The path to the opened file.</summary> private readonly string _path; /// <summary>The next available byte to be read from the _buffer.</summary> private int _readPos; /// <summary>The number of valid bytes in _buffer.</summary> private int _readLength; /// <summary>The next location in which a write should occur to the buffer.</summary> private int _writePos; /// <summary> /// Whether asynchronous read/write/flush operations should be performed using async I/O. /// On Windows FileOptions.Asynchronous controls how the file handle is configured, /// and then as a result how operations are issued against that file handle. On Unix, /// there isn't any distinction around how file descriptors are created for async vs /// sync, but we still differentiate how the operations are issued in order to provide /// similar behavioral semantics and performance characteristics as on Windows. On /// Windows, if non-async, async read/write requests just delegate to the base stream, /// and no attempt is made to synchronize between sync and async operations on the stream; /// if async, then async read/write requests are implemented specially, and sync read/write /// requests are coordinated with async ones by implementing the sync ones over the async /// ones. On Unix, we do something similar. If non-async, async read/write requests just /// delegate to the base stream, and no attempt is made to synchronize. If async, we use /// a semaphore to coordinate both sync and async operations. /// </summary> private readonly bool _useAsyncIO; /// <summary> /// Currently cached position in the stream. This should always mirror the underlying file's actual position, /// and should only ever be out of sync if another stream with access to this same file manipulates it, at which /// point we attempt to error out. /// </summary> private long _filePosition; /// <summary>Whether the file stream's handle has been exposed.</summary> private bool _exposedHandle; [Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead. http://go.microsoft.com/fwlink/?linkid=14202")] public FileStream(IntPtr handle, FileAccess access) : this(handle, access, true, DefaultBufferSize, false) { } [Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")] public FileStream(IntPtr handle, FileAccess access, bool ownsHandle) : this(handle, access, ownsHandle, DefaultBufferSize, false) { } [Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")] public FileStream(IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize) : this(handle, access, ownsHandle, bufferSize, false) { } [Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")] public FileStream(IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync) : this(new SafeFileHandle(handle, ownsHandle), access, bufferSize, isAsync) { } public FileStream(SafeFileHandle handle, FileAccess access) : this(handle, access, DefaultBufferSize) { } public FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) : this(handle, access, bufferSize, GetDefaultIsAsync(handle)) { } public FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) { if (handle.IsInvalid) throw new ArgumentException(SR.Arg_InvalidHandle, nameof(handle)); if (access < FileAccess.Read || access > FileAccess.ReadWrite) throw new ArgumentOutOfRangeException(nameof(access), SR.ArgumentOutOfRange_Enum); if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); if (handle.IsClosed) throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed); if (handle.IsAsync.HasValue && isAsync != handle.IsAsync.Value) throw new ArgumentException(SR.Arg_HandleNotAsync, nameof(handle)); _access = access; _useAsyncIO = isAsync; _exposedHandle = true; _bufferLength = bufferSize; _fileHandle = handle; InitFromHandle(handle); } public FileStream(string path, FileMode mode) : this(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), DefaultShare, DefaultBufferSize, DefaultIsAsync) { } public FileStream(string path, FileMode mode, FileAccess access) : this(path, mode, access, DefaultShare, DefaultBufferSize, DefaultIsAsync) { } public FileStream(string path, FileMode mode, FileAccess access, FileShare share) : this(path, mode, access, share, DefaultBufferSize, DefaultIsAsync) { } public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize) : this(path, mode, access, share, bufferSize, DefaultIsAsync) { } public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync) : this(path, mode, access, share, bufferSize, useAsync ? FileOptions.Asynchronous : FileOptions.None) { } public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options) { if (path == null) throw new ArgumentNullException(nameof(path), SR.ArgumentNull_Path); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); // don't include inheritable in our bounds check for share FileShare tempshare = share & ~FileShare.Inheritable; string badArg = null; if (mode < FileMode.CreateNew || mode > FileMode.Append) badArg = nameof(mode); else if (access < FileAccess.Read || access > FileAccess.ReadWrite) badArg = nameof(access); else if (tempshare < FileShare.None || tempshare > (FileShare.ReadWrite | FileShare.Delete)) badArg = nameof(share); if (badArg != null) throw new ArgumentOutOfRangeException(badArg, SR.ArgumentOutOfRange_Enum); // NOTE: any change to FileOptions enum needs to be matched here in the error validation if (options != FileOptions.None && (options & ~(FileOptions.WriteThrough | FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.DeleteOnClose | FileOptions.SequentialScan | FileOptions.Encrypted | (FileOptions)0x20000000 /* NoBuffering */)) != 0) throw new ArgumentOutOfRangeException(nameof(options), SR.ArgumentOutOfRange_Enum); if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); // Write access validation if ((access & FileAccess.Write) == 0) { if (mode == FileMode.Truncate || mode == FileMode.CreateNew || mode == FileMode.Create || mode == FileMode.Append) { // No write access, mode and access disagree but flag access since mode comes first throw new ArgumentException(SR.Format(SR.Argument_InvalidFileModeAndAccessCombo, mode, access), nameof(access)); } } if ((access & FileAccess.Read) != 0 && mode == FileMode.Append) throw new ArgumentException(SR.Argument_InvalidAppendMode, nameof(access)); string fullPath = Path.GetFullPath(path); _path = fullPath; _access = access; _bufferLength = bufferSize; if ((options & FileOptions.Asynchronous) != 0) _useAsyncIO = true; _fileHandle = OpenHandle(mode, share, options); try { Init(mode, share); } catch { // If anything goes wrong while setting up the stream, make sure we deterministically dispose // of the opened handle. _fileHandle.Dispose(); _fileHandle = null; throw; } } private static bool GetDefaultIsAsync(SafeFileHandle handle) { // This will eventually get more complicated as we can actually check the underlying handle type on Windows return handle.IsAsync.HasValue ? handle.IsAsync.Value : false; } [Obsolete("This property has been deprecated. Please use FileStream's SafeFileHandle property instead. http://go.microsoft.com/fwlink/?linkid=14202")] public virtual IntPtr Handle { get { return SafeFileHandle.DangerousGetHandle(); } } public virtual void Lock(long position, long length) { if (position < 0 || length < 0) { throw new ArgumentOutOfRangeException(position < 0 ? nameof(position) : nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum); } if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } LockInternal(position, length); } public virtual void Unlock(long position, long length) { if (position < 0 || length < 0) { throw new ArgumentOutOfRangeException(position < 0 ? nameof(position) : nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum); } if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } UnlockInternal(position, length); } public override Task FlushAsync(CancellationToken cancellationToken) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Flush() which a subclass might have overridden. To be safe // we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Flush) when we are not sure. if (GetType() != typeof(FileStream)) return base.FlushAsync(cancellationToken); return FlushAsyncInternal(cancellationToken); } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Read() or ReadAsync() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Read/ReadAsync) when we are not sure. if (GetType() != typeof(FileStream)) return base.ReadAsync(buffer, offset, count, cancellationToken); if (cancellationToken.IsCancellationRequested) return Task.FromCanceled<int>(cancellationToken); if (IsClosed) throw Error.GetFileNotOpen(); return ReadAsyncInternal(buffer, offset, count, cancellationToken); } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() or WriteAsync() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write/WriteAsync) when we are not sure. if (GetType() != typeof(FileStream)) return base.WriteAsync(buffer, offset, count, cancellationToken); if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); if (IsClosed) throw Error.GetFileNotOpen(); return WriteAsyncInternal(buffer, offset, count, cancellationToken); } /// <summary> /// Clears buffers for this stream and causes any buffered data to be written to the file. /// </summary> public override void Flush() { // Make sure that we call through the public virtual API Flush(flushToDisk: false); } /// <summary> /// Clears buffers for this stream, and if <param name="flushToDisk"/> is true, /// causes any buffered data to be written to the file. /// </summary> public virtual void Flush(bool flushToDisk) { if (IsClosed) throw Error.GetFileNotOpen(); FlushInternalBuffer(); if (flushToDisk && CanWrite) { FlushOSBuffer(); } } /// <summary>Gets a value indicating whether the current stream supports reading.</summary> public override bool CanRead { get { return !_fileHandle.IsClosed && (_access & FileAccess.Read) != 0; } } /// <summary>Gets a value indicating whether the current stream supports writing.</summary> public override bool CanWrite { get { return !_fileHandle.IsClosed && (_access & FileAccess.Write) != 0; } } /// <summary>Validates arguments to Read and Write and throws resulting exceptions.</summary> /// <param name="array">The buffer to read from or write to.</param> /// <param name="offset">The zero-based offset into the array.</param> /// <param name="count">The maximum number of bytes to read or write.</param> private void ValidateReadWriteArgs(byte[] array, int offset, int count) { if (array == null) throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/); if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); } /// <summary>Sets the length of this stream to the given value.</summary> /// <param name="value">The new length of the stream.</param> public override void SetLength(long value) { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (!CanSeek) throw Error.GetSeekNotSupported(); if (!CanWrite) throw Error.GetWriteNotSupported(); SetLengthInternal(value); } public virtual SafeFileHandle SafeFileHandle { get { Flush(); _exposedHandle = true; return _fileHandle; } } /// <summary>Gets the path that was passed to the constructor.</summary> public virtual string Name { get { return _path ?? SR.IO_UnknownFileName; } } /// <summary>Gets a value indicating whether the stream was opened for I/O to be performed synchronously or asynchronously.</summary> public virtual bool IsAsync { get { return _useAsyncIO; } } /// <summary>Gets the length of the stream in bytes.</summary> public override long Length { get { if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (!CanSeek) throw Error.GetSeekNotSupported(); return GetLengthInternal(); } } /// <summary> /// Verify that the actual position of the OS's handle equals what we expect it to. /// This will fail if someone else moved the UnixFileStream's handle or if /// our position updating code is incorrect. /// </summary> private void VerifyOSHandlePosition() { bool verifyPosition = _exposedHandle; // in release, only verify if we've given out the handle such that someone else could be manipulating it #if DEBUG verifyPosition = true; // in debug, always make sure our position matches what the OS says it should be #endif if (verifyPosition && CanSeek) { long oldPos = _filePosition; // SeekCore will override the current _position, so save it now long curPos = SeekCore(0, SeekOrigin.Current); if (oldPos != curPos) { // For reads, this is non-fatal but we still could have returned corrupted // data in some cases, so discard the internal buffer. For writes, // this is a problem; discard the buffer and error out. _readPos = _readLength = 0; if (_writePos > 0) { _writePos = 0; throw new IOException(SR.IO_FileStreamHandlePosition); } } } } /// <summary>Verifies that state relating to the read/write buffer is consistent.</summary> [Conditional("DEBUG")] private void AssertBufferInvariants() { // Read buffer values must be in range: 0 <= _bufferReadPos <= _bufferReadLength <= _bufferLength Debug.Assert(0 <= _readPos && _readPos <= _readLength && _readLength <= _bufferLength); // Write buffer values must be in range: 0 <= _bufferWritePos <= _bufferLength Debug.Assert(0 <= _writePos && _writePos <= _bufferLength); // Read buffering and write buffering can't both be active Debug.Assert((_readPos == 0 && _readLength == 0) || _writePos == 0); } /// <summary>Validates that we're ready to read from the stream.</summary> private void PrepareForReading() { if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (_readLength == 0 && !CanRead) throw Error.GetReadNotSupported(); AssertBufferInvariants(); } /// <summary>Gets or sets the position within the current stream</summary> public override long Position { get { if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (!CanSeek) throw Error.GetSeekNotSupported(); AssertBufferInvariants(); VerifyOSHandlePosition(); // We may have read data into our buffer from the handle, such that the handle position // is artificially further along than the consumer's view of the stream's position. // Thus, when reading, our position is really starting from the handle position negatively // offset by the number of bytes in the buffer and positively offset by the number of // bytes into that buffer we've read. When writing, both the read length and position // must be zero, and our position is just the handle position offset positive by how many // bytes we've written into the buffer. return (_filePosition - _readLength) + _readPos + _writePos; } set { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); Seek(value, SeekOrigin.Begin); } } internal virtual bool IsClosed => _fileHandle.IsClosed; /// <summary> /// Gets the array used for buffering reading and writing. /// If the array hasn't been allocated, this will lazily allocate it. /// </summary> /// <returns>The buffer.</returns> private byte[] GetBuffer() { Debug.Assert(_buffer == null || _buffer.Length == _bufferLength); if (_buffer == null) { _buffer = new byte[_bufferLength]; OnBufferAllocated(); } return _buffer; } partial void OnBufferAllocated(); /// <summary> /// Flushes the internal read/write buffer for this stream. If write data has been buffered, /// that data is written out to the underlying file. Or if data has been buffered for /// reading from the stream, the data is dumped and our position in the underlying file /// is rewound as necessary. This does not flush the OS buffer. /// </summary> private void FlushInternalBuffer() { AssertBufferInvariants(); if (_writePos > 0) { FlushWriteBuffer(); } else if (_readPos < _readLength && CanSeek) { FlushReadBuffer(); } } /// <summary>Dumps any read data in the buffer and rewinds our position in the stream, accordingly, as necessary.</summary> private void FlushReadBuffer() { // Reading is done by blocks from the file, but someone could read // 1 byte from the buffer then write. At that point, the OS's file // pointer is out of sync with the stream's position. All write // functions should call this function to preserve the position in the file. AssertBufferInvariants(); Debug.Assert(_writePos == 0, "FileStream: Write buffer must be empty in FlushReadBuffer!"); int rewind = _readPos - _readLength; if (rewind != 0) { Debug.Assert(CanSeek, "FileStream will lose buffered read data now."); SeekCore(rewind, SeekOrigin.Current); } _readPos = _readLength = 0; } private int ReadByteCore() { PrepareForReading(); byte[] buffer = GetBuffer(); if (_readPos == _readLength) { FlushWriteBuffer(); Debug.Assert(_bufferLength > 0, "_bufferSize > 0"); _readLength = ReadNative(buffer, 0, _bufferLength); _readPos = 0; if (_readLength == 0) { return -1; } } return buffer[_readPos++]; } private void WriteByteCore(byte value) { PrepareForWriting(); // Flush the write buffer if it's full if (_writePos == _bufferLength) FlushWriteBuffer(); // We now have space in the buffer. Store the byte. GetBuffer()[_writePos++] = value; } /// <summary> /// Validates that we're ready to write to the stream, /// including flushing a read buffer if necessary. /// </summary> private void PrepareForWriting() { if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); // Make sure we're good to write. We only need to do this if there's nothing already // in our write buffer, since if there is something in the buffer, we've already done // this checking and flushing. if (_writePos == 0) { if (!CanWrite) throw Error.GetWriteNotSupported(); FlushReadBuffer(); Debug.Assert(_bufferLength > 0, "_bufferSize > 0"); } } ~FileStream() { // Preserved for compatibility since FileStream has defined a // finalizer in past releases and derived classes may depend // on Dispose(false) call. Dispose(false); } public override IAsyncResult BeginRead(byte[] array, int offset, int numBytes, AsyncCallback callback, object state) { if (array == null) throw new ArgumentNullException(nameof(array)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (numBytes < 0) throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - offset < numBytes) throw new ArgumentException(SR.Argument_InvalidOffLen); if (IsClosed) throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed); if (!CanRead) throw new NotSupportedException(SR.NotSupported_UnreadableStream); if (!IsAsync) return base.BeginRead(array, offset, numBytes, callback, state); else return TaskToApm.Begin(ReadAsyncInternal(array, offset, numBytes, CancellationToken.None), callback, state); } public override IAsyncResult BeginWrite(byte[] array, int offset, int numBytes, AsyncCallback callback, object state) { if (array == null) throw new ArgumentNullException(nameof(array)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (numBytes < 0) throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - offset < numBytes) throw new ArgumentException(SR.Argument_InvalidOffLen); if (IsClosed) throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed); if (!CanWrite) throw new NotSupportedException(SR.NotSupported_UnwritableStream); if (!IsAsync) return base.BeginWrite(array, offset, numBytes, callback, state); else return TaskToApm.Begin(WriteAsyncInternal(array, offset, numBytes, CancellationToken.None), callback, state); } public override int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); if (!IsAsync) return base.EndRead(asyncResult); else return TaskToApm.End<int>(asyncResult); } public override void EndWrite(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); if (!IsAsync) base.EndWrite(asyncResult); else TaskToApm.End(asyncResult); } } }
/* * 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 OpenMetaverse; using System; using System.Collections.Generic; namespace OpenSim.Framework { public static class SLUtil { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Asset types used only in OpenSim. /// To avoid clashing with the code numbers used in Second Life, use only negative numbers here. /// </summary> public enum OpenSimAssetType : sbyte { Material = -2 } #region SL / file extension / content-type conversions private static Dictionary<sbyte, string> asset2Content; private static Dictionary<sbyte, string> asset2Extension; private static Dictionary<string, sbyte> content2Asset; private static Dictionary<string, InventoryType> content2Inventory; private static Dictionary<InventoryType, string> inventory2Content; /// <summary> /// Maps between AssetType, InventoryType and Content-Type. /// Where more than one possibility exists, the first one takes precedence. E.g.: /// AssetType "AssetType.Texture" -> Content-Type "image-xj2c" /// Content-Type "image/x-j2c" -> InventoryType "InventoryType.Texture" /// </summary> private static TypeMapping[] MAPPINGS = new TypeMapping[] { new TypeMapping(AssetType.Unknown, InventoryType.Unknown, "application/octet-stream", "bin"), new TypeMapping(AssetType.Texture, InventoryType.Texture, "image/x-j2c", "image/jp2", "j2c"), new TypeMapping(AssetType.Texture, InventoryType.Snapshot, "image/x-j2c", "image/jp2", "j2c"), new TypeMapping(AssetType.TextureTGA, InventoryType.Texture, "image/tga", "tga"), new TypeMapping(AssetType.ImageTGA, InventoryType.Texture, "image/tga", "tga"), new TypeMapping(AssetType.ImageJPEG, InventoryType.Texture, "image/jpeg", "jpg"), new TypeMapping(AssetType.Sound, InventoryType.Sound, "audio/ogg", "application/ogg", "ogg"), new TypeMapping(AssetType.SoundWAV, InventoryType.Sound, "audio/x-wav", "wav"), new TypeMapping(AssetType.CallingCard, InventoryType.CallingCard, "application/vnd.ll.callingcard", "application/x-metaverse-callingcard", "callingcard"), new TypeMapping(AssetType.Landmark, InventoryType.Landmark, "application/vnd.ll.landmark", "application/x-metaverse-landmark", "landmark"), new TypeMapping(AssetType.Clothing, InventoryType.Wearable, "application/vnd.ll.clothing", "application/x-metaverse-clothing", "clothing"), new TypeMapping(AssetType.Object, InventoryType.Object, "application/vnd.ll.primitive", "application/x-metaverse-primitive", "primitive"), new TypeMapping(AssetType.Object, InventoryType.Attachment, "application/vnd.ll.primitive", "application/x-metaverse-primitive", "primitive"), new TypeMapping(AssetType.Notecard, InventoryType.Notecard, "application/vnd.ll.notecard", "application/x-metaverse-notecard", "notecard"), new TypeMapping(AssetType.Folder, InventoryType.Folder, "application/vnd.ll.folder", "folder"), new TypeMapping(AssetType.RootFolder, InventoryType.RootCategory, "application/vnd.ll.rootfolder", "rootfolder"), new TypeMapping(AssetType.LSLText, InventoryType.LSL, "application/vnd.ll.lsltext", "application/x-metaverse-lsl", "lsl"), new TypeMapping(AssetType.LSLBytecode, InventoryType.LSL, "application/vnd.ll.lslbyte", "application/x-metaverse-lso", "lso"), new TypeMapping(AssetType.Bodypart, InventoryType.Wearable, "application/vnd.ll.bodypart", "application/x-metaverse-bodypart", "bodypart"), new TypeMapping(AssetType.TrashFolder, InventoryType.Folder, "application/vnd.ll.trashfolder", "trashfolder"), new TypeMapping(AssetType.SnapshotFolder, InventoryType.Folder, "application/vnd.ll.snapshotfolder", "snapshotfolder"), new TypeMapping(AssetType.LostAndFoundFolder, InventoryType.Folder, "application/vnd.ll.lostandfoundfolder", "lostandfoundfolder"), new TypeMapping(AssetType.Animation, InventoryType.Animation, "application/vnd.ll.animation", "application/x-metaverse-animation", "animation"), new TypeMapping(AssetType.Gesture, InventoryType.Gesture, "application/vnd.ll.gesture", "application/x-metaverse-gesture", "gesture"), new TypeMapping(AssetType.Simstate, InventoryType.Snapshot, "application/x-metaverse-simstate", "simstate"), new TypeMapping(AssetType.FavoriteFolder, InventoryType.Unknown, "application/vnd.ll.favoritefolder", "favoritefolder"), new TypeMapping(AssetType.Link, InventoryType.Unknown, "application/vnd.ll.link", "link"), new TypeMapping(AssetType.LinkFolder, InventoryType.Unknown, "application/vnd.ll.linkfolder", "linkfolder"), new TypeMapping(AssetType.CurrentOutfitFolder, InventoryType.Unknown, "application/vnd.ll.currentoutfitfolder", "currentoutfitfolder"), new TypeMapping(AssetType.OutfitFolder, InventoryType.Unknown, "application/vnd.ll.outfitfolder", "outfitfolder"), new TypeMapping(AssetType.MyOutfitsFolder, InventoryType.Unknown, "application/vnd.ll.myoutfitsfolder", "myoutfitsfolder"), new TypeMapping(AssetType.Mesh, InventoryType.Mesh, "application/vnd.ll.mesh", "llm"), new TypeMapping(OpenSimAssetType.Material, InventoryType.Unknown, "application/llsd+xml", "material") }; static SLUtil() { asset2Content = new Dictionary<sbyte, string>(); asset2Extension = new Dictionary<sbyte, string>(); inventory2Content = new Dictionary<InventoryType, string>(); content2Asset = new Dictionary<string, sbyte>(); content2Inventory = new Dictionary<string, InventoryType>(); foreach (TypeMapping mapping in MAPPINGS) { sbyte assetType = mapping.AssetTypeCode; if (!asset2Content.ContainsKey(assetType)) asset2Content.Add(assetType, mapping.ContentType); if (!asset2Extension.ContainsKey(assetType)) asset2Extension.Add(assetType, mapping.Extension); if (!inventory2Content.ContainsKey(mapping.InventoryType)) inventory2Content.Add(mapping.InventoryType, mapping.ContentType); if (!content2Asset.ContainsKey(mapping.ContentType)) content2Asset.Add(mapping.ContentType, assetType); if (!content2Inventory.ContainsKey(mapping.ContentType)) content2Inventory.Add(mapping.ContentType, mapping.InventoryType); if (mapping.ContentType2 != null) { if (!content2Asset.ContainsKey(mapping.ContentType2)) content2Asset.Add(mapping.ContentType2, assetType); if (!content2Inventory.ContainsKey(mapping.ContentType2)) content2Inventory.Add(mapping.ContentType2, mapping.InventoryType); } } } /// <summary> /// Returns the Enum entry corresponding to the given code, regardless of whether it belongs /// to the AssetType or OpenSimAssetType enums. /// </summary> public static object AssetTypeFromCode(sbyte assetType) { if (Enum.IsDefined(typeof(OpenMetaverse.AssetType), assetType)) return (OpenMetaverse.AssetType)assetType; else if (Enum.IsDefined(typeof(OpenSimAssetType), assetType)) return (OpenSimAssetType)assetType; else return OpenMetaverse.AssetType.Unknown; } public static sbyte ContentTypeToSLAssetType(string contentType) { sbyte assetType; if (!content2Asset.TryGetValue(contentType, out assetType)) assetType = (sbyte)AssetType.Unknown; return (sbyte)assetType; } public static sbyte ContentTypeToSLInvType(string contentType) { InventoryType invType; if (!content2Inventory.TryGetValue(contentType, out invType)) invType = InventoryType.Unknown; return (sbyte)invType; } public static string SLAssetTypeToContentType(int assetType) { string contentType; if (!asset2Content.TryGetValue((sbyte)assetType, out contentType)) contentType = asset2Content[(sbyte)AssetType.Unknown]; return contentType; } public static string SLAssetTypeToExtension(int assetType) { string extension; if (!asset2Extension.TryGetValue((sbyte)assetType, out extension)) extension = asset2Extension[(sbyte)AssetType.Unknown]; return extension; } public static string SLInvTypeToContentType(int invType) { string contentType; if (!inventory2Content.TryGetValue((InventoryType)invType, out contentType)) contentType = inventory2Content[InventoryType.Unknown]; return contentType; } private class TypeMapping { private sbyte assetType; private string contentType; private string contentType2; private string extension; private InventoryType inventoryType; public TypeMapping(AssetType assetType, InventoryType inventoryType, string contentType, string contentType2, string extension) : this((sbyte)assetType, inventoryType, contentType, contentType2, extension) { } public TypeMapping(AssetType assetType, InventoryType inventoryType, string contentType, string extension) : this((sbyte)assetType, inventoryType, contentType, null, extension) { } public TypeMapping(OpenSimAssetType assetType, InventoryType inventoryType, string contentType, string extension) : this((sbyte)assetType, inventoryType, contentType, null, extension) { } private TypeMapping(sbyte assetType, InventoryType inventoryType, string contentType, string contentType2, string extension) { this.assetType = assetType; this.inventoryType = inventoryType; this.contentType = contentType; this.contentType2 = contentType2; this.extension = extension; } public object AssetType { get { return AssetTypeFromCode(assetType); } } public sbyte AssetTypeCode { get { return assetType; } } public string ContentType { get { return contentType; } } public string ContentType2 { get { return contentType2; } } public string Extension { get { return extension; } } public InventoryType InventoryType { get { return inventoryType; } } } #endregion SL / file extension / content-type conversions /// <summary> /// Parse a notecard in Linden format to a list of ordinary lines. /// </summary> /// <param name="rawInput"></param> /// <returns></returns> public static List<string> ParseNotecardToList(string rawInput) { string[] input; int idx = 0; int level = 0; List<string> output = new List<string>(); string[] words; //The Linden format always ends with a } after the input data. //Strip off trailing } so there is nothing after the input data. int i = rawInput.LastIndexOf("}"); rawInput = rawInput.Remove(i, rawInput.Length - i); input = rawInput.Replace("\r", "").Split('\n'); while (idx < input.Length) { if (input[idx] == "{") { level++; idx++; continue; } if (input[idx] == "}") { level--; idx++; continue; } switch (level) { case 0: words = input[idx].Split(' '); // Linden text ver // Notecards are created *really* empty. Treat that as "no text" (just like after saving an empty notecard) if (words.Length < 3) return output; int version = int.Parse(words[3]); if (version != 2) return output; break; case 1: words = input[idx].Split(' '); if (words[0] == "LLEmbeddedItems") break; if (words[0] == "Text") { idx++; //Now points to first line of notecard text //Number of lines in notecard. int lines = input.Length - idx; int line = 0; while (line < lines) { // m_log.DebugFormat("[PARSE NOTECARD]: Adding line {0}", input[idx]); output.Add(input[idx]); idx++; line++; } return output; } break; case 2: words = input[idx].Split(' '); // count if (words[0] == "count") { int c = int.Parse(words[1]); if (c > 0) return output; break; } break; } idx++; } return output; } /// <summary> /// Parse a notecard in Linden format to a string of ordinary text. /// </summary> /// <param name="rawInput"></param> /// <returns></returns> public static string ParseNotecardToString(string rawInput) { string[] output = ParseNotecardToList(rawInput).ToArray(); // foreach (string line in output) // m_log.DebugFormat("[PARSE NOTECARD]: ParseNotecardToString got line {0}", line); return string.Join("\n", output); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; using System.Diagnostics; namespace System.Globalization { //////////////////////////////////////////////////////////////////////////// // // Used in HebrewNumber.ParseByChar to maintain the context information ( // the state in the state machine and current Hebrew number values, etc.) // when parsing Hebrew number character by character. // //////////////////////////////////////////////////////////////////////////// internal struct HebrewNumberParsingContext { // The current state of the state machine for parsing Hebrew numbers. internal HebrewNumber.HS state; // The current value of the Hebrew number. // The final value is determined when state is FoundEndOfHebrewNumber. internal int result; public HebrewNumberParsingContext(int result) { // Set the start state of the state machine for parsing Hebrew numbers. state = HebrewNumber.HS.Start; this.result = result; } } //////////////////////////////////////////////////////////////////////////// // // Please see ParseByChar() for comments about different states defined here. // //////////////////////////////////////////////////////////////////////////// internal enum HebrewNumberParsingState { InvalidHebrewNumber, NotHebrewDigit, FoundEndOfHebrewNumber, ContinueParsing, } //////////////////////////////////////////////////////////////////////////// // // class HebrewNumber // // Provides static methods for formatting integer values into // Hebrew text and parsing Hebrew number text. // // Limitations: // Parse can only handle value 1 ~ 999. // Append() can only handle 1 ~ 999. If value is greater than 5000, // 5000 will be subtracted from the value. // //////////////////////////////////////////////////////////////////////////// internal static class HebrewNumber { //////////////////////////////////////////////////////////////////////////// // // Append // // Converts the given number to Hebrew letters according to the numeric // value of each Hebrew letter, appending to the supplied StringBuilder. // Basically, this converts the lunar year and the lunar month to letters. // // The character of a year is described by three letters of the Hebrew // alphabet, the first and third giving, respectively, the days of the // weeks on which the New Year occurs and Passover begins, while the // second is the initial of the Hebrew word for defective, normal, or // complete. // // Defective Year : Both Heshvan and Kislev are defective (353 or 383 days) // Normal Year : Heshvan is defective, Kislev is full (354 or 384 days) // Complete Year : Both Heshvan and Kislev are full (355 or 385 days) // //////////////////////////////////////////////////////////////////////////// internal static void Append(StringBuilder outputBuffer, int Number) { Debug.Assert(outputBuffer != null); int outputBufferStartingLength = outputBuffer.Length; char cTens = '\x0'; char cUnits; // tens and units chars int Hundreds, Tens; // hundreds and tens values // // Adjust the number if greater than 5000. // if (Number > 5000) { Number -= 5000; } Debug.Assert(Number > 0 && Number <= 999, "Number is out of range."); // // Get the Hundreds. // Hundreds = Number / 100; if (Hundreds > 0) { Number -= Hundreds * 100; // \x05e7 = 100 // \x05e8 = 200 // \x05e9 = 300 // \x05ea = 400 // If the number is greater than 400, use the multiples of 400. for (int i = 0; i < (Hundreds / 4); i++) { outputBuffer.Append('\x05ea'); } int remains = Hundreds % 4; if (remains > 0) { outputBuffer.Append((char)((int)'\x05e6' + remains)); } } // // Get the Tens. // Tens = Number / 10; Number %= 10; switch (Tens) { case (0): cTens = '\x0'; break; case (1): cTens = '\x05d9'; // Hebrew Letter Yod break; case (2): cTens = '\x05db'; // Hebrew Letter Kaf break; case (3): cTens = '\x05dc'; // Hebrew Letter Lamed break; case (4): cTens = '\x05de'; // Hebrew Letter Mem break; case (5): cTens = '\x05e0'; // Hebrew Letter Nun break; case (6): cTens = '\x05e1'; // Hebrew Letter Samekh break; case (7): cTens = '\x05e2'; // Hebrew Letter Ayin break; case (8): cTens = '\x05e4'; // Hebrew Letter Pe break; case (9): cTens = '\x05e6'; // Hebrew Letter Tsadi break; } // // Get the Units. // cUnits = (char)(Number > 0 ? ((int)'\x05d0' + Number - 1) : 0); if ((cUnits == '\x05d4') && // Hebrew Letter He (5) (cTens == '\x05d9')) { // Hebrew Letter Yod (10) cUnits = '\x05d5'; // Hebrew Letter Vav (6) cTens = '\x05d8'; // Hebrew Letter Tet (9) } if ((cUnits == '\x05d5') && // Hebrew Letter Vav (6) (cTens == '\x05d9')) { // Hebrew Letter Yod (10) cUnits = '\x05d6'; // Hebrew Letter Zayin (7) cTens = '\x05d8'; // Hebrew Letter Tet (9) } // // Copy the appropriate info to the given buffer. // if (cTens != '\x0') { outputBuffer.Append(cTens); } if (cUnits != '\x0') { outputBuffer.Append(cUnits); } if (outputBuffer.Length - outputBufferStartingLength > 1) { outputBuffer.Insert(outputBuffer.Length - 1, '"'); } else { outputBuffer.Append('\''); } } //////////////////////////////////////////////////////////////////////////// // // Token used to tokenize a Hebrew word into tokens so that we can use in the // state machine. // //////////////////////////////////////////////////////////////////////////// private enum HebrewToken : short { Invalid = -1, Digit400 = 0, Digit200_300 = 1, Digit100 = 2, Digit10 = 3, // 10 ~ 90 Digit1 = 4, // 1, 2, 3, 4, 5, 8, Digit6_7 = 5, Digit7 = 6, Digit9 = 7, SingleQuote = 8, DoubleQuote = 9, } //////////////////////////////////////////////////////////////////////////// // // This class is used to map a token into its Hebrew digit value. // //////////////////////////////////////////////////////////////////////////// private struct HebrewValue { internal HebrewToken token; internal short value; internal HebrewValue(HebrewToken token, short value) { this.token = token; this.value = value; } } // // Map a Hebrew character from U+05D0 ~ U+05EA to its digit value. // The value is -1 if the Hebrew character does not have a associated value. // private static readonly HebrewValue[] s_hebrewValues = { new HebrewValue(HebrewToken.Digit1, 1), // '\x05d0 new HebrewValue(HebrewToken.Digit1, 2), // '\x05d1 new HebrewValue(HebrewToken.Digit1, 3), // '\x05d2 new HebrewValue(HebrewToken.Digit1, 4), // '\x05d3 new HebrewValue(HebrewToken.Digit1, 5), // '\x05d4 new HebrewValue(HebrewToken.Digit6_7, 6), // '\x05d5 new HebrewValue(HebrewToken.Digit6_7, 7), // '\x05d6 new HebrewValue(HebrewToken.Digit1, 8), // '\x05d7 new HebrewValue(HebrewToken.Digit9, 9), // '\x05d8 new HebrewValue(HebrewToken.Digit10, 10), // '\x05d9; // Hebrew Letter Yod new HebrewValue(HebrewToken.Invalid, -1), // '\x05da; new HebrewValue(HebrewToken.Digit10, 20), // '\x05db; // Hebrew Letter Kaf new HebrewValue(HebrewToken.Digit10, 30), // '\x05dc; // Hebrew Letter Lamed new HebrewValue(HebrewToken.Invalid, -1), // '\x05dd; new HebrewValue(HebrewToken.Digit10, 40), // '\x05de; // Hebrew Letter Mem new HebrewValue(HebrewToken.Invalid, -1), // '\x05df; new HebrewValue(HebrewToken.Digit10, 50), // '\x05e0; // Hebrew Letter Nun new HebrewValue(HebrewToken.Digit10, 60), // '\x05e1; // Hebrew Letter Samekh new HebrewValue(HebrewToken.Digit10, 70), // '\x05e2; // Hebrew Letter Ayin new HebrewValue(HebrewToken.Invalid, -1), // '\x05e3; new HebrewValue(HebrewToken.Digit10, 80), // '\x05e4; // Hebrew Letter Pe new HebrewValue(HebrewToken.Invalid, -1), // '\x05e5; new HebrewValue(HebrewToken.Digit10, 90), // '\x05e6; // Hebrew Letter Tsadi new HebrewValue(HebrewToken.Digit100, 100), // '\x05e7; new HebrewValue(HebrewToken.Digit200_300, 200), // '\x05e8; new HebrewValue(HebrewToken.Digit200_300, 300), // '\x05e9; new HebrewValue(HebrewToken.Digit400, 400), // '\x05ea; }; private const int minHebrewNumberCh = 0x05d0; private static readonly char s_maxHebrewNumberCh = (char)(minHebrewNumberCh + s_hebrewValues.Length - 1); //////////////////////////////////////////////////////////////////////////// // // Hebrew number parsing State // The current state and the next token will lead to the next state in the state machine. // DQ = Double Quote // //////////////////////////////////////////////////////////////////////////// internal enum HS : sbyte { _err = -1, // an error state Start = 0, S400 = 1, // a Hebrew digit 400 S400_400 = 2, // Two Hebrew digit 400 S400_X00 = 3, // Two Hebrew digit 400 and followed by 100 S400_X0 = 4, // Hebrew digit 400 and followed by 10 ~ 90 X00_DQ = 5, // A hundred number and followed by a double quote. S400_X00_X0 = 6, X0_DQ = 7, // A two-digit number and followed by a double quote. X = 8, // A single digit Hebrew number. X0 = 9, // A two-digit Hebrew number X00 = 10, // A three-digit Hebrew number S400_DQ = 11, // A Hebrew digit 400 and followed by a double quote. S400_400_DQ = 12, S400_400_100 = 13, S9 = 14, // Hebrew digit 9 X00_S9 = 15, // A hundered number and followed by a digit 9 S9_DQ = 16, // Hebrew digit 9 and followed by a double quote END = 100, // A terminial state is reached. } // // The state machine for Hebrew number pasing. // private static readonly HS[] s_numberPasingState = { // 400 300/200 100 90~10 8~1 6, 7, 9, ' " /* 0 */ HS.S400, HS.X00, HS.X00, HS.X0, HS.X, HS.X, HS.X, HS.S9, HS._err, HS._err, /* 1: S400 */ HS.S400_400, HS.S400_X00, HS.S400_X00, HS.S400_X0, HS._err, HS._err, HS._err, HS.X00_S9, HS.END, HS.S400_DQ, /* 2: S400_400 */ HS._err, HS._err, HS.S400_400_100, HS.S400_X0, HS._err, HS._err, HS._err, HS.X00_S9, HS._err, HS.S400_400_DQ, /* 3: S400_X00 */ HS._err, HS._err, HS._err, HS.S400_X00_X0, HS._err, HS._err, HS._err, HS.X00_S9, HS._err, HS.X00_DQ, /* 4: S400_X0 */ HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.X0_DQ, /* 5: X00_DQ */ HS._err, HS._err, HS._err, HS.END, HS.END, HS.END, HS.END, HS.END, HS._err, HS._err, /* 6: S400_X00_X0 */ HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.X0_DQ, /* 7: X0_DQ */ HS._err, HS._err, HS._err, HS._err, HS.END, HS.END, HS.END, HS.END, HS._err, HS._err, /* 8: X */ HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.END, HS._err, /* 9: X0 */ HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.END, HS.X0_DQ, /* 10: X00 */ HS._err, HS._err, HS._err, HS.S400_X0, HS._err, HS._err, HS._err, HS.X00_S9, HS.END, HS.X00_DQ, /* 11: S400_DQ */ HS.END, HS.END, HS.END, HS.END, HS.END, HS.END, HS.END, HS.END, HS._err, HS._err, /* 12: S400_400_DQ*/ HS._err, HS._err, HS.END, HS.END, HS.END, HS.END, HS.END, HS.END, HS._err, HS._err, /* 13: S400_400_100*/ HS._err, HS._err, HS._err, HS.S400_X00_X0, HS._err, HS._err, HS._err, HS.X00_S9, HS._err, HS.X00_DQ, /* 14: S9 */ HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.END, HS.S9_DQ, /* 15: X00_S9 */ HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.S9_DQ, /* 16: S9_DQ */ HS._err, HS._err, HS._err, HS._err, HS._err, HS.END, HS.END, HS._err, HS._err, HS._err }; // Count of valid HebrewToken, column count in the NumberPasingState array private const int HebrewTokenCount = 10; //////////////////////////////////////////////////////////////////////// // // Actions: // Parse the Hebrew number by passing one character at a time. // The state between characters are maintained at HebrewNumberPasingContext. // Returns: // Return a enum of HebrewNumberParsingState. // NotHebrewDigit: The specified ch is not a valid Hebrew digit. // InvalidHebrewNumber: After parsing the specified ch, it will lead into // an invalid Hebrew number text. // FoundEndOfHebrewNumber: A terminal state is reached. This means that // we find a valid Hebrew number text after the specified ch is parsed. // ContinueParsing: The specified ch is a valid Hebrew digit, and // it will lead into a valid state in the state machine, we should // continue to parse incoming characters. // //////////////////////////////////////////////////////////////////////// internal static HebrewNumberParsingState ParseByChar(char ch, ref HebrewNumberParsingContext context) { Debug.Assert(s_numberPasingState.Length == HebrewTokenCount * ((int)HS.S9_DQ + 1)); HebrewToken token; if (ch == '\'') { token = HebrewToken.SingleQuote; } else if (ch == '\"') { token = HebrewToken.DoubleQuote; } else { int index = (int)ch - minHebrewNumberCh; if (index >= 0 && index < s_hebrewValues.Length) { token = s_hebrewValues[index].token; if (token == HebrewToken.Invalid) { return HebrewNumberParsingState.NotHebrewDigit; } context.result += s_hebrewValues[index].value; } else { // Not in valid Hebrew digit range. return HebrewNumberParsingState.NotHebrewDigit; } } context.state = s_numberPasingState[(int)context.state * (int)HebrewTokenCount + (int)token]; if (context.state == HS._err) { // Invalid Hebrew state. This indicates an incorrect Hebrew number. return HebrewNumberParsingState.InvalidHebrewNumber; } if (context.state == HS.END) { // Reach a terminal state. return HebrewNumberParsingState.FoundEndOfHebrewNumber; } // We should continue to parse. return HebrewNumberParsingState.ContinueParsing; } //////////////////////////////////////////////////////////////////////// // // Actions: // Check if the ch is a valid Hebrew number digit. // This function will return true if the specified char is a legal Hebrew // digit character, single quote, or double quote. // Returns: // true if the specified character is a valid Hebrew number character. // //////////////////////////////////////////////////////////////////////// internal static bool IsDigit(char ch) { if (ch >= minHebrewNumberCh && ch <= s_maxHebrewNumberCh) { return s_hebrewValues[ch - minHebrewNumberCh].value >= 0; } return ch == '\'' || ch == '\"'; } } }
// ================================================================================================= // ADOBE SYSTEMS INCORPORATED // Copyright 2006 Adobe Systems Incorporated // All Rights Reserved // // NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms // of the Adobe license agreement accompanying it. // ================================================================================================= using System.Collections.Generic; using System.IO; using Com.Adobe.Xmp; using Com.Adobe.Xmp.Options; using Sharpen; namespace Com.Adobe.Xmp.Impl { /// <summary>Serializes the <code>XMPMeta</code>-object using the standard RDF serialization format.</summary> /// <remarks> /// Serializes the <code>XMPMeta</code>-object using the standard RDF serialization format. /// The output is written to an <code>OutputStream</code> /// according to the <code>SerializeOptions</code>. /// </remarks> /// <since>11.07.2006</since> public class XMPSerializerRDF { /// <summary>default padding</summary> private const int DefaultPad = 2048; private const string PacketHeader = "<?xpacket begin=\"\uFEFF\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>"; /// <summary>The w/r is missing inbetween</summary> private const string PacketTrailer = "<?xpacket end=\""; private const string PacketTrailer2 = "\"?>"; private const string RdfXmpmetaStart = "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" x:xmptk=\""; private const string RdfXmpmetaEnd = "</x:xmpmeta>"; private const string RdfRdfStart = "<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">"; private const string RdfRdfEnd = "</rdf:RDF>"; private const string RdfSchemaStart = "<rdf:Description rdf:about="; private const string RdfSchemaEnd = "</rdf:Description>"; private const string RdfStructStart = "<rdf:Description"; private const string RdfStructEnd = "</rdf:Description>"; private const string RdfEmptyStruct = "<rdf:Description/>"; /// <summary>a set of all rdf attribute qualifier</summary> internal static readonly ICollection<object> RdfAttrQualifier = new HashSet<object>(Arrays.AsList(new string[] { XMPConstConstants.XmlLang, "rdf:resource", "rdf:ID", "rdf:bagID", "rdf:nodeID" })); /// <summary>the metadata object to be serialized.</summary> private XMPMetaImpl xmp; /// <summary>the output stream to serialize to</summary> private CountOutputStream outputStream; /// <summary>this writer is used to do the actual serialization</summary> private OutputStreamWriter writer; /// <summary>the stored serialization options</summary> private SerializeOptions options; /// <summary> /// the size of one unicode char, for UTF-8 set to 1 /// (Note: only valid for ASCII chars lower than 0x80), /// set to 2 in case of UTF-16 /// </summary> private int unicodeSize = 1; /// <summary> /// the padding in the XMP Packet, or the length of the complete packet in /// case of option <em>exactPacketLength</em>. /// </summary> private int padding; // UTF-8 /// <summary>The actual serialization.</summary> /// <param name="xmp">the metadata object to be serialized</param> /// <param name="out">outputStream the output stream to serialize to</param> /// <param name="options">the serialization options</param> /// <exception cref="Com.Adobe.Xmp.XMPException">If case of wrong options or any other serialization error.</exception> public virtual void Serialize(XMPMeta xmp, OutputStream @out, SerializeOptions options) { try { outputStream = new CountOutputStream(@out); writer = new OutputStreamWriter(outputStream, options.GetEncoding()); this.xmp = (XMPMetaImpl)xmp; this.options = options; this.padding = options.GetPadding(); writer = new OutputStreamWriter(outputStream, options.GetEncoding()); CheckOptionsConsistence(); // serializes the whole packet, but don't write the tail yet // and flush to make sure that the written bytes are calculated correctly string tailStr = SerializeAsRDF(); writer.Flush(); // adds padding AddPadding(tailStr.Length); // writes the tail Write(tailStr); writer.Flush(); outputStream.Close(); } catch (IOException) { throw new XMPException("Error writing to the OutputStream", XMPErrorConstants.Unknown); } } /// <summary>Calculates the padding according to the options and write it to the stream.</summary> /// <param name="tailLength">the length of the tail string</param> /// <exception cref="Com.Adobe.Xmp.XMPException">thrown if packet size is to small to fit the padding</exception> /// <exception cref="System.IO.IOException">forwards writer errors</exception> private void AddPadding(int tailLength) { if (options.GetExactPacketLength()) { // the string length is equal to the length of the UTF-8 encoding int minSize = outputStream.GetBytesWritten() + tailLength * unicodeSize; if (minSize > padding) { throw new XMPException("Can't fit into specified packet size", XMPErrorConstants.Badserialize); } padding -= minSize; } // Now the actual amount of padding to add. // fix rest of the padding according to Unicode unit size. padding /= unicodeSize; int newlineLen = options.GetNewline().Length; if (padding >= newlineLen) { padding -= newlineLen; // Write this newline last. while (padding >= (100 + newlineLen)) { WriteChars(100, ' '); WriteNewline(); padding -= (100 + newlineLen); } WriteChars(padding, ' '); WriteNewline(); } else { WriteChars(padding, ' '); } } /// <summary>Checks if the supplied options are consistent.</summary> /// <exception cref="Com.Adobe.Xmp.XMPException">Thrown if options are conflicting</exception> protected internal virtual void CheckOptionsConsistence() { if (options.GetEncodeUTF16BE() | options.GetEncodeUTF16LE()) { unicodeSize = 2; } if (options.GetExactPacketLength()) { if (options.GetOmitPacketWrapper() | options.GetIncludeThumbnailPad()) { throw new XMPException("Inconsistent options for exact size serialize", XMPErrorConstants.Badoptions); } if ((options.GetPadding() & (unicodeSize - 1)) != 0) { throw new XMPException("Exact size must be a multiple of the Unicode element", XMPErrorConstants.Badoptions); } } else { if (options.GetReadOnlyPacket()) { if (options.GetOmitPacketWrapper() | options.GetIncludeThumbnailPad()) { throw new XMPException("Inconsistent options for read-only packet", XMPErrorConstants.Badoptions); } padding = 0; } else { if (options.GetOmitPacketWrapper()) { if (options.GetIncludeThumbnailPad()) { throw new XMPException("Inconsistent options for non-packet serialize", XMPErrorConstants.Badoptions); } padding = 0; } else { if (padding == 0) { padding = DefaultPad * unicodeSize; } if (options.GetIncludeThumbnailPad()) { if (!xmp.DoesPropertyExist(XMPConstConstants.NsXmp, "Thumbnails")) { padding += 10000 * unicodeSize; } } } } } } /// <summary>Writes the (optional) packet header and the outer rdf-tags.</summary> /// <returns>Returns the packet end processing instraction to be written after the padding.</returns> /// <exception cref="System.IO.IOException">Forwarded writer exceptions.</exception> /// <exception cref="Com.Adobe.Xmp.XMPException"></exception> private string SerializeAsRDF() { int level = 0; // Write the packet header PI. if (!options.GetOmitPacketWrapper()) { WriteIndent(level); Write(PacketHeader); WriteNewline(); } // Write the x:xmpmeta element's start tag. if (!options.GetOmitXmpMetaElement()) { WriteIndent(level); Write(RdfXmpmetaStart); // Note: this flag can only be set by unit tests if (!options.GetOmitVersionAttribute()) { Write(XMPMetaFactory.GetVersionInfo().GetMessage()); } Write("\">"); WriteNewline(); level++; } // Write the rdf:RDF start tag. WriteIndent(level); Write(RdfRdfStart); WriteNewline(); // Write all of the properties. if (options.GetUseCanonicalFormat()) { SerializeCanonicalRDFSchemas(level); } else { SerializeCompactRDFSchemas(level); } // Write the rdf:RDF end tag. WriteIndent(level); Write(RdfRdfEnd); WriteNewline(); // Write the xmpmeta end tag. if (!options.GetOmitXmpMetaElement()) { level--; WriteIndent(level); Write(RdfXmpmetaEnd); WriteNewline(); } // Write the packet trailer PI into the tail string as UTF-8. string tailStr = string.Empty; if (!options.GetOmitPacketWrapper()) { for (level = options.GetBaseIndent(); level > 0; level--) { tailStr += options.GetIndent(); } tailStr += PacketTrailer; tailStr += options.GetReadOnlyPacket() ? 'r' : 'w'; tailStr += PacketTrailer2; } return tailStr; } /// <summary>Serializes the metadata in pretty-printed manner.</summary> /// <param name="level">indent level</param> /// <exception cref="System.IO.IOException">Forwarded writer exceptions</exception> /// <exception cref="Com.Adobe.Xmp.XMPException"></exception> private void SerializeCanonicalRDFSchemas(int level) { if (xmp.GetRoot().GetChildrenLength() > 0) { StartOuterRDFDescription(xmp.GetRoot(), level); for (Iterator it = xmp.GetRoot().IterateChildren(); it.HasNext(); ) { XMPNode currSchema = (XMPNode)it.Next(); SerializeCanonicalRDFSchema(currSchema, level); } EndOuterRDFDescription(level); } else { WriteIndent(level + 1); Write(RdfSchemaStart); // Special case an empty XMP object. WriteTreeName(); Write("/>"); WriteNewline(); } } /// <exception cref="System.IO.IOException"/> private void WriteTreeName() { Write('"'); string name = xmp.GetRoot().GetName(); if (name != null) { AppendNodeValue(name, true); } Write('"'); } /// <summary>Serializes the metadata in compact manner.</summary> /// <param name="level">indent level to start with</param> /// <exception cref="System.IO.IOException">Forwarded writer exceptions</exception> /// <exception cref="Com.Adobe.Xmp.XMPException"></exception> private void SerializeCompactRDFSchemas(int level) { // Begin the rdf:Description start tag. WriteIndent(level + 1); Write(RdfSchemaStart); WriteTreeName(); // Write all necessary xmlns attributes. ICollection<object> usedPrefixes = new HashSet<object>(); usedPrefixes.Add("xml"); usedPrefixes.Add("rdf"); for (Iterator it = xmp.GetRoot().IterateChildren(); it.HasNext(); ) { XMPNode schema = (XMPNode)it.Next(); DeclareUsedNamespaces(schema, usedPrefixes, level + 3); } // Write the top level "attrProps" and close the rdf:Description start tag. bool allAreAttrs = true; for (Iterator it_1 = xmp.GetRoot().IterateChildren(); it_1.HasNext(); ) { XMPNode schema = (XMPNode)it_1.Next(); allAreAttrs &= SerializeCompactRDFAttrProps(schema, level + 2); } if (!allAreAttrs) { Write('>'); WriteNewline(); } else { Write("/>"); WriteNewline(); return; } // ! Done if all properties in all schema are written as attributes. // Write the remaining properties for each schema. for (Iterator it_2 = xmp.GetRoot().IterateChildren(); it_2.HasNext(); ) { XMPNode schema = (XMPNode)it_2.Next(); SerializeCompactRDFElementProps(schema, level + 2); } // Write the rdf:Description end tag. WriteIndent(level + 1); Write(RdfSchemaEnd); WriteNewline(); } /// <summary>Write each of the parent's simple unqualified properties as an attribute.</summary> /// <remarks> /// Write each of the parent's simple unqualified properties as an attribute. Returns true if all /// of the properties are written as attributes. /// </remarks> /// <param name="parentNode">the parent property node</param> /// <param name="indent">the current indent level</param> /// <returns>Returns true if all properties can be rendered as RDF attribute.</returns> /// <exception cref="System.IO.IOException"/> private bool SerializeCompactRDFAttrProps(XMPNode parentNode, int indent) { bool allAreAttrs = true; for (Iterator it = parentNode.IterateChildren(); it.HasNext(); ) { XMPNode prop = (XMPNode)it.Next(); if (CanBeRDFAttrProp(prop)) { WriteNewline(); WriteIndent(indent); Write(prop.GetName()); Write("=\""); AppendNodeValue(prop.GetValue(), true); Write('"'); } else { allAreAttrs = false; } } return allAreAttrs; } /// <summary> /// Recursively handles the "value" for a node that must be written as an RDF /// property element. /// </summary> /// <remarks> /// Recursively handles the "value" for a node that must be written as an RDF /// property element. It does not matter if it is a top level property, a /// field of a struct, or an item of an array. The indent is that for the /// property element. The patterns bwlow ignore attribute qualifiers such as /// xml:lang, they don't affect the output form. /// <blockquote> /// <pre> /// &lt;ns:UnqualifiedStructProperty-1 /// ... The fields as attributes, if all are simple and unqualified /// /&gt; /// &lt;ns:UnqualifiedStructProperty-2 rdf:parseType=&quot;Resource&quot;&gt; /// ... The fields as elements, if none are simple and unqualified /// &lt;/ns:UnqualifiedStructProperty-2&gt; /// &lt;ns:UnqualifiedStructProperty-3&gt; /// &lt;rdf:Description /// ... The simple and unqualified fields as attributes /// &gt; /// ... The compound or qualified fields as elements /// &lt;/rdf:Description&gt; /// &lt;/ns:UnqualifiedStructProperty-3&gt; /// &lt;ns:UnqualifiedArrayProperty&gt; /// &lt;rdf:Bag&gt; or Seq or Alt /// ... Array items as rdf:li elements, same forms as top level properties /// &lt;/rdf:Bag&gt; /// &lt;/ns:UnqualifiedArrayProperty&gt; /// &lt;ns:QualifiedProperty rdf:parseType=&quot;Resource&quot;&gt; /// &lt;rdf:value&gt; ... Property &quot;value&quot; /// following the unqualified forms ... &lt;/rdf:value&gt; /// ... Qualifiers looking like named struct fields /// &lt;/ns:QualifiedProperty&gt; /// </pre> /// </blockquote> /// *** Consider numbered array items, but has compatibility problems. /// Consider qualified form with rdf:Description and attributes. /// </remarks> /// <param name="parentNode">the parent node</param> /// <param name="indent">the current indent level</param> /// <exception cref="System.IO.IOException">Forwards writer exceptions</exception> /// <exception cref="Com.Adobe.Xmp.XMPException">If qualifier and element fields are mixed.</exception> private void SerializeCompactRDFElementProps(XMPNode parentNode, int indent) { for (Iterator it = parentNode.IterateChildren(); it.HasNext(); ) { XMPNode node = (XMPNode)it.Next(); if (CanBeRDFAttrProp(node)) { continue; } bool emitEndTag = true; bool indentEndTag = true; // Determine the XML element name, write the name part of the start tag. Look over the // qualifiers to decide on "normal" versus "rdf:value" form. Emit the attribute // qualifiers at the same time. string elemName = node.GetName(); if (XMPConstConstants.ArrayItemName.Equals(elemName)) { elemName = "rdf:li"; } WriteIndent(indent); Write('<'); Write(elemName); bool hasGeneralQualifiers = false; bool hasRDFResourceQual = false; for (Iterator iq = node.IterateQualifier(); iq.HasNext(); ) { XMPNode qualifier = (XMPNode)iq.Next(); if (!RdfAttrQualifier.Contains(qualifier.GetName())) { hasGeneralQualifiers = true; } else { hasRDFResourceQual = "rdf:resource".Equals(qualifier.GetName()); Write(' '); Write(qualifier.GetName()); Write("=\""); AppendNodeValue(qualifier.GetValue(), true); Write('"'); } } // Process the property according to the standard patterns. if (hasGeneralQualifiers) { SerializeCompactRDFGeneralQualifier(indent, node); } else { // This node has only attribute qualifiers. Emit as a property element. if (!node.GetOptions().IsCompositeProperty()) { object[] result = SerializeCompactRDFSimpleProp(node); emitEndTag = ((bool)result[0]); indentEndTag = ((bool)result[1]); } else { if (node.GetOptions().IsArray()) { SerializeCompactRDFArrayProp(node, indent); } else { emitEndTag = SerializeCompactRDFStructProp(node, indent, hasRDFResourceQual); } } } // Emit the property element end tag. if (emitEndTag) { if (indentEndTag) { WriteIndent(indent); } Write("</"); Write(elemName); Write('>'); WriteNewline(); } } } /// <summary>Serializes a simple property.</summary> /// <param name="node">an XMPNode</param> /// <returns>Returns an array containing the flags emitEndTag and indentEndTag.</returns> /// <exception cref="System.IO.IOException">Forwards the writer exceptions.</exception> private object[] SerializeCompactRDFSimpleProp(XMPNode node) { // This is a simple property. bool emitEndTag = true; bool indentEndTag = true; if (node.GetOptions().IsURI()) { Write(" rdf:resource=\""); AppendNodeValue(node.GetValue(), true); Write("\"/>"); WriteNewline(); emitEndTag = false; } else { if (node.GetValue() == null || node.GetValue().Length == 0) { Write("/>"); WriteNewline(); emitEndTag = false; } else { Write('>'); AppendNodeValue(node.GetValue(), false); indentEndTag = false; } } return new object[] { emitEndTag, indentEndTag }; } /// <summary>Serializes an array property.</summary> /// <param name="node">an XMPNode</param> /// <param name="indent">the current indent level</param> /// <exception cref="System.IO.IOException">Forwards the writer exceptions.</exception> /// <exception cref="Com.Adobe.Xmp.XMPException">If qualifier and element fields are mixed.</exception> private void SerializeCompactRDFArrayProp(XMPNode node, int indent) { // This is an array. Write('>'); WriteNewline(); EmitRDFArrayTag(node, true, indent + 1); if (node.GetOptions().IsArrayAltText()) { XMPNodeUtils.NormalizeLangArray(node); } SerializeCompactRDFElementProps(node, indent + 2); EmitRDFArrayTag(node, false, indent + 1); } /// <summary>Serializes a struct property.</summary> /// <param name="node">an XMPNode</param> /// <param name="indent">the current indent level</param> /// <param name="hasRDFResourceQual">Flag if the element has resource qualifier</param> /// <returns>Returns true if an end flag shall be emitted.</returns> /// <exception cref="System.IO.IOException">Forwards the writer exceptions.</exception> /// <exception cref="Com.Adobe.Xmp.XMPException">If qualifier and element fields are mixed.</exception> private bool SerializeCompactRDFStructProp(XMPNode node, int indent, bool hasRDFResourceQual) { // This must be a struct. bool hasAttrFields = false; bool hasElemFields = false; bool emitEndTag = true; for (Iterator ic = node.IterateChildren(); ic.HasNext(); ) { XMPNode field = (XMPNode)ic.Next(); if (CanBeRDFAttrProp(field)) { hasAttrFields = true; } else { hasElemFields = true; } if (hasAttrFields && hasElemFields) { break; } } // No sense looking further. if (hasRDFResourceQual && hasElemFields) { throw new XMPException("Can't mix rdf:resource qualifier and element fields", XMPErrorConstants.Badrdf); } if (!node.HasChildren()) { // Catch an empty struct as a special case. The case // below would emit an empty // XML element, which gets reparsed as a simple property // with an empty value. Write(" rdf:parseType=\"Resource\"/>"); WriteNewline(); emitEndTag = false; } else { if (!hasElemFields) { // All fields can be attributes, use the // emptyPropertyElt form. SerializeCompactRDFAttrProps(node, indent + 1); Write("/>"); WriteNewline(); emitEndTag = false; } else { if (!hasAttrFields) { // All fields must be elements, use the // parseTypeResourcePropertyElt form. Write(" rdf:parseType=\"Resource\">"); WriteNewline(); SerializeCompactRDFElementProps(node, indent + 1); } else { // Have a mix of attributes and elements, use an inner rdf:Description. Write('>'); WriteNewline(); WriteIndent(indent + 1); Write(RdfStructStart); SerializeCompactRDFAttrProps(node, indent + 2); Write(">"); WriteNewline(); SerializeCompactRDFElementProps(node, indent + 1); WriteIndent(indent + 1); Write(RdfStructEnd); WriteNewline(); } } } return emitEndTag; } /// <summary>Serializes the general qualifier.</summary> /// <param name="node">the root node of the subtree</param> /// <param name="indent">the current indent level</param> /// <exception cref="System.IO.IOException">Forwards all writer exceptions.</exception> /// <exception cref="Com.Adobe.Xmp.XMPException">If qualifier and element fields are mixed.</exception> private void SerializeCompactRDFGeneralQualifier(int indent, XMPNode node) { // The node has general qualifiers, ones that can't be // attributes on a property element. // Emit using the qualified property pseudo-struct form. The // value is output by a call // to SerializePrettyRDFProperty with emitAsRDFValue set. Write(" rdf:parseType=\"Resource\">"); WriteNewline(); SerializeCanonicalRDFProperty(node, false, true, indent + 1); for (Iterator iq = node.IterateQualifier(); iq.HasNext(); ) { XMPNode qualifier = (XMPNode)iq.Next(); SerializeCanonicalRDFProperty(qualifier, false, false, indent + 1); } } /// <summary> /// Serializes one schema with all contained properties in pretty-printed /// manner.<br /> /// Each schema's properties are written to a single /// rdf:Description element. /// </summary> /// <remarks> /// Serializes one schema with all contained properties in pretty-printed /// manner.<br /> /// Each schema's properties are written to a single /// rdf:Description element. All of the necessary namespaces are declared in /// the rdf:Description element. The baseIndent is the base level for the /// entire serialization, that of the x:xmpmeta element. An xml:lang /// qualifier is written as an attribute of the property start tag, not by /// itself forcing the qualified property form. /// <blockquote> /// <pre> /// &lt;rdf:Description rdf:about=&quot;TreeName&quot; xmlns:ns=&quot;URI&quot; ... &gt; /// ... The actual properties of the schema, see SerializePrettyRDFProperty /// &lt;!-- ns1:Alias is aliased to ns2:Actual --&gt; ... If alias comments are wanted /// &lt;/rdf:Description&gt; /// </pre> /// </blockquote> /// </remarks> /// <param name="schemaNode">a schema node</param> /// <param name="level"></param> /// <exception cref="System.IO.IOException">Forwarded writer exceptions</exception> /// <exception cref="Com.Adobe.Xmp.XMPException"></exception> private void SerializeCanonicalRDFSchema(XMPNode schemaNode, int level) { // Write each of the schema's actual properties. for (Iterator it = schemaNode.IterateChildren(); it.HasNext(); ) { XMPNode propNode = (XMPNode)it.Next(); SerializeCanonicalRDFProperty(propNode, options.GetUseCanonicalFormat(), false, level + 2); } } /// <summary>Writes all used namespaces of the subtree in node to the output.</summary> /// <remarks> /// Writes all used namespaces of the subtree in node to the output. /// The subtree is recursivly traversed. /// </remarks> /// <param name="node">the root node of the subtree</param> /// <param name="usedPrefixes">a set containing currently used prefixes</param> /// <param name="indent">the current indent level</param> /// <exception cref="System.IO.IOException">Forwards all writer exceptions.</exception> private void DeclareUsedNamespaces(XMPNode node, ICollection<object> usedPrefixes, int indent) { if (node.GetOptions().IsSchemaNode()) { // The schema node name is the URI, the value is the prefix. string prefix = Sharpen.Runtime.Substring(node.GetValue(), 0, node.GetValue().Length - 1); DeclareNamespace(prefix, node.GetName(), usedPrefixes, indent); } else { if (node.GetOptions().IsStruct()) { for (Iterator it = node.IterateChildren(); it.HasNext(); ) { XMPNode field = (XMPNode)it.Next(); DeclareNamespace(field.GetName(), null, usedPrefixes, indent); } } } for (Iterator it_1 = node.IterateChildren(); it_1.HasNext(); ) { XMPNode child = (XMPNode)it_1.Next(); DeclareUsedNamespaces(child, usedPrefixes, indent); } for (Iterator it_2 = node.IterateQualifier(); it_2.HasNext(); ) { XMPNode qualifier = (XMPNode)it_2.Next(); DeclareNamespace(qualifier.GetName(), null, usedPrefixes, indent); DeclareUsedNamespaces(qualifier, usedPrefixes, indent); } } /// <summary>Writes one namespace declaration to the output.</summary> /// <param name="prefix">a namespace prefix (without colon) or a complete qname (when namespace == null)</param> /// <param name="namespace">the a namespace</param> /// <param name="usedPrefixes">a set containing currently used prefixes</param> /// <param name="indent">the current indent level</param> /// <exception cref="System.IO.IOException">Forwards all writer exceptions.</exception> private void DeclareNamespace(string prefix, string @namespace, ICollection<object> usedPrefixes, int indent) { if (@namespace == null) { // prefix contains qname, extract prefix and lookup namespace with prefix QName qname = new QName(prefix); if (qname.HasPrefix()) { prefix = qname.GetPrefix(); // add colon for lookup @namespace = XMPMetaFactory.GetSchemaRegistry().GetNamespaceURI(prefix + ":"); // prefix w/o colon DeclareNamespace(prefix, @namespace, usedPrefixes, indent); } else { return; } } if (!usedPrefixes.Contains(prefix)) { WriteNewline(); WriteIndent(indent); Write("xmlns:"); Write(prefix); Write("=\""); Write(@namespace); Write('"'); usedPrefixes.Add(prefix); } } /// <summary>Start the outer rdf:Description element, including all needed xmlns attributes.</summary> /// <remarks> /// Start the outer rdf:Description element, including all needed xmlns attributes. /// Leave the element open so that the compact form can add property attributes. /// </remarks> /// <exception cref="System.IO.IOException">If the writing to</exception> private void StartOuterRDFDescription(XMPNode schemaNode, int level) { WriteIndent(level + 1); Write(RdfSchemaStart); WriteTreeName(); ICollection<object> usedPrefixes = new HashSet<object>(); usedPrefixes.Add("xml"); usedPrefixes.Add("rdf"); DeclareUsedNamespaces(schemaNode, usedPrefixes, level + 3); Write('>'); WriteNewline(); } /// <summary>Write the </rdf:Description> end tag.</summary> /// <exception cref="System.IO.IOException"/> private void EndOuterRDFDescription(int level) { WriteIndent(level + 1); Write(RdfSchemaEnd); WriteNewline(); } /// <summary>Recursively handles the "value" for a node.</summary> /// <remarks> /// Recursively handles the "value" for a node. It does not matter if it is a /// top level property, a field of a struct, or an item of an array. The /// indent is that for the property element. An xml:lang qualifier is written /// as an attribute of the property start tag, not by itself forcing the /// qualified property form. The patterns below mostly ignore attribute /// qualifiers like xml:lang. Except for the one struct case, attribute /// qualifiers don't affect the output form. /// <blockquote> /// <pre> /// &lt;ns:UnqualifiedSimpleProperty&gt;value&lt;/ns:UnqualifiedSimpleProperty&gt; /// &lt;ns:UnqualifiedStructProperty&gt; (If no rdf:resource qualifier) /// &lt;rdf:Description&gt; /// ... Fields, same forms as top level properties /// &lt;/rdf:Description&gt; /// &lt;/ns:UnqualifiedStructProperty&gt; /// &lt;ns:ResourceStructProperty rdf:resource=&quot;URI&quot; /// ... Fields as attributes /// &gt; /// &lt;ns:UnqualifiedArrayProperty&gt; /// &lt;rdf:Bag&gt; or Seq or Alt /// ... Array items as rdf:li elements, same forms as top level properties /// &lt;/rdf:Bag&gt; /// &lt;/ns:UnqualifiedArrayProperty&gt; /// &lt;ns:QualifiedProperty&gt; /// &lt;rdf:Description&gt; /// &lt;rdf:value&gt; ... Property &quot;value&quot; following the unqualified /// forms ... &lt;/rdf:value&gt; /// ... Qualifiers looking like named struct fields /// &lt;/rdf:Description&gt; /// &lt;/ns:QualifiedProperty&gt; /// </pre> /// </blockquote> /// </remarks> /// <param name="node">the property node</param> /// <param name="emitAsRDFValue">property shall be rendered as attribute rather than tag</param> /// <param name="useCanonicalRDF"> /// use canonical form with inner description tag or /// the compact form with rdf:ParseType=&quot;resource&quot; attribute. /// </param> /// <param name="indent">the current indent level</param> /// <exception cref="System.IO.IOException">Forwards all writer exceptions.</exception> /// <exception cref="Com.Adobe.Xmp.XMPException">If &quot;rdf:resource&quot; and general qualifiers are mixed.</exception> private void SerializeCanonicalRDFProperty(XMPNode node, bool useCanonicalRDF, bool emitAsRDFValue, int indent) { bool emitEndTag = true; bool indentEndTag = true; // Determine the XML element name. Open the start tag with the name and // attribute qualifiers. string elemName = node.GetName(); if (emitAsRDFValue) { elemName = "rdf:value"; } else { if (XMPConstConstants.ArrayItemName.Equals(elemName)) { elemName = "rdf:li"; } } WriteIndent(indent); Write('<'); Write(elemName); bool hasGeneralQualifiers = false; bool hasRDFResourceQual = false; for (Iterator it = node.IterateQualifier(); it.HasNext(); ) { XMPNode qualifier = (XMPNode)it.Next(); if (!RdfAttrQualifier.Contains(qualifier.GetName())) { hasGeneralQualifiers = true; } else { hasRDFResourceQual = "rdf:resource".Equals(qualifier.GetName()); if (!emitAsRDFValue) { Write(' '); Write(qualifier.GetName()); Write("=\""); AppendNodeValue(qualifier.GetValue(), true); Write('"'); } } } // Process the property according to the standard patterns. if (hasGeneralQualifiers && !emitAsRDFValue) { // This node has general, non-attribute, qualifiers. Emit using the // qualified property form. // ! The value is output by a recursive call ON THE SAME NODE with // emitAsRDFValue set. if (hasRDFResourceQual) { throw new XMPException("Can't mix rdf:resource and general qualifiers", XMPErrorConstants.Badrdf); } // Change serialization to canonical format with inner rdf:Description-tag // depending on option if (useCanonicalRDF) { Write(">"); WriteNewline(); indent++; WriteIndent(indent); Write(RdfStructStart); Write(">"); } else { Write(" rdf:parseType=\"Resource\">"); } WriteNewline(); SerializeCanonicalRDFProperty(node, useCanonicalRDF, true, indent + 1); for (Iterator it_1 = node.IterateQualifier(); it_1.HasNext(); ) { XMPNode qualifier = (XMPNode)it_1.Next(); if (!RdfAttrQualifier.Contains(qualifier.GetName())) { SerializeCanonicalRDFProperty(qualifier, useCanonicalRDF, false, indent + 1); } } if (useCanonicalRDF) { WriteIndent(indent); Write(RdfStructEnd); WriteNewline(); indent--; } } else { // This node has no general qualifiers. Emit using an unqualified form. if (!node.GetOptions().IsCompositeProperty()) { // This is a simple property. if (node.GetOptions().IsURI()) { Write(" rdf:resource=\""); AppendNodeValue(node.GetValue(), true); Write("\"/>"); WriteNewline(); emitEndTag = false; } else { if (node.GetValue() == null || string.Empty.Equals(node.GetValue())) { Write("/>"); WriteNewline(); emitEndTag = false; } else { Write('>'); AppendNodeValue(node.GetValue(), false); indentEndTag = false; } } } else { if (node.GetOptions().IsArray()) { // This is an array. Write('>'); WriteNewline(); EmitRDFArrayTag(node, true, indent + 1); if (node.GetOptions().IsArrayAltText()) { XMPNodeUtils.NormalizeLangArray(node); } for (Iterator it_1 = node.IterateChildren(); it_1.HasNext(); ) { XMPNode child = (XMPNode)it_1.Next(); SerializeCanonicalRDFProperty(child, useCanonicalRDF, false, indent + 2); } EmitRDFArrayTag(node, false, indent + 1); } else { if (!hasRDFResourceQual) { // This is a "normal" struct, use the rdf:parseType="Resource" form. if (!node.HasChildren()) { // Change serialization to canonical format with inner rdf:Description-tag // if option is set if (useCanonicalRDF) { Write(">"); WriteNewline(); WriteIndent(indent + 1); Write(RdfEmptyStruct); } else { Write(" rdf:parseType=\"Resource\"/>"); emitEndTag = false; } WriteNewline(); } else { // Change serialization to canonical format with inner rdf:Description-tag // if option is set if (useCanonicalRDF) { Write(">"); WriteNewline(); indent++; WriteIndent(indent); Write(RdfStructStart); Write(">"); } else { Write(" rdf:parseType=\"Resource\">"); } WriteNewline(); for (Iterator it_1 = node.IterateChildren(); it_1.HasNext(); ) { XMPNode child = (XMPNode)it_1.Next(); SerializeCanonicalRDFProperty(child, useCanonicalRDF, false, indent + 1); } if (useCanonicalRDF) { WriteIndent(indent); Write(RdfStructEnd); WriteNewline(); indent--; } } } else { // This is a struct with an rdf:resource attribute, use the // "empty property element" form. for (Iterator it_1 = node.IterateChildren(); it_1.HasNext(); ) { XMPNode child = (XMPNode)it_1.Next(); if (!CanBeRDFAttrProp(child)) { throw new XMPException("Can't mix rdf:resource and complex fields", XMPErrorConstants.Badrdf); } WriteNewline(); WriteIndent(indent + 1); Write(' '); Write(child.GetName()); Write("=\""); AppendNodeValue(child.GetValue(), true); Write('"'); } Write("/>"); WriteNewline(); emitEndTag = false; } } } } // Emit the property element end tag. if (emitEndTag) { if (indentEndTag) { WriteIndent(indent); } Write("</"); Write(elemName); Write('>'); WriteNewline(); } } /// <summary>Writes the array start and end tags.</summary> /// <param name="arrayNode">an array node</param> /// <param name="isStartTag">flag if its the start or end tag</param> /// <param name="indent">the current indent level</param> /// <exception cref="System.IO.IOException">forwards writer exceptions</exception> private void EmitRDFArrayTag(XMPNode arrayNode, bool isStartTag, int indent) { if (isStartTag || arrayNode.HasChildren()) { WriteIndent(indent); Write(isStartTag ? "<rdf:" : "</rdf:"); if (arrayNode.GetOptions().IsArrayAlternate()) { Write("Alt"); } else { if (arrayNode.GetOptions().IsArrayOrdered()) { Write("Seq"); } else { Write("Bag"); } } if (isStartTag && !arrayNode.HasChildren()) { Write("/>"); } else { Write(">"); } WriteNewline(); } } /// <summary>Serializes the node value in XML encoding.</summary> /// <remarks> /// Serializes the node value in XML encoding. Its used for tag bodies and /// attributes. <em>Note:</em> The attribute is always limited by quotes, /// thats why <code>&amp;apos;</code> is never serialized. <em>Note:</em> /// Control chars are written unescaped, but if the user uses others than tab, LF /// and CR the resulting XML will become invalid. /// </remarks> /// <param name="value">the value of the node</param> /// <param name="forAttribute">flag if value is an attribute value</param> /// <exception cref="System.IO.IOException"/> private void AppendNodeValue(string value, bool forAttribute) { if (value == null) { value = string.Empty; } Write(Utils.EscapeXML(value, forAttribute, true)); } /// <summary> /// A node can be serialized as RDF-Attribute, if it meets the following conditions: /// <ul> /// <li>is not array item /// <li>don't has qualifier /// <li>is no URI /// <li>is no composite property /// </ul> /// </summary> /// <param name="node">an XMPNode</param> /// <returns>Returns true if the node serialized as RDF-Attribute</returns> private bool CanBeRDFAttrProp(XMPNode node) { return !node.HasQualifier() && !node.GetOptions().IsURI() && !node.GetOptions().IsCompositeProperty() && !XMPConstConstants.ArrayItemName.Equals(node.GetName()); } /// <summary>Writes indents and automatically includes the baseindend from the options.</summary> /// <param name="times">number of indents to write</param> /// <exception cref="System.IO.IOException">forwards exception</exception> private void WriteIndent(int times) { for (int i = options.GetBaseIndent() + times; i > 0; i--) { writer.Write(options.GetIndent()); } } /// <summary>Writes a char to the output.</summary> /// <param name="c">a char</param> /// <exception cref="System.IO.IOException">forwards writer exceptions</exception> private void Write(int c) { writer.Write(c); } /// <summary>Writes a String to the output.</summary> /// <param name="str">a String</param> /// <exception cref="System.IO.IOException">forwards writer exceptions</exception> private void Write(string str) { writer.Write(str); } /// <summary>Writes an amount of chars, mostly spaces</summary> /// <param name="number">number of chars</param> /// <param name="c">a char</param> /// <exception cref="System.IO.IOException"/> private void WriteChars(int number, char c) { for (; number > 0; number--) { writer.Write(c); } } /// <summary>Writes a newline according to the options.</summary> /// <exception cref="System.IO.IOException">Forwards exception</exception> private void WriteNewline() { writer.Write(options.GetNewline()); } } }
// -------------------------------------------------------------------------------------------- #region // Copyright (c) 2013, SIL International. // <copyright from='2003' to='2013' company='SIL International'> // Copyright (c) 2013, SIL International. // // Distributable under the terms of the MIT License (http://sil.mit-license.org/) // </copyright> #endregion // // File: ScrPassageControl.cs // -------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Media; using System.Windows.Forms; using System.Windows.Forms.VisualStyles; using SIL.PlatformUtilities; using SIL.Scripture; using SIL.Windows.Forms.Extensions; using SIL.Windows.Forms.FileDialogExtender; namespace SIL.Windows.Forms.Scripture { /// <summary> /// ScrPassageControl. /// </summary> public class ScrPassageControl : UserControl, IMessageFilter { #region Data members private const int kButtonWidthOnToolstrip = 11; /// <summary>The string that separates chapter numbers from verse numbers.</summary> public const string ChapterVerseSepr = ":"; private IContainer components; private bool m_mouseDown = false; private bool m_buttonHot = false; private bool m_textBoxHot = false; /// <summary>The object that provides all the information about book names and abbreviations</summary> protected MultilingScrBooks m_mulScrBooks; /// <summary>The versification system to use</summary> protected IScrVers m_versification; /// <summary></summary> protected Form m_dropdownForm; private BookLabel[] m_bookLabels; private List<int> m_availableBookIds; //array of available book nums private BCVRef m_scRef; private int[] m_rgnEncodings; private bool m_fParentIsToolstrip = false; /// <summary></summary> protected TextBox txtScrRef; private ToolTip toolTip1; /// <summary></summary> protected Panel btnScrPsgDropDown; private string m_errorCaption; /// <summary></summary> public event PassageChangedHandler PassageChanged; /// <summary></summary> public delegate void PassageChangedHandler(BCVRef newReference); #endregion #region Construction, Destruction, and initialization /// ------------------------------------------------------------------------------------ /// <summary> /// Constructor /// </summary> /// ------------------------------------------------------------------------------------ public ScrPassageControl() { SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.DoubleBuffer | ControlStyles.UserPaint | ControlStyles.ResizeRedraw, true); // This call is required by the Windows.Forms Form Designer. InitializeComponent(); if (DesignMode) return; m_mulScrBooks = new MultilingScrBooks(); m_dropdownForm = null; if (!Platform.IsWindows) { // Setting MinumumSize allows mono's buggy ToolStrip layout of ToolStripControlHost's to work. MinimumSize = new Size(100, 20); } } /// ------------------------------------------------------------------------------------ /// <summary> /// Initialization following the default constructor. /// </summary> /// <param name="reference">Initial reference</param> /// <param name="versification">The versification to use if scrProj is not set.</param> /// ------------------------------------------------------------------------------------ public void Initialize(BCVRef reference, IScrVers versification) { Initialize(reference, versification, null); } /// ------------------------------------------------------------------------------------ /// <summary> /// Initialization following the default constructor, with constrained set of books to /// display. /// </summary> /// <param name="reference">Initial reference</param> /// <param name="versification">The versification to use if scrProj is not set.</param> /// <param name="availableBooks">Array of canonical book IDs to include</param> /// ------------------------------------------------------------------------------------ public void Initialize(BCVRef reference, IScrVers versification, int[] availableBooks) { m_versification = versification; m_availableBookIds = null; if (availableBooks != null) { Array.Sort(availableBooks); m_availableBookIds = availableBooks.Distinct().ToList(); InitializeBookLabels(); } else BookLabels = m_mulScrBooks.BookLabels; if (reference != null && !reference.IsEmpty) ScReference = reference; else if (m_bookLabels != null && m_bookLabels.Length > 0) ScReference = new BCVRef(m_bookLabels[0].BookNum, 1, 1); else ScReference = BCVRef.Empty; Reference = m_mulScrBooks.GetRefString(ScReference); } /// ------------------------------------------------------------------------------------ /// <summary> /// Clean up any resources being used. /// </summary> /// ------------------------------------------------------------------------------------ protected override void Dispose(bool disposing) { Debug.WriteLineIf(!disposing, "****** Missing Dispose() call for " + GetType().Name + ". ****** "); // Must not be run more than once. if (IsDisposed) return; if (disposing) { // Just in case we didn't remove our message filter (which would now be invalid // since we would be disposed) when losing focus, we remove it here (TE-8297) Application.RemoveMessageFilter(this); if (components != null) components.Dispose(); if (m_dropdownForm != null) m_dropdownForm.Dispose(); } m_mulScrBooks = null; m_rgnEncodings = null; m_availableBookIds = null; m_bookLabels = null; m_dropdownForm = null; base.Dispose( disposing ); } /// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// ------------------------------------------------------------------------------------ private void InitializeBookLabels() { // Get list of books in import files BookLabel[] bookNames = new BookLabel[m_availableBookIds.Count]; int iName = 0; foreach (int bookOrd in m_availableBookIds) bookNames[iName++] = new BookLabel(m_mulScrBooks.GetBookName(bookOrd), bookOrd); BookLabels = bookNames; } #endregion #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ScrPassageControl)); this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); this.txtScrRef = new System.Windows.Forms.TextBox(); this.btnScrPsgDropDown = new System.Windows.Forms.Panel(); this.SuspendLayout(); // // txtScrRef // resources.ApplyResources(this.txtScrRef, "txtScrRef"); this.txtScrRef.BorderStyle = System.Windows.Forms.BorderStyle.None; this.txtScrRef.Name = "txtScrRef"; this.txtScrRef.MouseLeave += new System.EventHandler(this.txtScrRef_MouseLeave); this.txtScrRef.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtScrRef_KeyDown); this.txtScrRef.Leave += new System.EventHandler(this.txtScrRef_LostFocus); this.txtScrRef.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtScrRef_KeyPress); this.txtScrRef.Enter += new System.EventHandler(this.txtScrRef_GotFocus); this.txtScrRef.MouseEnter += new System.EventHandler(this.txtScrRef_MouseEnter); // // btnScrPsgDropDown // this.btnScrPsgDropDown.BackColor = System.Drawing.SystemColors.Highlight; resources.ApplyResources(this.btnScrPsgDropDown, "btnScrPsgDropDown"); this.btnScrPsgDropDown.Name = "btnScrPsgDropDown"; this.btnScrPsgDropDown.MouseLeave += new System.EventHandler(this.btnScrPsgDropDown_MouseLeave); this.btnScrPsgDropDown.Paint += new System.Windows.Forms.PaintEventHandler(this.btnScrPsgDropDown_Paint); this.btnScrPsgDropDown.MouseDown += new System.Windows.Forms.MouseEventHandler(this.btnScrPsgDropDown_MouseDown); this.btnScrPsgDropDown.MouseUp += new System.Windows.Forms.MouseEventHandler(this.btnScrPsgDropDown_MouseUp); this.btnScrPsgDropDown.MouseEnter += new System.EventHandler(this.btnScrPsgDropDown_MouseEnter); // // ScrPassageControl // this.BackColor = System.Drawing.SystemColors.Window; this.Controls.Add(this.btnScrPsgDropDown); this.Controls.Add(this.txtScrRef); this.Name = "ScrPassageControl"; resources.ApplyResources(this, "$this"); this.ResumeLayout(false); this.PerformLayout(); } #endregion #region Properties /// ------------------------------------------------------------------------------------ /// <summary> /// Gets or sets the caption to use when displaying an error in a message box. /// </summary> /// ------------------------------------------------------------------------------------ [SuppressMessage("Gendarme.Rules.Correctness", "EnsureLocalDisposalRule", Justification="FindForm() returns a reference")] public string ErrorCaption { get { if (m_errorCaption != null) return m_errorCaption; Form owningForm = FindForm(); return owningForm == null ? string.Empty : owningForm.Text; } set { m_errorCaption = value; } } /// ------------------------------------------------------------------------------------ /// <summary> /// Gets or sets the contents of the text portion of the control. /// </summary> /// ------------------------------------------------------------------------------------ [Description("The contents of the text portion of the control.")] public virtual string Reference { get {return txtScrRef.Text;} set {txtScrRef.Text = value;} } /// ------------------------------------------------------------------------------------ /// <summary> /// Gets or sets the array containing the primary and secondary encodings. /// </summary> /// ------------------------------------------------------------------------------------ [Description("The array containing the primary & secondary encodings.")] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int[] WritingSystems { get {return m_rgnEncodings;} set {m_rgnEncodings = value;} } /// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// ------------------------------------------------------------------------------------ [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public MultilingScrBooks MulScrBooks { get {return m_mulScrBooks;} } /// ------------------------------------------------------------------------------------ /// <summary> /// Gets or sets the Scripture Reference. /// </summary> /// ------------------------------------------------------------------------------------ [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public BCVRef ScReference { get { return (m_scRef == null) ? null : new BCVRef(m_scRef); } set { m_scRef = new BCVRef(value); if (m_scRef.Valid) Reference = m_scRef.AsString; } } /// ------------------------------------------------------------------------------------ /// <summary> /// Gets or sets the Scripture book "labels" (i.e., the names or abbreviations that /// appear in the UI). If setter is used, the labels supplied should be localized or /// invariant. /// </summary> /// ------------------------------------------------------------------------------------ [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public BookLabel[] BookLabels { get {return m_bookLabels;} set {m_bookLabels = value;} } /// ------------------------------------------------------------------------------------ /// <summary> /// Return a value indicating whether or not the text in the control represents a /// valid Scripture reference. /// </summary> /// ------------------------------------------------------------------------------------ [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool Valid { get { return m_mulScrBooks.ParseRefString(Reference).Valid; } } /// ------------------------------------------------------------------------------------ /// <summary> /// Gets or sets the tooltip for the scripture passage control. /// </summary> /// ------------------------------------------------------------------------------------ [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string ToolTip { get {return toolTip1.GetToolTip(this);} set { if (value != null) { toolTip1.SetToolTip(this, value); toolTip1.SetToolTip(txtScrRef, value); toolTip1.SetToolTip(btnScrPsgDropDown, value); } } } #endregion #region IMessageFilter Members /// ------------------------------------------------------------------------------------ /// <summary> /// Because Del and Ctrl+A are menu item shortcuts, if our ref. text box has focus, /// then we need to trap them before the menu system gets a crack at them. /// </summary> /// ------------------------------------------------------------------------------------ public bool PreFilterMessage(ref Message m) { if (m.Msg == (int)Msg.WM_KEYDOWN) { if (m.WParam.ToInt32() == (int)Keys.Delete) { // There's probably a better way of passing this on to the // text box, but I'm hard-pressed to figure it out now. txtScrRef.SendMessage(m.Msg, m.WParam.ToInt32(), m.LParam.ToInt32()); return true; } if (m.WParam.ToInt32() == (int)Keys.A && Control.ModifierKeys == Keys.Control) { txtScrRef.SelectAll(); return true; } } return false; } #endregion #region Overriden methods /// ------------------------------------------------------------------------------------ /// <summary> /// Make sure the panel control behind the text box takes on the same back color as the /// text box. /// </summary> /// ------------------------------------------------------------------------------------ protected override void OnEnabledChanged(EventArgs e) { base.OnEnabledChanged(e); BackColor = (this.Enabled ? txtScrRef.BackColor : SystemColors.Control); } /// ------------------------------------------------------------------------------------ /// <summary> /// Determine whether or not this control has been placed on a toolstrip control. /// </summary> /// ------------------------------------------------------------------------------------ protected override void OnParentChanged(EventArgs e) { base.OnParentChanged(e); Control parent = Parent; // Determine whether or not the control is hosted on a toolstrip. while (parent != null) { if (parent is ToolStrip) { m_fParentIsToolstrip = true; DockPadding.All = 1; btnScrPsgDropDown.Width = kButtonWidthOnToolstrip; MouseEnter += txtScrRef_MouseEnter; MouseLeave += txtScrRef_MouseLeave; SizeChanged += HandleSizeChanged; return; } parent = parent.Parent; } m_fParentIsToolstrip = false; using (TextBox txtTmp = new TextBox()) txtScrRef.Font = txtTmp.Font.Clone() as Font; DockPadding.All = (Application.RenderWithVisualStyles ? SystemInformation.BorderSize.Width : SystemInformation.Border3DSize.Width); btnScrPsgDropDown.Dock = DockStyle.Right; } /// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// ------------------------------------------------------------------------------------ void HandleSizeChanged(object sender, EventArgs e) { if (m_fParentIsToolstrip) { // Make sure the height of the control when it's on a toolstrip // doesn't exceed the height of a normal toolstrip combo. box. SizeChanged -= HandleSizeChanged; using (ToolStripComboBox cboTmp = new ToolStripComboBox()) { txtScrRef.Font = cboTmp.Font.Clone() as Font; Height = cboTmp.Height; } SizeChanged += HandleSizeChanged; } } /// ------------------------------------------------------------------------------------ /// <summary> /// Make sure the dropdown control isn't left hanging around after this control goes /// away. /// </summary> /// ------------------------------------------------------------------------------------ protected override void OnHandleDestroyed(EventArgs e) { if (m_dropdownForm != null && m_dropdownForm.Visible) m_dropdownForm.Close(); } #endregion #region Misc. Methods /// ------------------------------------------------------------------------------------ /// <summary> /// Owners of this control may use this method to display a message box telling /// the user his specified Scripture reference is invalid. This is a default /// message and is available for convenience. Alternatively, the owner may choose /// to display a different message when the Scripture reference is invalid. /// (Note: use the Valid property to determine whether or not the specified /// Scripture reference is valid.) /// </summary> /// ------------------------------------------------------------------------------------ [SuppressMessage("Gendarme.Rules.Correctness", "EnsureLocalDisposalRule", Justification="FindForm() returns a reference")] public void DisplayErrorMessage() { MessageBox.Show(FindForm(), string.Format(Properties.Resources.kstidInvalidScrRefEntered, Reference), ErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); } /// ------------------------------------------------------------------------------------ /// <summary> /// Resolve the reference specified in the text box /// </summary> /// ------------------------------------------------------------------------------------ public void ResolveReference() { // Trim leading and trailing spaces from the text box Reference = Reference.Trim(); // Get the first reference that matches. BCVRef newScRef = ParseRefString(Reference); // make sure that the book is valid if (newScRef.Book == 0) { int spacePos = Reference.IndexOf(" "); if (spacePos != -1) txtScrRef.Select(0, spacePos); SystemSounds.Beep.Play(); return; } // Use the versification scheme to make sure the chapter number is valid. int lastChapter = m_versification.GetLastChapter(newScRef.Book); if (newScRef.Chapter > lastChapter) { newScRef.Chapter = lastChapter; newScRef.Verse = 1; newScRef.Verse = m_versification.GetLastVerse(newScRef.Book, lastChapter); } else { int lastVerse = m_versification.GetLastVerse(newScRef.Book, newScRef.Chapter); // Make sure the verse number is valid if (newScRef.Verse > lastVerse) newScRef.Verse = lastVerse; } // set the text of the control to the resolved reference Reference = newScRef.AsString; if (newScRef.BBCCCVVV != ScReference.BBCCCVVV) { ScReference = newScRef; InvokePassageChanged(newScRef); } else { // Since the user has pressed enter we have to set the focus back to the // text, even if the passage didn't change. // HACK (EberhardB): This is a little bit of a hack. The passage hasn't actually // changed, but this is the easiest way to put the focus back to where it belongs. InvokePassageChanged(BCVRef.Empty); } } /// ------------------------------------------------------------------------------------ /// <summary> /// Parses the user typed in string. Creates and returns a BCVRef object. /// </summary> /// <param name="sTextToBeParsed">Reference string the user types in.</param> /// <returns>The generated scReference object.</returns> /// ------------------------------------------------------------------------------------ public BCVRef ParseRefString(string sTextToBeParsed) { if (m_availableBookIds == null) return m_mulScrBooks.ParseRefString(sTextToBeParsed); var scrRef = new BCVRef(); if (m_availableBookIds.Count == 0) return scrRef; // Search for a reference that is actually in the database.) for (var startBook = 0; startBook < 66; ) { var prevStartBook = startBook; scrRef = m_mulScrBooks.ParseRefString(sTextToBeParsed, startBook); // If the book is in the Scripture project // (or if we get the same book back from the parse method or go back to the start)... if (m_availableBookIds.Contains(scrRef.Book) || prevStartBook == scrRef.Book || prevStartBook > scrRef.Book) { break; // we're finished searching. } startBook = scrRef.Book; // start searching in next book returned. } // If the Scripture reference is not in the project (and we have books)... if (!m_availableBookIds.Contains(scrRef.Book)) { // set it to the first book in the project. return new BCVRef(m_availableBookIds[0], 1, 1); } return scrRef; } /// ------------------------------------------------------------------------------------ /// <summary> /// Determines whether the specified BCVRef is in the list of available books. /// </summary> /// <param name="scrRef">The given BCVRef</param> /// <returns><c>true</c> if the book reference is in the list of available books; /// otherwise, <c>false</c>. /// </returns> /// ------------------------------------------------------------------------------------ public bool IsReferenceValid(BCVRef scrRef) { return BookLabels != null && BookLabels.Any(bookLabel => bookLabel.BookNum == scrRef.Book); } /// ------------------------------------------------------------------------------------ /// <summary> /// Invoke the PassageChanged event /// </summary> /// <param name="reference">The reference.</param> /// ------------------------------------------------------------------------------------ protected virtual void InvokePassageChanged(BCVRef reference) { if (PassageChanged != null) PassageChanged(new BCVRef(reference)); } #endregion #region Drop-down handling methods /// ------------------------------------------------------------------------------------ /// <summary> /// Create a new <see cref="ScrPassageDropDown"/> object /// </summary> /// <param name="owner">The ScrPassageControl that will own the drop-down control</param> /// ------------------------------------------------------------------------------------ protected virtual ScrPassageDropDown CreateScrPassageDropDown(ScrPassageControl owner) { return new ScrPassageDropDown(owner, false, m_versification); } /// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// ------------------------------------------------------------------------------------ [SuppressMessage("Gendarme.Rules.Correctness", "EnsureLocalDisposalRule", Justification="spDropDown gets assigned to m_dropdownForm and disposed there")] private void DisplayDropDown() { // Create, position, and display the drop-down form. ScrPassageDropDown spDropDown = CreateScrPassageDropDown(this); PositionDropDown(spDropDown); spDropDown.Closed += DropDownClosed; spDropDown.BookSelected += DropDownBookSelected; spDropDown.ChapterSelected += DropDownChapterSelected; m_dropdownForm = spDropDown; m_dropdownForm.Show(); // Select the book portion of the reference in the text box. txtScrRef.HideSelection = false; int i = Reference.LastIndexOf(' '); if (i >= 0) { txtScrRef.SelectionStart = 0; txtScrRef.SelectionLength = i; } } /// ------------------------------------------------------------------------------------ /// <summary> /// Position the drop down control. /// </summary> /// ------------------------------------------------------------------------------------ private void PositionDropDown(ScrPassageDropDown dropDown) { Point screenPoint = PointToScreen(new Point(0, 0)); // If there is no room below the ScrPassageControl for the drop down then // position above, otherwise position below. if (DropDownShouldGoUp(screenPoint, dropDown)) screenPoint.Y -= dropDown.Height; else screenPoint.Y += Height; dropDown.DesktopLocation = screenPoint; // Make sure that the drop down fits on the screen. Rectangle rect = new Rectangle(dropDown.DesktopLocation, new Size(dropDown.Width, dropDown.Height)); ScreenHelper.EnsureVisibleRect(ref rect); dropDown.DesktopLocation = new Point(rect.Left, rect.Top); } /// ------------------------------------------------------------------------------------ /// <summary> /// Determine if the drop down should go above the ScrPassageControl or /// below it. /// </summary> /// <param name="screenPoint">point on the screen of the</param> /// <param name="dropDown">drop down control</param> /// <returns>true to go above, false to go below</returns> /// ------------------------------------------------------------------------------------ private bool DropDownShouldGoUp(Point screenPoint, ScrPassageDropDown dropDown) { // determine the usable space on the screen that contains the top left // corner of the ScrPassageControl. Rectangle rcAllowable = ScreenHelper.AdjustedWorkingArea(Screen.FromPoint(screenPoint)); // If there is not enough space to go down, then go up return (rcAllowable.Height - screenPoint.Y - Height - dropDown.Height < 0); } /// ------------------------------------------------------------------------------------ /// <summary> /// If the book has changed, parse the new reference and display it in the text box. /// </summary> /// ------------------------------------------------------------------------------------ protected virtual void DropDownBookSelected(int book) { if (ScReference.Book != book) { Reference = m_mulScrBooks.GetRefString(new BCVRef(book, 1, 1)); } // Select the chapter portion of the reference in the text box. int space = Reference.LastIndexOf(' '); int sepr = Reference.LastIndexOf(ChapterVerseSepr); if (space >= 0 && sepr >= 0 && sepr > space) { txtScrRef.SelectionStart = space + 1; txtScrRef.SelectionLength = sepr - space - 1; } } /// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// ------------------------------------------------------------------------------------ private void DropDownChapterSelected(int book, int chapter) { // If the book or chapter have changed, parse the new reference and display it // in the text box. if (ScReference.Book != book || ScReference.Chapter != chapter) { Reference = m_mulScrBooks.GetRefString(new BCVRef(book, chapter, 1)); } // Select the verse portion of the reference in the text box. int sepr = Reference.LastIndexOf(ChapterVerseSepr); if (sepr >= 0) { txtScrRef.SelectionStart = sepr + 1; txtScrRef.SelectionLength = Reference.Length - sepr; } } /// ------------------------------------------------------------------------------------ /// <summary> /// This is the method that the dropdown will call to notify me that it is closed. /// </summary> /// ------------------------------------------------------------------------------------ private void DropDownClosed(object sender, EventArgs e) { if (m_dropdownForm == null) return; bool fCanceled = ((ScrPassageDropDown)m_dropdownForm).Canceled; BCVRef curRef = ((ScrPassageDropDown)m_dropdownForm).CurrentScRef; m_dropdownForm.Dispose(); m_dropdownForm = null; // If the drop-down wasn't canceled, then save the reference chosen from it. // Otherwise, restore what the reference was before showing the drop-down. if (fCanceled) Reference = ScReference.AsString; else InvokePassageChanged(curRef); txtScrRef.Focus(); // If the user canceled the drop down we want to leave the focus in the combo box // - similar to a real combo box if (fCanceled) { txtScrRef.Focus(); Focus(); } txtScrRef.HideSelection = true; Invalidate(true); } #endregion #region Delegate methods /// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// ------------------------------------------------------------------------------------ private void txtScrRef_MouseEnter(object sender, EventArgs e) { m_textBoxHot = true; Invalidate(true); } /// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// ------------------------------------------------------------------------------------ private void txtScrRef_MouseLeave(object sender, EventArgs e) { m_textBoxHot = false; Invalidate(true); } /// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// ------------------------------------------------------------------------------------ protected void txtScrRef_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Down && (e.Modifiers & Keys.Alt) > 0) { // Show the drop-down e.Handled = true; HandleDropDown(); } else if (e.KeyCode == Keys.Escape) { e.Handled = true; Reference = ScReference.AsString; // HACK (EberhardB): This is a little bit of a hack. The passage hasn't actually // changed, but this is the easiest way to put the focus back to where it belongs. InvokePassageChanged(BCVRef.Empty); } } /// ------------------------------------------------------------------------------------ /// <summary> /// Handle the key press to look for Enter keys. /// </summary> /// ------------------------------------------------------------------------------------ protected void txtScrRef_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.Enter) { e.Handled = true; ResolveReference(); } } /// ------------------------------------------------------------------------------------ /// <summary> /// Handle the text box losing focus. Resolve the reference that has been typed in. /// </summary> /// ------------------------------------------------------------------------------------ private void txtScrRef_LostFocus(object sender, System.EventArgs e) { if (!m_fParentIsToolstrip) ResolveReference(); else { Application.RemoveMessageFilter(this); Reference = ScReference.AsString; } } /// ------------------------------------------------------------------------------------ /// <summary> /// When gaining the focus, highlight the entire text. /// </summary> /// ------------------------------------------------------------------------------------ private void txtScrRef_GotFocus(object sender, System.EventArgs e) { if (m_fParentIsToolstrip) Application.AddMessageFilter(this); txtScrRef.SelectAll(); } /// ------------------------------------------------------------------------------------ /// <summary> /// This will center the text box vertically within the control. /// </summary> /// ------------------------------------------------------------------------------------ protected override void OnResize(EventArgs e) { base.OnResize(e); int newTop = (Height - txtScrRef.Height) / 2; txtScrRef.Top = (newTop < 0 ? 0 : newTop); } /// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// ------------------------------------------------------------------------------------ protected override void OnPaint(PaintEventArgs e) { base.OnPaintBackground(e); if (m_fParentIsToolstrip) { PaintOnToolbar(e); return; } if (!Application.RenderWithVisualStyles) ControlPaint.DrawBorder3D(e.Graphics, ClientRectangle, Border3DStyle.Sunken); else { VisualStyleRenderer renderer; renderer = new VisualStyleRenderer(Enabled ? VisualStyleElement.TextBox.TextEdit.Normal : VisualStyleElement.TextBox.TextEdit.Disabled); renderer.DrawBackground(e.Graphics, ClientRectangle, e.ClipRectangle); // When the textbox background is drawn in normal mode (at least when the // theme is one of the standard XP themes), it's drawn with a white background // and not the System Window background color. Therefore, we need to create // a rectangle that doesn't include the border. Then fill it with the text // box's background color. Rectangle rc = renderer.GetBackgroundExtent(e.Graphics, ClientRectangle); int dx = (rc.Width - ClientRectangle.Width) / 2; int dy = (rc.Height - ClientRectangle.Height) / 2; rc = ClientRectangle; rc.Inflate(-dx, -dy); using (SolidBrush br = new SolidBrush(txtScrRef.BackColor)) e.Graphics.FillRectangle(br, rc); } } /// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// ------------------------------------------------------------------------------------ private void PaintOnToolbar(PaintEventArgs e) { if ((!m_textBoxHot && m_dropdownForm == null) || !Enabled) return; Rectangle rc = ClientRectangle; rc.Width--; rc.Height--; using (Pen pen = new Pen(ProfessionalColors.ButtonSelectedHighlightBorder)) { e.Graphics.DrawRectangle(pen, rc); Point pt1 = new Point(btnScrPsgDropDown.Left - 1, 0); Point pt2 = new Point(btnScrPsgDropDown.Left - 1, Height); e.Graphics.DrawLine(pen, pt1, pt2); } } /// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// ------------------------------------------------------------------------------------ private void btnScrPsgDropDown_Paint(object sender, PaintEventArgs e) { if (m_fParentIsToolstrip) { btnScrPsgDropDown_PaintOnToolstrip(e); return; } ButtonState state = ButtonState.Normal; VisualStyleElement element = VisualStyleElement.ComboBox.DropDownButton.Normal; if (!Enabled) { state = ButtonState.Inactive; element = VisualStyleElement.ComboBox.DropDownButton.Disabled; } else if (m_mouseDown) { state = ButtonState.Pushed; element = VisualStyleElement.ComboBox.DropDownButton.Pressed; } else if (m_buttonHot) element = VisualStyleElement.ComboBox.DropDownButton.Hot; if (!Application.RenderWithVisualStyles) PaintNonThemeButton(e.Graphics, state); else { VisualStyleRenderer renderer = new VisualStyleRenderer(element); renderer.DrawBackground(e.Graphics, btnScrPsgDropDown.ClientRectangle, e.ClipRectangle); } } /// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// ------------------------------------------------------------------------------------ private void btnScrPsgDropDown_PaintOnToolstrip(PaintEventArgs e) { Color clr1 = (Application.RenderWithVisualStyles ? ProfessionalColors.ToolStripGradientBegin : SystemColors.Control); Color clr2 = (Application.RenderWithVisualStyles ? ProfessionalColors.ToolStripGradientEnd : SystemColors.Control); if (!Enabled) { clr1 = SystemColors.Control; clr2 = SystemColors.Control; } else if (m_mouseDown || m_dropdownForm != null) { clr1 = ProfessionalColors.ButtonPressedGradientBegin; clr2 = ProfessionalColors.ButtonPressedGradientEnd; } else if (m_textBoxHot && Application.RenderWithVisualStyles) { clr1 = ProfessionalColors.ButtonSelectedGradientBegin; clr2 = ProfessionalColors.ButtonSelectedGradientEnd; } using (LinearGradientBrush br = new LinearGradientBrush( btnScrPsgDropDown.ClientRectangle, clr1, clr2, LinearGradientMode.Vertical)) { e.Graphics.FillRectangle(br, btnScrPsgDropDown.ClientRectangle); } e.Graphics.DrawImageUnscaledAndClipped(Properties.Resources.DropDownArrowNarrow, btnScrPsgDropDown.ClientRectangle); } /// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// ------------------------------------------------------------------------------------ private void PaintNonThemeButton(Graphics graphics, ButtonState state) { ControlPaint.DrawButton(graphics, btnScrPsgDropDown.ClientRectangle, state); var arrow = Properties.Resources.DropDownArrowWide; var x = btnScrPsgDropDown.ClientRectangle.Size.Width / 2 - arrow.Width / 2; var y = btnScrPsgDropDown.ClientRectangle.Size.Height / 2 - arrow.Height / 2; if (Enabled) graphics.DrawImage(arrow, x, y, arrow.Width, arrow.Height); else ControlPaint.DrawImageDisabled(graphics, arrow, x, y, Color.DarkGray); } /// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// ------------------------------------------------------------------------------------ private void btnScrPsgDropDown_MouseEnter(object sender, System.EventArgs e) { m_buttonHot = true; if (!m_fParentIsToolstrip) btnScrPsgDropDown.Invalidate(); else { m_textBoxHot = true; Invalidate(true); } } /// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// ------------------------------------------------------------------------------------ private void btnScrPsgDropDown_MouseLeave(object sender, System.EventArgs e) { m_buttonHot = false; if (!m_fParentIsToolstrip) btnScrPsgDropDown.Invalidate(); else { m_textBoxHot = false; Invalidate(true); } } /// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// ------------------------------------------------------------------------------------ protected void btnScrPsgDropDown_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { // Repaint the drop down button so that it displays pressed if (e.Button == MouseButtons.Left) { m_mouseDown = true; btnScrPsgDropDown.Invalidate(); } // Strangely enough - Windows drops the DropDown of a combo box in the mouse down, // not the click event as almost anywhere else in Windows. HandleDropDown(); } /// ------------------------------------------------------------------------------------ /// <summary> /// Display the drop down if it doesn't show, or close it if it does show. /// </summary> /// ------------------------------------------------------------------------------------ private void HandleDropDown() { if (m_dropdownForm != null) { // Close the drop-down form since it is already open. m_dropdownForm.Close(); m_dropdownForm = null; } else { // Save what's in the text box. txtScrRef.Tag = Reference; // Parse what the user has entered ScReference = m_mulScrBooks.ParseRefString(Reference); Reference = ScReference.AsString; DisplayDropDown(); } } /// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// ------------------------------------------------------------------------------------ private void btnScrPsgDropDown_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) { // Repaint the drop down button so that it displays normal instead of pressed if (m_mouseDown) { m_mouseDown = false; btnScrPsgDropDown.Invalidate(); } } //private void txtScrRef_MouseDown(object sender, MouseEventArgs e) //{ // ScrPassageDropDown scrPsgDropDown = m_dropdownForm as ScrPassageDropDown; // if (scrPsgDropDown != null && // (scrPsgDropDown.CurrentListType != ScrPassageDropDown.ListTypes.Books)) // { // // User partially selected a reference using the drop-down, so don't // // discard it. // txtScrRef.Text = scrPsgDropDown.CurrentScRef.AsString; // if (scrPsgDropDown.CurrentListType == ScrPassageDropDown.ListTypes.Chapters) // { // txtScrRef.SelectionStart = txtScrRef.Text.IndexOf(' ') + 1; // txtScrRef.SelectionLength = txtScrRef.Text.IndexOf(':') - txtScrRef.SelectionStart; // } // else if (scrPsgDropDown.CurrentListType == ScrPassageDropDown.ListTypes.Verses) // { // txtScrRef.SelectionStart = txtScrRef.Text.IndexOf(':') + 1; // txtScrRef.SelectionLength = txtScrRef.Text.Length - txtScrRef.SelectionStart; // } // } //} #endregion } }
using CorDebugInterop; using System; using System.Diagnostics; using BreakpointDef = nanoFramework.Tools.Debugger.WireProtocol.Commands.Debugging_Execution_BreakpointDef; namespace nanoFramework.Tools.VisualStudio.Debugger { public class CorDebugStepper : CorDebugBreakpointBase, ICorDebugStepper, ICorDebugStepper2 { //if a stepper steps into/out of a frame, need to update m_frame CorDebugFrame m_frame; CorDebugThread m_thread; COR_DEBUG_STEP_RANGE[] m_ranges; CorDebugStepReason m_reasonStopped; CorDebugIntercept m_interceptMask; public CorDebugStepper( CorDebugFrame frame ) : base( frame.AppDomain ) { Initialize( frame ); } private void Initialize( CorDebugFrame frame ) { m_frame = frame; m_thread = frame.Thread; InitializeBreakpointDef(); } private new ushort Kind { [System.Diagnostics.DebuggerHidden] get { return base.Kind; } set { if((value & BreakpointDef.c_STEP_IN) != 0) value |= BreakpointDef.c_STEP_OVER; value |= BreakpointDef.c_STEP_OUT | BreakpointDef.c_EXCEPTION_CAUGHT | BreakpointDef.c_THREAD_TERMINATED; base.Kind = value; } } private void InitializeBreakpointDef() { m_breakpointDef.m_depth = m_frame.DepthnanoCLR; m_breakpointDef.m_pid = m_thread.ID; if(m_ranges != null && m_ranges.Length > 0) { m_breakpointDef.m_IPStart = m_ranges[0].startOffset; m_breakpointDef.m_IPEnd = m_ranges[0].endOffset; } else { m_breakpointDef.m_IPStart = 0; m_breakpointDef.m_IPEnd = 0; } Dirty(); } private void Activate( ushort kind ) { InitializeBreakpointDef(); Debug.Assert( !this.Active ); //currently, we don't support ignoring filters in a step. cpde always seems to set this flag though. //So it may not be very important to support ignoring filters. Debug.Assert((m_interceptMask & CorDebugIntercept.INTERCEPT_EXCEPTION_FILTER) != 0); this.Kind = kind; this.Active = true; } public override bool ShouldBreak( BreakpointDef breakpointDef ) { bool fStop = true; CorDebugStepReason reason; //optimize, optimize, optimize No reason to get list of threads, and get thread stack for each step!!! ushort flags = breakpointDef.m_flags; int depthOld = (int)m_frame.DepthnanoCLR; int depthNew = (int)breakpointDef.m_depth; int dDepth = depthNew - depthOld; if((flags & BreakpointDef.c_STEP) != 0) { if ((flags & BreakpointDef.c_STEP_IN) != 0) { if (this.Process.Engine.Capabilities.ExceptionFilters && breakpointDef.m_depthExceptionHandler == BreakpointDef.c_DEPTH_STEP_INTERCEPT) { reason = CorDebugStepReason.STEP_INTERCEPT; } else { reason = CorDebugStepReason.STEP_CALL; } } else if ((flags & BreakpointDef.c_STEP_OVER) != 0) { reason = CorDebugStepReason.STEP_NORMAL; } else { if (this.Process.Engine.Capabilities.ExceptionFilters & breakpointDef.m_depthExceptionHandler == BreakpointDef.c_DEPTH_STEP_EXCEPTION_HANDLER) { reason = CorDebugStepReason.STEP_EXCEPTION_HANDLER; } else { reason = CorDebugStepReason.STEP_RETURN; } } } else if((flags & BreakpointDef.c_EXCEPTION_CAUGHT) != 0) { reason = CorDebugStepReason.STEP_EXCEPTION_HANDLER; if(dDepth > 0) fStop = false; else if(dDepth == 0) fStop = (this.Debugging_Execution_BreakpointDef.m_flags & BreakpointDef.c_STEP_OVER) != 0; else fStop = true; } else if ((flags & BreakpointDef.c_THREAD_TERMINATED) != 0) { reason = CorDebugStepReason.STEP_EXIT; this.Active = false; fStop = false; } else { Debug.Assert(false); throw new ApplicationException("Invalid stepper hit received"); } if(m_ranges != null && reason == CorDebugStepReason.STEP_NORMAL && breakpointDef.m_depth == this.Debugging_Execution_BreakpointDef.m_depth) { foreach(COR_DEBUG_STEP_RANGE range in m_ranges) { if(Utility.InRange( breakpointDef.m_IP, range.startOffset, range.endOffset - 1 )) { fStop = false; break; } } Debug.Assert( Utility.FImplies( m_ranges != null && m_ranges.Length == 1, fStop ) ); } if(fStop && reason != CorDebugStepReason.STEP_EXIT) { uint depth = breakpointDef.m_depth; CorDebugFrame frame = this.m_thread.Chain.GetFrameFromDepthnanoCLR( depth ); m_ranges = null; Initialize( frame ); //Will callback with wrong reason if stepping through internal calls????? //If we don't stop at an internal call, we need to reset/remember the range somehow? //This might be broken if a StepRange is called that causes us to enter an internal function fStop = !m_frame.Function.IsInternal; } m_reasonStopped = reason; return fStop; } public override void Hit( BreakpointDef breakpointDef ) { this.m_ranges = null; this.Active = false; this.Process.EnqueueEvent( new ManagedCallbacks.ManagedCallbackStepComplete( m_frame.Thread, this, m_reasonStopped ) ); } #region ICorDebugStepper Members int ICorDebugStepper.IsActive( out int pbActive ) { pbActive = Boolean.BoolToInt( this.Active ); return COM_HResults.S_OK; } int ICorDebugStepper.Deactivate() { this.Active = false; return COM_HResults.S_OK; } int ICorDebugStepper.StepRange( int bStepIn, COR_DEBUG_STEP_RANGE[] ranges, uint cRangeCount ) { //This isn't a correct method signature. However, since we don't support this (yet), it doesn't really matter //Add CorDebugStepper.StepRange is not implemented m_ranges = ranges; Debug.Assert( cRangeCount == 1 ); for(int iRange = 0; iRange < m_ranges.Length; iRange++) { COR_DEBUG_STEP_RANGE range = m_ranges[iRange]; m_ranges[iRange].startOffset = this.m_frame.Function.GetILnanoCLRFromILCLR( range.startOffset ); m_ranges[iRange].endOffset = this.m_frame.Function.GetILnanoCLRFromILCLR( range.endOffset ); } Activate( Boolean.IntToBool( bStepIn ) ? BreakpointDef.c_STEP_IN : BreakpointDef.c_STEP_OVER ); return COM_HResults.S_OK; } int ICorDebugStepper.SetUnmappedStopMask( CorDebugUnmappedStop mask ) { return COM_HResults.S_OK; } int ICorDebugStepper.SetInterceptMask( CorDebugIntercept mask ) { m_interceptMask = mask; return COM_HResults.S_OK; } int ICorDebugStepper.Step( int bStepIn ) { m_ranges = null; Activate( Boolean.IntToBool( bStepIn ) ? BreakpointDef.c_STEP_IN : BreakpointDef.c_STEP_OVER ); return COM_HResults.S_OK; } int ICorDebugStepper.SetRangeIL( int bIL ) { return COM_HResults.E_NOTIMPL; } int ICorDebugStepper.StepOut() { m_ranges = null; Activate( BreakpointDef.c_STEP_OUT ); return COM_HResults.S_OK; } #endregion #region ICorDebugStepper2 Members int ICorDebugStepper2.SetJMC( int fIsJMCStepper ) { // CorDebugStepper.SetJMC is not implemented bool fJMC = Boolean.IntToBool( fIsJMCStepper ); bool fJMCOld = (this.Debugging_Execution_BreakpointDef.m_flags & BreakpointDef.c_STEP_JMC) != 0; if(fJMC != fJMCOld) { if(fJMC) this.Debugging_Execution_BreakpointDef.m_flags |= BreakpointDef.c_STEP_JMC; else unchecked { this.Debugging_Execution_BreakpointDef.m_flags &= (ushort)(~BreakpointDef.c_STEP_JMC); } this.Dirty(); } return COM_HResults.S_OK; } #endregion } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections; using System.Globalization; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections.Generic; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json.Utilities { internal static class BufferUtils { public static char[] RentBuffer(IArrayPool<char> bufferPool, int minSize) { if (bufferPool == null) { return new char[minSize]; } char[] buffer = bufferPool.Rent(minSize); return buffer; } public static void ReturnBuffer(IArrayPool<char> bufferPool, char[] buffer) { if (bufferPool == null) { return; } bufferPool.Return(buffer); } public static char[] EnsureBufferSize(IArrayPool<char> bufferPool, int size, char[] buffer) { if (bufferPool == null) { return new char[size]; } if (buffer != null) { bufferPool.Return(buffer); } return bufferPool.Rent(size); } } internal static class JavaScriptUtils { internal static readonly bool[] SingleQuoteCharEscapeFlags = new bool[128]; internal static readonly bool[] DoubleQuoteCharEscapeFlags = new bool[128]; internal static readonly bool[] HtmlCharEscapeFlags = new bool[128]; private const int UnicodeTextLength = 6; static JavaScriptUtils() { IList<char> escapeChars = new List<char> { '\n', '\r', '\t', '\\', '\f', '\b', }; for (int i = 0; i < ' '; i++) { escapeChars.Add((char)i); } foreach (char escapeChar in escapeChars.Union(new[] { '\'' })) { SingleQuoteCharEscapeFlags[escapeChar] = true; } foreach (char escapeChar in escapeChars.Union(new[] { '"' })) { DoubleQuoteCharEscapeFlags[escapeChar] = true; } foreach (char escapeChar in escapeChars.Union(new[] { '"', '\'', '<', '>', '&' })) { HtmlCharEscapeFlags[escapeChar] = true; } } private const string EscapedUnicodeText = "!"; public static bool[] GetCharEscapeFlags(StringEscapeHandling stringEscapeHandling, char quoteChar) { if (stringEscapeHandling == StringEscapeHandling.EscapeHtml) { return HtmlCharEscapeFlags; } if (quoteChar == '"') { return DoubleQuoteCharEscapeFlags; } return SingleQuoteCharEscapeFlags; } public static bool ShouldEscapeJavaScriptString(string s, bool[] charEscapeFlags) { if (s == null) { return false; } foreach (char c in s) { if (c >= charEscapeFlags.Length || charEscapeFlags[c]) { return true; } } return false; } public static void WriteEscapedJavaScriptString(TextWriter writer, string s, char delimiter, bool appendDelimiters, bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, IArrayPool<char> bufferPool, ref char[] writeBuffer) { // leading delimiter if (appendDelimiters) { writer.Write(delimiter); } if (s != null) { int lastWritePosition = 0; for (int i = 0; i < s.Length; i++) { char c = s[i]; if (c < charEscapeFlags.Length && !charEscapeFlags[c]) { continue; } string escapedValue; switch (c) { case '\t': escapedValue = @"\t"; break; case '\n': escapedValue = @"\n"; break; case '\r': escapedValue = @"\r"; break; case '\f': escapedValue = @"\f"; break; case '\b': escapedValue = @"\b"; break; case '\\': escapedValue = @"\\"; break; case '\u0085': // Next Line escapedValue = @"\u0085"; break; case '\u2028': // Line Separator escapedValue = @"\u2028"; break; case '\u2029': // Paragraph Separator escapedValue = @"\u2029"; break; default: if (c < charEscapeFlags.Length || stringEscapeHandling == StringEscapeHandling.EscapeNonAscii) { if (c == '\'' && stringEscapeHandling != StringEscapeHandling.EscapeHtml) { escapedValue = @"\'"; } else if (c == '"' && stringEscapeHandling != StringEscapeHandling.EscapeHtml) { escapedValue = @"\"""; } else { if (writeBuffer == null || writeBuffer.Length < UnicodeTextLength) { writeBuffer = BufferUtils.EnsureBufferSize(bufferPool, UnicodeTextLength, writeBuffer); } StringUtils.ToCharAsUnicode(c, writeBuffer); // slightly hacky but it saves multiple conditions in if test escapedValue = EscapedUnicodeText; } } else { escapedValue = null; } break; } if (escapedValue == null) { continue; } bool isEscapedUnicodeText = string.Equals(escapedValue, EscapedUnicodeText); if (i > lastWritePosition) { int length = i - lastWritePosition + ((isEscapedUnicodeText) ? UnicodeTextLength : 0); int start = (isEscapedUnicodeText) ? UnicodeTextLength : 0; if (writeBuffer == null || writeBuffer.Length < length) { char[] newBuffer = BufferUtils.RentBuffer(bufferPool, length); // the unicode text is already in the buffer // copy it over when creating new buffer if (isEscapedUnicodeText) { Array.Copy(writeBuffer, newBuffer, UnicodeTextLength); } BufferUtils.ReturnBuffer(bufferPool, writeBuffer); writeBuffer = newBuffer; } s.CopyTo(lastWritePosition, writeBuffer, start, length - start); // write unchanged chars before writing escaped text writer.Write(writeBuffer, start, length - start); } lastWritePosition = i + 1; if (!isEscapedUnicodeText) { writer.Write(escapedValue); } else { writer.Write(writeBuffer, 0, UnicodeTextLength); } } if (lastWritePosition == 0) { // no escaped text, write entire string writer.Write(s); } else { int length = s.Length - lastWritePosition; if (writeBuffer == null || writeBuffer.Length < length) { writeBuffer = BufferUtils.EnsureBufferSize(bufferPool, length, writeBuffer); } s.CopyTo(lastWritePosition, writeBuffer, 0, length); // write remaining text writer.Write(writeBuffer, 0, length); } } // trailing delimiter if (appendDelimiters) { writer.Write(delimiter); } } public static string ToEscapedJavaScriptString(string value, char delimiter, bool appendDelimiters, StringEscapeHandling stringEscapeHandling) { bool[] charEscapeFlags = GetCharEscapeFlags(stringEscapeHandling, delimiter); using (StringWriter w = StringUtils.CreateStringWriter(value?.Length ?? 16)) { char[] buffer = null; WriteEscapedJavaScriptString(w, value, delimiter, appendDelimiters, charEscapeFlags, stringEscapeHandling, null, ref buffer); return w.ToString(); } } } }
//////////////////////////////////////////////////////////////////////////////// // // @module Events Pro // @author Osipov Stanislav lacost.st@gmail.com // //////////////////////////////////////////////////////////////////////////////// using UnityEngine; using System; using System.Collections.Generic; public class EventDispatcher : MonoBehaviour, IDispatcher { private Dictionary<int, List<EventHandlerFunction>> listners = new Dictionary<int, List<EventHandlerFunction>>(); private Dictionary<int, List<DataEventHandlerFunction>> dataListners = new Dictionary<int, List<DataEventHandlerFunction>>(); //-------------------------------------- // ADD LISTENER'S //-------------------------------------- public void addEventListener(string eventName, EventHandlerFunction handler) { addEventListener(eventName.GetHashCode(), handler, eventName); } public void addEventListener(int eventID, EventHandlerFunction handler) { addEventListener(eventID, handler, eventID.ToString()); } private void addEventListener(int eventID, EventHandlerFunction handler, string eventGraphName) { if(listners.ContainsKey(eventID)) { listners[eventID].Add(handler); } else { List<EventHandlerFunction> handlers = new List<EventHandlerFunction>(); handlers.Add(handler); listners.Add(eventID, handlers); } } public void addEventListener(string eventName, DataEventHandlerFunction handler) { addEventListener(eventName.GetHashCode(), handler, eventName); } public void addEventListener(int eventID, DataEventHandlerFunction handler) { addEventListener(eventID, handler, eventID.ToString()); } private void addEventListener(int eventID, DataEventHandlerFunction handler, string eventGraphName) { if(dataListners.ContainsKey(eventID)) { dataListners[eventID].Add(handler); } else { List<DataEventHandlerFunction> handlers = new List<DataEventHandlerFunction>(); handlers.Add(handler); dataListners.Add(eventID, handlers); } } //-------------------------------------- // REMOVE LISTENER'S //-------------------------------------- public void removeEventListener(string eventName, EventHandlerFunction handler) { removeEventListener(eventName.GetHashCode(), handler, eventName); } public void removeEventListener(int eventID, EventHandlerFunction handler) { removeEventListener(eventID, handler, eventID.ToString()); } public void removeEventListener(int eventID, EventHandlerFunction handler, string eventGraphName) { if(listners.ContainsKey(eventID)) { List<EventHandlerFunction> handlers = listners[eventID]; handlers.Remove(handler); if(handlers.Count == 0) { listners.Remove(eventID); } } } public void removeEventListener(string eventName, DataEventHandlerFunction handler) { removeEventListener(eventName.GetHashCode(), handler, eventName); } public void removeEventListener(int eventID, DataEventHandlerFunction handler) { removeEventListener(eventID, handler, eventID.ToString()); } public void removeEventListener(int eventID, DataEventHandlerFunction handler, string eventGraphName) { if(dataListners.ContainsKey(eventID)) { List<DataEventHandlerFunction> handlers = dataListners[eventID]; handlers.Remove(handler); if(handlers.Count == 0) { dataListners.Remove(eventID); } } } //-------------------------------------- // DISPATCH I1 //-------------------------------------- public void dispatchEvent(string eventName) { dispatch(eventName.GetHashCode(), null, eventName); } public void dispatchEvent(string eventName, object data) { dispatch(eventName.GetHashCode(), data, eventName); } public void dispatchEvent(int eventID) { dispatch(eventID, null, string.Empty); } public void dispatchEvent(int eventID, object data) { dispatch(eventID, data, string.Empty); } //-------------------------------------- // DISPATCH I2 //-------------------------------------- public void dispatch(string eventName) { dispatch(eventName.GetHashCode(), null, eventName); } public void dispatch(string eventName, object data) { dispatch(eventName.GetHashCode(), data, eventName); } public void dispatch(int eventID) { dispatch(eventID, null, string.Empty); } public void dispatch(int eventID, object data) { dispatch(eventID, data, string.Empty); } //-------------------------------------- // PRIVATE DISPATCH I2 //-------------------------------------- private void dispatch(int eventID, object data, string eventName) { CEvent e = new CEvent(eventID, eventName, data, this); if(dataListners.ContainsKey(eventID)) { List<DataEventHandlerFunction> handlers = cloenArray(dataListners[eventID]); int len = handlers.Count; for(int i = 0; i < len; i++) { if(e.canBeDisptached(handlers[i].Target)) { handlers[i](e); } } } if(listners.ContainsKey(eventID)) { List<EventHandlerFunction> handlers = cloenArray(listners[eventID]); int len = handlers.Count; for(int i = 0; i < len; i++) { if(e.canBeDisptached(handlers[i].Target)) { handlers[i](); } } } } //-------------------------------------- // PUBLIC METHODS //-------------------------------------- public void clearEvents() { listners.Clear(); dataListners.Clear(); } //-------------------------------------- // GET / SET //-------------------------------------- //-------------------------------------- // PRIVATE METHODS //-------------------------------------- private List<EventHandlerFunction> cloenArray(List<EventHandlerFunction> list) { List<EventHandlerFunction> nl = new List<EventHandlerFunction>(); int len = list.Count; for(int i = 0; i < len; i++) { nl.Add(list[i]); } return nl; } private List<DataEventHandlerFunction> cloenArray(List<DataEventHandlerFunction> list) { List<DataEventHandlerFunction> nl = new List<DataEventHandlerFunction>(); int len = list.Count; for(int i = 0; i < len; i++) { nl.Add(list[i]); } return nl; } //-------------------------------------- // DestroyCEvent //-------------------------------------- protected virtual void OnDestroy() { clearEvents(); } }
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copyright (c) 2008 Jonathan Skeet. 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. #endregion namespace MoreLinq.Test { using System; using NUnit.Framework; [TestFixture] public class MaxByTest { [Test] public void MaxByIsLazy() { new BreakingSequence<int>().MaxBy(BreakingFunc.Of<int, int>()); } [Test] public void MaxByReturnsMaxima() { Assert.AreEqual(new[] { "hello", "world" }, SampleData.Strings.MaxBy(x => x.Length)); } [Test] public void MaxByNullComparer() { Assert.AreEqual(SampleData.Strings.MaxBy(x => x.Length), SampleData.Strings.MaxBy(x => x.Length, null)); } [Test] public void MaxByEmptySequence() { Assert.That(new string[0].MaxBy(x => x.Length), Is.Empty); } [Test] public void MaxByWithNaturalComparer() { Assert.AreEqual(new[] { "az" }, SampleData.Strings.MaxBy(x => x[1])); } [Test] public void MaxByWithComparer() { Assert.AreEqual(new[] { "aa" }, SampleData.Strings.MaxBy(x => x[1], Comparable<char>.DescendingOrderComparer)); } public class First { [Test] public void ReturnsMaximum() { using var strings = SampleData.Strings.AsTestingSequence(); var maxima = strings.MaxBy(s => s.Length); Assert.That(MoreEnumerable.First(maxima), Is.EqualTo("hello")); } [Test] public void WithComparerReturnsMaximum() { using var strings = SampleData.Strings.AsTestingSequence(); var maxima = strings.MaxBy(s => s.Length, Comparable<int>.DescendingOrderComparer); Assert.That(MoreEnumerable.First(maxima), Is.EqualTo("ax")); } [Test] public void WithEmptySourceThrows() { using var strings = Enumerable.Empty<string>().AsTestingSequence(); Assert.Throws<InvalidOperationException>(() => MoreEnumerable.First(strings.MaxBy(s => s.Length))); } [Test] public void WithEmptySourceWithComparerThrows() { using var strings = Enumerable.Empty<string>().AsTestingSequence(); Assert.Throws<InvalidOperationException>(() => MoreEnumerable.First(strings.MaxBy(s => s.Length, Comparable<int>.DescendingOrderComparer))); } } public class FirstOrDefault { [Test] public void ReturnsMaximum() { using var strings = SampleData.Strings.AsTestingSequence(); var maxima = strings.MaxBy(s => s.Length); Assert.That(MoreEnumerable.FirstOrDefault(maxima), Is.EqualTo("hello")); } [Test] public void WithComparerReturnsMaximum() { using var strings = SampleData.Strings.AsTestingSequence(); var maxima = strings.MaxBy(s => s.Length, Comparable<int>.DescendingOrderComparer); Assert.That(MoreEnumerable.FirstOrDefault(maxima), Is.EqualTo("ax")); } [Test] public void WithEmptySourceReturnsDefault() { using var strings = Enumerable.Empty<string>().AsTestingSequence(); var maxima = strings.MaxBy(s => s.Length); Assert.That(MoreEnumerable.FirstOrDefault(maxima), Is.Null); } [Test] public void WithEmptySourceWithComparerReturnsDefault() { using var strings = Enumerable.Empty<string>().AsTestingSequence(); var maxima = strings.MaxBy(s => s.Length, Comparable<int>.DescendingOrderComparer); Assert.That(MoreEnumerable.FirstOrDefault(maxima), Is.Null); } } public class Last { [Test] public void ReturnsMaximum() { using var strings = SampleData.Strings.AsTestingSequence(); var maxima = strings.MaxBy(s => s.Length); Assert.That(MoreEnumerable.Last(maxima), Is.EqualTo("world")); } [Test] public void WithComparerReturnsMaximumPerComparer() { using var strings = SampleData.Strings.AsTestingSequence(); var maxima = strings.MaxBy(s => s.Length, Comparable<int>.DescendingOrderComparer); Assert.That(MoreEnumerable.Last(maxima), Is.EqualTo("az")); } [Test] public void WithEmptySourceThrows() { using var strings = Enumerable.Empty<string>().AsTestingSequence(); Assert.Throws<InvalidOperationException>(() => MoreEnumerable.Last(strings.MaxBy(s => s.Length))); } [Test] public void WithEmptySourceWithComparerThrows() { using var strings = Enumerable.Empty<string>().AsTestingSequence(); Assert.Throws<InvalidOperationException>(() => MoreEnumerable.Last(strings.MaxBy(s => s.Length, Comparable<int>.DescendingOrderComparer))); } } public class LastOrDefault { [Test] public void ReturnsMaximum() { using var strings = SampleData.Strings.AsTestingSequence(); var maxima = strings.MaxBy(s => s.Length); Assert.That(MoreEnumerable.LastOrDefault(maxima), Is.EqualTo("world")); } [Test] public void WithComparerReturnsMaximumPerComparer() { using var strings = SampleData.Strings.AsTestingSequence(); var maxima = strings.MaxBy(s => s.Length, Comparable<int>.DescendingOrderComparer); Assert.That(MoreEnumerable.LastOrDefault(maxima), Is.EqualTo("az")); } [Test] public void WithEmptySourceReturnsDefault() { using var strings = Enumerable.Empty<string>().AsTestingSequence(); var maxima = strings.MaxBy(s => s.Length); Assert.That(MoreEnumerable.LastOrDefault(maxima), Is.Null); } [Test] public void WithEmptySourceWithComparerReturnsDefault() { using var strings = Enumerable.Empty<string>().AsTestingSequence(); var maxima = strings.MaxBy(s => s.Length, Comparable<int>.DescendingOrderComparer); Assert.That(MoreEnumerable.LastOrDefault(maxima), Is.Null); } } public class Take { [TestCase(0, ExpectedResult = new string[0] )] [TestCase(1, ExpectedResult = new[] { "hello" })] [TestCase(2, ExpectedResult = new[] { "hello", "world" })] [TestCase(3, ExpectedResult = new[] { "hello", "world" })] public string[] ReturnsMaxima(int count) { using var strings = SampleData.Strings.AsTestingSequence(); return strings.MaxBy(s => s.Length).Take(count).ToArray(); } [TestCase(0, 0, ExpectedResult = new string[0] )] [TestCase(3, 1, ExpectedResult = new[] { "aa" })] [TestCase(1, 0, ExpectedResult = new[] { "ax" })] [TestCase(2, 0, ExpectedResult = new[] { "ax", "aa" })] [TestCase(3, 0, ExpectedResult = new[] { "ax", "aa", "ab" })] [TestCase(4, 0, ExpectedResult = new[] { "ax", "aa", "ab", "ay" })] [TestCase(5, 0, ExpectedResult = new[] { "ax", "aa", "ab", "ay", "az" })] [TestCase(6, 0, ExpectedResult = new[] { "ax", "aa", "ab", "ay", "az" })] public string[] WithComparerReturnsMaximaPerComparer(int count, int index) { using var strings = SampleData.Strings.AsTestingSequence(); return strings.MaxBy(s => s[index], Comparable<char>.DescendingOrderComparer) .Take(count) .ToArray(); } } public class TakeLast { [TestCase(0, ExpectedResult = new string[0] )] [TestCase(1, ExpectedResult = new[] { "world" })] [TestCase(2, ExpectedResult = new[] { "hello", "world" })] [TestCase(3, ExpectedResult = new[] { "hello", "world" })] public string[] TakeLastReturnsMaxima(int count) { using var strings = SampleData.Strings.AsTestingSequence(); return strings.MaxBy(s => s.Length).TakeLast(count).ToArray(); } [TestCase(0, 0, ExpectedResult = new string[0] )] [TestCase(3, 1, ExpectedResult = new[] { "aa" })] [TestCase(1, 0, ExpectedResult = new[] { "az" })] [TestCase(2, 0, ExpectedResult = new[] { "ay", "az" })] [TestCase(3, 0, ExpectedResult = new[] { "ab", "ay", "az" })] [TestCase(4, 0, ExpectedResult = new[] { "aa", "ab", "ay", "az" })] [TestCase(5, 0, ExpectedResult = new[] { "ax", "aa", "ab", "ay", "az" })] [TestCase(6, 0, ExpectedResult = new[] { "ax", "aa", "ab", "ay", "az" })] public string[] WithComparerReturnsMaximaPerComparer(int count, int index) { using var strings = SampleData.Strings.AsTestingSequence(); return strings.MaxBy(s => s[index], Comparable<char>.DescendingOrderComparer) .TakeLast(count) .ToArray(); } } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT namespace NLog.UnitTests.LogReceiverService { using System.Collections.Generic; using System.Data; using System.Linq; using System.ServiceModel; using System.ServiceModel.Description; using System.Threading; using System; using System.IO; using Xunit; #if WCF_SUPPORTED using System.Runtime.Serialization; #endif using System.Xml; using System.Xml.Serialization; using NLog.Layouts; using NLog.LogReceiverService; public class LogReceiverServiceTests : NLogTestBase { private const string logRecieverUrl = "http://localhost:8080/logrecievertest"; [Fact] public void ToLogEventInfoTest() { var events = new NLogEvents { BaseTimeUtc = new DateTime(2010, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).Ticks, ClientName = "foo", LayoutNames = new StringCollection { "foo", "bar", "baz" }, Strings = new StringCollection { "logger1", "logger2", "logger3", "zzz", "message1" }, Events = new[] { new NLogEvent { Id = 1, LevelOrdinal = 2, LoggerOrdinal = 0, TimeDelta = 30000000, MessageOrdinal = 4, Values = "0|1|2" }, new NLogEvent { Id = 2, LevelOrdinal = 3, LoggerOrdinal = 2, MessageOrdinal = 4, TimeDelta = 30050000, Values = "0|1|3", } } }; var converted = events.ToEventInfo(); Assert.Equal(2, converted.Count); Assert.Equal("message1", converted[0].FormattedMessage); Assert.Equal("message1", converted[1].FormattedMessage); Assert.Equal(new DateTime(2010, 1, 1, 0, 0, 3, 0, DateTimeKind.Utc), converted[0].TimeStamp.ToUniversalTime()); Assert.Equal(new DateTime(2010, 1, 1, 0, 0, 3, 5, DateTimeKind.Utc), converted[1].TimeStamp.ToUniversalTime()); Assert.Equal("logger1", converted[0].LoggerName); Assert.Equal("logger3", converted[1].LoggerName); Assert.Equal(LogLevel.Info, converted[0].Level); Assert.Equal(LogLevel.Warn, converted[1].Level); Layout fooLayout = "${event-context:foo}"; Layout barLayout = "${event-context:bar}"; Layout bazLayout = "${event-context:baz}"; Assert.Equal("logger1", fooLayout.Render(converted[0])); Assert.Equal("logger1", fooLayout.Render(converted[1])); Assert.Equal("logger2", barLayout.Render(converted[0])); Assert.Equal("logger2", barLayout.Render(converted[1])); Assert.Equal("logger3", bazLayout.Render(converted[0])); Assert.Equal("zzz", bazLayout.Render(converted[1])); } [Fact] public void NoLayoutsTest() { var events = new NLogEvents { BaseTimeUtc = new DateTime(2010, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).Ticks, ClientName = "foo", LayoutNames = new StringCollection(), Strings = new StringCollection { "logger1", "logger2", "logger3", "zzz", "message1" }, Events = new[] { new NLogEvent { Id = 1, LevelOrdinal = 2, LoggerOrdinal = 0, TimeDelta = 30000000, MessageOrdinal = 4, Values = null, }, new NLogEvent { Id = 2, LevelOrdinal = 3, LoggerOrdinal = 2, MessageOrdinal = 4, TimeDelta = 30050000, Values = null, } } }; var converted = events.ToEventInfo(); Assert.Equal(2, converted.Count); Assert.Equal("message1", converted[0].FormattedMessage); Assert.Equal("message1", converted[1].FormattedMessage); Assert.Equal(new DateTime(2010, 1, 1, 0, 0, 3, 0, DateTimeKind.Utc), converted[0].TimeStamp.ToUniversalTime()); Assert.Equal(new DateTime(2010, 1, 1, 0, 0, 3, 5, DateTimeKind.Utc), converted[1].TimeStamp.ToUniversalTime()); Assert.Equal("logger1", converted[0].LoggerName); Assert.Equal("logger3", converted[1].LoggerName); Assert.Equal(LogLevel.Info, converted[0].Level); Assert.Equal(LogLevel.Warn, converted[1].Level); } #if !SILVERLIGHT /// <summary> /// Ensures that serialization formats of DataContractSerializer and XmlSerializer are the same /// on the same <see cref="NLogEvents"/> object. /// </summary> [Fact] public void CompareSerializationFormats() { var events = new NLogEvents { BaseTimeUtc = DateTime.UtcNow.Ticks, ClientName = "foo", LayoutNames = new StringCollection { "foo", "bar", "baz" }, Strings = new StringCollection { "logger1", "logger2", "logger3" }, Events = new[] { new NLogEvent { Id = 1, LevelOrdinal = 2, LoggerOrdinal = 0, TimeDelta = 34, Values = "1|2|3" }, new NLogEvent { Id = 2, LevelOrdinal = 3, LoggerOrdinal = 2, TimeDelta = 345, Values = "1|2|3", } } }; var serializer1 = new XmlSerializer(typeof(NLogEvents)); var sw1 = new StringWriter(); using (var writer1 = XmlWriter.Create(sw1, new XmlWriterSettings { Indent = true })) { var namespaces = new XmlSerializerNamespaces(); namespaces.Add("i", "http://www.w3.org/2001/XMLSchema-instance"); serializer1.Serialize(writer1, events, namespaces); } var serializer2 = new DataContractSerializer(typeof(NLogEvents)); var sw2 = new StringWriter(); using (var writer2 = XmlWriter.Create(sw2, new XmlWriterSettings { Indent = true })) { serializer2.WriteObject(writer2, events); } var xml1 = sw1.ToString(); var xml2 = sw2.ToString(); Assert.Equal(xml1, xml2); } #endif #if WCF_SUPPORTED [Fact] public void RealTestLogReciever1() { LogManager.Configuration = CreateConfigurationFromString(string.Format(@" <nlog throwExceptions='true'> <targets> <target type='LogReceiverService' name='s1' endpointAddress='{0}' useBinaryEncoding='false' includeEventProperties='false'> <parameter layout='testparam1' name='String' type='String'/> </target> </targets> <rules> <logger name='logger1' minlevel='Trace' writeTo='s1' /> </rules> </nlog>", logRecieverUrl)); ExecLogRecieverAndCheck(ExecLogging1, CheckRecieved1, 2); } /// <summary> /// Create WCF service, logs and listen to the events /// </summary> /// <param name="logFunc">function for logging the messages</param> /// <param name="logCheckFunc">function for checking the received messsages</param> /// <param name="messageCount">message count for wait for listen and checking</param> public void ExecLogRecieverAndCheck(Action<Logger> logFunc, Action<List<NLogEvents>> logCheckFunc, int messageCount) { Uri baseAddress = new Uri(logRecieverUrl); // Create the ServiceHost. using (ServiceHost host = new ServiceHost(typeof(LogRecieverMock), baseAddress)) { // Enable metadata publishing. ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15; host.Description.Behaviors.Add(smb); // Open the ServiceHost to start listening for messages. Since // no endpoints are explicitly configured, the runtime will create // one endpoint per base address for each service contract implemented // by the service. host.Open(); //wait for 2 events var countdownEvent = new CountdownEvent(messageCount); //reset LogRecieverMock.recievedEvents = new List<NLogEvents>(); LogRecieverMock.CountdownEvent = countdownEvent; var logger1 = LogManager.GetLogger("logger1"); logFunc(logger1); countdownEvent.Wait(20000); //we need some extra time for completion Thread.Sleep(1000); var recieved = LogRecieverMock.recievedEvents; Assert.Equal(messageCount, recieved.Count); logCheckFunc(recieved); // Close the ServiceHost. host.Close(); } } private static void CheckRecieved1(List<NLogEvents> recieved) { var log1 = recieved[0].ToEventInfo().First(); Assert.Equal("test 1", log1.Message); var log2 = recieved[1].ToEventInfo().First(); } private static void ExecLogging1(Logger logger) { logger.Info("test 1"); logger.Info(new InvalidConstraintException("boo"), "test2"); } public class LogRecieverMock : ILogReceiverServer { public static CountdownEvent CountdownEvent; public static List<NLogEvents> recievedEvents = new List<NLogEvents>(); /// <summary> /// Processes the log messages. /// </summary> /// <param name="events">The events.</param> public void ProcessLogMessages(NLogEvents events) { if (CountdownEvent == null) { throw new Exception("test not prepared well"); } recievedEvents.Add(events); CountdownEvent.Signal(); } } #endif } } #endif
using Lucene.Net.Index; using System; using System.Diagnostics; using BytesRef = Lucene.Net.Util.BytesRef; namespace Lucene.Net.Codecs.Lucene3x { /* * 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 FieldInfos = Lucene.Net.Index.FieldInfos; using IndexInput = Lucene.Net.Store.IndexInput; using Term = Lucene.Net.Index.Term; /// <summary> /// @lucene.experimental /// </summary> [Obsolete("(4.0)")] internal sealed class SegmentTermPositions : SegmentTermDocs { private IndexInput proxStream; private IndexInput proxStreamOrig; private int proxCount; private int position; private BytesRef payload; // the current payload length private int payloadLength; // indicates whether the payload of the current position has // been read from the proxStream yet private bool needToLoadPayload; // these variables are being used to remember information // for a lazy skip private long lazySkipPointer = -1; private int lazySkipProxCount = 0; /* SegmentTermPositions(SegmentReader p) { super(p); this.proxStream = null; // the proxStream will be cloned lazily when nextPosition() is called for the first time } */ public SegmentTermPositions(IndexInput freqStream, IndexInput proxStream, TermInfosReader tis, FieldInfos fieldInfos) : base(freqStream, tis, fieldInfos) { this.proxStreamOrig = proxStream; // the proxStream will be cloned lazily when nextPosition() is called for the first time } internal override void Seek(TermInfo ti, Term term) { base.Seek(ti, term); if (ti != null) { lazySkipPointer = ti.ProxPointer; } lazySkipProxCount = 0; proxCount = 0; payloadLength = 0; needToLoadPayload = false; } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { if (proxStream != null) { proxStream.Dispose(); } } } public int NextPosition() { if (m_indexOptions != IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) // this field does not store positions, payloads { return 0; } // perform lazy skips if necessary LazySkip(); proxCount--; return position += ReadDeltaPosition(); } private int ReadDeltaPosition() { int delta = proxStream.ReadVInt32(); if (m_currentFieldStoresPayloads) { // if the current field stores payloads then // the position delta is shifted one bit to the left. // if the LSB is set, then we have to read the current // payload length if ((delta & 1) != 0) { payloadLength = proxStream.ReadVInt32(); } delta = (int)((uint)delta >> 1); needToLoadPayload = true; } else if (delta == -1) { delta = 0; // LUCENE-1542 correction } return delta; } protected internal sealed override void SkippingDoc() { // we remember to skip a document lazily lazySkipProxCount += freq; } public sealed override bool Next() { // we remember to skip the remaining positions of the current // document lazily lazySkipProxCount += proxCount; if (base.Next()) // run super { proxCount = freq; // note frequency position = 0; // reset position return true; } return false; } public sealed override int Read(int[] docs, int[] freqs) { throw new System.NotSupportedException("TermPositions does not support processing multiple documents in one call. Use TermDocs instead."); } /// <summary> /// Called by <c>base.SkipTo()</c>. </summary> protected internal override void SkipProx(long proxPointer, int payloadLength) { // we save the pointer, we might have to skip there lazily lazySkipPointer = proxPointer; lazySkipProxCount = 0; proxCount = 0; this.payloadLength = payloadLength; needToLoadPayload = false; } private void SkipPositions(int n) { Debug.Assert(m_indexOptions == IndexOptions.DOCS_AND_FREQS_AND_POSITIONS); for (int f = n; f > 0; f--) // skip unread positions { ReadDeltaPosition(); SkipPayload(); } } private void SkipPayload() { if (needToLoadPayload && payloadLength > 0) { proxStream.Seek(proxStream.GetFilePointer() + payloadLength); } needToLoadPayload = false; } // It is not always necessary to move the prox pointer // to a new document after the freq pointer has been moved. // Consider for example a phrase query with two terms: // the freq pointer for term 1 has to move to document x // to answer the question if the term occurs in that document. But // only if term 2 also matches document x, the positions have to be // read to figure out if term 1 and term 2 appear next // to each other in document x and thus satisfy the query. // So we move the prox pointer lazily to the document // as soon as positions are requested. private void LazySkip() { if (proxStream == null) { // clone lazily proxStream = (IndexInput)proxStreamOrig.Clone(); } // we might have to skip the current payload // if it was not read yet SkipPayload(); if (lazySkipPointer != -1) { proxStream.Seek(lazySkipPointer); lazySkipPointer = -1; } if (lazySkipProxCount != 0) { SkipPositions(lazySkipProxCount); lazySkipProxCount = 0; } } public int PayloadLength { get { return payloadLength; } } public BytesRef GetPayload() { if (payloadLength <= 0) { return null; // no payload } if (needToLoadPayload) { // read payloads lazily if (payload == null) { payload = new BytesRef(payloadLength); } else { payload.Grow(payloadLength); } proxStream.ReadBytes(payload.Bytes, payload.Offset, payloadLength); payload.Length = payloadLength; needToLoadPayload = false; } return payload; } public bool IsPayloadAvailable { get { return needToLoadPayload && payloadLength > 0; } } } }
using System; using System.ComponentModel; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Drawing; using System.Windows.Forms; namespace UsbLibrary { /// <summary> /// This class provides an usb component. This can be placed ont to your form. /// </summary> [ToolboxBitmap(typeof(UsbHidPort), "UsbHidBmp.bmp")] public partial class UsbHidPort : Component { //private memebers private int product_id; private int vendor_id; private Guid device_class; private IntPtr usb_event_handle; private SpecifiedDevice specified_device; private IntPtr handle; //events /// <summary> /// This event will be triggered when the device you specified is pluged into your usb port on /// the computer. And it is completly enumerated by windows and ready for use. /// </summary> [Description("The event that occurs when a usb hid device with the specified vendor id and product id is found on the bus")] [Category("Embedded Event")] [DisplayName("OnSpecifiedDeviceArrived")] public event EventHandler OnSpecifiedDeviceArrived; /// <summary> /// This event will be triggered when the device you specified is removed from your computer. /// </summary> [Description("The event that occurs when a usb hid device with the specified vendor id and product id is removed from the bus")] [Category("Embedded Event")] [DisplayName("OnSpecifiedDeviceRemoved")] public event EventHandler OnSpecifiedDeviceRemoved; /// <summary> /// This event will be triggered when a device is pluged into your usb port on /// the computer. And it is completly enumerated by windows and ready for use. /// </summary> [Description("The event that occurs when a usb hid device is found on the bus")] [Category("Embedded Event")] [DisplayName("OnDeviceArrived")] public event EventHandler OnDeviceArrived; /// <summary> /// This event will be triggered when a device is removed from your computer. /// </summary> [Description("The event that occurs when a usb hid device is removed from the bus")] [Category("Embedded Event")] [DisplayName("OnDeviceRemoved")] public event EventHandler OnDeviceRemoved; /// <summary> /// This event will be triggered when data is recieved from the device specified by you. /// </summary> [Description("The event that occurs when data is recieved from the embedded system")] [Category("Embedded Event")] [DisplayName("OnDataRecieved")] public event DataRecievedEventHandler OnDataRecieved; /// <summary> /// This event will be triggered when data is send to the device. /// It will only occure when this action wass succesfull. /// </summary> [Description("The event that occurs when data is send from the host to the embedded system")] [Category("Embedded Event")] [DisplayName("OnDataSend")] public event EventHandler OnDataSend; public UsbHidPort() { //initializing in initial state product_id = 0; vendor_id = 0; specified_device = null; device_class = Win32Usb.HIDGuid; InitializeComponent(); } public UsbHidPort(IContainer container) { //initializing in initial state product_id = 0; vendor_id = 0; specified_device = null; device_class = Win32Usb.HIDGuid; container.Add(this); InitializeComponent(); } [Description("The product id from the USB device you want to use")] [DefaultValue("(none)")] [Category("Embedded Details")] public int ProductId{ get { return this.product_id; } set { this.product_id = value; } } [Description("The vendor id from the USB device you want to use")] [DefaultValue("(none)")] [Category("Embedded Details")] public int VendorId { get { return this.vendor_id; } set { this.vendor_id = value; } } [Description("The Device Class the USB device belongs to")] [DefaultValue("(none)")] [Category("Embedded Details")] public Guid DeviceClass { get { return device_class; } } [Description("The Device witch applies to the specifications you set")] [DefaultValue("(none)")] [Category("Embedded Details")] public SpecifiedDevice SpecifiedDevice { get { return this.specified_device; } } /// <summary> /// Registers this application, so it will be notified for usb events. /// </summary> /// <param name="Handle">a IntPtr, that is a handle to the application.</param> /// <example> This sample shows how to implement this method in your form. /// <code> ///protected override void OnHandleCreated(EventArgs e) ///{ /// base.OnHandleCreated(e); /// usb.RegisterHandle(Handle); ///} ///</code> ///</example> public void RegisterHandle(IntPtr Handle){ usb_event_handle = Win32Usb.RegisterForUsbEvents(Handle, device_class); this.handle = Handle; //Check if the device is already present. CheckDevicePresent(); } /// <summary> /// Unregisters this application, so it won't be notified for usb events. /// </summary> /// <returns>Returns if it wass succesfull to unregister.</returns> public bool UnregisterHandle() { if (this.handle != null) { return Win32Usb.UnregisterForUsbEvents(this.handle); } return false; } /// <summary> /// This method will filter the messages that are passed for usb device change messages only. /// And parse them and take the appropriate action /// </summary> /// <param name="m">a ref to Messages, The messages that are thrown by windows to the application.</param> /// <example> This sample shows how to implement this method in your form. /// <code> ///protected override void WndProc(ref Message m) ///{ /// usb.ParseMessages(ref m); /// base.WndProc(ref m); // pass message on to base form ///} ///</code> ///</example> public void ParseMessages(ref Message m) { if (m.Msg == Win32Usb.WM_DEVICECHANGE) // we got a device change message! A USB device was inserted or removed { switch (m.WParam.ToInt32()) // Check the W parameter to see if a device was inserted or removed { case Win32Usb.DEVICE_ARRIVAL: // inserted if (OnDeviceArrived != null) { OnDeviceArrived(this, new EventArgs()); CheckDevicePresent(); } break; case Win32Usb.DEVICE_REMOVECOMPLETE: // removed if (OnDeviceRemoved != null) { OnDeviceRemoved(this, new EventArgs()); CheckDevicePresent(); } break; } } } /// <summary> /// Checks the devices that are present at the moment and checks if one of those /// is the device you defined by filling in the product id and vendor id. /// </summary> public void CheckDevicePresent() { try { //Mind if the specified device existed before. bool history = false; if(specified_device != null ){ history = true; } specified_device = SpecifiedDevice.FindSpecifiedDevice(this.vendor_id, this.product_id); // look for the device on the USB bus if (specified_device != null) // did we find it? { if (OnSpecifiedDeviceArrived != null) { this.OnSpecifiedDeviceArrived(this, new EventArgs()); specified_device.DataRecieved += new DataRecievedEventHandler(OnDataRecieved); specified_device.DataSend += new DataSendEventHandler(OnDataSend); } } else { if (OnSpecifiedDeviceRemoved != null && history) { this.OnSpecifiedDeviceRemoved(this, new EventArgs()); } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } private void DataRecieved(object sender, DataRecievedEventArgs args) { if(this.OnDataRecieved != null){ this.OnDataRecieved(sender, args); } } private void DataSend(object sender, DataSendEventArgs args) { if (this.OnDataSend != null) { this.OnDataSend(sender, args); } } } }
using System; using System.Runtime.Serialization; using System.Threading.Tasks; using Orleans.CodeGeneration; using Orleans.Serialization; namespace Orleans.Runtime { /// <summary> /// Indicates that a <see cref="GrainReference"/> was not bound to the runtime before being used. /// </summary> [Serializable] public class GrainReferenceNotBoundException : OrleansException { internal GrainReferenceNotBoundException(GrainReference grainReference) : base(CreateMessage(grainReference)) { } private static string CreateMessage(GrainReference grainReference) { return $"Attempted to use a GrainReference which has not been bound to the runtime: {grainReference.ToDetailedString()}." + $" Use the {nameof(IGrainFactory)}.{nameof(IGrainFactory.BindGrainReference)} method to bind this reference to the runtime."; } internal GrainReferenceNotBoundException(string msg) : base(msg) { } internal GrainReferenceNotBoundException(string message, Exception innerException) : base(message, innerException) { } protected GrainReferenceNotBoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// This is the base class for all typed grain references. /// </summary> [Serializable] public class GrainReference : IAddressable, IEquatable<GrainReference>, ISerializable { private readonly string genericArguments; private readonly GuidId observerId; /// <summary> /// Invoke method options specific to this grain reference instance /// </summary> [NonSerialized] private readonly InvokeMethodOptions invokeMethodOptions; internal bool IsSystemTarget { get { return GrainId.IsSystemTarget; } } internal bool IsObserverReference { get { return GrainId.IsClient; } } internal GuidId ObserverId { get { return observerId; } } internal bool HasGenericArgument { get { return !String.IsNullOrEmpty(genericArguments); } } internal IGrainReferenceRuntime Runtime { get { if (this.runtime == null) throw new GrainReferenceNotBoundException(this); return this.runtime; } } /// <summary> /// Gets a value indicating whether this instance is bound to a runtime and hence valid for making requests. /// </summary> internal bool IsBound => this.runtime != null; internal GrainId GrainId { get; private set; } /// <summary> /// Called from generated code. /// </summary> protected internal readonly SiloAddress SystemTargetSilo; [NonSerialized] private IGrainReferenceRuntime runtime; /// <summary> /// Whether the runtime environment for system targets has been initialized yet. /// Called from generated code. /// </summary> protected internal bool IsInitializedSystemTarget { get { return SystemTargetSilo != null; } } internal string GenericArguments => this.genericArguments; #region Constructors /// <summary>Constructs a reference to the grain with the specified Id.</summary> /// <param name="grainId">The Id of the grain to refer to.</param> /// <param name="genericArgument">Type arguments in case of a generic grain.</param> /// <param name="systemTargetSilo">Target silo in case of a system target reference.</param> /// <param name="observerId">Observer ID in case of an observer reference.</param> /// <param name="runtime">The runtime which this grain reference is bound to.</param> private GrainReference(GrainId grainId, string genericArgument, SiloAddress systemTargetSilo, GuidId observerId, IGrainReferenceRuntime runtime) { GrainId = grainId; this.genericArguments = genericArgument; this.SystemTargetSilo = systemTargetSilo; this.observerId = observerId; this.runtime = runtime; if (String.IsNullOrEmpty(genericArgument)) { genericArguments = null; // always keep it null instead of empty. } // SystemTarget checks if (grainId.IsSystemTarget && systemTargetSilo==null) { throw new ArgumentNullException("systemTargetSilo", String.Format("Trying to create a GrainReference for SystemTarget grain id {0}, but passing null systemTargetSilo.", grainId)); } if (grainId.IsSystemTarget && genericArguments != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference for SystemTarget grain id {0}, and also passing non-null genericArguments {1}.", grainId, genericArguments), "genericArgument"); } if (grainId.IsSystemTarget && observerId != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference for SystemTarget grain id {0}, and also passing non-null observerId {1}.", grainId, observerId), "genericArgument"); } if (!grainId.IsSystemTarget && systemTargetSilo != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference for non-SystemTarget grain id {0}, but passing a non-null systemTargetSilo {1}.", grainId, systemTargetSilo), "systemTargetSilo"); } // ObserverId checks if (grainId.IsClient && observerId == null) { throw new ArgumentNullException("observerId", String.Format("Trying to create a GrainReference for Observer with Client grain id {0}, but passing null observerId.", grainId)); } if (grainId.IsClient && genericArguments != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference for Client grain id {0}, and also passing non-null genericArguments {1}.", grainId, genericArguments), "genericArgument"); } if (grainId.IsClient && systemTargetSilo != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference for Client grain id {0}, and also passing non-null systemTargetSilo {1}.", grainId, systemTargetSilo), "genericArgument"); } if (!grainId.IsClient && observerId != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference with non null Observer {0}, but non Client grain id {1}.", observerId, grainId), "observerId"); } } /// <summary> /// Constructs a copy of a grain reference. /// </summary> /// <param name="other">The reference to copy.</param> protected GrainReference(GrainReference other) : this(other.GrainId, other.genericArguments, other.SystemTargetSilo, other.ObserverId, other.runtime) { this.invokeMethodOptions = other.invokeMethodOptions; } protected internal GrainReference(GrainReference other, InvokeMethodOptions invokeMethodOptions) : this(other) { this.invokeMethodOptions = invokeMethodOptions; } #endregion #region Instance creator factory functions /// <summary>Constructs a reference to the grain with the specified ID.</summary> /// <param name="grainId">The ID of the grain to refer to.</param> /// <param name="runtime">The runtime client</param> /// <param name="genericArguments">Type arguments in case of a generic grain.</param> /// <param name="systemTargetSilo">Target silo in case of a system target reference.</param> internal static GrainReference FromGrainId(GrainId grainId, IGrainReferenceRuntime runtime, string genericArguments = null, SiloAddress systemTargetSilo = null) { return new GrainReference(grainId, genericArguments, systemTargetSilo, null, runtime); } internal static GrainReference NewObserverGrainReference(GrainId grainId, GuidId observerId, IGrainReferenceRuntime runtime) { return new GrainReference(grainId, null, null, observerId, runtime); } #endregion /// <summary> /// Binds this instance to a runtime. /// </summary> /// <param name="runtime">The runtime.</param> internal void Bind(IGrainReferenceRuntime runtime) { this.runtime = runtime; } /// <summary> /// Tests this reference for equality to another object. /// Two grain references are equal if they both refer to the same grain. /// </summary> /// <param name="obj">The object to test for equality against this reference.</param> /// <returns><c>true</c> if the object is equal to this reference.</returns> public override bool Equals(object obj) { return Equals(obj as GrainReference); } public bool Equals(GrainReference other) { if (other == null) return false; if (genericArguments != other.genericArguments) return false; if (!GrainId.Equals(other.GrainId)) { return false; } if (IsSystemTarget) { return Equals(SystemTargetSilo, other.SystemTargetSilo); } if (IsObserverReference) { return observerId.Equals(other.observerId); } return true; } /// <summary> Calculates a hash code for a grain reference. </summary> public override int GetHashCode() { int hash = GrainId.GetHashCode(); if (IsSystemTarget) { hash = hash ^ SystemTargetSilo.GetHashCode(); } if (IsObserverReference) { hash = hash ^ observerId.GetHashCode(); } return hash; } /// <summary>Get a uniform hash code for this grain reference.</summary> public uint GetUniformHashCode() { // GrainId already includes the hashed type code for generic arguments. return GrainId.GetUniformHashCode(); } /// <summary> /// Compares two references for equality. /// Two grain references are equal if they both refer to the same grain. /// </summary> /// <param name="reference1">First grain reference to compare.</param> /// <param name="reference2">Second grain reference to compare.</param> /// <returns><c>true</c> if both grain references refer to the same grain (by grain identifier).</returns> public static bool operator ==(GrainReference reference1, GrainReference reference2) { if (((object)reference1) == null) return ((object)reference2) == null; return reference1.Equals(reference2); } /// <summary> /// Compares two references for inequality. /// Two grain references are equal if they both refer to the same grain. /// </summary> /// <param name="reference1">First grain reference to compare.</param> /// <param name="reference2">Second grain reference to compare.</param> /// <returns><c>false</c> if both grain references are resolved to the same grain (by grain identifier).</returns> public static bool operator !=(GrainReference reference1, GrainReference reference2) { if (((object)reference1) == null) return ((object)reference2) != null; return !reference1.Equals(reference2); } #region Protected members /// <summary> /// Implemented by generated subclasses to return a constant /// Implemented in generated code. /// </summary> public virtual int InterfaceId { get { throw new InvalidOperationException("Should be overridden by subclass"); } } /// <summary> /// Implemented in generated code. /// </summary> public virtual ushort InterfaceVersion { get { throw new InvalidOperationException("Should be overridden by subclass"); } } /// <summary> /// Implemented in generated code. /// </summary> public virtual bool IsCompatible(int interfaceId) { throw new InvalidOperationException("Should be overridden by subclass"); } /// <summary> /// Return the name of the interface for this GrainReference. /// Implemented in Orleans generated code. /// </summary> public virtual string InterfaceName { get { throw new InvalidOperationException("Should be overridden by subclass"); } } /// <summary> /// Return the method name associated with the specified interfaceId and methodId values. /// </summary> /// <param name="interfaceId">Interface Id</param> /// <param name="methodId">Method Id</param> /// <returns>Method name string.</returns> public virtual string GetMethodName(int interfaceId, int methodId) { throw new InvalidOperationException("Should be overridden by subclass"); } /// <summary> /// Called from generated code. /// </summary> protected void InvokeOneWayMethod(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None, SiloAddress silo = null) { this.Runtime.InvokeOneWayMethod(this, methodId, arguments, options | invokeMethodOptions, silo); } /// <summary> /// Called from generated code. /// </summary> protected Task<T> InvokeMethodAsync<T>(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None, SiloAddress silo = null) { return this.Runtime.InvokeMethodAsync<T>(this, methodId, arguments, options | invokeMethodOptions, silo); } #endregion private const string GRAIN_REFERENCE_STR = "GrainReference"; private const string SYSTEM_TARGET_STR = "SystemTarget"; private const string OBSERVER_ID_STR = "ObserverId"; private const string GENERIC_ARGUMENTS_STR = "GenericArguments"; /// <summary>Returns a string representation of this reference.</summary> public override string ToString() { if (IsSystemTarget) { return String.Format("{0}:{1}/{2}", SYSTEM_TARGET_STR, GrainId, SystemTargetSilo); } if (IsObserverReference) { return String.Format("{0}:{1}/{2}", OBSERVER_ID_STR, GrainId, observerId); } return String.Format("{0}:{1}{2}", GRAIN_REFERENCE_STR, GrainId, !HasGenericArgument ? String.Empty : String.Format("<{0}>", genericArguments)); } internal string ToDetailedString() { if (IsSystemTarget) { return String.Format("{0}:{1}/{2}", SYSTEM_TARGET_STR, GrainId.ToDetailedString(), SystemTargetSilo); } if (IsObserverReference) { return String.Format("{0}:{1}/{2}", OBSERVER_ID_STR, GrainId.ToDetailedString(), observerId.ToDetailedString()); } return String.Format("{0}:{1}{2}", GRAIN_REFERENCE_STR, GrainId.ToDetailedString(), !HasGenericArgument ? String.Empty : String.Format("<{0}>", genericArguments)); } /// <summary> Get the key value for this grain, as a string. </summary> public string ToKeyString() { if (IsObserverReference) { return String.Format("{0}={1} {2}={3}", GRAIN_REFERENCE_STR, GrainId.ToParsableString(), OBSERVER_ID_STR, observerId.ToParsableString()); } if (IsSystemTarget) { return String.Format("{0}={1} {2}={3}", GRAIN_REFERENCE_STR, GrainId.ToParsableString(), SYSTEM_TARGET_STR, SystemTargetSilo.ToParsableString()); } if (HasGenericArgument) { return String.Format("{0}={1} {2}={3}", GRAIN_REFERENCE_STR, GrainId.ToParsableString(), GENERIC_ARGUMENTS_STR, genericArguments); } return String.Format("{0}={1}", GRAIN_REFERENCE_STR, GrainId.ToParsableString()); } internal static GrainReference FromKeyString(string key, IGrainReferenceRuntime runtime) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentNullException("key", "GrainReference.FromKeyString cannot parse null key"); string trimmed = key.Trim(); string grainIdStr; int grainIdIndex = (GRAIN_REFERENCE_STR + "=").Length; int genericIndex = trimmed.IndexOf(GENERIC_ARGUMENTS_STR + "=", StringComparison.Ordinal); int observerIndex = trimmed.IndexOf(OBSERVER_ID_STR + "=", StringComparison.Ordinal); int systemTargetIndex = trimmed.IndexOf(SYSTEM_TARGET_STR + "=", StringComparison.Ordinal); if (genericIndex >= 0) { grainIdStr = trimmed.Substring(grainIdIndex, genericIndex - grainIdIndex).Trim(); string genericStr = trimmed.Substring(genericIndex + (GENERIC_ARGUMENTS_STR + "=").Length); if (String.IsNullOrEmpty(genericStr)) { genericStr = null; } return FromGrainId(GrainId.FromParsableString(grainIdStr), runtime, genericStr); } else if (observerIndex >= 0) { grainIdStr = trimmed.Substring(grainIdIndex, observerIndex - grainIdIndex).Trim(); string observerIdStr = trimmed.Substring(observerIndex + (OBSERVER_ID_STR + "=").Length); GuidId observerId = GuidId.FromParsableString(observerIdStr); return NewObserverGrainReference(GrainId.FromParsableString(grainIdStr), observerId, runtime); } else if (systemTargetIndex >= 0) { grainIdStr = trimmed.Substring(grainIdIndex, systemTargetIndex - grainIdIndex).Trim(); string systemTargetStr = trimmed.Substring(systemTargetIndex + (SYSTEM_TARGET_STR + "=").Length); SiloAddress siloAddress = SiloAddress.FromParsableString(systemTargetStr); return FromGrainId(GrainId.FromParsableString(grainIdStr), runtime, null, siloAddress); } else { grainIdStr = trimmed.Substring(grainIdIndex); return FromGrainId(GrainId.FromParsableString(grainIdStr), runtime); } } #region ISerializable Members public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { // Use the AddValue method to specify serialized values. info.AddValue("GrainId", GrainId.ToParsableString(), typeof(string)); if (IsSystemTarget) { info.AddValue("SystemTargetSilo", SystemTargetSilo.ToParsableString(), typeof(string)); } if (IsObserverReference) { info.AddValue(OBSERVER_ID_STR, observerId.ToParsableString(), typeof(string)); } string genericArg = String.Empty; if (HasGenericArgument) genericArg = genericArguments; info.AddValue("GenericArguments", genericArg, typeof(string)); } // The special constructor is used to deserialize values. protected GrainReference(SerializationInfo info, StreamingContext context) { // Reset the property value using the GetValue method. var grainIdStr = info.GetString("GrainId"); GrainId = GrainId.FromParsableString(grainIdStr); if (IsSystemTarget) { var siloAddressStr = info.GetString("SystemTargetSilo"); SystemTargetSilo = SiloAddress.FromParsableString(siloAddressStr); } if (IsObserverReference) { var observerIdStr = info.GetString(OBSERVER_ID_STR); observerId = GuidId.FromParsableString(observerIdStr); } var genericArg = info.GetString("GenericArguments"); if (String.IsNullOrEmpty(genericArg)) genericArg = null; genericArguments = genericArg; var serializerContext = context.Context as ISerializerContext; this.runtime = serializerContext?.ServiceProvider.GetService(typeof(IGrainReferenceRuntime)) as IGrainReferenceRuntime; } #endregion } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using Microsoft.PythonTools.Parsing; namespace Microsoft.PythonTools.Options { public sealed class GeneralOptions{ private readonly PythonToolsService _pyService; private Severity _indentationInconsistencySeverity; private const string AdvancedCategory = "Advanced"; private const string GeneralCategory = "Advanced"; private const string IndentationInconsistencySeveritySetting = "IndentationInconsistencySeverity"; private const string AutoAnalysisSetting = "AutoAnalysis"; private const string CrossModuleAnalysisLimitSetting = "CrossModuleAnalysisLimit"; private const string UpdateSearchPathsWhenAddingLinkedFilesSetting = "UpdateSearchPathsWhenAddingLinkedFiles"; private const string ShowOutputWindowForVirtualEnvCreateSetting = "ShowOutputWindowForVirtualEnvCreate"; private const string ShowOutputWindowForPackageInstallationSetting = "ShowOutputWindowForPackageInstallation"; private const string PromptForEnvCreateSetting = "PromptForEnvCreate"; private const string PromptForPackageInstallationSetting = "PromptForPackageInstallation"; private const string PromptForTestFrameWorkInfoBarSetting = "PromptForTestFrameWorkInfoBar"; private const string PromptForPythonVersionNotSupportedInfoBarSetting = "PromptForPythonVersionNotSupportedInfoBarSetting"; private const string ElevatePipSetting = "ElevatePip"; private const string UnresolvedImportWarningSetting = "UnresolvedImportWarning"; private const string InvalidEncodingWarningSetting = "InvalidEncodingWarningWarning"; private const string ClearGlobalPythonPathSetting = "ClearGlobalPythonPath"; private const string DefaultSurveyNewsFeedUrl = "https://go.microsoft.com/fwlink/?LinkId=303967"; private const string DefaultSurveyNewsIndexUrl = "https://go.microsoft.com/fwlink/?LinkId=309158"; internal GeneralOptions(PythonToolsService service) { _pyService = service; } public void Load() { ShowOutputWindowForVirtualEnvCreate = _pyService.LoadBool(ShowOutputWindowForVirtualEnvCreateSetting, GeneralCategory) ?? true; ShowOutputWindowForPackageInstallation = _pyService.LoadBool(ShowOutputWindowForPackageInstallationSetting, GeneralCategory) ?? true; PromptForEnvCreate = _pyService.LoadBool(PromptForEnvCreateSetting, GeneralCategory) ?? true; PromptForPackageInstallation = _pyService.LoadBool(PromptForPackageInstallationSetting, GeneralCategory) ?? true; PromptForTestFrameWorkInfoBar = _pyService.LoadBool(PromptForTestFrameWorkInfoBarSetting, GeneralCategory) ?? true; PromptForPythonVersionNotSupported = _pyService.LoadBool(PromptForPythonVersionNotSupportedInfoBarSetting, GeneralCategory) ?? true; ElevatePip = _pyService.LoadBool(ElevatePipSetting, GeneralCategory) ?? false; UnresolvedImportWarning = _pyService.LoadBool(UnresolvedImportWarningSetting, GeneralCategory) ?? true; InvalidEncodingWarning = _pyService.LoadBool(InvalidEncodingWarningSetting, GeneralCategory) ?? true; ClearGlobalPythonPath = _pyService.LoadBool(ClearGlobalPythonPathSetting, GeneralCategory) ?? true; AutoAnalyzeStandardLibrary = _pyService.LoadBool(AutoAnalysisSetting, AdvancedCategory) ?? true; IndentationInconsistencySeverity = _pyService.LoadEnum<Severity>(IndentationInconsistencySeveritySetting, AdvancedCategory) ?? Severity.Warning; UpdateSearchPathsWhenAddingLinkedFiles = _pyService.LoadBool(UpdateSearchPathsWhenAddingLinkedFilesSetting, AdvancedCategory) ?? true; var analysisLimit = _pyService.LoadString(CrossModuleAnalysisLimitSetting, AdvancedCategory); if (analysisLimit == null) { CrossModuleAnalysisLimit = 1300; // default analysis limit } else if (analysisLimit == "-") { CrossModuleAnalysisLimit = null; } else { CrossModuleAnalysisLimit = Convert.ToInt32(analysisLimit); } Changed?.Invoke(this, EventArgs.Empty); } public void Save() { _pyService.SaveBool(ShowOutputWindowForVirtualEnvCreateSetting, GeneralCategory, ShowOutputWindowForVirtualEnvCreate); _pyService.SaveBool(ShowOutputWindowForPackageInstallationSetting, GeneralCategory, ShowOutputWindowForPackageInstallation); _pyService.SaveBool(PromptForEnvCreateSetting, GeneralCategory, PromptForEnvCreate); _pyService.SaveBool(PromptForPackageInstallationSetting, GeneralCategory, PromptForPackageInstallation); _pyService.SaveBool(PromptForTestFrameWorkInfoBarSetting, GeneralCategory, PromptForTestFrameWorkInfoBar); _pyService.SaveBool(PromptForPythonVersionNotSupportedInfoBarSetting, GeneralCategory, PromptForPythonVersionNotSupported); _pyService.SaveBool(ElevatePipSetting, GeneralCategory, ElevatePip); _pyService.SaveBool(UnresolvedImportWarningSetting, GeneralCategory, UnresolvedImportWarning); _pyService.SaveBool(ClearGlobalPythonPathSetting, GeneralCategory, ClearGlobalPythonPath); _pyService.SaveBool(AutoAnalysisSetting, AdvancedCategory, AutoAnalyzeStandardLibrary); _pyService.SaveBool(UpdateSearchPathsWhenAddingLinkedFilesSetting, AdvancedCategory, UpdateSearchPathsWhenAddingLinkedFiles); _pyService.SaveEnum(IndentationInconsistencySeveritySetting, AdvancedCategory, _indentationInconsistencySeverity); if (CrossModuleAnalysisLimit != null) { _pyService.SaveInt(CrossModuleAnalysisLimitSetting, AdvancedCategory, CrossModuleAnalysisLimit.Value); } else { _pyService.SaveString(CrossModuleAnalysisLimitSetting, AdvancedCategory, "-"); } Changed?.Invoke(this, EventArgs.Empty); } public void Reset() { ShowOutputWindowForVirtualEnvCreate = true; ShowOutputWindowForPackageInstallation = true; PromptForEnvCreate = true; PromptForPackageInstallation = true; PromptForTestFrameWorkInfoBar = true; PromptForPythonVersionNotSupported = true; ElevatePip = false; UnresolvedImportWarning = true; ClearGlobalPythonPath = true; IndentationInconsistencySeverity = Severity.Warning; AutoAnalyzeStandardLibrary = true; UpdateSearchPathsWhenAddingLinkedFiles = true; CrossModuleAnalysisLimit = null; Changed?.Invoke(this, EventArgs.Empty); } public event EventHandler Changed; /// <summary> /// True to start analyzing an environment when it is used and has no /// database. Default is true. /// </summary> public bool AutoAnalyzeStandardLibrary { get; set; } /// <summary> /// The severity to apply to inconsistent indentation. Default is warn. /// </summary> public Severity IndentationInconsistencySeverity { get { return _indentationInconsistencySeverity; } set { _indentationInconsistencySeverity = value; var changed = IndentationInconsistencyChanged; if (changed != null) { changed(this, EventArgs.Empty); } } } /// <summary> /// Maximum number of calls between modules to analyze. Default is 1300. /// </summary> public int? CrossModuleAnalysisLimit { get; set; } /// <summary> /// True to update search paths when adding linked files. Default is /// true. /// </summary> /// <remarks>New in 1.1</remarks> public bool UpdateSearchPathsWhenAddingLinkedFiles { get; set; } public event EventHandler IndentationInconsistencyChanged; /// <summary> /// Show the output window for virtual environment creation. /// </summary> /// <remarks>New in 2.0</remarks> public bool ShowOutputWindowForVirtualEnvCreate { get; set; } /// <summary> /// Show the output window for package installation. /// </summary> /// <remarks>New in 2.0</remarks> public bool ShowOutputWindowForPackageInstallation { get; set; } /// <summary> /// Show an info bar to propose creating an environment. /// </summary> /// <remarks>New in 2.0</remarks> public bool PromptForEnvCreate { get; set; } /// <summary> /// Show an info bar to propose installing missing packages. /// </summary> /// <remarks>New in 2.0</remarks> public bool PromptForPackageInstallation { get; set; } /// <summary> /// Show an info bar to set up a testing framework /// </summary> /// <remarks>New in 2.0</remarks> public bool PromptForTestFrameWorkInfoBar { get; set; } /// <summary> /// Show an info bar if an unsupported Python version is in use /// </summary> /// <remarks>New in 2.0</remarks> public bool PromptForPythonVersionNotSupported { get; set; } /// <summary> /// True to always run pip elevated when installing or uninstalling /// packages. /// </summary> public bool ElevatePip { get; set; } /// <summary> /// True to warn when a module is not resolved. /// </summary> /// <remarks>New in 2.1</remarks> public bool UnresolvedImportWarning { get; set; } /// <summary> /// True to mask global environment paths when launching projects. /// </summary> /// <remarks>New in 2.1</remarks> public bool ClearGlobalPythonPath { get; set; } /// <summary> /// True to warn when a file encoding does not match Python /// 'coding' designation in the beginning of the file. /// </summary> /// <remarks>New in 3.3</remarks> public bool InvalidEncodingWarning { get; set; } } }
using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Text; namespace Orleans.Runtime { /// <summary> /// The Utils class contains a variety of utility methods for use in application and grain code. /// </summary> public static class Utils { /// <summary> /// Returns a human-readable text string that describes an IEnumerable collection of objects. /// </summary> /// <typeparam name="T">The type of the list elements.</typeparam> /// <param name="collection">The IEnumerable to describe.</param> /// <param name="toString">Converts the element to a string. If none specified, <see cref="object.ToString"/> will be used.</param> /// <param name="separator">The separator to use.</param> /// <param name="putInBrackets">Puts elements within brackets</param> /// <returns>A string assembled by wrapping the string descriptions of the individual /// elements with square brackets and separating them with commas.</returns> public static string EnumerableToString<T>(IEnumerable<T> collection, Func<T, string> toString = null, string separator = ", ", bool putInBrackets = true) { if (collection == null) { if (putInBrackets) return "[]"; else return "null"; } var sb = new StringBuilder(); if (putInBrackets) sb.Append("["); var enumerator = collection.GetEnumerator(); bool firstDone = false; while (enumerator.MoveNext()) { T value = enumerator.Current; string val; if (toString != null) val = toString(value); else val = value == null ? "null" : value.ToString(); if (firstDone) { sb.Append(separator); sb.Append(val); } else { sb.Append(val); firstDone = true; } } if (putInBrackets) sb.Append("]"); return sb.ToString(); } /// <summary> /// Returns a human-readable text string that describes a dictionary that maps objects to objects. /// </summary> /// <typeparam name="T1">The type of the dictionary keys.</typeparam> /// <typeparam name="T2">The type of the dictionary elements.</typeparam> /// <param name="dict">The dictionary to describe.</param> /// <param name="toString">Converts the element to a string. If none specified, <see cref="object.ToString"/> will be used.</param> /// <param name="separator">The separator to use. If none specified, the elements should appear separated by a new line.</param> /// <returns>A string assembled by wrapping the string descriptions of the individual /// pairs with square brackets and separating them with commas. /// Each key-value pair is represented as the string description of the key followed by /// the string description of the value, /// separated by " -> ", and enclosed in curly brackets.</returns> public static string DictionaryToString<T1, T2>(ICollection<KeyValuePair<T1, T2>> dict, Func<T2, string> toString = null, string separator = null) { if (dict == null || dict.Count == 0) { return "[]"; } if (separator == null) { separator = Environment.NewLine; } var sb = new StringBuilder("["); var enumerator = dict.GetEnumerator(); int index = 0; while (enumerator.MoveNext()) { var pair = enumerator.Current; sb.Append("{"); sb.Append(pair.Key); sb.Append(" -> "); string val; if (toString != null) val = toString(pair.Value); else val = pair.Value == null ? "null" : pair.Value.ToString(); sb.Append(val); sb.Append("}"); if (index++ < dict.Count - 1) sb.Append(separator); } sb.Append("]"); return sb.ToString(); } public static string TimeSpanToString(TimeSpan timeSpan) { //00:03:32.8289777 return String.Format("{0}h:{1}m:{2}s.{3}ms", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds); } public static long TicksToMilliSeconds(long ticks) { return (long)TimeSpan.FromTicks(ticks).TotalMilliseconds; } public static float AverageTicksToMilliSeconds(float ticks) { return (float)TimeSpan.FromTicks((long)ticks).TotalMilliseconds; } /// <summary> /// Parse a Uri as an IPEndpoint. /// </summary> /// <param name="uri">The input Uri</param> /// <returns></returns> public static System.Net.IPEndPoint ToIPEndPoint(this Uri uri) { switch (uri.Scheme) { case "gwy.tcp": return new System.Net.IPEndPoint(System.Net.IPAddress.Parse(uri.Host), uri.Port); } return null; } /// <summary> /// Parse a Uri as a Silo address, including the IPEndpoint and generation identifier. /// </summary> /// <param name="uri">The input Uri</param> /// <returns></returns> public static SiloAddress ToSiloAddress(this Uri uri) { switch (uri.Scheme) { case "gwy.tcp": return SiloAddress.New(uri.ToIPEndPoint(), uri.Segments.Length > 1 ? int.Parse(uri.Segments[1]) : 0); } return null; } /// <summary> /// Represent an IP end point in the gateway URI format.. /// </summary> /// <param name="ep">The input IP end point</param> /// <returns></returns> public static Uri ToGatewayUri(this System.Net.IPEndPoint ep) { var builder = new UriBuilder("gwy.tcp", ep.Address.ToString(), ep.Port, "0"); return builder.Uri; } /// <summary> /// Represent a silo address in the gateway URI format. /// </summary> /// <param name="address">The input silo address</param> /// <returns></returns> public static Uri ToGatewayUri(this SiloAddress address) { var builder = new UriBuilder("gwy.tcp", address.Endpoint.Address.ToString(), address.Endpoint.Port, address.Generation.ToString()); return builder.Uri; } /// <summary> /// Calculates an integer hash value based on the consistent identity hash of a string. /// </summary> /// <param name="text">The string to hash.</param> /// <returns>An integer hash for the string.</returns> public static int CalculateIdHash(string text) { SHA256 sha = SHA256.Create(); // This is one implementation of the abstract class SHA1. int hash = 0; try { byte[] data = Encoding.Unicode.GetBytes(text); byte[] result = sha.ComputeHash(data); for (int i = 0; i < result.Length; i += 4) { int tmp = (result[i] << 24) | (result[i + 1] << 16) | (result[i + 2] << 8) | (result[i + 3]); hash = hash ^ tmp; } } finally { sha.Dispose(); } return hash; } /// <summary> /// Calculates a Guid hash value based on the consistent identity a string. /// </summary> /// <param name="text">The string to hash.</param> /// <returns>An integer hash for the string.</returns> internal static Guid CalculateGuidHash(string text) { SHA256 sha = SHA256.Create(); // This is one implementation of the abstract class SHA1. byte[] hash = new byte[16]; try { byte[] data = Encoding.Unicode.GetBytes(text); byte[] result = sha.ComputeHash(data); for (int i = 0; i < result.Length; i ++) { byte tmp = (byte)(hash[i % 16] ^ result[i]); hash[i%16] = tmp; } } finally { sha.Dispose(); } return new Guid(hash); } public static bool TryFindException(Exception original, Type targetType, out Exception target) { if (original.GetType() == targetType) { target = original; return true; } else if (original is AggregateException) { var baseEx = original.GetBaseException(); if (baseEx.GetType() == targetType) { target = baseEx; return true; } else { var newEx = ((AggregateException)original).Flatten(); foreach (var exc in newEx.InnerExceptions) { if (exc.GetType() == targetType) { target = newEx; return true; } } } } target = null; return false; } public static void SafeExecute(Action action, ILogger logger = null, string caller = null) { SafeExecute(action, logger, caller==null ? (Func<string>)null : () => caller); } // a function to safely execute an action without any exception being thrown. // callerGetter function is called only in faulty case (now string is generated in the success case). [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public static void SafeExecute(Action action, ILogger logger, Func<string> callerGetter) { try { action(); } catch (Exception exc) { try { if (logger != null) { string caller = null; if (callerGetter != null) { try { caller = callerGetter(); }catch (Exception) { } } foreach (var e in exc.FlattenAggregate()) { logger.Warn(ErrorCode.Runtime_Error_100325, $"Ignoring {e.GetType().FullName} exception thrown from an action called by {caller ?? String.Empty}.", exc); } } } catch (Exception) { // now really, really ignore. } } } public static TimeSpan Since(DateTime start) { return DateTime.UtcNow.Subtract(start); } public static List<Exception> FlattenAggregate(this Exception exc) { var result = new List<Exception>(); if (exc is AggregateException) result.AddRange(exc.InnerException.FlattenAggregate()); else result.Add(exc); return result; } public static AggregateException Flatten(this ReflectionTypeLoadException rtle) { // if ReflectionTypeLoadException is thrown, we need to provide the // LoaderExceptions property in order to make it meaningful. var all = new List<Exception> { rtle }; all.AddRange(rtle.LoaderExceptions); throw new AggregateException("A ReflectionTypeLoadException has been thrown. The original exception and the contents of the LoaderExceptions property have been aggregated for your convenience.", all); } /// <summary> /// </summary> public static IEnumerable<List<T>> BatchIEnumerable<T>(this IEnumerable<T> sequence, int batchSize) { var batch = new List<T>(batchSize); foreach (var item in sequence) { batch.Add(item); // when we've accumulated enough in the batch, send it out if (batch.Count >= batchSize) { yield return batch; // batch.ToArray(); batch = new List<T>(batchSize); } } if (batch.Count > 0) { yield return batch; //batch.ToArray(); } } [MethodImpl(MethodImplOptions.NoInlining)] public static string GetStackTrace(int skipFrames = 0) { skipFrames += 1; //skip this method from the stack trace #if NETSTANDARD skipFrames += 2; //skip the 2 Environment.StackTrace related methods. var stackTrace = Environment.StackTrace; for (int i = 0; i < skipFrames; i++) { stackTrace = stackTrace.Substring(stackTrace.IndexOf(Environment.NewLine) + Environment.NewLine.Length); } return stackTrace; #else return new System.Diagnostics.StackTrace(skipFrames).ToString(); #endif } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using MicroOrm.Dapper.Repositories.SqlGenerator; namespace MicroOrm.Dapper.Repositories { /// <summary> /// interface for repository /// </summary> public interface IDapperRepository<TEntity> where TEntity : class { /// <summary> /// DB Connection /// </summary> IDbConnection Connection { get; } /// <summary> /// SQL Genetator /// </summary> ISqlGenerator<TEntity> SqlGenerator { get; } /// <summary> /// Get number of rows /// </summary> int Count(); /// <summary> /// Get number of rows /// </summary> int Count(IDbTransaction transaction); /// <summary> /// Get number of rows with WHERE clause /// </summary> int Count(Expression<Func<TEntity, bool>> predicate); /// <summary> /// Get number of rows with WHERE clause /// </summary> int Count(Expression<Func<TEntity, bool>> predicate, IDbTransaction transaction); /// <summary> /// Get number of rows with DISTINCT clause /// </summary> int Count(Expression<Func<TEntity, object>> distinctField); /// <summary> /// Get number of rows with DISTINCT clause /// </summary> int Count(Expression<Func<TEntity, object>> distinctField, IDbTransaction transaction); /// <summary> /// Get number of rows with DISTINCT and WHERE clause /// </summary> int Count(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> distinctField); /// <summary> /// Get number of rows with DISTINCT and WHERE clause /// </summary> int Count(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> distinctField, IDbTransaction transaction); /// <summary> /// Get number of rows /// </summary> Task<int> CountAsync(); /// <summary> /// Get number of rows /// </summary> Task<int> CountAsync(IDbTransaction transaction); /// <summary> /// Get number of rows with WHERE clause /// </summary> Task<int> CountAsync(Expression<Func<TEntity, bool>> predicate); /// <summary> /// Get number of rows with WHERE clause /// </summary> Task<int> CountAsync(Expression<Func<TEntity, bool>> predicate, IDbTransaction transaction); /// <summary> /// Get number of rows with DISTINCT clause /// </summary> Task<int> CountAsync(Expression<Func<TEntity, object>> distinctField); /// <summary> /// Get number of rows with DISTINCT clause /// </summary> Task<int> CountAsync(Expression<Func<TEntity, object>> distinctField, IDbTransaction transaction); /// <summary> /// Get number of rows with DISTINCT and WHERE clause /// </summary> Task<int> CountAsync(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> distinctField); /// <summary> /// Get number of rows with DISTINCT and WHERE clause /// </summary> Task<int> CountAsync(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> distinctField, IDbTransaction transaction); /// <summary> /// Get first object /// </summary> TEntity Find(); /// <summary> /// Get first object /// </summary> TEntity Find(Expression<Func<TEntity, bool>> predicate); /// <summary> /// Get first object /// </summary> TEntity Find(IDbTransaction transaction); /// <summary> /// Get first object /// </summary> TEntity Find(Expression<Func<TEntity, bool>> predicate, IDbTransaction transaction); /// <summary> /// Get first object with join objects /// </summary> TEntity Find<TChild1>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, IDbTransaction transaction = null); /// <summary> /// Get first object with join objects /// </summary> TEntity Find<TChild1, TChild2>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, IDbTransaction transaction = null); /// <summary> /// Get first object with join objects /// </summary> TEntity Find<TChild1, TChild2, TChild3>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, IDbTransaction transaction = null); /// <summary> /// Get first object with join objects /// </summary> TEntity Find<TChild1, TChild2, TChild3, TChild4>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, Expression<Func<TEntity, object>> tChild4, IDbTransaction transaction = null); /// <summary> /// Get first object with join objects /// </summary> TEntity Find<TChild1, TChild2, TChild3, TChild4, TChild5>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, Expression<Func<TEntity, object>> tChild4, Expression<Func<TEntity, object>> tChild5, IDbTransaction transaction = null); /// <summary> /// Get first object with join objects /// </summary> TEntity Find<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, Expression<Func<TEntity, object>> tChild4, Expression<Func<TEntity, object>> tChild5, Expression<Func<TEntity, object>> tChild6, IDbTransaction transaction = null); /// <summary> /// Get object by Id /// </summary> TEntity FindById(object id); /// <summary> /// Get object by Id /// </summary> TEntity FindById(object id, IDbTransaction transaction); /// <summary> /// Get object by Id with join objects /// </summary> TEntity FindById<TChild1>(object id, Expression<Func<TEntity, object>> tChild1, IDbTransaction transaction = null); /// <summary> /// Get object by Id with join objects /// </summary> TEntity FindById<TChild1, TChild2>(object id, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, IDbTransaction transaction = null); /// <summary> /// Get object by Id with join objects /// </summary> TEntity FindById<TChild1, TChild2, TChild3>(object id, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, IDbTransaction transaction = null); /// <summary> /// Get object by Id with join objects /// </summary> TEntity FindById<TChild1, TChild2, TChild3, TChild4>(object id, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, Expression<Func<TEntity, object>> tChild4, IDbTransaction transaction = null); /// <summary> /// Get object by Id with join objects /// </summary> TEntity FindById<TChild1, TChild2, TChild3, TChild4, TChild5>(object id, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, Expression<Func<TEntity, object>> tChild4, Expression<Func<TEntity, object>> tChild5, IDbTransaction transaction = null); /// <summary> /// Get object by Id with join objects /// </summary> TEntity FindById<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(object id, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, Expression<Func<TEntity, object>> tChild4, Expression<Func<TEntity, object>> tChild5, Expression<Func<TEntity, object>> tChild6, IDbTransaction transaction = null); /// <summary> /// Get object by Id /// </summary> Task<TEntity> FindByIdAsync(object id); /// <summary> /// Get object by Id /// </summary> Task<TEntity> FindByIdAsync(object id, IDbTransaction transaction); /// <summary> /// Get object by Id with join objects /// </summary> Task<TEntity> FindByIdAsync<TChild1>(object id, Expression<Func<TEntity, object>> tChild1, IDbTransaction transaction = null); /// <summary> /// Get object by Id with join objects /// </summary> Task<TEntity> FindByIdAsync<TChild1, TChild2>(object id, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, IDbTransaction transaction = null); /// <summary> /// Get object by Id with join objects /// </summary> Task<TEntity> FindByIdAsync<TChild1, TChild2, TChild3>(object id, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, IDbTransaction transaction = null); /// <summary> /// Get object by Id with join objects /// </summary> Task<TEntity> FindByIdAsync<TChild1, TChild2, TChild3, TChild4>(object id, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, Expression<Func<TEntity, object>> tChild4, IDbTransaction transaction = null); /// <summary> /// Get object by Id with join objects /// </summary> Task<TEntity> FindByIdAsync<TChild1, TChild2, TChild3, TChild4, TChild5>(object id, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, Expression<Func<TEntity, object>> tChild4, Expression<Func<TEntity, object>> tChild5, IDbTransaction transaction = null); /// <summary> /// Get object by Id with join objects /// </summary> Task<TEntity> FindByIdAsync<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(object id, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, Expression<Func<TEntity, object>> tChild4, Expression<Func<TEntity, object>> tChild5, Expression<Func<TEntity, object>> tChild6, IDbTransaction transaction = null); /// <summary> /// Get first object /// </summary> Task<TEntity> FindAsync(); /// <summary> /// Get first object /// </summary> Task<TEntity> FindAsync(IDbTransaction transaction); /// <summary> /// Get first object /// </summary> Task<TEntity> FindAsync(Expression<Func<TEntity, bool>> predicate); /// <summary> /// Get first object /// </summary> Task<TEntity> FindAsync(Expression<Func<TEntity, bool>> predicate, IDbTransaction transaction); /// <summary> /// Get first object with join objects /// </summary> Task<TEntity> FindAsync<TChild1>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, IDbTransaction transaction = null); /// <summary> /// Get first object with join objects /// </summary> Task<TEntity> FindAsync<TChild1, TChild2>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, IDbTransaction transaction = null); /// <summary> /// Get first object with join objects /// </summary> Task<TEntity> FindAsync<TChild1, TChild2, TChild3>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, IDbTransaction transaction = null); /// <summary> /// Get first object with join objects /// </summary> Task<TEntity> FindAsync<TChild1, TChild2, TChild3, TChild4>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, Expression<Func<TEntity, object>> tChild4, IDbTransaction transaction = null); /// <summary> /// Get first object with join objects /// </summary> Task<TEntity> FindAsync<TChild1, TChild2, TChild3, TChild4, TChild5>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, Expression<Func<TEntity, object>> tChild4, Expression<Func<TEntity, object>> tChild5, IDbTransaction transaction = null); /// <summary> /// Get first object with join objects /// </summary> Task<TEntity> FindAsync<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, Expression<Func<TEntity, object>> tChild4, Expression<Func<TEntity, object>> tChild5, Expression<Func<TEntity, object>> tChild6, IDbTransaction transaction = null); /// <summary> /// Get all objects /// </summary> IEnumerable<TEntity> FindAll(IDbTransaction transaction = null); /// <summary> /// Get all objects /// </summary> IEnumerable<TEntity> FindAll(Expression<Func<TEntity, bool>> predicate, IDbTransaction transaction = null); /// <summary> /// Get all objects with join objects /// </summary> IEnumerable<TEntity> FindAll<TChild1>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, IDbTransaction transaction = null); /// <summary> /// Get all objects with join objects /// </summary> IEnumerable<TEntity> FindAll<TChild1, TChild2>( Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, IDbTransaction transaction = null); /// <summary> /// Get all objects with join objects /// </summary> IEnumerable<TEntity> FindAll<TChild1, TChild2, TChild3>( Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, IDbTransaction transaction = null); /// <summary> /// Get all objects with join objects /// </summary> IEnumerable<TEntity> FindAll<TChild1, TChild2, TChild3, TChild4>( Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, Expression<Func<TEntity, object>> tChild4, IDbTransaction transaction = null); /// <summary> /// Get all objects with join objects /// </summary> IEnumerable<TEntity> FindAll<TChild1, TChild2, TChild3, TChild4, TChild5>( Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, Expression<Func<TEntity, object>> tChild4, Expression<Func<TEntity, object>> tChild5, IDbTransaction transaction = null); /// <summary> /// Get all objects with join objects /// </summary> IEnumerable<TEntity> FindAll<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>( Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, Expression<Func<TEntity, object>> tChild4, Expression<Func<TEntity, object>> tChild5, Expression<Func<TEntity, object>> tChild6, IDbTransaction transaction = null); /// <summary> /// Get all objects /// </summary> Task<IEnumerable<TEntity>> FindAllAsync(IDbTransaction transaction = null); /// <summary> /// Get all objects /// </summary> Task<IEnumerable<TEntity>> FindAllAsync(Expression<Func<TEntity, bool>> predicate, IDbTransaction transaction = null); /// <summary> /// Get all objects with join objects /// </summary> Task<IEnumerable<TEntity>> FindAllAsync<TChild1>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, IDbTransaction transaction = null); /// <summary> /// Get all objects with join objects /// </summary> Task<IEnumerable<TEntity>> FindAllAsync<TChild1, TChild2>( Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, IDbTransaction transaction = null); /// <summary> /// Get all objects with join objects /// </summary> Task<IEnumerable<TEntity>> FindAllAsync<TChild1, TChild2, TChild3>( Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, IDbTransaction transaction = null); /// <summary> /// Get all objects with join objects /// </summary> Task<IEnumerable<TEntity>> FindAllAsync<TChild1, TChild2, TChild3, TChild4>( Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, Expression<Func<TEntity, object>> tChild4, IDbTransaction transaction = null); /// <summary> /// Get all objects with join objects /// </summary> Task<IEnumerable<TEntity>> FindAllAsync<TChild1, TChild2, TChild3, TChild4, TChild5>( Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, Expression<Func<TEntity, object>> tChild4, Expression<Func<TEntity, object>> tChild5, IDbTransaction transaction = null); /// <summary> /// Get all objects with join objects /// </summary> Task<IEnumerable<TEntity>> FindAllAsync<TChild1, TChild2, TChild3, TChild4, TChild5, TChild6>( Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> tChild1, Expression<Func<TEntity, object>> tChild2, Expression<Func<TEntity, object>> tChild3, Expression<Func<TEntity, object>> tChild4, Expression<Func<TEntity, object>> tChild5, Expression<Func<TEntity, object>> tChild6, IDbTransaction transaction = null); /// <summary> /// Insert object to DB /// </summary> bool Insert(TEntity instance); /// <summary> /// Insert object to DB /// </summary> bool Insert(TEntity instance, IDbTransaction transaction); /// <summary> /// Insert object to DB /// </summary> Task<bool> InsertAsync(TEntity instance); /// <summary> /// Insert object to DB /// </summary> Task<bool> InsertAsync(TEntity instance, IDbTransaction transaction); /// <summary> /// Bulk Insert objects to DB /// </summary> int BulkInsert(IEnumerable<TEntity> instances, IDbTransaction transaction = null); /// <summary> /// Bulk Insert objects to DB /// </summary> Task<int> BulkInsertAsync(IEnumerable<TEntity> instances, IDbTransaction transaction = null); /// <summary> /// Delete object from DB /// </summary> bool Delete(TEntity instance, IDbTransaction transaction = null); /// <summary> /// Delete object from DB /// </summary> Task<bool> DeleteAsync(TEntity instance, IDbTransaction transaction = null); /// <summary> /// Delete objects from DB /// </summary> bool Delete(Expression<Func<TEntity, bool>> predicate, IDbTransaction transaction = null); /// <summary> /// Delete objects from DB /// </summary> Task<bool> DeleteAsync(Expression<Func<TEntity, bool>> predicate, IDbTransaction transaction = null); /// <summary> /// Update object in DB /// </summary> bool Update(TEntity instance); /// <summary> /// Update object in DB /// </summary> bool Update(TEntity instance, IDbTransaction transaction); /// <summary> /// Update object in DB /// </summary> Task<bool> UpdateAsync(TEntity instance); /// <summary> /// Update object in DB /// </summary> Task<bool> UpdateAsync(TEntity instance, IDbTransaction transaction); /// <summary> /// Update object in DB /// </summary> bool Update(Expression<Func<TEntity, bool>> predicate, TEntity instance); /// <summary> /// Update object in DB /// </summary> bool Update(Expression<Func<TEntity, bool>> predicate, TEntity instance, IDbTransaction transaction); /// <summary> /// Update object in DB /// </summary> Task<bool> UpdateAsync(Expression<Func<TEntity, bool>> predicate, TEntity instance); /// <summary> /// Update object in DB /// </summary> Task<bool> UpdateAsync(Expression<Func<TEntity, bool>> predicate, TEntity instance, IDbTransaction transaction); /// <summary> /// Bulk Update objects in DB /// </summary> Task<bool> BulkUpdateAsync(IEnumerable<TEntity> instances); /// <summary> /// Bulk Update objects in DB /// </summary> Task<bool> BulkUpdateAsync(IEnumerable<TEntity> instances, IDbTransaction transaction); /// <summary> /// Bulk Update objects in DB /// </summary> Task<bool> BulkUpsertAsync(IEnumerable<TEntity> instances); /// <summary> /// Bulk Upsert objects in DB /// </summary> Task<bool> BulkUpsertAsync(IEnumerable<TEntity> instances, IDbTransaction transaction); /// <summary> /// Updates or Insert object in DB /// </summary> bool UpSert(TEntity instance, IDbTransaction transaction = null); /// <summary> /// Updates or Insert object in DB async /// </summary> /// <param name="instance"></param> /// <param name="transaction"></param> /// <returns></returns> Task<bool> UpSertAsync(TEntity instance, IDbTransaction transaction = null); /// <summary> /// Bulk Update objects in DB /// </summary> bool BulkUpdate(IEnumerable<TEntity> instances); /// <summary> /// Bulk Update objects in DB /// </summary> bool BulkUpdate(IEnumerable<TEntity> instances, IDbTransaction transaction); /// <summary> /// Get all objects with BETWEEN query /// </summary> IEnumerable<TEntity> FindAllBetween(object from, object to, Expression<Func<TEntity, object>> btwField, IDbTransaction transaction = null); /// <summary> /// Get all objects with BETWEEN query /// </summary> IEnumerable<TEntity> FindAllBetween(object from, object to, Expression<Func<TEntity, object>> btwField, Expression<Func<TEntity, bool>> predicate = null, IDbTransaction transaction = null); /// <summary> /// Get all objects with BETWEEN query /// </summary> IEnumerable<TEntity> FindAllBetween(DateTime from, DateTime to, Expression<Func<TEntity, object>> btwField, IDbTransaction transaction = null); /// <summary> /// Get all objects with BETWEEN query /// </summary> IEnumerable<TEntity> FindAllBetween(DateTime from, DateTime to, Expression<Func<TEntity, object>> btwField, Expression<Func<TEntity, bool>> predicate, IDbTransaction transaction = null); /// <summary> /// Get all objects with BETWEEN query /// </summary> Task<IEnumerable<TEntity>> FindAllBetweenAsync(object from, object to, Expression<Func<TEntity, object>> btwField, IDbTransaction transaction = null); /// <summary> /// Get all objects with BETWEEN query /// </summary> Task<IEnumerable<TEntity>> FindAllBetweenAsync(object from, object to, Expression<Func<TEntity, object>> btwField, Expression<Func<TEntity, bool>> predicate, IDbTransaction transaction = null); /// <summary> /// Get all objects with BETWEEN query /// </summary> Task<IEnumerable<TEntity>> FindAllBetweenAsync(DateTime from, DateTime to, Expression<Func<TEntity, object>> btwField, IDbTransaction transaction = null); /// <summary> /// Get all objects with BETWEEN query /// </summary> Task<IEnumerable<TEntity>> FindAllBetweenAsync(DateTime from, DateTime to, Expression<Func<TEntity, object>> btwField, Expression<Func<TEntity, bool>> predicate, IDbTransaction transaction = null); } }
// Copyright (c) Microsoft Open Technologies, Inc. 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.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class CSharpTypeInferenceService { private class TypeInferrer { private readonly SemanticModel semanticModel; private readonly CancellationToken cancellationToken; private readonly HashSet<ExpressionSyntax> seenExpressionInferType = new HashSet<ExpressionSyntax>(); private readonly HashSet<ExpressionSyntax> seenExpressionGetType = new HashSet<ExpressionSyntax>(); internal TypeInferrer( SemanticModel semanticModel, CancellationToken cancellationToken) { this.semanticModel = semanticModel; this.cancellationToken = cancellationToken; } private Compilation Compilation { get { return this.semanticModel.Compilation; } } public IEnumerable<ITypeSymbol> InferTypes(ExpressionSyntax expression) { if (expression != null) { if (seenExpressionInferType.Add(expression)) { var types = InferTypesWorker(expression); if (types.Any()) { return types.Where(t => !IsUnusableType(t)).Distinct(); } } } return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } public IEnumerable<ITypeSymbol> InferTypes(int position) { var types = InferTypesWorker(position); if (types.Any()) { return types.Where(t => !IsUnusableType(t)).Distinct(); } return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } private static bool IsUnusableType(ITypeSymbol otherSideType) { if (otherSideType == null) { return true; } return otherSideType.IsErrorType() && (otherSideType.Name == string.Empty || otherSideType.Name == "var"); } // TODO: Add support for Expression<T> private IEnumerable<ITypeSymbol> GetTypes(ExpressionSyntax expression) { if (seenExpressionGetType.Add(expression)) { IEnumerable<ITypeSymbol> types; // BUG: (vladres) Are following expressions parenthesized correctly? // BUG: // BUG: (davip) It is parenthesized incorrectly. This problem was introduced in Changeset 822325 when // BUG: this method was changed from returning a single ITypeSymbol to returning an IEnumerable<ITypeSymbol> // BUG: to better deal with overloads. The old version was: // BUG: // BUG: if (!IsUnusableType(type = GetTypeSimple(expression)) || // BUG: !IsUnusableType(type = GetTypeComplex(expression))) // BUG: { return type; } // BUG: // BUG: The intent is to only use *usable* types, whether simple or complex. I have confirmed this intent with Ravi, who made the change. // BUG: // BUG: Note that the current implementation of GetTypesComplex and GetTypesSimple already ensure the returned value // BUG: is a usable type, so there should not (currently) be any observable effect of this logic error. // BUG: // BUG: (vladres) Please remove this comment once the bug is fixed. if ((types = GetTypesSimple(expression).Where(t => !IsUnusableType(t))).Any() || (types = GetTypesComplex(expression)).Where(t => !IsUnusableType(t)).Any()) { return types; } } return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } private IEnumerable<ITypeSymbol> GetTypesComplex(ExpressionSyntax expression) { var binaryExpression = expression as BinaryExpressionSyntax; if (binaryExpression != null) { var types = InferTypeInBinaryExpression(binaryExpression, binaryExpression.Left).Where(t => !IsUnusableType(t)); if (types.IsEmpty()) { types = InferTypeInBinaryExpression(binaryExpression, binaryExpression.Right).Where(t => !IsUnusableType(t)); } return types; } // TODO(cyrusn): More cases if necessary. return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } private IEnumerable<ITypeSymbol> GetTypesSimple(ExpressionSyntax expression) { if (expression != null) { var typeInfo = this.semanticModel.GetTypeInfo(expression, cancellationToken); var symbolInfo = this.semanticModel.GetSymbolInfo(expression, cancellationToken); if (symbolInfo.CandidateReason != CandidateReason.WrongArity) { ITypeSymbol type = typeInfo.Type; // If it bound to a method, try to get the Action/Func form of that method. if (type == null && symbolInfo.GetAllSymbols().Count() == 1 && symbolInfo.GetAllSymbols().First().Kind == SymbolKind.Method) { var method = symbolInfo.GetAllSymbols().First(); type = method.ConvertToType(this.Compilation); } if (!IsUnusableType(type)) { return SpecializedCollections.SingletonEnumerable(type); } } } return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } private IEnumerable<ITypeSymbol> InferTypesWorker(ExpressionSyntax expression) { expression = expression.WalkUpParentheses(); var parent = expression.Parent; return parent.TypeSwitch( (AnonymousObjectMemberDeclaratorSyntax memberDeclarator) => InferTypeInMemberDeclarator(memberDeclarator), (ArgumentSyntax argument) => InferTypeInArgument(argument), (CheckedExpressionSyntax checkedExpression) => InferTypes(checkedExpression), (ArrayCreationExpressionSyntax arrayCreationExpression) => InferTypeInArrayCreationExpression(arrayCreationExpression), (ArrayRankSpecifierSyntax arrayRankSpecifier) => InferTypeInArrayRankSpecifier(arrayRankSpecifier), (ArrayTypeSyntax arrayType) => InferTypeInArrayType(arrayType), (AttributeArgumentSyntax attribute) => InferTypeInAttributeArgument(attribute), (AttributeSyntax attribute) => InferTypeInAttribute(attribute), (BinaryExpressionSyntax binaryExpression) => InferTypeInBinaryExpression(binaryExpression, expression), (CastExpressionSyntax castExpression) => InferTypeInCastExpression(castExpression, expression), (CatchDeclarationSyntax catchDeclaration) => InferTypeInCatchDeclaration(catchDeclaration), (ConditionalExpressionSyntax conditionalExpression) => InferTypeInConditionalExpression(conditionalExpression, expression), (DoStatementSyntax doStatement) => InferTypeInDoStatement(doStatement), (EqualsValueClauseSyntax equalsValue) => InferTypeInEqualsValueClause(equalsValue), (ExpressionStatementSyntax expressionStatement) => InferTypeInExpressionStatement(expressionStatement), (ForEachStatementSyntax forEachStatement) => InferTypeInForEachStatement(forEachStatement, expression), (ForStatementSyntax forStatement) => InferTypeInForStatement(forStatement, expression), (IfStatementSyntax ifStatement) => InferTypeInIfStatement(ifStatement), (InitializerExpressionSyntax initializerExpression) => InferTypeInInitializerExpression(initializerExpression, expression), (LockStatementSyntax lockStatement) => InferTypeInLockStatement(lockStatement), (NameEqualsSyntax nameEquals) => InferTypeInNameEquals(nameEquals), (ParenthesizedLambdaExpressionSyntax parenthesizedLambdaExpression) => InferTypeInParenthesizedLambdaExpression(parenthesizedLambdaExpression), (PostfixUnaryExpressionSyntax postfixUnary) => InferTypeInPostfixUnaryExpression(postfixUnary), (PrefixUnaryExpressionSyntax prefixUnary) => InferTypeInPrefixUnaryExpression(prefixUnary), (ReturnStatementSyntax returnStatement) => InferTypeForReturnStatement(returnStatement), (SimpleLambdaExpressionSyntax simpleLambdaExpression) => InferTypeInSimpleLambdaExpression(simpleLambdaExpression), (SwitchLabelSyntax switchLabel) => InferTypeInSwitchLabel(switchLabel), (SwitchStatementSyntax switchStatement) => InferTypeInSwitchStatement(switchStatement), (ThrowStatementSyntax throwStatement) => InferTypeInThrowStatement(throwStatement), (UsingStatementSyntax usingStatement) => InferTypeInUsingStatement(usingStatement), (WhileStatementSyntax whileStatement) => InferTypeInWhileStatement(whileStatement), (YieldStatementSyntax yieldStatement) => InferTypeInYieldStatement(yieldStatement), _ => SpecializedCollections.EmptyEnumerable<ITypeSymbol>()); } private IEnumerable<ITypeSymbol> InferTypesWorker(int position) { var syntaxTree = (SyntaxTree)this.semanticModel.SyntaxTree; var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); var parent = token.Parent; return parent.TypeSwitch( (AnonymousObjectMemberDeclaratorSyntax memberDeclarator) => InferTypeInMemberDeclarator(memberDeclarator, token), (ArgumentSyntax argument) => InferTypeInArgument(argument, token), (ArgumentListSyntax argument) => InferTypeInArgumentList(argument, token), (AttributeArgumentSyntax argument) => InferTypeInAttributeArgument(argument, token), (AttributeArgumentListSyntax attributeArgumentList) => InferTypeInAttributeArgumentList(attributeArgumentList, token), (CheckedExpressionSyntax checkedExpression) => InferTypes(checkedExpression), (ArrayCreationExpressionSyntax arrayCreationExpression) => InferTypeInArrayCreationExpression(arrayCreationExpression, token), (ArrayRankSpecifierSyntax arrayRankSpecifier) => InferTypeInArrayRankSpecifier(arrayRankSpecifier, token), (ArrayTypeSyntax arrayType) => InferTypeInArrayType(arrayType, token), (AttributeListSyntax attributeDeclaration) => InferTypeInAttributeDeclaration(attributeDeclaration, token), (BinaryExpressionSyntax binaryExpression) => InferTypeInBinaryExpression(binaryExpression, previousToken: token), (BracketedArgumentListSyntax bracketedArgumentList) => InferTypeInBracketedArgumentList(bracketedArgumentList, token), (CastExpressionSyntax castExpression) => InferTypeInCastExpression(castExpression, previousToken: token), (CatchDeclarationSyntax catchDeclaration) => InferTypeInCatchDeclaration(catchDeclaration, token), (ConditionalExpressionSyntax conditionalExpression) => InferTypeInConditionalExpression(conditionalExpression, previousToken: token), (DoStatementSyntax doStatement) => InferTypeInDoStatement(doStatement, token), (EqualsValueClauseSyntax equalsValue) => InferTypeInEqualsValueClause(equalsValue, token), (ExpressionStatementSyntax expressionStatement) => InferTypeInExpressionStatement(expressionStatement, token), (ForEachStatementSyntax forEachStatement) => InferTypeInForEachStatement(forEachStatement, previousToken: token), (ForStatementSyntax forStatement) => InferTypeInForStatement(forStatement, previousToken: token), (IfStatementSyntax ifStatement) => InferTypeInIfStatement(ifStatement, token), (InitializerExpressionSyntax initializerExpression) => InferTypeInInitializerExpression(initializerExpression, previousToken: token), (LockStatementSyntax lockStatement) => InferTypeInLockStatement(lockStatement, token), (NameColonSyntax nameColon) => InferTypeInNameColon(nameColon, token), (NameEqualsSyntax nameEquals) => InferTypeInNameEquals(nameEquals, token), (ParenthesizedLambdaExpressionSyntax parenthesizedLambdaExpression) => InferTypeInParenthesizedLambdaExpression(parenthesizedLambdaExpression, token), (PostfixUnaryExpressionSyntax postfixUnary) => InferTypeInPostfixUnaryExpression(postfixUnary, token), (PrefixUnaryExpressionSyntax prefixUnary) => InferTypeInPrefixUnaryExpression(prefixUnary, token), (ReturnStatementSyntax returnStatement) => InferTypeForReturnStatement(returnStatement, token), (SimpleLambdaExpressionSyntax simpleLambdaExpression) => InferTypeInSimpleLambdaExpression(simpleLambdaExpression, token), (SwitchLabelSyntax switchLabel) => InferTypeInSwitchLabel(switchLabel, token), (SwitchStatementSyntax switchStatement) => InferTypeInSwitchStatement(switchStatement, token), (ThrowStatementSyntax throwStatement) => InferTypeInThrowStatement(throwStatement, token), (UsingStatementSyntax usingStatement) => InferTypeInUsingStatement(usingStatement, token), (WhileStatementSyntax whileStatement) => InferTypeInWhileStatement(whileStatement, token), (YieldStatementSyntax yieldStatement) => InferTypeInYieldStatement(yieldStatement, token), _ => SpecializedCollections.EmptyEnumerable<ITypeSymbol>()); } private IEnumerable<ITypeSymbol> InferTypeInArgument(ArgumentSyntax argument, SyntaxToken? previousToken = null) { if (previousToken.HasValue) { // If we have a position, then it must be after the colon in a named argument. if (argument.NameColon == null || argument.NameColon.ColonToken != previousToken) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } } if (argument.Parent != null) { var initializer = argument.Parent.Parent as ConstructorInitializerSyntax; if (initializer != null) { var index = initializer.ArgumentList.Arguments.IndexOf(argument); return InferTypeInConstructorInitializer(initializer, index, argument); } if (argument.Parent.IsParentKind(SyntaxKind.InvocationExpression)) { var invocation = argument.Parent.Parent as InvocationExpressionSyntax; var index = invocation.ArgumentList.Arguments.IndexOf(argument); return InferTypeInInvocationExpression(invocation, index, argument); } if (argument.Parent.IsParentKind(SyntaxKind.ObjectCreationExpression)) { // new Outer(Foo()); // // new Outer(a: Foo()); // // etc. var creation = argument.Parent.Parent as ObjectCreationExpressionSyntax; var index = creation.ArgumentList.Arguments.IndexOf(argument); return InferTypeInObjectCreationExpression(creation, index, argument); } if (argument.Parent.IsParentKind(SyntaxKind.ElementAccessExpression)) { // Outer[Foo()]; // // Outer[a: Foo()]; // // etc. var elementAccess = argument.Parent.Parent as ElementAccessExpressionSyntax; var index = elementAccess.ArgumentList.Arguments.IndexOf(argument); return InferTypeInElementAccessExpression(elementAccess, index, argument); } } return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } private IEnumerable<ITypeSymbol> InferTypeInAttributeArgument(AttributeArgumentSyntax argument, SyntaxToken? previousToken = null, ArgumentSyntax argumentOpt = null) { if (previousToken.HasValue) { // If we have a position, then it must be after the colon or equals in an argument. if (argument.NameColon == null || argument.NameColon.ColonToken != previousToken || argument.NameEquals.EqualsToken != previousToken) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } } if (argument.Parent != null) { var attribute = argument.Parent.Parent as AttributeSyntax; if (attribute != null) { var index = attribute.ArgumentList.Arguments.IndexOf(argument); return InferTypeInAttribute(attribute, index, argument); } } return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } private IEnumerable<ITypeSymbol> InferTypeInConstructorInitializer(ConstructorInitializerSyntax initializer, int index, ArgumentSyntax argument = null) { var info = this.semanticModel.GetSymbolInfo(initializer, cancellationToken); var methods = info.GetBestOrAllSymbols().OfType<IMethodSymbol>(); return InferTypeInArgument(index, methods, argument); } private IEnumerable<ITypeSymbol> InferTypeInObjectCreationExpression(ObjectCreationExpressionSyntax creation, int index, ArgumentSyntax argumentOpt = null) { var info = this.semanticModel.GetSymbolInfo(creation.Type, cancellationToken); var type = info.Symbol as INamedTypeSymbol; if (type == null) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } if (type.TypeKind == TypeKind.Delegate) { // new SomeDelegateType( here ); // // They're actually instantiating a delegate, so the delegate type is // that type. return SpecializedCollections.SingletonEnumerable(type); } var constructors = type.InstanceConstructors.Where(m => m.Parameters.Length > index); return InferTypeInArgument(index, constructors, argumentOpt); } private IEnumerable<ITypeSymbol> InferTypeInInvocationExpression( InvocationExpressionSyntax invocation, int index, ArgumentSyntax argumentOpt = null) { // Check all the methods that have at least enough arguments to support // being called with argument at this position. Note: if they're calling an // extension method then it will need one more argument in order for us to // call it. var info = this.semanticModel.GetSymbolInfo(invocation, cancellationToken); IEnumerable<IMethodSymbol> methods = null; // Overload resolution (see DevDiv 611477) in certain extension method cases // can result in GetSymbolInfo returning nothing. In this case, get the // method group info, which is what signature help already does. if (info.CandidateReason == CandidateReason.None) { methods = ((SemanticModel)semanticModel).GetMemberGroup(invocation.Expression, cancellationToken) .OfType<IMethodSymbol>(); } else { methods = info.GetBestOrAllSymbols().OfType<IMethodSymbol>(); } return InferTypeInArgument(index, methods, argumentOpt); } private IEnumerable<ITypeSymbol> InferTypeInArgumentList(ArgumentListSyntax argumentList, SyntaxToken previousToken) { // Has to follow the ( or a , if (previousToken != argumentList.OpenParenToken && previousToken.CSharpKind() != SyntaxKind.CommaToken) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } var invocation = argumentList.Parent as InvocationExpressionSyntax; if (invocation != null) { var index = this.GetArgumentListIndex(argumentList, previousToken); return InferTypeInInvocationExpression(invocation, index); } var objectCreation = argumentList.Parent as ObjectCreationExpressionSyntax; if (objectCreation != null) { var index = this.GetArgumentListIndex(argumentList, previousToken); return InferTypeInObjectCreationExpression(objectCreation, index); } var constructorInitializer = argumentList.Parent as ConstructorInitializerSyntax; if (constructorInitializer != null) { var index = this.GetArgumentListIndex(argumentList, previousToken); return InferTypeInConstructorInitializer(constructorInitializer, index); } return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } private IEnumerable<ITypeSymbol> InferTypeInAttributeArgumentList(AttributeArgumentListSyntax attributeArgumentList, SyntaxToken previousToken) { // Has to follow the ( or a , if (previousToken != attributeArgumentList.OpenParenToken && previousToken.CSharpKind() != SyntaxKind.CommaToken) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } var attribute = attributeArgumentList.Parent as AttributeSyntax; if (attribute != null) { var index = this.GetArgumentListIndex(attributeArgumentList, previousToken); return InferTypeInAttribute(attribute, index); } return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } private IEnumerable<ITypeSymbol> InferTypeInAttribute(AttributeSyntax attribute, int index, AttributeArgumentSyntax argumentOpt = null) { var info = this.semanticModel.GetSymbolInfo(attribute, cancellationToken); var methods = info.GetBestOrAllSymbols().OfType<IMethodSymbol>(); return InferTypeInAttributeArgument(index, methods, argumentOpt); } private IEnumerable<ITypeSymbol> InferTypeInElementAccessExpression( ElementAccessExpressionSyntax elementAccess, int index, ArgumentSyntax argumentOpt = null) { var info = this.semanticModel.GetTypeInfo(elementAccess.Expression, cancellationToken); var type = info.Type as INamedTypeSymbol; if (type != null) { var indexers = type.GetMembers().OfType<IPropertySymbol>() .Where(p => p.IsIndexer && p.Parameters.Length > index); if (indexers.Any()) { return indexers.SelectMany(i => InferTypeInArgument(index, SpecializedCollections.SingletonEnumerable(i.Parameters), argumentOpt)); } } // For everything else, assume it's an integer. Note: this won't be correct for // type parameters that implement some interface, but that seems like a major // corner case for now. // // This does, however, cover the more common cases of // arrays/pointers/errors/dynamic. return SpecializedCollections.SingletonEnumerable(this.Compilation.GetSpecialType(SpecialType.System_Int32)); } private IEnumerable<ITypeSymbol> InferTypeInAttributeArgument(int index, IEnumerable<IMethodSymbol> methods, AttributeArgumentSyntax argumentOpt = null) { return InferTypeInAttributeArgument(index, methods.Select(m => m.Parameters), argumentOpt); } private IEnumerable<ITypeSymbol> InferTypeInArgument(int index, IEnumerable<IMethodSymbol> methods, ArgumentSyntax argumentOpt) { return InferTypeInArgument(index, methods.Select(m => m.Parameters), argumentOpt); } private IEnumerable<ITypeSymbol> InferTypeInAttributeArgument( int index, IEnumerable<ImmutableArray<IParameterSymbol>> parameterizedSymbols, AttributeArgumentSyntax argumentOpt = null) { if (argumentOpt != null && argumentOpt.NameEquals != null) { // [MyAttribute(Prop = ... return InferTypeInNameEquals(argumentOpt.NameEquals, argumentOpt.NameEquals.EqualsToken); } var name = argumentOpt != null && argumentOpt.NameColon != null ? argumentOpt.NameColon.Name.Identifier.ValueText : null; return InferTypeInArgument(index, parameterizedSymbols, name); } private IEnumerable<ITypeSymbol> InferTypeInArgument( int index, IEnumerable<ImmutableArray<IParameterSymbol>> parameterizedSymbols, ArgumentSyntax argumentOpt) { var name = argumentOpt != null && argumentOpt.NameColon != null ? argumentOpt.NameColon.Name.Identifier.ValueText : null; return InferTypeInArgument(index, parameterizedSymbols, name); } private IEnumerable<ITypeSymbol> InferTypeInArgument( int index, IEnumerable<ImmutableArray<IParameterSymbol>> parameterizedSymbols, string name) { // If the callsite has a named argument, then try to find a method overload that has a // parameter with that name. If we can find one, then return the type of that one. if (name != null) { var parameters = parameterizedSymbols.SelectMany(m => m) .Where(p => p.Name == name) .Select(p => p.Type); if (parameters.Any()) { return parameters; } } else { // Otherwise, just take the first overload and pick what type this parameter is // based on index. var q = from parameterSet in parameterizedSymbols where index < parameterSet.Length select parameterSet[index].Type; return q; } return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } private IEnumerable<ITypeSymbol> InferTypeInArrayCreationExpression( ArrayCreationExpressionSyntax arrayCreationExpression, SyntaxToken? previousToken = null) { if (previousToken.HasValue && previousToken.Value != arrayCreationExpression.NewKeyword) { // Has to follow the 'new' keyword. return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } var outerTypes = InferTypes(arrayCreationExpression); return outerTypes.Where(o => o is IArrayTypeSymbol); } private IEnumerable<ITypeSymbol> InferTypeInArrayRankSpecifier(ArrayRankSpecifierSyntax arrayRankSpecifier, SyntaxToken? previousToken = null) { // If we have a token, and it's not the open bracket or one of the commas, then no // inference. if (previousToken == arrayRankSpecifier.CloseBracketToken) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } return SpecializedCollections.SingletonEnumerable(this.Compilation.GetSpecialType(SpecialType.System_Int32)); } private IEnumerable<ITypeSymbol> InferTypeInArrayType(ArrayTypeSyntax arrayType, SyntaxToken? previousToken = null) { if (previousToken.HasValue) { // TODO(cyrusn): NYI. Handle this appropriately if we need to. return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } // Bind the array type, then unwrap whatever we get back based on the number of rank // specifiers we see. var currentTypes = InferTypes(arrayType); for (var i = 0; i < arrayType.RankSpecifiers.Count; i++) { currentTypes = currentTypes.OfType<IArrayTypeSymbol>().Select(c => c.ElementType); } return currentTypes; } private IEnumerable<ITypeSymbol> InferTypeInAttribute(AttributeSyntax attribute) { return SpecializedCollections.SingletonEnumerable(this.Compilation.AttributeType()); } private IEnumerable<ITypeSymbol> InferTypeInAttributeDeclaration(AttributeListSyntax attributeDeclaration, SyntaxToken? previousToken) { // If we have a position, then it has to be after the open bracket. if (previousToken.HasValue && previousToken.Value != attributeDeclaration.AtToken) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } return SpecializedCollections.SingletonEnumerable(this.Compilation.AttributeType()); } //private IEnumerable<ITypeSymbol> InferTypeInAttributeTargetSpecifier( // AttributeTargetSpecifierSyntax attributeTargetSpecifier, // SyntaxToken? previousToken) //{ // // If we have a position, then it has to be after the colon. // if (previousToken.HasValue && previousToken.Value != attributeTargetSpecifier.ColonToken) // { // return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); // } // return SpecializedCollections.SingletonEnumerable(this.Compilation.AttributeType()); //} private IEnumerable<ITypeSymbol> InferTypeInBracketedArgumentList(BracketedArgumentListSyntax bracketedArgumentList, SyntaxToken previousToken) { // Has to follow the [ or a , if (previousToken != bracketedArgumentList.OpenBracketToken && previousToken.CSharpKind() != SyntaxKind.CommaToken) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } var elementAccess = bracketedArgumentList.Parent as ElementAccessExpressionSyntax; if (elementAccess != null) { var index = GetArgumentListIndex(bracketedArgumentList, previousToken); return InferTypeInElementAccessExpression( elementAccess, index); } return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } private int GetArgumentListIndex(BaseArgumentListSyntax argumentList, SyntaxToken previousToken) { if (previousToken == argumentList.GetOpenToken()) { return 0; } //// ( node0 , node1 , node2 , node3 , // // Tokidx 0 1 2 3 4 5 6 7 // // index 1 2 3 // // index = (Tokidx + 1) / 2 var tokenIndex = argumentList.Arguments.GetWithSeparators().IndexOf(previousToken); return (tokenIndex + 1) / 2; } private int GetArgumentListIndex(AttributeArgumentListSyntax attributeArgumentList, SyntaxToken previousToken) { if (previousToken == attributeArgumentList.OpenParenToken) { return 0; } //// ( node0 , node1 , node2 , node3 , // // Tokidx 0 1 2 3 4 5 6 7 // // index 1 2 3 // // index = (Tokidx + 1) / 2 var tokenIndex = attributeArgumentList.Arguments.GetWithSeparators().IndexOf(previousToken); return (tokenIndex + 1) / 2; } private IEnumerable<ITypeSymbol> InferTypeInBinaryExpression(BinaryExpressionSyntax binop, ExpressionSyntax expressionOpt = null, SyntaxToken? previousToken = null) { // If we got here through a token, then it must have actually been the binary // operator's token. Contract.ThrowIfTrue(previousToken.HasValue && previousToken.Value != binop.OperatorToken); if (binop.CSharpKind() == SyntaxKind.CoalesceExpression) { return InferTypeInCoalesceExpression(binop, expressionOpt, previousToken); } var onRightOfToken = binop.Right == expressionOpt || previousToken.HasValue; switch (binop.OperatorToken.CSharpKind()) { case SyntaxKind.LessThanLessThanToken: case SyntaxKind.GreaterThanGreaterThanToken: case SyntaxKind.LessThanLessThanEqualsToken: case SyntaxKind.GreaterThanGreaterThanEqualsToken: if (onRightOfToken) { // x << Foo(), x >> Foo(), x <<= Foo(), x >>= Foo() return SpecializedCollections.SingletonEnumerable(this.Compilation.GetSpecialType(SpecialType.System_Int32)); } break; } // Infer operands of && and || as bool regardless of the other operand. if (binop.OperatorToken.CSharpKind() == SyntaxKind.AmpersandAmpersandToken || binop.OperatorToken.CSharpKind() == SyntaxKind.BarBarToken) { return SpecializedCollections.SingletonEnumerable(this.Compilation.GetSpecialType(SpecialType.System_Boolean)); } // Try to figure out what's on the other side of the binop. If we can, then just that // type. This is often a reasonable heuristics to use for most operators. NOTE(cyrusn): // we could try to bind the token to see what overloaded operators it corresponds to. // But the gain is pretty marginal IMO. var otherSide = onRightOfToken ? binop.Left : binop.Right; var otherSideTypes = GetTypes(otherSide); if (otherSideTypes.Any()) { return otherSideTypes; } // For &, &=, |, |=, ^, and ^=, since we couldn't infer the type of either side, // try to infer the type of the entire binary expression. if (binop.OperatorToken.CSharpKind() == SyntaxKind.AmpersandToken || binop.OperatorToken.CSharpKind() == SyntaxKind.AmpersandEqualsToken || binop.OperatorToken.CSharpKind() == SyntaxKind.BarToken || binop.OperatorToken.CSharpKind() == SyntaxKind.BarEqualsToken || binop.OperatorToken.CSharpKind() == SyntaxKind.CaretToken || binop.OperatorToken.CSharpKind() == SyntaxKind.CaretEqualsToken) { var parentTypes = InferTypes(binop); if (parentTypes.Any()) { return parentTypes; } } // If it's a plus operator, then do some smarts in case it might be a string or // delegate. if (binop.OperatorToken.CSharpKind() == SyntaxKind.PlusToken) { // See Bug 6045. Note: we've already checked the other side of the operator. So this // is the case where the other side was also unknown. So we walk one higher and if // we get a delegate or a string type, then use that type here. var parentTypes = InferTypes(binop); if (parentTypes.Any(parentType => parentType.SpecialType == SpecialType.System_String || parentType.TypeKind == TypeKind.Delegate)) { return parentTypes.Where(parentType => parentType.SpecialType == SpecialType.System_String || parentType.TypeKind == TypeKind.Delegate); } } // Otherwise pick some sane defaults for certain common cases. switch (binop.OperatorToken.CSharpKind()) { case SyntaxKind.BarToken: case SyntaxKind.CaretToken: case SyntaxKind.AmpersandToken: case SyntaxKind.LessThanToken: case SyntaxKind.LessThanEqualsToken: case SyntaxKind.GreaterThanToken: case SyntaxKind.GreaterThanEqualsToken: case SyntaxKind.PlusToken: case SyntaxKind.MinusToken: case SyntaxKind.AsteriskToken: case SyntaxKind.SlashToken: case SyntaxKind.PercentToken: case SyntaxKind.CaretEqualsToken: case SyntaxKind.PlusEqualsToken: case SyntaxKind.MinusEqualsToken: case SyntaxKind.AsteriskEqualsToken: case SyntaxKind.SlashEqualsToken: case SyntaxKind.PercentEqualsToken: case SyntaxKind.LessThanLessThanToken: case SyntaxKind.GreaterThanGreaterThanToken: case SyntaxKind.LessThanLessThanEqualsToken: case SyntaxKind.GreaterThanGreaterThanEqualsToken: return SpecializedCollections.SingletonEnumerable(this.Compilation.GetSpecialType(SpecialType.System_Int32)); case SyntaxKind.BarEqualsToken: case SyntaxKind.AmpersandEqualsToken: // NOTE(cyrusn): |= and &= can be used for both ints and bools However, in the // case where there isn't enough information to determine which the user wanted, // i'm just defaulting to bool based on personal preference. return SpecializedCollections.SingletonEnumerable(this.Compilation.GetSpecialType(SpecialType.System_Boolean)); } return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } private IEnumerable<ITypeSymbol> InferTypeInCastExpression(CastExpressionSyntax castExpression, ExpressionSyntax expressionOpt = null, SyntaxToken? previousToken = null) { if (expressionOpt != null && castExpression.Expression != expressionOpt) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } // If we have a position, then it has to be after the close paren. if (previousToken.HasValue && previousToken.Value != castExpression.CloseParenToken) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } return this.GetTypes(castExpression.Type); } private IEnumerable<ITypeSymbol> InferTypeInCatchDeclaration(CatchDeclarationSyntax catchDeclaration, SyntaxToken? previousToken = null) { // If we have a positoin, it has to be after "catch(" if (previousToken.HasValue && previousToken.Value != catchDeclaration.OpenParenToken) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } return SpecializedCollections.SingletonEnumerable(this.Compilation.ExceptionType()); } private IEnumerable<ITypeSymbol> InferTypeInCoalesceExpression( BinaryExpressionSyntax coalesceExpression, ExpressionSyntax expressionOpt = null, SyntaxToken? previousToken = null) { // If we got here through a token, then it must have actually been the binary // operator's token. Contract.ThrowIfTrue(previousToken.HasValue && previousToken.Value != coalesceExpression.OperatorToken); var onRightSide = coalesceExpression.Right == expressionOpt || previousToken.HasValue; if (onRightSide) { var leftTypes = GetTypes(coalesceExpression.Left); return leftTypes .Select(x => x.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T ? ((INamedTypeSymbol)x).TypeArguments[0] // nullableExpr ?? Foo() : x); // normalExpr ?? Foo() } var rightTypes = GetTypes(coalesceExpression.Right); if (!rightTypes.Any()) { return SpecializedCollections.SingletonEnumerable( this.Compilation.GetSpecialType(SpecialType.System_Nullable_T) .Construct(Compilation.GetSpecialType(SpecialType.System_Object))); } return rightTypes .Select(x => x.IsValueType ? this.Compilation.GetSpecialType(SpecialType.System_Nullable_T).Construct(x) // Foo() ?? 0 : x); // Foo() ?? "" } private IEnumerable<ITypeSymbol> InferTypeInConditionalExpression(ConditionalExpressionSyntax conditional, ExpressionSyntax expressionOpt = null, SyntaxToken? previousToken = null) { if (expressionOpt != null && conditional.Condition == expressionOpt) { // Foo() ? a : b return SpecializedCollections.SingletonEnumerable(this.Compilation.GetSpecialType(SpecialType.System_Boolean)); } // a ? Foo() : b // // a ? b : Foo() var inTrueClause = (conditional.WhenTrue == expressionOpt) || (previousToken == conditional.QuestionToken); var inFalseClause = (conditional.WhenFalse == expressionOpt) || (previousToken == conditional.ColonToken); var otherTypes = inTrueClause ? GetTypes(conditional.WhenFalse) : inFalseClause ? GetTypes(conditional.WhenTrue) : SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); return otherTypes.IsEmpty() ? InferTypes(conditional) : otherTypes; } private IEnumerable<ITypeSymbol> InferTypeInDoStatement(DoStatementSyntax doStatement, SyntaxToken? previousToken = null) { // If we have a position, we need to be after "do { } while(" if (previousToken.HasValue && previousToken.Value != doStatement.OpenParenToken) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } return SpecializedCollections.SingletonEnumerable(this.Compilation.GetSpecialType(SpecialType.System_Boolean)); } private IEnumerable<ITypeSymbol> InferTypeInEqualsValueClause(EqualsValueClauseSyntax equalsValue, SyntaxToken? previousToken = null) { // If we have a position, it has to be after the = if (previousToken.HasValue && previousToken.Value != equalsValue.EqualsToken) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } if (equalsValue.IsParentKind(SyntaxKind.VariableDeclarator)) { return InferTypeInVariableDeclarator((VariableDeclaratorSyntax)equalsValue.Parent); } if (equalsValue.IsParentKind(SyntaxKind.Parameter)) { var parameter = this.semanticModel.GetDeclaredSymbol(equalsValue.Parent, cancellationToken) as IParameterSymbol; if (parameter != null) { return SpecializedCollections.SingletonEnumerable(parameter.Type); } } return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } private IEnumerable<ITypeSymbol> InferTypeInExpressionStatement(ExpressionStatementSyntax expressionStatement, SyntaxToken? previousToken = null) { // If we're position based, then that means we're after the semicolon. In this case // we don't have any sort of type to infer. if (previousToken.HasValue) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } return SpecializedCollections.SingletonEnumerable(this.Compilation.GetSpecialType(SpecialType.System_Void)); } private IEnumerable<ITypeSymbol> InferTypeInForEachStatement(ForEachStatementSyntax forEachStatementSyntax, ExpressionSyntax expressionOpt = null, SyntaxToken? previousToken = null) { // If we have a position, then we have to be after "foreach(... in" if (previousToken.HasValue && previousToken.Value != forEachStatementSyntax.InKeyword) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } if (expressionOpt != null && expressionOpt != forEachStatementSyntax.Expression) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } // foreach (int v = Foo()) var variableTypes = GetTypes(forEachStatementSyntax.Type); if (!variableTypes.Any()) { return SpecializedCollections.SingletonEnumerable( this.Compilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T) .Construct(Compilation.GetSpecialType(SpecialType.System_Object))); } var type = this.Compilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T); return variableTypes.Select(v => type.Construct(v)); } private IEnumerable<ITypeSymbol> InferTypeInForStatement(ForStatementSyntax forStatement, ExpressionSyntax expressionOpt = null, SyntaxToken? previousToken = null) { // If we have a position, it has to be after "for(...;" if (previousToken.HasValue && previousToken.Value != forStatement.FirstSemicolonToken) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } if (expressionOpt != null && forStatement.Condition != expressionOpt) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } return SpecializedCollections.SingletonEnumerable(this.Compilation.GetSpecialType(SpecialType.System_Boolean)); } private IEnumerable<ITypeSymbol> InferTypeInIfStatement(IfStatementSyntax ifStatement, SyntaxToken? previousToken = null) { // If we have a position, we have to be after the "if(" if (previousToken.HasValue && previousToken.Value != ifStatement.OpenParenToken) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } return SpecializedCollections.SingletonEnumerable(this.Compilation.GetSpecialType(SpecialType.System_Boolean)); } private IEnumerable<ITypeSymbol> InferTypeInInitializerExpression( InitializerExpressionSyntax initializerExpression, ExpressionSyntax expressionOpt = null, SyntaxToken? previousToken = null) { if (initializerExpression.IsParentKind(SyntaxKind.ImplicitArrayCreationExpression)) { // First, try to infer the type that the array should be. If we can infer an // appropriate array type, then use the element type of the array. Otherwise, // look at the siblings of this expression and use their type instead. var arrayTypes = this.InferTypes((ExpressionSyntax)initializerExpression.Parent); var elementTypes = arrayTypes.OfType<IArrayTypeSymbol>().Select(a => a.ElementType).Where(e => !IsUnusableType(e)); if (elementTypes.Any()) { return elementTypes; } // { foo(), | if (previousToken.HasValue && previousToken.Value.CSharpKind() == SyntaxKind.CommaToken) { var sibling = initializerExpression.Expressions.FirstOrDefault(e => e.SpanStart < previousToken.Value.SpanStart); if (sibling != null) { var types = GetTypes(sibling); if (types.Any()) { return types; } } } foreach (var sibling in initializerExpression.Expressions) { if (sibling != expressionOpt) { var types = GetTypes(sibling); if (types.Any()) { return types; } } } } else if (initializerExpression.IsParentKind(SyntaxKind.ArrayCreationExpression)) { // new int[] { Foo() } var arrayCreation = (ArrayCreationExpressionSyntax)initializerExpression.Parent; IEnumerable<ITypeSymbol> type = GetTypes(arrayCreation); // BUG: (vladres) Is it a correct type check? // BUG: Is there a type that implements both IEnumerable<ITypeSymbol> and IArrayTypeSymbol? // BUG: Or it was intended to be: // BUG: type.FirstOrDefault() as IArrayTypeSymbol // BUG: or // BUG: type.OfType<IArrayTypeSymbol>().FirstOrDefault() ? // BUG: (see other similar problems below) if (type is IArrayTypeSymbol) { return SpecializedCollections.SingletonEnumerable(((IArrayTypeSymbol)type).ElementType); } } else if (initializerExpression.IsParentKind(SyntaxKind.ObjectCreationExpression)) { // new List<T> { Foo() } var objectCreation = (ObjectCreationExpressionSyntax)initializerExpression.Parent; // BUG: (vladres) Is it a correct type check? // BUG: Is there a type that implements both IEnumerable<ITypeSymbol> and INamedTypeSymbol? // BUG: (see other similar problems below) var type = GetTypes(objectCreation) as INamedTypeSymbol; return GetCollectionElementType(type, parameterIndex: 0, parameterCount: 1); } else if ( initializerExpression.IsParentKind(SyntaxKind.ComplexElementInitializerExpression) && initializerExpression.Parent.IsParentKind(SyntaxKind.ObjectCreationExpression)) { // new Dictionary<K,V> { { Foo(), ... } } var objectCreation = (ObjectCreationExpressionSyntax)initializerExpression.Parent.Parent; // BUG: (vladres) Is it a correct type check? // BUG: Is there a type that implements both IEnumerable<ITypeSymbol> and INamedTypeSymbol? // BUG: (see other similar problems below) var type = GetTypes(objectCreation) as INamedTypeSymbol; var parameterIndex = previousToken.HasValue ? initializerExpression.Expressions.GetWithSeparators().IndexOf(previousToken.Value) + 1 : initializerExpression.Expressions.IndexOf(expressionOpt); return GetCollectionElementType(type, parameterIndex: parameterIndex, parameterCount: initializerExpression.Expressions.Count); } else if (initializerExpression.IsParentKind(SyntaxKind.SimpleAssignmentExpression)) { // new Foo { a = { Foo() } } var assignExpression = (BinaryExpressionSyntax)initializerExpression.Parent; // BUG: (vladres) Is it a correct type check? // BUG: Is there a type that implements both IEnumerable<ITypeSymbol> and INamedTypeSymbol? var type = GetTypes(assignExpression.Left) as INamedTypeSymbol; var parameterIndex = previousToken.HasValue ? initializerExpression.Expressions.GetWithSeparators().IndexOf(previousToken.Value) + 1 : initializerExpression.Expressions.IndexOf(expressionOpt); return GetCollectionElementType(type, parameterIndex: parameterIndex, parameterCount: initializerExpression.Expressions.Count); } return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } private IEnumerable<ITypeSymbol> InferTypeInLockStatement(LockStatementSyntax lockStatement, SyntaxToken? previousToken = null) { // If we're position based, then we have to be after the "lock(" if (previousToken.HasValue && previousToken.Value != lockStatement.OpenParenToken) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } return SpecializedCollections.SingletonEnumerable(this.Compilation.GetSpecialType(SpecialType.System_Object)); } private IEnumerable<ITypeSymbol> InferTypeInParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax lambdaExpression, SyntaxToken? previousToken = null) { // If we have a position, it has to be after the lambda arrow. if (previousToken.HasValue && previousToken.Value != lambdaExpression.ArrowToken) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } return InferTypeInLambdaExpression(lambdaExpression); } private IEnumerable<ITypeSymbol> InferTypeInSimpleLambdaExpression(SimpleLambdaExpressionSyntax lambdaExpression, SyntaxToken? previousToken = null) { // If we have a position, it has to be after the lambda arrow. if (previousToken.HasValue && previousToken.Value != lambdaExpression.ArrowToken) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } return InferTypeInLambdaExpression(lambdaExpression); } private IEnumerable<ITypeSymbol> InferTypeInLambdaExpression(ExpressionSyntax lambdaExpression) { // Func<int,string> = i => Foo(); var types = InferTypes(lambdaExpression); var type = types.FirstOrDefault().GetDelegateType(this.Compilation); if (type != null) { var invoke = type.DelegateInvokeMethod; if (invoke != null) { return SpecializedCollections.SingletonEnumerable(invoke.ReturnType); } } return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } private IEnumerable<ITypeSymbol> InferTypeInMemberDeclarator(AnonymousObjectMemberDeclaratorSyntax memberDeclarator, SyntaxToken? previousTokenOpt = null) { if (memberDeclarator.NameEquals != null && memberDeclarator.Parent is AnonymousObjectCreationExpressionSyntax) { // If we're position based, then we have to be after the = if (previousTokenOpt.HasValue && previousTokenOpt.Value != memberDeclarator.NameEquals.EqualsToken) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } var types = InferTypes((AnonymousObjectCreationExpressionSyntax)memberDeclarator.Parent); return types.Where(t => t.IsAnonymousType()) .SelectMany(t => t.GetValidAnonymousTypeProperties() .Where(p => p.Name == memberDeclarator.NameEquals.Name.Identifier.ValueText) .Select(p => p.Type)); } return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } private IEnumerable<ITypeSymbol> InferTypeInNameColon(NameColonSyntax nameColon, SyntaxToken previousToken) { if (previousToken != nameColon.ColonToken) { // Must follow the colon token. return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } var argumentSyntax = nameColon.Parent as ArgumentSyntax; if (argumentSyntax != null) { return InferTypeInArgument(argumentSyntax); } return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } private IEnumerable<ITypeSymbol> InferTypeInNameEquals(NameEqualsSyntax nameEquals, SyntaxToken? previousToken = null) { if (previousToken == nameEquals.EqualsToken) { // we're on the right of the equals. Try to bind the left name to see if it // gives us anything useful. return GetTypes(nameEquals.Name); } var attributeArgumentSyntax = nameEquals.Parent as AttributeArgumentSyntax; if (attributeArgumentSyntax != null) { var argumentExpression = attributeArgumentSyntax.Expression; return this.GetTypes(argumentExpression); } return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } private IEnumerable<ITypeSymbol> InferTypeInPostfixUnaryExpression(PostfixUnaryExpressionSyntax postfixUnaryExpressionSyntax, SyntaxToken? previousToken = null) { // If we're after a postfix ++ or -- then we can't infer anything. if (previousToken.HasValue) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } switch (postfixUnaryExpressionSyntax.CSharpKind()) { case SyntaxKind.PostDecrementExpression: case SyntaxKind.PostIncrementExpression: return SpecializedCollections.SingletonEnumerable(this.Compilation.GetSpecialType(SpecialType.System_Int32)); } return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } private IEnumerable<ITypeSymbol> InferTypeInPrefixUnaryExpression(PrefixUnaryExpressionSyntax prefixUnaryExpression, SyntaxToken? previousToken = null) { // If we have a position, then we must be after the prefix token. Contract.ThrowIfTrue(previousToken.HasValue && previousToken.Value != prefixUnaryExpression.OperatorToken); switch (prefixUnaryExpression.CSharpKind()) { case SyntaxKind.AwaitExpression: // await <expression> var types = InferTypes(prefixUnaryExpression); var task = this.Compilation.TaskType(); var taskOfT = this.Compilation.TaskOfTType(); if (task == null || taskOfT == null) { break; } if (!types.Any()) { return SpecializedCollections.SingletonEnumerable(task); } return types.Select(t => t.SpecialType == SpecialType.System_Void ? task : taskOfT.Construct(t)); case SyntaxKind.PreDecrementExpression: case SyntaxKind.PreIncrementExpression: case SyntaxKind.UnaryPlusExpression: case SyntaxKind.UnaryMinusExpression: case SyntaxKind.BitwiseNotExpression: // ++, --, +Foo(), -Foo(), ~Foo(); return SpecializedCollections.SingletonEnumerable(this.Compilation.GetSpecialType(SpecialType.System_Int32)); case SyntaxKind.LogicalNotExpression: // !Foo() return SpecializedCollections.SingletonEnumerable(this.Compilation.GetSpecialType(SpecialType.System_Boolean)); } return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } private IEnumerable<ITypeSymbol> InferTypeInYieldStatement(YieldStatementSyntax yieldStatement, SyntaxToken? previousToken = null) { // If we are position based, then we have to be after the return keyword if (previousToken.HasValue && (previousToken.Value != yieldStatement.ReturnOrBreakKeyword || yieldStatement.ReturnOrBreakKeyword.IsKind(SyntaxKind.BreakKeyword))) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } var memberSymbol = GetDeclaredMemberSymbolFromOriginalSemanticModel(this.semanticModel, yieldStatement.GetAncestorOrThis<MemberDeclarationSyntax>()); var memberType = memberSymbol.TypeSwitch( (IMethodSymbol method) => method.ReturnType, (IPropertySymbol property) => property.Type); if (memberType is INamedTypeSymbol) { if (memberType.OriginalDefinition.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T || memberType.OriginalDefinition.SpecialType == SpecialType.System_Collections_Generic_IEnumerator_T) { return SpecializedCollections.SingletonEnumerable(((INamedTypeSymbol)memberType).TypeArguments[0]); } } return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } private IEnumerable<ITypeSymbol> InferTypeForReturnStatement(ReturnStatementSyntax returnStatement, SyntaxToken? previousToken = null) { // If we are position based, then we have to be after the return statement. if (previousToken.HasValue && previousToken.Value != returnStatement.ReturnKeyword) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } // If we're in a a lambda, then use the return type of the lambda to figure out what to // infer. i.e. Func<int,string> f = i => { return Foo(); } var lambda = returnStatement.GetAncestorsOrThis<ExpressionSyntax>() .FirstOrDefault(e => e.MatchesKind(SyntaxKind.ParenthesizedLambdaExpression, SyntaxKind.SimpleLambdaExpression)); if (lambda != null) { return InferTypeInLambdaExpression(lambda); } var memberSymbol = GetDeclaredMemberSymbolFromOriginalSemanticModel(this.semanticModel, returnStatement.GetAncestorOrThis<MemberDeclarationSyntax>()); if (memberSymbol.IsKind(SymbolKind.Method)) { var method = memberSymbol as IMethodSymbol; if (method.IsAsync) { var typeArguments = method.ReturnType.GetTypeArguments(); var taskOfT = this.Compilation.TaskOfTType(); return taskOfT != null && method.ReturnType.OriginalDefinition == taskOfT && typeArguments.Any() ? SpecializedCollections.SingletonEnumerable(typeArguments.First()) : SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } else { return SpecializedCollections.SingletonEnumerable(method.ReturnType); } } else if (memberSymbol.IsKind(SymbolKind.Property)) { return SpecializedCollections.SingletonEnumerable((memberSymbol as IPropertySymbol).Type); } else if (memberSymbol.IsKind(SymbolKind.Field)) { return SpecializedCollections.SingletonEnumerable((memberSymbol as IFieldSymbol).Type); } return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } private ISymbol GetDeclaredMemberSymbolFromOriginalSemanticModel(SemanticModel currentSemanticModel, MemberDeclarationSyntax declarationInCurrentTree) { var originalSemanticModel = currentSemanticModel.GetOriginalSemanticModel(); MemberDeclarationSyntax declaration; if (currentSemanticModel.IsSpeculativeSemanticModel) { var tokenInOriginalTree = originalSemanticModel.SyntaxTree.GetRoot(cancellationToken).FindToken(currentSemanticModel.OriginalPositionForSpeculation); declaration = tokenInOriginalTree.GetAncestor<MemberDeclarationSyntax>(); } else { declaration = declarationInCurrentTree; } return originalSemanticModel.GetDeclaredSymbol(declaration, cancellationToken); } private IEnumerable<ITypeSymbol> InferTypeInSwitchLabel( SwitchLabelSyntax switchLabel, SyntaxToken? previousToken = null) { if (previousToken.HasValue) { if (previousToken.Value != switchLabel.CaseOrDefaultKeyword || switchLabel.CSharpKind() != SyntaxKind.CaseSwitchLabel) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } } var switchStatement = (SwitchStatementSyntax)switchLabel.Parent.Parent; return GetTypes(switchStatement.Expression); } private IEnumerable<ITypeSymbol> InferTypeInSwitchStatement( SwitchStatementSyntax switchStatement, SyntaxToken? previousToken = null) { // If we have a position, then it has to be after "switch(" if (previousToken.HasValue && previousToken.Value != switchStatement.OpenParenToken) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } // Use the first case label to determine the return type. var firstCase = switchStatement.Sections.SelectMany(ss => ss.Labels) .FirstOrDefault(label => label.CSharpKind() == SyntaxKind.CaseSwitchLabel); if (firstCase != null) { var result = GetTypes(firstCase.Value); if (result.Any()) { return result; } } return SpecializedCollections.SingletonEnumerable(this.Compilation.GetSpecialType(SpecialType.System_Int32)); } private IEnumerable<ITypeSymbol> InferTypeInThrowStatement(ThrowStatementSyntax throwStatement, SyntaxToken? previousToken = null) { // If we have a position, it has to be after the 'throw' keyword. if (previousToken.HasValue && previousToken.Value != throwStatement.ThrowKeyword) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } return SpecializedCollections.SingletonEnumerable(this.Compilation.ExceptionType()); } private IEnumerable<ITypeSymbol> InferTypeInUsingStatement(UsingStatementSyntax usingStatement, SyntaxToken? previousToken = null) { // If we have a position, it has to be after "using(" if (previousToken.HasValue && previousToken.Value != usingStatement.OpenParenToken) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } return SpecializedCollections.SingletonEnumerable(this.Compilation.GetSpecialType(SpecialType.System_IDisposable)); } private IEnumerable<ITypeSymbol> InferTypeInVariableDeclarator(VariableDeclaratorSyntax variableDeclarator) { var variableType = variableDeclarator.GetVariableType(); if (variableType == null) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } var types = GetTypes(variableType).Where(t => !IsUnusableType(t)); if (variableType.IsVar) { var variableDeclaration = variableDeclarator.Parent as VariableDeclarationSyntax; if (variableDeclaration != null) { if (variableDeclaration.IsParentKind(SyntaxKind.UsingStatement)) { // using (var v = Foo()) return SpecializedCollections.SingletonEnumerable(this.Compilation.GetSpecialType(SpecialType.System_IDisposable)); } if (variableDeclaration.IsParentKind(SyntaxKind.ForStatement)) { // for (var v = Foo(); .. return SpecializedCollections.SingletonEnumerable(this.Compilation.GetSpecialType(SpecialType.System_Int32)); } // Return the types here if they actually bound to a type called 'var'. return types.Where(t => t.Name == "var"); } } return types; } private IEnumerable<ITypeSymbol> InferTypeInWhileStatement(WhileStatementSyntax whileStatement, SyntaxToken? previousToken = null) { // If we're position based, then we have to be after the "while(" if (previousToken.HasValue && previousToken.Value != whileStatement.OpenParenToken) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } return SpecializedCollections.SingletonEnumerable(this.Compilation.GetSpecialType(SpecialType.System_Boolean)); } private IEnumerable<ITypeSymbol> GetCollectionElementType(INamedTypeSymbol type, int parameterIndex, int parameterCount) { if (type != null) { // TODO(cyrusn): Move to use matt's Lookup method once he's checked in. #if false var addMethods = this.Binding.Lookup(leftType, "Add").OfType<MethodSymbol>(); var method = addMethods.Where(m => !m.IsStatic) .Where(m => m.Arity == 0) .Where(m => m.Parameters.Count == parameterCount).FirstOrDefault(); if (method != null) { return method.Parameters[parameterIndex].Type; } #endif } return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Security { using System.Collections.Generic; using System.ServiceModel.Channels; using System.ServiceModel; using System.Collections.ObjectModel; using System.IdentityModel.Claims; using System.IdentityModel.Policy; using System.IdentityModel.Tokens; using System.IdentityModel.Selectors; using System.Security.Cryptography; using System.ServiceModel.Security.Tokens; using System.Text; using System.Runtime.Serialization; using System.Xml; using System.ComponentModel; [TypeConverter(typeof(System.ServiceModel.Configuration.SecurityAlgorithmSuiteConverter))] public abstract class SecurityAlgorithmSuite { static SecurityAlgorithmSuite basic256; static SecurityAlgorithmSuite basic192; static SecurityAlgorithmSuite basic128; static SecurityAlgorithmSuite tripleDes; static SecurityAlgorithmSuite basic256Rsa15; static SecurityAlgorithmSuite basic192Rsa15; static SecurityAlgorithmSuite basic128Rsa15; static SecurityAlgorithmSuite tripleDesRsa15; static SecurityAlgorithmSuite basic256Sha256; static SecurityAlgorithmSuite basic192Sha256; static SecurityAlgorithmSuite basic128Sha256; static SecurityAlgorithmSuite tripleDesSha256; static SecurityAlgorithmSuite basic256Sha256Rsa15; static SecurityAlgorithmSuite basic192Sha256Rsa15; static SecurityAlgorithmSuite basic128Sha256Rsa15; static SecurityAlgorithmSuite tripleDesSha256Rsa15; static internal SecurityAlgorithmSuite KerberosDefault { get { return Basic128; } } static public SecurityAlgorithmSuite Default { get { return Basic256; } } static public SecurityAlgorithmSuite Basic256 { get { if (basic256 == null) basic256 = new Basic256SecurityAlgorithmSuite(); return basic256; } } static public SecurityAlgorithmSuite Basic192 { get { if (basic192 == null) basic192 = new Basic192SecurityAlgorithmSuite(); return basic192; } } static public SecurityAlgorithmSuite Basic128 { get { if (basic128 == null) basic128 = new Basic128SecurityAlgorithmSuite(); return basic128; } } static public SecurityAlgorithmSuite TripleDes { get { if (tripleDes == null) tripleDes = new TripleDesSecurityAlgorithmSuite(); return tripleDes; } } static public SecurityAlgorithmSuite Basic256Rsa15 { get { if (basic256Rsa15 == null) basic256Rsa15 = new Basic256Rsa15SecurityAlgorithmSuite(); return basic256Rsa15; } } static public SecurityAlgorithmSuite Basic192Rsa15 { get { if (basic192Rsa15 == null) basic192Rsa15 = new Basic192Rsa15SecurityAlgorithmSuite(); return basic192Rsa15; } } static public SecurityAlgorithmSuite Basic128Rsa15 { get { if (basic128Rsa15 == null) basic128Rsa15 = new Basic128Rsa15SecurityAlgorithmSuite(); return basic128Rsa15; } } static public SecurityAlgorithmSuite TripleDesRsa15 { get { if (tripleDesRsa15 == null) tripleDesRsa15 = new TripleDesRsa15SecurityAlgorithmSuite(); return tripleDesRsa15; } } static public SecurityAlgorithmSuite Basic256Sha256 { get { if (basic256Sha256 == null) basic256Sha256 = new Basic256Sha256SecurityAlgorithmSuite(); return basic256Sha256; } } static public SecurityAlgorithmSuite Basic192Sha256 { get { if (basic192Sha256 == null) basic192Sha256 = new Basic192Sha256SecurityAlgorithmSuite(); return basic192Sha256; } } static public SecurityAlgorithmSuite Basic128Sha256 { get { if (basic128Sha256 == null) basic128Sha256 = new Basic128Sha256SecurityAlgorithmSuite(); return basic128Sha256; } } static public SecurityAlgorithmSuite TripleDesSha256 { get { if (tripleDesSha256 == null) tripleDesSha256 = new TripleDesSha256SecurityAlgorithmSuite(); return tripleDesSha256; } } static public SecurityAlgorithmSuite Basic256Sha256Rsa15 { get { if (basic256Sha256Rsa15 == null) basic256Sha256Rsa15 = new Basic256Sha256Rsa15SecurityAlgorithmSuite(); return basic256Sha256Rsa15; } } static public SecurityAlgorithmSuite Basic192Sha256Rsa15 { get { if (basic192Sha256Rsa15 == null) basic192Sha256Rsa15 = new Basic192Sha256Rsa15SecurityAlgorithmSuite(); return basic192Sha256Rsa15; } } static public SecurityAlgorithmSuite Basic128Sha256Rsa15 { get { if (basic128Sha256Rsa15 == null) basic128Sha256Rsa15 = new Basic128Sha256Rsa15SecurityAlgorithmSuite(); return basic128Sha256Rsa15; } } static public SecurityAlgorithmSuite TripleDesSha256Rsa15 { get { if (tripleDesSha256Rsa15 == null) tripleDesSha256Rsa15 = new TripleDesSha256Rsa15SecurityAlgorithmSuite(); return tripleDesSha256Rsa15; } } public abstract string DefaultCanonicalizationAlgorithm { get; } public abstract string DefaultDigestAlgorithm { get; } public abstract string DefaultEncryptionAlgorithm { get; } public abstract int DefaultEncryptionKeyDerivationLength { get; } public abstract string DefaultSymmetricKeyWrapAlgorithm { get; } public abstract string DefaultAsymmetricKeyWrapAlgorithm { get; } public abstract string DefaultSymmetricSignatureAlgorithm { get; } public abstract string DefaultAsymmetricSignatureAlgorithm { get; } public abstract int DefaultSignatureKeyDerivationLength { get; } public abstract int DefaultSymmetricKeyLength { get; } internal virtual XmlDictionaryString DefaultCanonicalizationAlgorithmDictionaryString { get { return null; } } internal virtual XmlDictionaryString DefaultDigestAlgorithmDictionaryString { get { return null; } } internal virtual XmlDictionaryString DefaultEncryptionAlgorithmDictionaryString { get { return null; } } internal virtual XmlDictionaryString DefaultSymmetricKeyWrapAlgorithmDictionaryString { get { return null; } } internal virtual XmlDictionaryString DefaultAsymmetricKeyWrapAlgorithmDictionaryString { get { return null; } } internal virtual XmlDictionaryString DefaultSymmetricSignatureAlgorithmDictionaryString { get { return null; } } internal virtual XmlDictionaryString DefaultAsymmetricSignatureAlgorithmDictionaryString { get { return null; } } protected SecurityAlgorithmSuite() { } public virtual bool IsCanonicalizationAlgorithmSupported(string algorithm) { return algorithm == DefaultCanonicalizationAlgorithm; } public virtual bool IsDigestAlgorithmSupported(string algorithm) { return algorithm == DefaultDigestAlgorithm; } public virtual bool IsEncryptionAlgorithmSupported(string algorithm) { return algorithm == DefaultEncryptionAlgorithm; } public virtual bool IsEncryptionKeyDerivationAlgorithmSupported(string algorithm) { return (algorithm == SecurityAlgorithms.Psha1KeyDerivation) || (algorithm == SecurityAlgorithms.Psha1KeyDerivationDec2005); } public virtual bool IsSymmetricKeyWrapAlgorithmSupported(string algorithm) { return algorithm == DefaultSymmetricKeyWrapAlgorithm; } public virtual bool IsAsymmetricKeyWrapAlgorithmSupported(string algorithm) { return algorithm == DefaultAsymmetricKeyWrapAlgorithm; } public virtual bool IsSymmetricSignatureAlgorithmSupported(string algorithm) { return algorithm == DefaultSymmetricSignatureAlgorithm; } public virtual bool IsAsymmetricSignatureAlgorithmSupported(string algorithm) { return algorithm == DefaultAsymmetricSignatureAlgorithm; } public virtual bool IsSignatureKeyDerivationAlgorithmSupported(string algorithm) { return (algorithm == SecurityAlgorithms.Psha1KeyDerivation) || (algorithm == SecurityAlgorithms.Psha1KeyDerivationDec2005); } public abstract bool IsSymmetricKeyLengthSupported(int length); public abstract bool IsAsymmetricKeyLengthSupported(int length); internal static bool IsRsaSHA256(SecurityAlgorithmSuite suite) { if ( suite == null ) return false; return (suite == Basic128Sha256 || suite == Basic128Sha256Rsa15 || suite == Basic192Sha256 || suite == Basic192Sha256Rsa15 || suite == Basic256Sha256 || suite == Basic256Sha256Rsa15 || suite == TripleDesSha256 || suite == TripleDesSha256Rsa15); } internal string GetEncryptionKeyDerivationAlgorithm(SecurityToken token, SecureConversationVersion version) { if (token == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token"); string derivationAlgorithm = SecurityUtils.GetKeyDerivationAlgorithm(version); if (SecurityUtils.IsSupportedAlgorithm(derivationAlgorithm, token)) return derivationAlgorithm; else return null; } internal int GetEncryptionKeyDerivationLength(SecurityToken token, SecureConversationVersion version) { if (token == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token"); string derivationAlgorithm = SecurityUtils.GetKeyDerivationAlgorithm(version); if (SecurityUtils.IsSupportedAlgorithm(derivationAlgorithm, token)) { if (this.DefaultEncryptionKeyDerivationLength % 8 != 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.Psha1KeyLengthInvalid, this.DefaultEncryptionKeyDerivationLength))); return this.DefaultEncryptionKeyDerivationLength / 8; } else return 0; } internal void GetKeyWrapAlgorithm(SecurityToken token, out string keyWrapAlgorithm, out XmlDictionaryString keyWrapAlgorithmDictionaryString) { if (token == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token"); if (SecurityUtils.IsSupportedAlgorithm(this.DefaultSymmetricKeyWrapAlgorithm, token)) { keyWrapAlgorithm = this.DefaultSymmetricKeyWrapAlgorithm; keyWrapAlgorithmDictionaryString = this.DefaultSymmetricKeyWrapAlgorithmDictionaryString; } else { keyWrapAlgorithm = this.DefaultAsymmetricKeyWrapAlgorithm; keyWrapAlgorithmDictionaryString = this.DefaultAsymmetricKeyWrapAlgorithmDictionaryString; } } internal void GetSignatureAlgorithmAndKey(SecurityToken token, out string signatureAlgorithm, out SecurityKey key, out XmlDictionaryString signatureAlgorithmDictionaryString) { ReadOnlyCollection<SecurityKey> keys = token.SecurityKeys; if (keys == null || keys.Count == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SigningTokenHasNoKeys, token))); } for (int i = 0; i < keys.Count; i++) { if (keys[i].IsSupportedAlgorithm(this.DefaultSymmetricSignatureAlgorithm)) { signatureAlgorithm = this.DefaultSymmetricSignatureAlgorithm; signatureAlgorithmDictionaryString = this.DefaultSymmetricSignatureAlgorithmDictionaryString; key = keys[i]; return; } else if (keys[i].IsSupportedAlgorithm(this.DefaultAsymmetricSignatureAlgorithm)) { signatureAlgorithm = this.DefaultAsymmetricSignatureAlgorithm; signatureAlgorithmDictionaryString = this.DefaultAsymmetricSignatureAlgorithmDictionaryString; key = keys[i]; return; } } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SigningTokenHasNoKeysSupportingTheAlgorithmSuite, token, this))); } internal string GetSignatureKeyDerivationAlgorithm(SecurityToken token, SecureConversationVersion version) { if (token == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token"); string derivationAlgorithm = SecurityUtils.GetKeyDerivationAlgorithm(version); if (SecurityUtils.IsSupportedAlgorithm(derivationAlgorithm, token)) return derivationAlgorithm; else return null; } internal int GetSignatureKeyDerivationLength(SecurityToken token, SecureConversationVersion version) { if (token == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("token"); string derivationAlgorithm = SecurityUtils.GetKeyDerivationAlgorithm(version); if (SecurityUtils.IsSupportedAlgorithm(derivationAlgorithm, token)) { if (this.DefaultSignatureKeyDerivationLength % 8 != 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.Psha1KeyLengthInvalid, this.DefaultSignatureKeyDerivationLength))); return this.DefaultSignatureKeyDerivationLength / 8; } else return 0; } internal void EnsureAcceptableSymmetricSignatureAlgorithm(string algorithm) { if (!IsSymmetricSignatureAlgorithmSupported(algorithm)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.SuiteDoesNotAcceptAlgorithm, algorithm, "SymmetricSignature", this))); } } internal void EnsureAcceptableSignatureKeySize(SecurityKey securityKey, SecurityToken token) { AsymmetricSecurityKey asymmetricSecurityKey = securityKey as AsymmetricSecurityKey; if (asymmetricSecurityKey != null) { if (!IsAsymmetricKeyLengthSupported(asymmetricSecurityKey.KeySize)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException( SR.GetString(SR.TokenDoesNotMeetKeySizeRequirements, this, token, asymmetricSecurityKey.KeySize))); } } else { SymmetricSecurityKey symmetricSecurityKey = securityKey as SymmetricSecurityKey; if (symmetricSecurityKey == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.UnknownICryptoType, symmetricSecurityKey))); } EnsureAcceptableSignatureSymmetricKeySize(symmetricSecurityKey, token); } } // Ensure acceptable signing symmetric key. // 1) if derived key, validate derived key against DefaultSignatureKeyDerivationLength and validate // source key against DefaultSymmetricKeyLength // 2) if not derived key, validate key against DefaultSymmetricKeyLength internal void EnsureAcceptableSignatureSymmetricKeySize(SymmetricSecurityKey securityKey, SecurityToken token) { int keySize; DerivedKeySecurityToken dkt = token as DerivedKeySecurityToken; if (dkt != null) { token = dkt.TokenToDerive; keySize = ((SymmetricSecurityKey)token.SecurityKeys[0]).KeySize; // doing special case for derived key token signing length since // the sending side doesn't honor the algorithm suite. It used the DefaultSignatureKeyDerivationLength instead if (dkt.SecurityKeys[0].KeySize < this.DefaultSignatureKeyDerivationLength) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException( SR.GetString(SR.TokenDoesNotMeetKeySizeRequirements, this, dkt, dkt.SecurityKeys[0].KeySize))); } } else { keySize = securityKey.KeySize; } if (!IsSymmetricKeyLengthSupported(keySize)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException( SR.GetString(SR.TokenDoesNotMeetKeySizeRequirements, this, token, keySize))); } } // Ensure acceptable decrypting symmetric key. // 1) if derived key, validate derived key against DefaultEncryptionKeyDerivationLength and validate // source key against DefaultSymmetricKeyLength // 2) if not derived key, validate key against DefaultSymmetricKeyLength internal void EnsureAcceptableDecryptionSymmetricKeySize(SymmetricSecurityKey securityKey, SecurityToken token) { int keySize; DerivedKeySecurityToken dkt = token as DerivedKeySecurityToken; if (dkt != null) { token = dkt.TokenToDerive; keySize = ((SymmetricSecurityKey)token.SecurityKeys[0]).KeySize; // doing special case for derived key token signing length since // the sending side doesn't honor the algorithm suite. It used the DefaultSignatureKeyDerivationLength instead if (dkt.SecurityKeys[0].KeySize < this.DefaultEncryptionKeyDerivationLength) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException( SR.GetString(SR.TokenDoesNotMeetKeySizeRequirements, this, dkt, dkt.SecurityKeys[0].KeySize))); } } else { keySize = securityKey.KeySize; } if (!IsSymmetricKeyLengthSupported(keySize)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException( SR.GetString(SR.TokenDoesNotMeetKeySizeRequirements, this, token, keySize))); } } internal void EnsureAcceptableSignatureAlgorithm(SecurityKey verificationKey, string algorithm) { InMemorySymmetricSecurityKey symmeticKey = verificationKey as InMemorySymmetricSecurityKey; if (symmeticKey != null) { this.EnsureAcceptableSymmetricSignatureAlgorithm(algorithm); } else { AsymmetricSecurityKey asymmetricKey = verificationKey as AsymmetricSecurityKey; if (asymmetricKey == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.UnknownICryptoType, verificationKey))); } this.EnsureAcceptableAsymmetricSignatureAlgorithm(algorithm); } } internal void EnsureAcceptableAsymmetricSignatureAlgorithm(string algorithm) { if (!IsAsymmetricSignatureAlgorithmSupported(algorithm)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.SuiteDoesNotAcceptAlgorithm, algorithm, "AsymmetricSignature", this))); } } internal void EnsureAcceptableKeyWrapAlgorithm(string algorithm, bool isAsymmetric) { if (isAsymmetric) { if (!IsAsymmetricKeyWrapAlgorithmSupported(algorithm)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.SuiteDoesNotAcceptAlgorithm, algorithm, "AsymmetricKeyWrap", this))); } } else { if (!IsSymmetricKeyWrapAlgorithmSupported(algorithm)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.SuiteDoesNotAcceptAlgorithm, algorithm, "SymmetricKeyWrap", this))); } } } internal void EnsureAcceptableEncryptionAlgorithm(string algorithm) { if (!IsEncryptionAlgorithmSupported(algorithm)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.SuiteDoesNotAcceptAlgorithm, algorithm, "Encryption", this))); } } internal void EnsureAcceptableSignatureKeyDerivationAlgorithm(string algorithm) { if (!IsSignatureKeyDerivationAlgorithmSupported(algorithm)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.SuiteDoesNotAcceptAlgorithm, algorithm, "SignatureKeyDerivation", this))); } } internal void EnsureAcceptableEncryptionKeyDerivationAlgorithm(string algorithm) { if (!IsEncryptionKeyDerivationAlgorithmSupported(algorithm)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.SuiteDoesNotAcceptAlgorithm, algorithm, "EncryptionKeyDerivation", this))); } } internal void EnsureAcceptableDigestAlgorithm(string algorithm) { if (!IsDigestAlgorithmSupported(algorithm)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.SuiteDoesNotAcceptAlgorithm, algorithm, "Digest", this))); } } } public class Basic256SecurityAlgorithmSuite : SecurityAlgorithmSuite { public Basic256SecurityAlgorithmSuite() : base() { } public override string DefaultCanonicalizationAlgorithm { get { return DefaultCanonicalizationAlgorithmDictionaryString.Value; } } public override string DefaultDigestAlgorithm { get { return DefaultDigestAlgorithmDictionaryString.Value; } } public override string DefaultEncryptionAlgorithm { get { return DefaultEncryptionAlgorithmDictionaryString.Value; } } public override int DefaultEncryptionKeyDerivationLength { get { return 256; } } public override string DefaultSymmetricKeyWrapAlgorithm { get { return DefaultSymmetricKeyWrapAlgorithmDictionaryString.Value; } } public override string DefaultAsymmetricKeyWrapAlgorithm { get { return DefaultAsymmetricKeyWrapAlgorithmDictionaryString.Value; } } public override string DefaultSymmetricSignatureAlgorithm { get { return DefaultSymmetricSignatureAlgorithmDictionaryString.Value; } } public override string DefaultAsymmetricSignatureAlgorithm { get { return DefaultAsymmetricSignatureAlgorithmDictionaryString.Value; } } public override int DefaultSignatureKeyDerivationLength { get { return 192; } } public override int DefaultSymmetricKeyLength { get { return 256; } } public override bool IsSymmetricKeyLengthSupported(int length) { return length == 256; } public override bool IsAsymmetricKeyLengthSupported(int length) { return length >= 1024 && length <= 4096; } internal override XmlDictionaryString DefaultCanonicalizationAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.ExclusiveC14n; } } internal override XmlDictionaryString DefaultDigestAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Sha1Digest; } } internal override XmlDictionaryString DefaultEncryptionAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Aes256Encryption; } } internal override XmlDictionaryString DefaultSymmetricKeyWrapAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Aes256KeyWrap; } } internal override XmlDictionaryString DefaultAsymmetricKeyWrapAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaOaepKeyWrap; } } internal override XmlDictionaryString DefaultSymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.HmacSha1Signature; } } internal override XmlDictionaryString DefaultAsymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaSha1Signature; } } public override string ToString() { return "Basic256"; } } public class Basic192SecurityAlgorithmSuite : SecurityAlgorithmSuite { public Basic192SecurityAlgorithmSuite() : base() { } public override string DefaultCanonicalizationAlgorithm { get { return DefaultCanonicalizationAlgorithmDictionaryString.Value; } } public override string DefaultDigestAlgorithm { get { return DefaultDigestAlgorithmDictionaryString.Value; } } public override string DefaultEncryptionAlgorithm { get { return DefaultEncryptionAlgorithmDictionaryString.Value; } } public override int DefaultEncryptionKeyDerivationLength { get { return 192; } } public override string DefaultSymmetricKeyWrapAlgorithm { get { return DefaultSymmetricKeyWrapAlgorithmDictionaryString.Value; } } public override string DefaultAsymmetricKeyWrapAlgorithm { get { return DefaultAsymmetricKeyWrapAlgorithmDictionaryString.Value; } } public override string DefaultSymmetricSignatureAlgorithm { get { return DefaultSymmetricSignatureAlgorithmDictionaryString.Value; } } public override string DefaultAsymmetricSignatureAlgorithm { get { return DefaultAsymmetricSignatureAlgorithmDictionaryString.Value; } } public override int DefaultSignatureKeyDerivationLength { get { return 192; } } public override int DefaultSymmetricKeyLength { get { return 192; } } public override bool IsSymmetricKeyLengthSupported(int length) { return length >= 192 && length <= 256; } public override bool IsAsymmetricKeyLengthSupported(int length) { return length >= 1024 && length <= 4096; } internal override XmlDictionaryString DefaultCanonicalizationAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.ExclusiveC14n; } } internal override XmlDictionaryString DefaultDigestAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Sha1Digest; } } internal override XmlDictionaryString DefaultEncryptionAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Aes192Encryption; } } internal override XmlDictionaryString DefaultSymmetricKeyWrapAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Aes192KeyWrap; } } internal override XmlDictionaryString DefaultAsymmetricKeyWrapAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaOaepKeyWrap; } } internal override XmlDictionaryString DefaultSymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.HmacSha1Signature; } } internal override XmlDictionaryString DefaultAsymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaSha1Signature; } } public override string ToString() { return "Basic192"; } } public class Basic128SecurityAlgorithmSuite : SecurityAlgorithmSuite { public Basic128SecurityAlgorithmSuite() : base() { } public override string DefaultCanonicalizationAlgorithm { get { return this.DefaultCanonicalizationAlgorithmDictionaryString.Value; } } public override string DefaultDigestAlgorithm { get { return this.DefaultDigestAlgorithmDictionaryString.Value; } } public override string DefaultEncryptionAlgorithm { get { return this.DefaultEncryptionAlgorithmDictionaryString.Value; } } public override int DefaultEncryptionKeyDerivationLength { get { return 128; } } public override string DefaultSymmetricKeyWrapAlgorithm { get { return this.DefaultSymmetricKeyWrapAlgorithmDictionaryString.Value; } } public override string DefaultAsymmetricKeyWrapAlgorithm { get { return this.DefaultAsymmetricKeyWrapAlgorithmDictionaryString.Value; } } public override string DefaultSymmetricSignatureAlgorithm { get { return this.DefaultSymmetricSignatureAlgorithmDictionaryString.Value; } } public override string DefaultAsymmetricSignatureAlgorithm { get { return this.DefaultAsymmetricSignatureAlgorithmDictionaryString.Value; } } public override int DefaultSignatureKeyDerivationLength { get { return 128; } } public override int DefaultSymmetricKeyLength { get { return 128; } } public override bool IsSymmetricKeyLengthSupported(int length) { return length >= 128 && length <= 256; } public override bool IsAsymmetricKeyLengthSupported(int length) { return length >= 1024 && length <= 4096; } internal override XmlDictionaryString DefaultCanonicalizationAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.ExclusiveC14n; } } internal override XmlDictionaryString DefaultDigestAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Sha1Digest; } } internal override XmlDictionaryString DefaultEncryptionAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Aes128Encryption; } } internal override XmlDictionaryString DefaultSymmetricKeyWrapAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Aes128KeyWrap; } } internal override XmlDictionaryString DefaultAsymmetricKeyWrapAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaOaepKeyWrap; } } internal override XmlDictionaryString DefaultSymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.HmacSha1Signature; } } internal override XmlDictionaryString DefaultAsymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaSha1Signature; } } public override string ToString() { return "Basic128"; } } public class TripleDesSecurityAlgorithmSuite : SecurityAlgorithmSuite { public TripleDesSecurityAlgorithmSuite() : base() { } public override string DefaultCanonicalizationAlgorithm { get { return DefaultCanonicalizationAlgorithmDictionaryString.Value; } } public override string DefaultDigestAlgorithm { get { return DefaultDigestAlgorithmDictionaryString.Value; } } public override string DefaultEncryptionAlgorithm { get { return DefaultEncryptionAlgorithmDictionaryString.Value; } } public override int DefaultEncryptionKeyDerivationLength { get { return 192; } } public override string DefaultSymmetricKeyWrapAlgorithm { get { return DefaultSymmetricKeyWrapAlgorithmDictionaryString.Value; } } public override string DefaultAsymmetricKeyWrapAlgorithm { get { return this.DefaultAsymmetricKeyWrapAlgorithmDictionaryString.Value; } } public override string DefaultSymmetricSignatureAlgorithm { get { return DefaultSymmetricSignatureAlgorithmDictionaryString.Value; } } public override string DefaultAsymmetricSignatureAlgorithm { get { return DefaultAsymmetricSignatureAlgorithmDictionaryString.Value; } } public override int DefaultSignatureKeyDerivationLength { get { return 192; } } public override int DefaultSymmetricKeyLength { get { return 192; } } public override bool IsSymmetricKeyLengthSupported(int length) { return length >= 192 && length <= 256; } public override bool IsAsymmetricKeyLengthSupported(int length) { return length >= 1024 && length <= 4096; } internal override XmlDictionaryString DefaultCanonicalizationAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.ExclusiveC14n; } } internal override XmlDictionaryString DefaultDigestAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Sha1Digest; } } internal override XmlDictionaryString DefaultEncryptionAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.TripleDesEncryption; } } internal override XmlDictionaryString DefaultSymmetricKeyWrapAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.TripleDesKeyWrap; } } internal override XmlDictionaryString DefaultAsymmetricKeyWrapAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaOaepKeyWrap; } } internal override XmlDictionaryString DefaultSymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.HmacSha1Signature; } } internal override XmlDictionaryString DefaultAsymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaSha1Signature; } } public override string ToString() { return "TripleDes"; } } class Basic128Rsa15SecurityAlgorithmSuite : Basic128SecurityAlgorithmSuite { public Basic128Rsa15SecurityAlgorithmSuite() : base() { } internal override XmlDictionaryString DefaultAsymmetricKeyWrapAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaV15KeyWrap; } } public override string ToString() { return "Basic128Rsa15"; } } class Basic192Rsa15SecurityAlgorithmSuite : Basic192SecurityAlgorithmSuite { public Basic192Rsa15SecurityAlgorithmSuite() : base() { } internal override XmlDictionaryString DefaultAsymmetricKeyWrapAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaV15KeyWrap; } } public override string ToString() { return "Basic192Rsa15"; } } class Basic256Rsa15SecurityAlgorithmSuite : Basic256SecurityAlgorithmSuite { public Basic256Rsa15SecurityAlgorithmSuite() : base() { } internal override XmlDictionaryString DefaultAsymmetricKeyWrapAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaV15KeyWrap; } } public override string ToString() { return "Basic256Rsa15"; } } class TripleDesRsa15SecurityAlgorithmSuite : TripleDesSecurityAlgorithmSuite { public TripleDesRsa15SecurityAlgorithmSuite() : base() { } internal override XmlDictionaryString DefaultAsymmetricKeyWrapAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaV15KeyWrap; } } public override string ToString() { return "TripleDesRsa15"; } } class Basic256Sha256SecurityAlgorithmSuite : Basic256SecurityAlgorithmSuite { public Basic256Sha256SecurityAlgorithmSuite() : base() { } internal override XmlDictionaryString DefaultDigestAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Sha256Digest; } } internal override XmlDictionaryString DefaultSymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.HmacSha256Signature; } } internal override XmlDictionaryString DefaultAsymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaSha256Signature; } } public override string ToString() { return "Basic256Sha256"; } } class Basic192Sha256SecurityAlgorithmSuite : Basic192SecurityAlgorithmSuite { public Basic192Sha256SecurityAlgorithmSuite() : base() { } internal override XmlDictionaryString DefaultDigestAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Sha256Digest; } } internal override XmlDictionaryString DefaultSymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.HmacSha256Signature; } } internal override XmlDictionaryString DefaultAsymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaSha256Signature; } } public override string ToString() { return "Basic192Sha256"; } } class Basic128Sha256SecurityAlgorithmSuite : Basic128SecurityAlgorithmSuite { public Basic128Sha256SecurityAlgorithmSuite() : base() { } internal override XmlDictionaryString DefaultDigestAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Sha256Digest; } } internal override XmlDictionaryString DefaultSymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.HmacSha256Signature; } } internal override XmlDictionaryString DefaultAsymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaSha256Signature; } } public override string ToString() { return "Basic128Sha256"; } } class TripleDesSha256SecurityAlgorithmSuite : TripleDesSecurityAlgorithmSuite { public TripleDesSha256SecurityAlgorithmSuite() : base() { } internal override XmlDictionaryString DefaultDigestAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Sha256Digest; } } internal override XmlDictionaryString DefaultSymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.HmacSha256Signature; } } internal override XmlDictionaryString DefaultAsymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaSha256Signature; } } public override string ToString() { return "TripleDesSha256"; } } class Basic256Sha256Rsa15SecurityAlgorithmSuite : Basic256Rsa15SecurityAlgorithmSuite { public Basic256Sha256Rsa15SecurityAlgorithmSuite() : base() { } internal override XmlDictionaryString DefaultDigestAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Sha256Digest; } } internal override XmlDictionaryString DefaultSymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.HmacSha256Signature; } } internal override XmlDictionaryString DefaultAsymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaSha256Signature; } } public override string ToString() { return "Basic256Sha256Rsa15"; } } class Basic192Sha256Rsa15SecurityAlgorithmSuite : Basic192Rsa15SecurityAlgorithmSuite { public Basic192Sha256Rsa15SecurityAlgorithmSuite() : base() { } internal override XmlDictionaryString DefaultDigestAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Sha256Digest; } } internal override XmlDictionaryString DefaultSymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.HmacSha256Signature; } } internal override XmlDictionaryString DefaultAsymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaSha256Signature; } } public override string ToString() { return "Basic192Sha256Rsa15"; } } class Basic128Sha256Rsa15SecurityAlgorithmSuite : Basic128Rsa15SecurityAlgorithmSuite { public Basic128Sha256Rsa15SecurityAlgorithmSuite() : base() { } internal override XmlDictionaryString DefaultDigestAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Sha256Digest; } } internal override XmlDictionaryString DefaultSymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.HmacSha256Signature; } } internal override XmlDictionaryString DefaultAsymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaSha256Signature; } } public override string ToString() { return "Basic128Sha256Rsa15"; } } class TripleDesSha256Rsa15SecurityAlgorithmSuite : TripleDesRsa15SecurityAlgorithmSuite { public TripleDesSha256Rsa15SecurityAlgorithmSuite() : base() { } internal override XmlDictionaryString DefaultDigestAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.Sha256Digest; } } internal override XmlDictionaryString DefaultSymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.HmacSha256Signature; } } internal override XmlDictionaryString DefaultAsymmetricSignatureAlgorithmDictionaryString { get { return XD.SecurityAlgorithmDictionary.RsaSha256Signature; } } public override string ToString() { return "TripleDesSha256Rsa15"; } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; namespace System { /// <summary>Represents one or more errors that occur during application execution.</summary> /// <remarks> /// <see cref="AggregateException"/> is used to consolidate multiple failures into a single, throwable /// exception object. /// </remarks> [Serializable] [DebuggerDisplay("Count = {InnerExceptionCount}")] public class AggregateException : Exception { private static readonly string s_defaultMessage = "One or more errors occurred."; private static readonly string s_innerExceptionNull = "An element of innerExceptions was null."; private ReadOnlyCollection<Exception> m_innerExceptions; // Complete set of exceptions. /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class. /// </summary> public AggregateException() : base(s_defaultMessage) { m_innerExceptions = new ReadOnlyCollection<Exception>(new Exception[0]); } /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class with /// a specified error message. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> public AggregateException(string message) : base(message) { m_innerExceptions = new ReadOnlyCollection<Exception>(new Exception[0]); } /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class with a specified error /// message and a reference to the inner exception that is the cause of this exception. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerException">The exception that is the cause of the current exception.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="innerException"/> argument /// is null.</exception> public AggregateException(string message, Exception innerException) : base(message, innerException) { if (innerException == null) { throw new ArgumentNullException(nameof(innerException)); } m_innerExceptions = new ReadOnlyCollection<Exception>(new Exception[] { innerException }); } /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class with /// references to the inner exceptions that are the cause of this exception. /// </summary> /// <param name="innerExceptions">The exceptions that are the cause of the current exception.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptions"/> argument /// is null.</exception> /// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is /// null.</exception> public AggregateException(IEnumerable<Exception> innerExceptions) : this(s_defaultMessage, innerExceptions) { } /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class with /// references to the inner exceptions that are the cause of this exception. /// </summary> /// <param name="innerExceptions">The exceptions that are the cause of the current exception.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptions"/> argument /// is null.</exception> /// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is /// null.</exception> public AggregateException(params Exception[] innerExceptions) : this(s_defaultMessage, innerExceptions) { } /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class with a specified error /// message and references to the inner exceptions that are the cause of this exception. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerExceptions">The exceptions that are the cause of the current exception.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptions"/> argument /// is null.</exception> /// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is /// null.</exception> public AggregateException(string message, IEnumerable<Exception> innerExceptions) // If it's already an IList, pass that along (a defensive copy will be made in the delegated ctor). If it's null, just pass along // null typed correctly. Otherwise, create an IList from the enumerable and pass that along. : this(message, innerExceptions as IList<Exception> ?? (innerExceptions == null ? (List<Exception>)null : new List<Exception>(innerExceptions))) { } /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class with a specified error /// message and references to the inner exceptions that are the cause of this exception. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerExceptions">The exceptions that are the cause of the current exception.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptions"/> argument /// is null.</exception> /// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is /// null.</exception> public AggregateException(string message, params Exception[] innerExceptions) : this(message, (IList<Exception>)innerExceptions) { } /// <summary> /// Allocates a new aggregate exception with the specified message and list of inner exceptions. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerExceptions">The exceptions that are the cause of the current exception.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptions"/> argument /// is null.</exception> /// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is /// null.</exception> private AggregateException(string message, IList<Exception> innerExceptions) : base(message, innerExceptions != null && innerExceptions.Count > 0 ? innerExceptions[0] : null) { if (innerExceptions == null) { throw new ArgumentNullException(nameof(innerExceptions)); } // Copy exceptions to our internal array and validate them. We must copy them, // because we're going to put them into a ReadOnlyCollection which simply reuses // the list passed in to it. We don't want callers subsequently mutating. Exception[] exceptionsCopy = new Exception[innerExceptions.Count]; for (int i = 0; i < exceptionsCopy.Length; i++) { exceptionsCopy[i] = innerExceptions[i]; if (exceptionsCopy[i] == null) { throw new ArgumentException(s_innerExceptionNull); } } m_innerExceptions = new ReadOnlyCollection<Exception>(exceptionsCopy); } #if DISABLED_FOR_LLILUM /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class with /// references to the inner exception dispatch info objects that represent the cause of this exception. /// </summary> /// <param name="innerExceptionInfos"> /// Information about the exceptions that are the cause of the current exception. /// </param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptionInfos"/> argument /// is null.</exception> /// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptionInfos"/> is /// null.</exception> internal AggregateException(IEnumerable<ExceptionDispatchInfo> innerExceptionInfos) : this(s_defaultMessage, innerExceptionInfos) { } /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class with a specified error /// message and references to the inner exception dispatch info objects that represent the cause of /// this exception. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerExceptionInfos"> /// Information about the exceptions that are the cause of the current exception. /// </param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptionInfos"/> argument /// is null.</exception> /// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptionInfos"/> is /// null.</exception> internal AggregateException(string message, IEnumerable<ExceptionDispatchInfo> innerExceptionInfos) // If it's already an IList, pass that along (a defensive copy will be made in the delegated ctor). If it's null, just pass along // null typed correctly. Otherwise, create an IList from the enumerable and pass that along. : this(message, innerExceptionInfos as IList<ExceptionDispatchInfo> ?? (innerExceptionInfos == null ? (List<ExceptionDispatchInfo>)null : new List<ExceptionDispatchInfo>(innerExceptionInfos))) { } /// <summary> /// Allocates a new aggregate exception with the specified message and list of inner /// exception dispatch info objects. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerExceptionInfos"> /// Information about the exceptions that are the cause of the current exception. /// </param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptionInfos"/> argument /// is null.</exception> /// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptionInfos"/> is /// null.</exception> private AggregateException(string message, IList<ExceptionDispatchInfo> innerExceptionInfos) : base(message, innerExceptionInfos != null && innerExceptionInfos.Count > 0 && innerExceptionInfos[0] != null ? innerExceptionInfos[0].SourceException : null) { if (innerExceptionInfos == null) { throw new ArgumentNullException("innerExceptionInfos"); } // Copy exceptions to our internal array and validate them. We must copy them, // because we're going to put them into a ReadOnlyCollection which simply reuses // the list passed in to it. We don't want callers subsequently mutating. Exception[] exceptionsCopy = new Exception[innerExceptionInfos.Count]; for (int i = 0; i < exceptionsCopy.Length; i++) { var edi = innerExceptionInfos[i]; if (edi != null) exceptionsCopy[i] = edi.SourceException; if (exceptionsCopy[i] == null) { throw new ArgumentException(s_innerExceptionNull); } } m_innerExceptions = new ReadOnlyCollection<Exception>(exceptionsCopy); } /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds /// the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that /// contains contextual information about the source or destination. </param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info"/> argument is null.</exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The exception could not be deserialized correctly.</exception> [SecurityCritical] protected AggregateException(SerializationInfo info, StreamingContext context) : base(info, context) { if (info == null) { throw new ArgumentNullException("info"); } Exception[] innerExceptions = info.GetValue("InnerExceptions", typeof(Exception[])) as Exception[]; if (innerExceptions == null) { throw new SerializationException("The serialization stream contains no inner exceptions."); } m_innerExceptions = new ReadOnlyCollection<Exception>(innerExceptions); } /// <summary> /// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo"/> with information about /// the exception. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds /// the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that /// contains contextual information about the source or destination. </param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info"/> argument is null.</exception> [SecurityCritical] public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } base.GetObjectData(info, context); Exception[] innerExceptions = new Exception[m_innerExceptions.Count]; m_innerExceptions.CopyTo(innerExceptions, 0); info.AddValue("InnerExceptions", innerExceptions, typeof(Exception[])); } #endif // DISABLED_FOR_LLILUM /// <summary> /// Returns the <see cref="System.AggregateException"/> that is the root cause of this exception. /// </summary> public override Exception GetBaseException() { // Returns the first inner AggregateException that contains more or less than one inner exception // Recursively traverse the inner exceptions as long as the inner exception of type AggregateException and has only one inner exception Exception back = this; AggregateException backAsAggregate = this; while (backAsAggregate != null && backAsAggregate.InnerExceptions.Count == 1) { back = back.InnerException; backAsAggregate = back as AggregateException; } return back; } /// <summary> /// Gets a read-only collection of the <see cref="T:System.Exception"/> instances that caused the /// current exception. /// </summary> public ReadOnlyCollection<Exception> InnerExceptions { get { return m_innerExceptions; } } /// <summary> /// Invokes a handler on each <see cref="T:System.Exception"/> contained by this <see /// cref="AggregateException"/>. /// </summary> /// <param name="predicate">The predicate to execute for each exception. The predicate accepts as an /// argument the <see cref="T:System.Exception"/> to be processed and returns a Boolean to indicate /// whether the exception was handled.</param> /// <remarks> /// Each invocation of the <paramref name="predicate"/> returns true or false to indicate whether the /// <see cref="T:System.Exception"/> was handled. After all invocations, if any exceptions went /// unhandled, all unhandled exceptions will be put into a new <see cref="AggregateException"/> /// which will be thrown. Otherwise, the <see cref="Handle"/> method simply returns. If any /// invocations of the <paramref name="predicate"/> throws an exception, it will halt the processing /// of any more exceptions and immediately propagate the thrown exception as-is. /// </remarks> /// <exception cref="AggregateException">An exception contained by this <see /// cref="AggregateException"/> was not handled.</exception> /// <exception cref="T:System.ArgumentNullException">The <paramref name="predicate"/> argument is /// null.</exception> public void Handle(Func<Exception, bool> predicate) { if (predicate == null) { throw new ArgumentNullException(nameof(predicate)); } List<Exception> unhandledExceptions = null; for (int i = 0; i < m_innerExceptions.Count; i++) { // If the exception was not handled, lazily allocate a list of unhandled // exceptions (to be rethrown later) and add it. if (!predicate(m_innerExceptions[i])) { if (unhandledExceptions == null) { unhandledExceptions = new List<Exception>(); } unhandledExceptions.Add(m_innerExceptions[i]); } } // If there are unhandled exceptions remaining, throw them. if (unhandledExceptions != null) { throw new AggregateException(Message, unhandledExceptions); } } /// <summary> /// Flattens an <see cref="AggregateException"/> instances into a single, new instance. /// </summary> /// <returns>A new, flattened <see cref="AggregateException"/>.</returns> /// <remarks> /// If any inner exceptions are themselves instances of /// <see cref="AggregateException"/>, this method will recursively flatten all of them. The /// inner exceptions returned in the new <see cref="AggregateException"/> /// will be the union of all of the the inner exceptions from exception tree rooted at the provided /// <see cref="AggregateException"/> instance. /// </remarks> public AggregateException Flatten() { // Initialize a collection to contain the flattened exceptions. List<Exception> flattenedExceptions = new List<Exception>(); // Create a list to remember all aggregates to be flattened, this will be accessed like a FIFO queue List<AggregateException> exceptionsToFlatten = new List<AggregateException>(); exceptionsToFlatten.Add(this); int nDequeueIndex = 0; // Continue removing and recursively flattening exceptions, until there are no more. while (exceptionsToFlatten.Count > nDequeueIndex) { // dequeue one from exceptionsToFlatten IList<Exception> currentInnerExceptions = exceptionsToFlatten[nDequeueIndex++].InnerExceptions; for (int i = 0; i < currentInnerExceptions.Count; i++) { Exception currentInnerException = currentInnerExceptions[i]; if (currentInnerException == null) { continue; } AggregateException currentInnerAsAggregate = currentInnerException as AggregateException; // If this exception is an aggregate, keep it around for later. Otherwise, // simply add it to the list of flattened exceptions to be returned. if (currentInnerAsAggregate != null) { exceptionsToFlatten.Add(currentInnerAsAggregate); } else { flattenedExceptions.Add(currentInnerException); } } } return new AggregateException(Message, flattenedExceptions); } /// <summary> /// Creates and returns a string representation of the current <see cref="AggregateException"/>. /// </summary> /// <returns>A string representation of the current exception.</returns> public override string ToString() { string text = base.ToString(); for (int i = 0; i < m_innerExceptions.Count; i++) { text = string.Format( "{0}{1}---> (Inner Exception #{2}) {3}<---{5}", text, Environment.NewLine, i, m_innerExceptions[i].ToString(), Environment.NewLine); } return text; } /// <summary> /// This helper property is used by the DebuggerDisplay. /// /// Note that we don't want to remove this property and change the debugger display to {InnerExceptions.Count} /// because DebuggerDisplay should be a single property access or parameterless method call, so that the debugger /// can use a fast path without using the expression evaluator. /// /// See http://msdn.microsoft.com/en-us/library/x810d419.aspx /// </summary> private int InnerExceptionCount { get { return InnerExceptions.Count; } } } }
/* * 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 NUnit.Framework; using WhitespaceAnalyzer = Lucene.Net.Analysis.WhitespaceAnalyzer; using Document = Lucene.Net.Documents.Document; using IndexReader = Lucene.Net.Index.IndexReader; using IndexWriter = Lucene.Net.Index.IndexWriter; using MultiReader = Lucene.Net.Index.MultiReader; using MaxFieldLength = Lucene.Net.Index.IndexWriter.MaxFieldLength; using RAMDirectory = Lucene.Net.Store.RAMDirectory; using ReaderUtil = Lucene.Net.Util.ReaderUtil; namespace Lucene.Net.Search { public class QueryUtils { [Serializable] private class AnonymousClassQuery:Query { public override System.String ToString(System.String field) { return "My Whacky Query"; } } private class AnonymousClassCollector:Collector { public AnonymousClassCollector(int[] order, int[] opidx, int skip_op, Lucene.Net.Search.Scorer scorer, int[] sdoc, float maxDiff, Lucene.Net.Search.Query q, Lucene.Net.Search.IndexSearcher s) { InitBlock(order, opidx, skip_op, scorer, sdoc, maxDiff, q, s); } private void InitBlock(int[] order, int[] opidx, int skip_op, Lucene.Net.Search.Scorer scorer, int[] sdoc, float maxDiff, Lucene.Net.Search.Query q, Lucene.Net.Search.IndexSearcher s) { this.order = order; this.opidx = opidx; this.skip_op = skip_op; this.scorer = scorer; this.sdoc = sdoc; this.maxDiff = maxDiff; this.q = q; this.s = s; } private int[] order; private int[] opidx; private int skip_op; private Lucene.Net.Search.Scorer scorer; private int[] sdoc; private float maxDiff; private Lucene.Net.Search.Query q; private Lucene.Net.Search.IndexSearcher s; private int base_Renamed = 0; private Scorer sc; public override void SetScorer(Scorer scorer) { this.sc = scorer; } public override void Collect(int doc) { doc = doc + base_Renamed; float score = sc.Score(); try { int op = order[(opidx[0]++) % order.Length]; // System.out.println(op==skip_op ? // "skip("+(sdoc[0]+1)+")":"next()"); bool more = op == skip_op?scorer.Advance(sdoc[0] + 1) != DocIdSetIterator.NO_MORE_DOCS:scorer.NextDoc() != DocIdSetIterator.NO_MORE_DOCS; sdoc[0] = scorer.DocID(); float scorerScore = scorer.Score(); float scorerScore2 = scorer.Score(); float scoreDiff = System.Math.Abs(score - scorerScore); float scorerDiff = System.Math.Abs(scorerScore2 - scorerScore); if (!more || doc != sdoc[0] || scoreDiff > maxDiff || scorerDiff > maxDiff) { System.Text.StringBuilder sbord = new System.Text.StringBuilder(); for (int i = 0; i < order.Length; i++) sbord.Append(order[i] == skip_op?" skip()":" next()"); throw new System.SystemException("ERROR matching docs:" + "\n\t" + (doc != sdoc[0]?"--> ":"") + "doc=" + sdoc[0] + "\n\t" + (!more?"--> ":"") + "tscorer.more=" + more + "\n\t" + (scoreDiff > maxDiff?"--> ":"") + "scorerScore=" + scorerScore + " scoreDiff=" + scoreDiff + " maxDiff=" + maxDiff + "\n\t" + (scorerDiff > maxDiff?"--> ":"") + "scorerScore2=" + scorerScore2 + " scorerDiff=" + scorerDiff + "\n\thitCollector.doc=" + doc + " score=" + score + "\n\t Scorer=" + scorer + "\n\t Query=" + q + " " + q.GetType().FullName + "\n\t Searcher=" + s + "\n\t Order=" + sbord + "\n\t Op=" + (op == skip_op?" skip()":" next()")); } } catch (System.IO.IOException e) { throw new System.SystemException("", e); } } public override void SetNextReader(IndexReader reader, int docBase) { base_Renamed = docBase; } public override bool AcceptsDocsOutOfOrder() { return true; } } private class AnonymousClassCollector1:Collector { public AnonymousClassCollector1(int[] lastDoc, Lucene.Net.Search.Query q, Lucene.Net.Search.IndexSearcher s, float maxDiff, IndexReader[] lastReader) { InitBlock(lastDoc, q, s, maxDiff, lastReader); } private void InitBlock(int[] lastDoc, Lucene.Net.Search.Query q, Lucene.Net.Search.IndexSearcher s, float maxDiff, IndexReader[] lastReader) { this.lastDoc = lastDoc; this.q = q; this.s = s; this.maxDiff = maxDiff; this.lastReader = lastReader; } private int[] lastDoc; private Lucene.Net.Search.Query q; private Lucene.Net.Search.IndexSearcher s; private float maxDiff; private Scorer scorer; private IndexReader reader; private IndexReader[] lastReader; public override void SetScorer(Scorer scorer) { this.scorer = scorer; } public override void Collect(int doc) { //System.out.println("doc="+doc); float score = this.scorer.Score(); try { for (int i = lastDoc[0] + 1; i <= doc; i++) { Weight w = q.Weight(s); Scorer scorer = w.Scorer(reader, true, false); Assert.IsTrue(scorer.Advance(i) != DocIdSetIterator.NO_MORE_DOCS, "query collected " + doc + " but skipTo(" + i + ") says no more docs!"); Assert.AreEqual(doc, scorer.DocID(), "query collected " + doc + " but skipTo(" + i + ") got to " + scorer.DocID()); float skipToScore = scorer.Score(); Assert.AreEqual(skipToScore, scorer.Score(), maxDiff, "unstable skipTo(" + i + ") score!"); Assert.AreEqual(score, skipToScore, maxDiff, "query assigned doc " + doc + " a score of <" + score + "> but skipTo(" + i + ") has <" + skipToScore + ">!"); } lastDoc[0] = doc; } catch (System.IO.IOException e) { throw new System.SystemException("", e); } } public override void SetNextReader(IndexReader reader, int docBase) { // confirm that skipping beyond the last doc, on the // previous reader, hits NO_MORE_DOCS if (lastReader[0] != null) { IndexReader previousReader = lastReader[0]; Weight w = q.Weight(new IndexSearcher(previousReader)); Scorer scorer = w.Scorer(previousReader, true, false); if (scorer != null) { bool more = scorer.Advance(lastDoc[0] + 1) != DocIdSetIterator.NO_MORE_DOCS; Assert.IsFalse(more, "query's last doc was " + lastDoc[0] + " but skipTo(" + (lastDoc[0] + 1) + ") got to " + scorer.DocID()); } } this.reader = lastReader[0] = reader; lastDoc[0] = -1; } public override bool AcceptsDocsOutOfOrder() { return false; } } /// <summary>Check the types of things query objects should be able to do. </summary> public static void Check(Query q) { CheckHashEquals(q); } /// <summary>check very basic hashCode and equals </summary> public static void CheckHashEquals(Query q) { Query q2 = (Query) q.Clone(); CheckEqual(q, q2); Query q3 = (Query) q.Clone(); q3.SetBoost(7.21792348f); CheckUnequal(q, q3); // test that a class check is done so that no exception is thrown // in the implementation of equals() Query whacky = new AnonymousClassQuery(); whacky.SetBoost(q.GetBoost()); CheckUnequal(q, whacky); } public static void CheckEqual(Query q1, Query q2) { Assert.AreEqual(q1, q2); Assert.AreEqual(q1.GetHashCode(), q2.GetHashCode()); } public static void CheckUnequal(Query q1, Query q2) { Assert.IsTrue(!q1.Equals(q2)); Assert.IsTrue(!q2.Equals(q1)); // possible this test can fail on a hash collision... if that // happens, please change test to use a different example. Assert.IsTrue(q1.GetHashCode() != q2.GetHashCode()); } /// <summary>deep check that explanations of a query 'score' correctly </summary> public static void CheckExplanations(Query q, Searcher s) { CheckHits.CheckExplanations(q, null, s, true); } /// <summary> Various query sanity checks on a searcher, some checks are only done for /// instanceof IndexSearcher. /// /// </summary> /// <seealso cref="Check(Query)"> /// </seealso> /// <seealso cref="checkFirstSkipTo"> /// </seealso> /// <seealso cref="checkSkipTo"> /// </seealso> /// <seealso cref="checkExplanations"> /// </seealso> /// <seealso cref="checkSerialization"> /// </seealso> /// <seealso cref="checkEqual"> /// </seealso> public static void Check(Query q1, Searcher s) { Check(q1, s, true); } private static void Check(Query q1, Searcher s, bool wrap) { try { Check(q1); if (s != null) { if (s is IndexSearcher) { IndexSearcher is_Renamed = (IndexSearcher) s; CheckFirstSkipTo(q1, is_Renamed); CheckSkipTo(q1, is_Renamed); if (wrap) { Check(q1, WrapUnderlyingReader(is_Renamed, - 1), false); Check(q1, WrapUnderlyingReader(is_Renamed, 0), false); Check(q1, WrapUnderlyingReader(is_Renamed, + 1), false); } } if (wrap) { Check(q1, WrapSearcher(s, - 1), false); Check(q1, WrapSearcher(s, 0), false); Check(q1, WrapSearcher(s, + 1), false); } CheckExplanations(q1, s); CheckSerialization(q1, s); Query q2 = (Query) q1.Clone(); CheckEqual(s.Rewrite(q1), s.Rewrite(q2)); } } catch (System.IO.IOException e) { throw new System.SystemException("", e); } } /// <summary> Given an IndexSearcher, returns a new IndexSearcher whose IndexReader /// is a MultiReader containing the Reader of the original IndexSearcher, /// as well as several "empty" IndexReaders -- some of which will have /// deleted documents in them. This new IndexSearcher should /// behave exactly the same as the original IndexSearcher. /// </summary> /// <param name="s">the searcher to wrap /// </param> /// <param name="edge">if negative, s will be the first sub; if 0, s will be in the middle, if positive s will be the last sub /// </param> public static IndexSearcher WrapUnderlyingReader(IndexSearcher s, int edge) { IndexReader r = s.GetIndexReader(); // we can't put deleted docs before the nested reader, because // it will throw off the docIds IndexReader[] readers = new IndexReader[]{edge < 0?r:IndexReader.Open(MakeEmptyIndex(0)), IndexReader.Open(MakeEmptyIndex(0)), new MultiReader(new IndexReader[]{IndexReader.Open(MakeEmptyIndex(edge < 0?4:0)), IndexReader.Open(MakeEmptyIndex(0)), 0 == edge?r:IndexReader.Open(MakeEmptyIndex(0))}), IndexReader.Open(MakeEmptyIndex(0 < edge?0:7)), IndexReader.Open(MakeEmptyIndex(0)), new MultiReader(new IndexReader[]{IndexReader.Open(MakeEmptyIndex(0 < edge?0:5)), IndexReader.Open(MakeEmptyIndex(0)), 0 < edge?r:IndexReader.Open(MakeEmptyIndex(0))})}; IndexSearcher out_Renamed = new IndexSearcher(new MultiReader(readers)); out_Renamed.SetSimilarity(s.GetSimilarity()); return out_Renamed; } /// <summary> Given a Searcher, returns a new MultiSearcher wrapping the /// the original Searcher, /// as well as several "empty" IndexSearchers -- some of which will have /// deleted documents in them. This new MultiSearcher /// should behave exactly the same as the original Searcher. /// </summary> /// <param name="s">the Searcher to wrap /// </param> /// <param name="edge">if negative, s will be the first sub; if 0, s will be in hte middle, if positive s will be the last sub /// </param> public static MultiSearcher WrapSearcher(Searcher s, int edge) { // we can't put deleted docs before the nested reader, because // it will through off the docIds Searcher[] searchers = new Searcher[]{edge < 0?s:new IndexSearcher(MakeEmptyIndex(0)), new MultiSearcher(new Searcher[]{new IndexSearcher(MakeEmptyIndex(edge < 0?65:0)), new IndexSearcher(MakeEmptyIndex(0)), 0 == edge?s:new IndexSearcher(MakeEmptyIndex(0))}), new IndexSearcher(MakeEmptyIndex(0 < edge?0:3)), new IndexSearcher(MakeEmptyIndex(0)), new MultiSearcher(new Searcher[]{new IndexSearcher(MakeEmptyIndex(0 < edge?0:5)), new IndexSearcher(MakeEmptyIndex(0)), 0 < edge?s:new IndexSearcher(MakeEmptyIndex(0))})}; MultiSearcher out_Renamed = new MultiSearcher(searchers); out_Renamed.SetSimilarity(s.GetSimilarity()); return out_Renamed; } private static RAMDirectory MakeEmptyIndex(int numDeletedDocs) { RAMDirectory d = new RAMDirectory(); IndexWriter w = new IndexWriter(d, new WhitespaceAnalyzer(), true, MaxFieldLength.LIMITED); for (int i = 0; i < numDeletedDocs; i++) { w.AddDocument(new Document()); } w.Commit(); w.DeleteDocuments(new MatchAllDocsQuery()); w.Commit(); if (0 < numDeletedDocs) Assert.IsTrue(w.HasDeletions(), "writer has no deletions"); Assert.AreEqual(numDeletedDocs, w.MaxDoc(), "writer is missing some deleted docs"); Assert.AreEqual(0, w.NumDocs(), "writer has non-deleted docs"); w.Close(); IndexReader r = IndexReader.Open(d); Assert.AreEqual(numDeletedDocs, r.NumDeletedDocs(), "reader has wrong number of deleted docs"); r.Close(); return d; } /// <summary>check that the query weight is serializable. </summary> /// <throws> IOException if serialization check fail. </throws> private static void CheckSerialization(Query q, Searcher s) { Weight w = q.Weight(s); try { System.IO.MemoryStream bos = new System.IO.MemoryStream(); System.IO.BinaryWriter oos = new System.IO.BinaryWriter(bos); System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.Serialize(oos.BaseStream, w); oos.Close(); System.IO.BinaryReader ois = new System.IO.BinaryReader(new System.IO.MemoryStream(bos.ToArray())); formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.Deserialize(ois.BaseStream); ois.Close(); //skip equals() test for now - most weights don't override equals() and we won't add this just for the tests. //TestCase.Assert.AreEqual(w2,w,"writeObject(w) != w. ("+w+")"); } catch (System.Exception e) { System.IO.IOException e2 = new System.IO.IOException("Serialization failed for " + w, e); throw e2; } } /// <summary>alternate scorer skipTo(),skipTo(),next(),next(),skipTo(),skipTo(), etc /// and ensure a hitcollector receives same docs and scores /// </summary> public static void CheckSkipTo(Query q, IndexSearcher s) { //System.out.println("Checking "+q); if (BooleanQuery.GetAllowDocsOutOfOrder()) return ; // in this case order of skipTo() might differ from that of next(). int skip_op = 0; int next_op = 1; int[][] orders = new int[][]{new int[]{next_op}, new int[]{skip_op}, new int[]{skip_op, next_op}, new int[]{next_op, skip_op}, new int[]{skip_op, skip_op, next_op, next_op}, new int[]{next_op, next_op, skip_op, skip_op}, new int[]{skip_op, skip_op, skip_op, next_op, next_op}}; for (int k = 0; k < orders.Length; k++) { int[] order = orders[k]; // System.out.print("Order:");for (int i = 0; i < order.length; i++) // System.out.print(order[i]==skip_op ? " skip()":" next()"); // System.out.println(); int[] opidx = new int[]{0}; Weight w = q.Weight(s); Scorer scorer = w.Scorer(s.GetIndexReader(), true, false); if (scorer == null) { continue; } // FUTURE: ensure scorer.doc()==-1 int[] sdoc = new int[]{- 1}; float maxDiff = 1e-5f; s.Search(q, new AnonymousClassCollector(order, opidx, skip_op, scorer, sdoc, maxDiff, q, s)); // make sure next call to scorer is false. int op = order[(opidx[0]++) % order.Length]; // System.out.println(op==skip_op ? "last: skip()":"last: next()"); bool more = (op == skip_op?scorer.Advance(sdoc[0] + 1):scorer.NextDoc()) != DocIdSetIterator.NO_MORE_DOCS; Assert.IsFalse(more); } } // check that first skip on just created scorers always goes to the right doc private static void CheckFirstSkipTo(Query q, IndexSearcher s) { //System.out.println("checkFirstSkipTo: "+q); float maxDiff = 1e-4f; //{{Lucene.Net-2.9.1}}Intentional diversion from Java Lucene int[] lastDoc = new int[]{- 1}; IndexReader[] lastReader = {null}; s.Search(q, new AnonymousClassCollector1(lastDoc, q, s, maxDiff, lastReader)); if(lastReader[0] != null) { // confirm that skipping beyond the last doc, on the // previous reader, hits NO_MORE_DOCS IndexReader previousReader = lastReader[0]; Weight w = q.Weight(new IndexSearcher(previousReader)); Scorer scorer = w.Scorer(previousReader, true, false); if (scorer != null) { bool more = scorer.Advance(lastDoc[0] + 1) != DocIdSetIterator.NO_MORE_DOCS; Assert.IsFalse(more, "query's last doc was " + lastDoc[0] + " but skipTo(" + (lastDoc[0] + 1) + ") got to " + scorer.DocID()); } } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Linq; using System.Reflection; using System.Text; namespace UtilsLib.ExtensionMethods { /// <summary> /// Extension methods for IEnumerable /// </summary> public static class IEnumerableExtensions { /// <summary> /// Checks if an IEnumerable collection is intialized or contains items /// </summary> /// <param name="list">The array to check</param> /// <returns>True if the list is null or empty, false otherwise</returns> public static bool IsNullOrEmpty<T>(this IEnumerable<T> list) { return list == null || !list.Any(); } /// <summary> /// /// </summary> /// <param name="list"></param> /// <typeparam name="T"></typeparam> /// <returns></returns> public static bool IsNull<T>(this IEnumerable<T> list) { return list == null; } /// <summary> /// Checks if an IEnumerable collection has elements safely without the risk of null exception /// </summary> /// <typeparam name="T" /> /// <param name="list" /> /// <returns>True if there are any items in this IEnumerable</returns> public static bool SafeAny<T>(this IEnumerable<T> list) { return list != null && list.Any(); } /// <summary> /// Checks if an IEnumerable collection has elements safely without the risk of null exception /// </summary> /// <typeparam name="T" /> /// <param name="list" /> /// <param name="predicate" /> /// <returns>True if there are any items in this IEnumerable which match the predicate</returns> public static bool SafeAny<T>(this IEnumerable<T> list, Func<T, bool> predicate) { return list != null && list.Any(predicate); } /// <summary> /// Returns a list containing the elements that exist in both lists /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> /// <param name="otherList"></param> /// <returns></returns> public static IEnumerable<T> In<T>(this IEnumerable<T> list, IEnumerable<T> otherList) { return list.Where(dd => otherList.SafeAny(dd2 => dd2.Equals(dd))); } /// <summary> /// Returns a list containing the elements not in the source list /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> /// <param name="otherList"></param> /// <returns></returns> public static IEnumerable<T> NotIn<T>(this IEnumerable<T> list, IEnumerable<T> otherList) { return list.Where(dd => !otherList.SafeAny(dd2 => dd2.Equals(dd))); } /// <summary> /// Gets the number of elements in a list, safely /// </summary> /// <typeparam name="T" /> /// <param name="list" /> /// <returns>The number of elements in the list</returns> public static int SafeCount<T>(this IEnumerable<T> list) { return list.SafeAny() ? list.Count() : 0; } /// <summary> /// Converts an IEnumerable collection of bytes to an encoded string using the default system encoding /// </summary> /// <param name="list"></param> /// <returns></returns> public static string ToEncodedString(this IEnumerable<byte> list) { byte[] bytes = list.ToArray(); return Encoding.Default.GetString(bytes); } /// <summary> /// Returns a string separated by the separator character /// </summary> /// <param name="list" /> /// <param name="separator" /> /// <param name="propertyToUse"></param> /// <param name="useStringValueForEnum"></param> /// <returns /> public static string ToSeparatedString<T>(this IEnumerable<T> list, string separator = ",", string propertyToUse = "", bool useStringValueForEnum = false) { StringBuilder builder = new StringBuilder(); if (list != null && list.SafeAny()) { foreach (T listItem in list) { string displayValue = listItem.ToString(); if (!propertyToUse.IsNullOrWhiteSpace()) { try { displayValue = listItem.GetType().GetProperty(propertyToUse).GetValue(listItem, null).ToString(); } catch (Exception) { displayValue = listItem.ToString(); } } if (listItem is Enum) { if (useStringValueForEnum) { builder.AppendFormat("{0}{1}", listItem, separator); } else { builder.AppendFormat("{0}{1}", Convert.ToInt32(listItem), separator); } } else { builder.AppendFormat("{0}{1}", displayValue, separator); } } } return builder.ToString().RemoveLastInstanceOfWord(separator); } /// <summary> /// Overload for Contains which can take a StrongComparison parameter /// </summary> /// <param name="value" /> /// <param name="valueToCheck" /> /// <param name="comparison" /> /// <returns /> public static bool Contains(this IEnumerable<string> value, string valueToCheck, StringComparison comparison) { bool contains = false; if (value.SafeAny()) { switch (comparison) { case StringComparison.CurrentCultureIgnoreCase: case StringComparison.InvariantCultureIgnoreCase: case StringComparison.OrdinalIgnoreCase: contains = value.SafeAny(v => v.ToUpper().TrimSafely().Contains(valueToCheck.ToUpper().TrimSafely())); break; default: contains = value.SafeAny(v => v.TrimSafely().Contains(valueToCheck.TrimSafely())); break; } } return contains; } /// <summary> /// Safely converts an IEnumerable collection of objects to a list /// </summary> /// <param name="list"></param> /// <typeparam name="T"></typeparam> /// <returns></returns> public static List<T> ToSafeList<T>(this IEnumerable<T> list) { if (list != null) { return list.ToList(); } return new List<T>(); } /// <summary> /// Splits an IEnumerable into equally sized IEnumerable lists /// </summary> /// <typeparam name="T" /> /// <param name="list" /> /// <param name="numberOfChunks" /> /// <returns /> public static IEnumerable<IEnumerable<T>> SplitIntoChunks<T>(this IEnumerable<T> list, int numberOfChunks) where T : class { List<List<T>> splitList = new List<List<T>>(); for (int currentChunk = 0; currentChunk < numberOfChunks; currentChunk++) { splitList.Add(new List<T>()); } if (list.SafeAny()) { int numberOfElements = list.Count(); for (int i = 0; i < numberOfChunks; i++) { List<T> currentList = splitList.ElementAt(i); for (int j = 0; j < numberOfElements; j++) { if (j % numberOfChunks == i) { T element = list.ElementAtOrDefault(j); if (element != null) { currentList.Add(element); } } } } } return splitList.Cast<IEnumerable<T>>(); } /// <summary> /// Coalesces List (Removes all Nulls) /// </summary> /// <typeparam name="T" /> /// <param name="source" /> /// <returns /> public static IEnumerable<T> Coalesce<T>(this IEnumerable<T?> source) where T : struct { return source.Where(x => x.HasValue).Select(x => x.GetValueOrDefault()); } /// <summary> /// Gets the Mode from Enumerable list of primitive values /// Mode: the value that occurs most often /// </summary> /// <typeparam name="T" /> /// <param name="list" /> /// <returns>The Mode of list</returns> public static T Mode<T>(this IEnumerable<T> list) where T : struct { T mode = default(T); if (list.SafeAny()) { mode = list.GroupBy(t => t).OrderByDescending(g => g.Count()).First().Key; } return mode; } /// <summary> /// Gets the Mode from Enumerable list of strings /// Mode: the string that occurs most often /// </summary> /// <param name="list" /> /// <returns>The Mode of list</returns> public static string Mode(this IEnumerable<string> list) { string mode = string.Empty; if (list.SafeAny()) { mode = list.GroupBy(t => t).OrderByDescending(g => g.Count()).First().Key; } return mode; } /// <summary> /// Gets the Median from Enumerable list of primitive values /// Median: middle value in the list /// NOTE: If list is even, the element that will be returned will be element at index ((Count - 1) / 2) /// </summary> /// <typeparam name="T" /> /// <param name="list" /> /// <returns>The Median of list</returns> public static T Median<T>(this IEnumerable<T> list) where T : struct { T median = default(T); if (list.SafeAny()) { int count = list.Count(); int itemIndex = count / 2; list = list.OrderBy(t => t); median = list.ElementAt(itemIndex); } return median; } /// <summary> /// Gets the Median from Enumerable list of strings /// Median: middle string in the list /// NOTE: If list is even, the string that will be returned will be string at index ((Count - 1) / 2) /// </summary> /// <param name="list" /> /// <returns>The Median of list</returns> public static string Median(this IEnumerable<string> list) { string median = string.Empty; if (list.SafeAny()) { int count = list.Count(); int itemIndex = count / 2; list = list.OrderBy(t => t); median = list.ElementAt(itemIndex); } return median; } /// <summary> /// Converts Enumerable collection into DataTable /// </summary> /// <typeparam name="T" /> /// <param name="collection" /> /// <returns>DataTable</returns> public static DataTable ToDataTable<T>(this IEnumerable<T> collection) { DataTable dataTable = new DataTable(); Type type = typeof(T); PropertyInfo[] properties = type.GetProperties(); //Create the columns in the DataTable foreach (PropertyInfo property in properties) { Type propertyType = property.PropertyType; if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) { propertyType = new NullableConverter(propertyType).UnderlyingType; } dataTable.Columns.Add(property.Name, propertyType); } //Populate the table foreach (T item in collection) { DataRow dataRow = dataTable.NewRow(); dataRow.BeginEdit(); foreach (PropertyInfo property in properties) { dataRow[property.Name] = property.GetValue(item, null); } dataRow.EndEdit(); dataTable.Rows.Add(dataRow); } return dataTable; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Buffers; using System.Linq; using System.Reflection.Metadata; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.ActionConstraints; using Microsoft.AspNetCore.Mvc.ApplicationModels; using Microsoft.AspNetCore.Mvc.ApplicationParts; using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata; using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Routing.Matching; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// Extension methods for setting up essential MVC services in an <see cref="IServiceCollection" />. /// </summary> public static class MvcCoreServiceCollectionExtensions { /// <summary> /// Adds the minimum essential MVC services to the specified <see cref="IServiceCollection" />. Additional services /// including MVC's support for authorization, formatters, and validation must be added separately using the /// <see cref="IMvcCoreBuilder"/> returned from this method. /// </summary> /// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param> /// <returns>An <see cref="IMvcCoreBuilder"/> that can be used to further configure the MVC services.</returns> /// <remarks> /// The <see cref="MvcCoreServiceCollectionExtensions.AddMvcCore(IServiceCollection)"/> approach for configuring /// MVC is provided for experienced MVC developers who wish to have full control over the set of default services /// registered. <see cref="MvcCoreServiceCollectionExtensions.AddMvcCore(IServiceCollection)"/> will register /// the minimum set of services necessary to route requests and invoke controllers. It is not expected that any /// application will satisfy its requirements with just a call to /// <see cref="MvcCoreServiceCollectionExtensions.AddMvcCore(IServiceCollection)"/>. Additional configuration using the /// <see cref="IMvcCoreBuilder"/> will be required. /// </remarks> public static IMvcCoreBuilder AddMvcCore(this IServiceCollection services) { if (services == null) { throw new ArgumentNullException(nameof(services)); } var environment = GetServiceFromCollection<IWebHostEnvironment>(services); var partManager = GetApplicationPartManager(services, environment); services.TryAddSingleton(partManager); ConfigureDefaultFeatureProviders(partManager); ConfigureDefaultServices(services); AddMvcCoreServices(services); var builder = new MvcCoreBuilder(services, partManager); return builder; } private static void ConfigureDefaultFeatureProviders(ApplicationPartManager manager) { if (!manager.FeatureProviders.OfType<ControllerFeatureProvider>().Any()) { manager.FeatureProviders.Add(new ControllerFeatureProvider()); } } private static ApplicationPartManager GetApplicationPartManager(IServiceCollection services, IWebHostEnvironment? environment) { var manager = GetServiceFromCollection<ApplicationPartManager>(services); if (manager == null) { manager = new ApplicationPartManager(); var entryAssemblyName = environment?.ApplicationName; if (string.IsNullOrEmpty(entryAssemblyName)) { return manager; } manager.PopulateDefaultParts(entryAssemblyName); } return manager; } private static T? GetServiceFromCollection<T>(IServiceCollection services) { return (T?)services .LastOrDefault(d => d.ServiceType == typeof(T)) ?.ImplementationInstance; } /// <summary> /// Adds the minimum essential MVC services to the specified <see cref="IServiceCollection" />. Additional services /// including MVC's support for authorization, formatters, and validation must be added separately using the /// <see cref="IMvcCoreBuilder"/> returned from this method. /// </summary> /// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param> /// <param name="setupAction">An <see cref="Action{MvcOptions}"/> to configure the provided <see cref="MvcOptions"/>.</param> /// <returns>An <see cref="IMvcCoreBuilder"/> that can be used to further configure the MVC services.</returns> /// <remarks> /// The <see cref="MvcCoreServiceCollectionExtensions.AddMvcCore(IServiceCollection)"/> approach for configuring /// MVC is provided for experienced MVC developers who wish to have full control over the set of default services /// registered. <see cref="MvcCoreServiceCollectionExtensions.AddMvcCore(IServiceCollection)"/> will register /// the minimum set of services necessary to route requests and invoke controllers. It is not expected that any /// application will satisfy its requirements with just a call to /// <see cref="MvcCoreServiceCollectionExtensions.AddMvcCore(IServiceCollection)"/>. Additional configuration using the /// <see cref="IMvcCoreBuilder"/> will be required. /// </remarks> public static IMvcCoreBuilder AddMvcCore( this IServiceCollection services, Action<MvcOptions> setupAction) { if (services == null) { throw new ArgumentNullException(nameof(services)); } if (setupAction == null) { throw new ArgumentNullException(nameof(setupAction)); } var builder = services.AddMvcCore(); services.Configure(setupAction); return builder; } // To enable unit testing internal static void AddMvcCoreServices(IServiceCollection services) { // // Options // services.TryAddEnumerable( ServiceDescriptor.Transient<IConfigureOptions<MvcOptions>, MvcCoreMvcOptionsSetup>()); services.TryAddEnumerable( ServiceDescriptor.Transient<IPostConfigureOptions<MvcOptions>, MvcCoreMvcOptionsSetup>()); services.TryAddEnumerable( ServiceDescriptor.Transient<IConfigureOptions<ApiBehaviorOptions>, ApiBehaviorOptionsSetup>()); services.TryAddEnumerable( ServiceDescriptor.Transient<IConfigureOptions<RouteOptions>, MvcCoreRouteOptionsSetup>()); // // Action Discovery // // These are consumed only when creating action descriptors, then they can be deallocated services.TryAddSingleton<ApplicationModelFactory>(); services.TryAddEnumerable( ServiceDescriptor.Transient<IApplicationModelProvider, DefaultApplicationModelProvider>()); services.TryAddEnumerable( ServiceDescriptor.Transient<IApplicationModelProvider, ApiBehaviorApplicationModelProvider>()); services.TryAddEnumerable( ServiceDescriptor.Transient<IActionDescriptorProvider, ControllerActionDescriptorProvider>()); services.TryAddSingleton<IActionDescriptorCollectionProvider, DefaultActionDescriptorCollectionProvider>(); // // Action Selection // services.TryAddSingleton<IActionSelector, ActionSelector>(); services.TryAddSingleton<ActionConstraintCache>(); // Will be cached by the DefaultActionSelector services.TryAddEnumerable(ServiceDescriptor.Transient<IActionConstraintProvider, DefaultActionConstraintProvider>()); // Policies for Endpoints services.TryAddEnumerable(ServiceDescriptor.Singleton<MatcherPolicy, ActionConstraintMatcherPolicy>()); // // Controller Factory // // This has a cache, so it needs to be a singleton services.TryAddSingleton<IControllerFactory, DefaultControllerFactory>(); // Will be cached by the DefaultControllerFactory services.TryAddTransient<IControllerActivator, DefaultControllerActivator>(); services.TryAddSingleton<IControllerFactoryProvider, ControllerFactoryProvider>(); services.TryAddSingleton<IControllerActivatorProvider, ControllerActivatorProvider>(); services.TryAddEnumerable( ServiceDescriptor.Transient<IControllerPropertyActivator, DefaultControllerPropertyActivator>()); // // Action Invoker // // The IActionInvokerFactory is cachable services.TryAddSingleton<IActionInvokerFactory, ActionInvokerFactory>(); services.TryAddEnumerable( ServiceDescriptor.Transient<IActionInvokerProvider, ControllerActionInvokerProvider>()); // These are stateless services.TryAddSingleton<ControllerActionInvokerCache>(); services.TryAddEnumerable( ServiceDescriptor.Singleton<IFilterProvider, DefaultFilterProvider>()); services.TryAddSingleton<IActionResultTypeMapper, ActionResultTypeMapper>(); // // Request body limit filters // services.TryAddTransient<RequestSizeLimitFilter>(); services.TryAddTransient<DisableRequestSizeLimitFilter>(); services.TryAddTransient<RequestFormLimitsFilter>(); // // ModelBinding, Validation // // The DefaultModelMetadataProvider does significant caching and should be a singleton. services.TryAddSingleton<IModelMetadataProvider, DefaultModelMetadataProvider>(); services.TryAdd(ServiceDescriptor.Transient<ICompositeMetadataDetailsProvider>(s => { var options = s.GetRequiredService<IOptions<MvcOptions>>().Value; return new DefaultCompositeMetadataDetailsProvider(options.ModelMetadataDetailsProviders); })); services.TryAddSingleton<IModelBinderFactory, ModelBinderFactory>(); services.TryAddSingleton<IObjectModelValidator>(s => { var options = s.GetRequiredService<IOptions<MvcOptions>>().Value; var metadataProvider = s.GetRequiredService<IModelMetadataProvider>(); return new DefaultObjectValidator(metadataProvider, options.ModelValidatorProviders, options); }); services.TryAddSingleton<ClientValidatorCache>(); services.TryAddSingleton<ParameterBinder>(); // // Random Infrastructure // services.TryAddSingleton<MvcMarkerService, MvcMarkerService>(); services.TryAddSingleton<ITypeActivatorCache, TypeActivatorCache>(); services.TryAddSingleton<IUrlHelperFactory, UrlHelperFactory>(); services.TryAddSingleton<IHttpRequestStreamReaderFactory, MemoryPoolHttpRequestStreamReaderFactory>(); services.TryAddSingleton<IHttpResponseStreamWriterFactory, MemoryPoolHttpResponseStreamWriterFactory>(); services.TryAddSingleton(ArrayPool<byte>.Shared); services.TryAddSingleton(ArrayPool<char>.Shared); services.TryAddSingleton<OutputFormatterSelector, DefaultOutputFormatterSelector>(); services.TryAddSingleton<IActionResultExecutor<ObjectResult>, ObjectResultExecutor>(); services.TryAddSingleton<IActionResultExecutor<PhysicalFileResult>, PhysicalFileResultExecutor>(); services.TryAddSingleton<IActionResultExecutor<VirtualFileResult>, VirtualFileResultExecutor>(); services.TryAddSingleton<IActionResultExecutor<FileStreamResult>, FileStreamResultExecutor>(); services.TryAddSingleton<IActionResultExecutor<FileContentResult>, FileContentResultExecutor>(); services.TryAddSingleton<IActionResultExecutor<RedirectResult>, RedirectResultExecutor>(); services.TryAddSingleton<IActionResultExecutor<LocalRedirectResult>, LocalRedirectResultExecutor>(); services.TryAddSingleton<IActionResultExecutor<RedirectToActionResult>, RedirectToActionResultExecutor>(); services.TryAddSingleton<IActionResultExecutor<RedirectToRouteResult>, RedirectToRouteResultExecutor>(); services.TryAddSingleton<IActionResultExecutor<RedirectToPageResult>, RedirectToPageResultExecutor>(); services.TryAddSingleton<IActionResultExecutor<ContentResult>, ContentResultExecutor>(); services.TryAddSingleton<IActionResultExecutor<JsonResult>, SystemTextJsonResultExecutor>(); services.TryAddSingleton<IClientErrorFactory, ProblemDetailsClientErrorFactory>(); services.TryAddSingleton<ProblemDetailsFactory, DefaultProblemDetailsFactory>(); // // Route Handlers // services.TryAddSingleton<MvcRouteHandler>(); // Only one per app services.TryAddTransient<MvcAttributeRouteHandler>(); // Many per app // // Endpoint Routing / Endpoints // services.TryAddSingleton<ControllerActionEndpointDataSourceFactory>(); services.TryAddSingleton<OrderedEndpointsSequenceProviderCache>(); services.TryAddSingleton<ControllerActionEndpointDataSourceIdProvider>(); services.TryAddSingleton<ActionEndpointFactory>(); services.TryAddSingleton<DynamicControllerEndpointSelectorCache>(); services.TryAddEnumerable(ServiceDescriptor.Singleton<MatcherPolicy, DynamicControllerEndpointMatcherPolicy>()); services.TryAddEnumerable(ServiceDescriptor.Singleton<IRequestDelegateFactory, ControllerRequestDelegateFactory>()); // // Middleware pipeline filter related // services.TryAddSingleton<MiddlewareFilterConfigurationProvider>(); // This maintains a cache of middleware pipelines, so it needs to be a singleton services.TryAddSingleton<MiddlewareFilterBuilder>(); // Sets ApplicationBuilder on MiddlewareFilterBuilder services.TryAddEnumerable(ServiceDescriptor.Singleton<IStartupFilter, MiddlewareFilterBuilderStartupFilter>()); } private static void ConfigureDefaultServices(IServiceCollection services) { services.AddRouting(); } } }
// **************************************************************** // Copyright 2007, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org // **************************************************************** using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using NUnit.Util; using NUnit.Core; using CP.Windows.Forms; namespace NUnit.UiKit { /// <summary> /// Summary description for ErrorDisplay. /// </summary> public class ErrorDisplay : System.Windows.Forms.UserControl, TestObserver { static readonly Font DefaultFixedFont = new Font(FontFamily.GenericMonospace, 8.0F); private ISettings settings = null; int hoverIndex = -1; private System.Windows.Forms.Timer hoverTimer; TipWindow tipWindow; private bool wordWrap = false; private System.Windows.Forms.ListBox detailList; public UiException.Controls.StackTraceDisplay stackTraceDisplay; public UiException.Controls.ErrorBrowser errorBrowser; private UiException.Controls.SourceCodeDisplay sourceCode; public System.Windows.Forms.Splitter tabSplitter; private System.Windows.Forms.ContextMenu detailListContextMenu; private System.Windows.Forms.MenuItem copyDetailMenuItem; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public ErrorDisplay() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Properties private bool WordWrap { get { return wordWrap; } set { if ( value != this.wordWrap ) { this.wordWrap = value; RefillDetailList(); } } } #endregion #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.detailList = new System.Windows.Forms.ListBox(); this.tabSplitter = new System.Windows.Forms.Splitter(); this.errorBrowser = new NUnit.UiException.Controls.ErrorBrowser(); this.sourceCode = new UiException.Controls.SourceCodeDisplay(); this.stackTraceDisplay = new UiException.Controls.StackTraceDisplay(); this.detailListContextMenu = new System.Windows.Forms.ContextMenu(); this.copyDetailMenuItem = new System.Windows.Forms.MenuItem(); this.SuspendLayout(); // // detailList // this.detailList.Dock = System.Windows.Forms.DockStyle.Top; this.detailList.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable; this.detailList.Font = DefaultFixedFont; this.detailList.HorizontalExtent = 2000; this.detailList.HorizontalScrollbar = true; this.detailList.ItemHeight = 16; this.detailList.Location = new System.Drawing.Point(0, 0); this.detailList.Name = "detailList"; this.detailList.ScrollAlwaysVisible = true; this.detailList.Size = new System.Drawing.Size(496, 128); this.detailList.TabIndex = 1; this.detailList.Resize += new System.EventHandler(this.detailList_Resize); this.detailList.MouseHover += new System.EventHandler(this.OnMouseHover); this.detailList.MeasureItem += new System.Windows.Forms.MeasureItemEventHandler(this.detailList_MeasureItem); this.detailList.MouseMove += new System.Windows.Forms.MouseEventHandler(this.detailList_MouseMove); this.detailList.MouseLeave += new System.EventHandler(this.detailList_MouseLeave); this.detailList.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.detailList_DrawItem); this.detailList.SelectedIndexChanged += new System.EventHandler(this.detailList_SelectedIndexChanged); // // tabSplitter // this.tabSplitter.Dock = System.Windows.Forms.DockStyle.Top; this.tabSplitter.Location = new System.Drawing.Point(0, 128); this.tabSplitter.MinSize = 100; this.tabSplitter.Name = "tabSplitter"; this.tabSplitter.Size = new System.Drawing.Size(496, 9); this.tabSplitter.TabIndex = 3; this.tabSplitter.TabStop = false; this.tabSplitter.SplitterMoved += new System.Windows.Forms.SplitterEventHandler(this.tabSplitter_SplitterMoved); // // errorBrowser // this.errorBrowser.Dock = System.Windows.Forms.DockStyle.Fill; this.errorBrowser.Location = new System.Drawing.Point(0, 137); this.errorBrowser.Name = "errorBrowser"; this.errorBrowser.Size = new System.Drawing.Size(496, 151); this.errorBrowser.StackTraceSource = null; this.errorBrowser.TabIndex = 4; // // configure and register SourceCodeDisplay // this.sourceCode.AutoSelectFirstItem = true; this.sourceCode.ListOrderPolicy = UiException.Controls.ErrorListOrderPolicy.ReverseOrder; this.sourceCode.SplitOrientation = Orientation.Vertical; this.sourceCode.SplitterDistance = 0.3f; this.stackTraceDisplay.Font = DefaultFixedFont; this.errorBrowser.RegisterDisplay(sourceCode); this.errorBrowser.RegisterDisplay(stackTraceDisplay); // // detailListContextMenu // this.detailListContextMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.copyDetailMenuItem}); // // copyDetailMenuItem // this.copyDetailMenuItem.Index = 0; this.copyDetailMenuItem.Text = "Copy"; this.copyDetailMenuItem.Click += new System.EventHandler(this.copyDetailMenuItem_Click); // // ErrorDisplay // this.Controls.Add(this.errorBrowser); this.Controls.Add(this.tabSplitter); this.Controls.Add(this.detailList); this.Name = "ErrorDisplay"; this.Size = new System.Drawing.Size(496, 288); this.ResumeLayout(false); } #endregion #region Form Level Events protected override void OnLoad(EventArgs e) { // NOTE: DesignMode is not true when display is nested in another // user control and the containing form is displayed in the designer. // This is a problem with VS.Net. // // Consequently, we rely on the fact that Services.UserSettings // returns a dummy Service, if the ServiceManager has not been // initialized. if ( !this.DesignMode ) { this.settings = Services.UserSettings; settings.Changed += new SettingsEventHandler(UserSettings_Changed); int splitPosition = settings.GetSetting( "Gui.ResultTabs.ErrorsTabSplitterPosition", tabSplitter.SplitPosition ); if ( splitPosition >= tabSplitter.MinSize && splitPosition < this.ClientSize.Height ) this.tabSplitter.SplitPosition = splitPosition; this.WordWrap = settings.GetSetting( "Gui.ResultTabs.ErrorsTab.WordWrapEnabled", true ); this.detailList.Font = this.stackTraceDisplay.Font = settings.GetSetting( "Gui.FixedFont", DefaultFixedFont ); Orientation splitOrientation = (Orientation)settings.GetSetting( "Gui.ResultTabs.ErrorBrowser.SplitterOrientation", Orientation.Vertical); float splitterDistance = splitOrientation == Orientation.Vertical ? settings.GetSetting( "Gui.ResultTabs.ErrorBrowser.VerticalPosition", 0.3f ) : settings.GetSetting( "Gui.ResultTabs.ErrorBrowser.HorizontalPosition", 0.3f ); sourceCode.SplitOrientation = splitOrientation; sourceCode.SplitterDistance = splitterDistance; sourceCode.SplitOrientationChanged += new EventHandler(sourceCode_SplitOrientationChanged); sourceCode.SplitterDistanceChanged += new EventHandler(sourceCode_SplitterDistanceChanged); if ( settings.GetSetting("Gui.ResultTabs.ErrorBrowser.SourceCodeDisplay", false) ) errorBrowser.SelectedDisplay = sourceCode; else errorBrowser.SelectedDisplay = stackTraceDisplay; errorBrowser.StackTraceDisplayChanged += new EventHandler(errorBrowser_StackTraceDisplayChanged); } base.OnLoad (e); } void errorBrowser_StackTraceDisplayChanged(object sender, EventArgs e) { settings.SaveSetting("Gui.ResultTabs.ErrorBrowser.SourceCodeDisplay", errorBrowser.SelectedDisplay == sourceCode); } void sourceCode_SplitterDistanceChanged(object sender, EventArgs e) { string distanceSetting = sourceCode.SplitOrientation == Orientation.Vertical ? "Gui.ResultTabs.ErrorBrowser.VerticalPosition" : "Gui.ResultTabs.ErrorBrowser.HorizontalPosition"; settings.SaveSetting(distanceSetting, sourceCode.SplitterDistance); } void sourceCode_SplitOrientationChanged(object sender, EventArgs e) { settings.SaveSetting("Gui.ResultTabs.ErrorBrowser.SplitterOrientation", sourceCode.SplitOrientation); string distanceSetting = sourceCode.SplitOrientation == Orientation.Vertical ? "Gui.ResultTabs.ErrorBrowser.VerticalPosition" : "Gui.ResultTabs.ErrorBrowser.HorizontalPosition"; sourceCode.SplitterDistance = settings.GetSetting(distanceSetting, 0.3f); } #endregion #region Public Methods public void Clear() { detailList.Items.Clear(); detailList.ContextMenu = null; errorBrowser.StackTraceSource = ""; } #endregion #region UserSettings Events private void UserSettings_Changed( object sender, SettingsEventArgs args ) { this.WordWrap = settings.GetSetting( "Gui.ResultTabs.ErrorsTab.WordWrapEnabled", true ); Font newFont = this.stackTraceDisplay.Font = this.sourceCode.CodeDisplayFont = settings.GetSetting("Gui.FixedFont", DefaultFixedFont); if (newFont != this.detailList.Font) { this.detailList.Font = newFont; RefillDetailList(); } } #endregion #region DetailList Events /// <summary> /// When one of the detail failure items is selected, display /// the stack trace and set up the tool tip for that item. /// </summary> private void detailList_SelectedIndexChanged(object sender, System.EventArgs e) { TestResultItem resultItem = (TestResultItem)detailList.SelectedItem; errorBrowser.StackTraceSource = resultItem.StackTrace; detailList.ContextMenu = detailListContextMenu; } private void detailList_MeasureItem(object sender, System.Windows.Forms.MeasureItemEventArgs e) { TestResultItem item = (TestResultItem) detailList.Items[e.Index]; //string s = item.ToString(); SizeF size = this.WordWrap ? e.Graphics.MeasureString(item.ToString(), detailList.Font, detailList.ClientSize.Width ) : e.Graphics.MeasureString(item.ToString(), detailList.Font ); e.ItemHeight = (int)size.Height; e.ItemWidth = (int)size.Width; } private void detailList_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e) { if (e.Index >= 0) { e.DrawBackground(); TestResultItem item = (TestResultItem) detailList.Items[e.Index]; bool selected = ((e.State & DrawItemState.Selected) == DrawItemState.Selected) ? true : false; Brush brush = selected ? SystemBrushes.HighlightText : SystemBrushes.WindowText; RectangleF layoutRect = e.Bounds; if ( this.WordWrap && layoutRect.Width > detailList.ClientSize.Width ) layoutRect.Width = detailList.ClientSize.Width; e.Graphics.DrawString(item.ToString(),detailList.Font, brush, layoutRect); } } private void detailList_Resize(object sender, System.EventArgs e) { if ( this.WordWrap ) RefillDetailList(); } private void RefillDetailList() { if ( this.detailList.Items.Count > 0 ) { this.detailList.BeginUpdate(); ArrayList copiedItems = new ArrayList( detailList.Items ); this.detailList.Items.Clear(); foreach( object item in copiedItems ) this.detailList.Items.Add( item ); this.detailList.EndUpdate(); } } private void copyDetailMenuItem_Click(object sender, System.EventArgs e) { if ( detailList.SelectedItem != null ) Clipboard.SetDataObject( detailList.SelectedItem.ToString() ); } private void OnMouseHover(object sender, System.EventArgs e) { if ( tipWindow != null ) tipWindow.Close(); if ( settings.GetSetting( "Gui.ResultTabs.ErrorsTab.ToolTipsEnabled", false ) && hoverIndex >= 0 && hoverIndex < detailList.Items.Count ) { Graphics g = Graphics.FromHwnd( detailList.Handle ); Rectangle itemRect = detailList.GetItemRectangle( hoverIndex ); string text = detailList.Items[hoverIndex].ToString(); SizeF sizeNeeded = g.MeasureString( text, detailList.Font ); bool expansionNeeded = itemRect.Width < (int)sizeNeeded.Width || itemRect.Height < (int)sizeNeeded.Height; if ( expansionNeeded ) { tipWindow = new TipWindow( detailList, hoverIndex ); tipWindow.ItemBounds = itemRect; tipWindow.TipText = text; tipWindow.Expansion = TipWindow.ExpansionStyle.Both; tipWindow.Overlay = true; tipWindow.WantClicks = true; tipWindow.Closed += new EventHandler( tipWindow_Closed ); tipWindow.Show(); } } } private void tipWindow_Closed( object sender, System.EventArgs e ) { tipWindow = null; hoverIndex = -1; ClearTimer(); } private void detailList_MouseLeave(object sender, System.EventArgs e) { hoverIndex = -1; ClearTimer(); } private void detailList_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) { ClearTimer(); hoverIndex = detailList.IndexFromPoint( e.X, e.Y ); if ( hoverIndex >= 0 && hoverIndex < detailList.Items.Count ) { // Workaround problem of IndexFromPoint returning an // index when mouse is over bottom part of list. Rectangle r = detailList.GetItemRectangle( hoverIndex ); if ( e.Y > r.Bottom ) hoverIndex = -1; else { hoverTimer = new System.Windows.Forms.Timer(); hoverTimer.Interval = 800; hoverTimer.Tick += new EventHandler( OnMouseHover ); hoverTimer.Start(); } } } private void ClearTimer() { if ( hoverTimer != null ) { hoverTimer.Stop(); hoverTimer.Dispose(); } } private void tabSplitter_SplitterMoved( object sender, SplitterEventArgs e ) { settings.SaveSetting( "Gui.ResultTabs.ErrorsTabSplitterPosition", tabSplitter.SplitPosition ); } #endregion #region TestObserver Interface public void Subscribe(ITestEvents events) { events.TestFinished += new TestEventHandler(OnTestFinished); events.SuiteFinished += new TestEventHandler(OnSuiteFinished); events.TestException += new TestEventHandler(OnTestException); } #endregion #region Test Event Handlers private void OnTestFinished(object sender, TestEventArgs args) { TestResult result = args.Result; switch (result.ResultState) { case ResultState.Failure: case ResultState.Error: case ResultState.Cancelled: if (result.FailureSite != FailureSite.Parent) InsertTestResultItem(result); break; case ResultState.NotRunnable: InsertTestResultItem(result); break; } } private void OnSuiteFinished(object sender, TestEventArgs args) { TestResult result = args.Result; if( result.FailureSite != FailureSite.Child ) switch (result.ResultState) { case ResultState.Failure: case ResultState.Error: case ResultState.Cancelled: InsertTestResultItem(result); break; } } private void OnTestException(object sender, TestEventArgs args) { string msg = string.Format( "An unhandled {0} was thrown while executing this test : {1}", args.Exception.GetType().FullName, args.Exception.Message ); TestResultItem item = new TestResultItem( args.Name, msg, args.Exception.StackTrace ); InsertTestResultItem( item ); } private void InsertTestResultItem( TestResult result ) { TestResultItem item = new TestResultItem(result); InsertTestResultItem( item ); } private void InsertTestResultItem( TestResultItem item ) { detailList.BeginUpdate(); detailList.Items.Insert(detailList.Items.Count, item); detailList.SelectedIndex = 0; detailList.EndUpdate(); } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyByte { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Models; /// <summary> /// ByteModel operations. /// </summary> public partial class ByteModel : IServiceOperations<AutoRestSwaggerBATByteService>, IByteModel { /// <summary> /// Initializes a new instance of the ByteModel class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> public ByteModel(AutoRestSwaggerBATByteService client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestSwaggerBATByteService /// </summary> public AutoRestSwaggerBATByteService Client { get; private set; } /// <summary> /// Get null byte value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<byte[]>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "byte/null").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<byte[]>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<byte[]>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get empty byte value '' /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<byte[]>> GetEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetEmpty", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "byte/empty").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<byte[]>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<byte[]>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get non-ascii byte string hex(FF FE FD FC FB FA F9 F8 F7 F6) /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<byte[]>> GetNonAsciiWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetNonAscii", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "byte/nonAscii").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<byte[]>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<byte[]>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put non-ascii byte string hex(FF FE FD FC FB FA F9 F8 F7 F6) /// </summary> /// <param name='byteBody'> /// Base64-encoded non-ascii byte string hex(FF FE FD FC FB FA F9 F8 F7 F6) /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse> PutNonAsciiWithHttpMessagesAsync(byte[] byteBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (byteBody == null) { throw new ValidationException(ValidationRules.CannotBeNull, "byteBody"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("byteBody", byteBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutNonAscii", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "byte/nonAscii").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = SafeJsonConvert.SerializeObject(byteBody, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get invalid byte value ':::SWAGGER::::' /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<byte[]>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetInvalid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "byte/invalid").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<byte[]>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<byte[]>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using 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; namespace SoftLogik.Win.Data { /// <summary> /// Strongly-typed collection for the Country class. /// </summary> [Serializable] public partial class CountryCollection : ActiveList<Country, CountryCollection> { public CountryCollection() {} } /// <summary> /// This is an ActiveRecord class which wraps the SLCountry table. /// </summary> [Serializable] public partial class Country : ActiveRecord<Country> { #region .ctors and Default Settings public Country() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public Country(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public Country(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public Country(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("SLCountry", TableType.Table, DataService.GetInstance("WinSubSonicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarCountryID = new TableSchema.TableColumn(schema); colvarCountryID.ColumnName = "CountryID"; colvarCountryID.DataType = DbType.Int32; colvarCountryID.MaxLength = 0; colvarCountryID.AutoIncrement = true; colvarCountryID.IsNullable = false; colvarCountryID.IsPrimaryKey = true; colvarCountryID.IsForeignKey = false; colvarCountryID.IsReadOnly = false; colvarCountryID.DefaultSetting = @""; colvarCountryID.ForeignKeyTableName = ""; schema.Columns.Add(colvarCountryID); TableSchema.TableColumn colvarCountryCode = new TableSchema.TableColumn(schema); colvarCountryCode.ColumnName = "CountryCode"; colvarCountryCode.DataType = DbType.AnsiStringFixedLength; colvarCountryCode.MaxLength = 2; colvarCountryCode.AutoIncrement = false; colvarCountryCode.IsNullable = false; colvarCountryCode.IsPrimaryKey = false; colvarCountryCode.IsForeignKey = false; colvarCountryCode.IsReadOnly = false; colvarCountryCode.DefaultSetting = @""; colvarCountryCode.ForeignKeyTableName = ""; schema.Columns.Add(colvarCountryCode); TableSchema.TableColumn colvarCountryX = new TableSchema.TableColumn(schema); colvarCountryX.ColumnName = "Country"; colvarCountryX.DataType = DbType.String; colvarCountryX.MaxLength = 255; colvarCountryX.AutoIncrement = false; colvarCountryX.IsNullable = false; colvarCountryX.IsPrimaryKey = false; colvarCountryX.IsForeignKey = false; colvarCountryX.IsReadOnly = false; colvarCountryX.DefaultSetting = @""; colvarCountryX.ForeignKeyTableName = ""; schema.Columns.Add(colvarCountryX); TableSchema.TableColumn colvarCurrencyCode = new TableSchema.TableColumn(schema); colvarCurrencyCode.ColumnName = "CurrencyCode"; colvarCurrencyCode.DataType = DbType.AnsiStringFixedLength; colvarCurrencyCode.MaxLength = 3; colvarCurrencyCode.AutoIncrement = false; colvarCurrencyCode.IsNullable = true; colvarCurrencyCode.IsPrimaryKey = false; colvarCurrencyCode.IsForeignKey = false; colvarCurrencyCode.IsReadOnly = false; colvarCurrencyCode.DefaultSetting = @""; colvarCurrencyCode.ForeignKeyTableName = ""; schema.Columns.Add(colvarCurrencyCode); TableSchema.TableColumn colvarCurrency = new TableSchema.TableColumn(schema); colvarCurrency.ColumnName = "Currency"; colvarCurrency.DataType = DbType.String; colvarCurrency.MaxLength = 255; colvarCurrency.AutoIncrement = false; colvarCurrency.IsNullable = true; colvarCurrency.IsPrimaryKey = false; colvarCurrency.IsForeignKey = false; colvarCurrency.IsReadOnly = false; colvarCurrency.DefaultSetting = @""; colvarCurrency.ForeignKeyTableName = ""; schema.Columns.Add(colvarCurrency); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["WinSubSonicProvider"].AddSchema("SLCountry",schema); } } #endregion #region Props [XmlAttribute("CountryID")] public int CountryID { get { return GetColumnValue<int>("CountryID"); } set { SetColumnValue("CountryID", value); } } [XmlAttribute("CountryCode")] public string CountryCode { get { return GetColumnValue<string>("CountryCode"); } set { SetColumnValue("CountryCode", value); } } [XmlAttribute("CountryX")] public string CountryX { get { return GetColumnValue<string>("Country"); } set { SetColumnValue("Country", value); } } [XmlAttribute("CurrencyCode")] public string CurrencyCode { get { return GetColumnValue<string>("CurrencyCode"); } set { SetColumnValue("CurrencyCode", value); } } [XmlAttribute("Currency")] public string Currency { get { return GetColumnValue<string>("Currency"); } set { SetColumnValue("Currency", value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varCountryCode,string varCountryX,string varCurrencyCode,string varCurrency) { Country item = new Country(); item.CountryCode = varCountryCode; item.CountryX = varCountryX; item.CurrencyCode = varCurrencyCode; item.Currency = varCurrency; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varCountryID,string varCountryCode,string varCountryX,string varCurrencyCode,string varCurrency) { Country item = new Country(); item.CountryID = varCountryID; item.CountryCode = varCountryCode; item.CountryX = varCountryX; item.CurrencyCode = varCurrencyCode; item.Currency = varCurrency; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Columns Struct public struct Columns { public static string CountryID = @"CountryID"; public static string CountryCode = @"CountryCode"; public static string CountryX = @"Country"; public static string CurrencyCode = @"CurrencyCode"; public static string Currency = @"Currency"; } #endregion } }
using System; using System.Text; using Machine.Core; using Machine.Core.Services; using NUnit.Framework; using Rhino.Mocks; namespace Machine.Migrations.Services.Impl { [TestFixture] public class SqlScriptMigrationFactoryTests : StandardFixture<SqlScriptMigrationFactory> { IFileSystem _fileSystem; string _migrationPath; MigrationReference _migrationReference; IDatabaseMigration resultingMigration; public override SqlScriptMigrationFactory Create() { _fileSystem = _mocks.DynamicMock<IFileSystem>(); return new SqlScriptMigrationFactory(_fileSystem); } public string ReadScriptWithoutMarkers { get { var builder = new StringBuilder(); builder.AppendFormat("some{0}", Environment.NewLine); builder.AppendFormat("multiline{0}", Environment.NewLine); builder.AppendFormat("script{0}", Environment.NewLine); builder.AppendFormat("without{0}", Environment.NewLine); builder.AppendFormat("markers{0}", Environment.NewLine); return builder.ToString(); } } public string UpScript { get { var builder = new StringBuilder(); builder.AppendFormat("{0}", Environment.NewLine); builder.AppendFormat("some{0}", Environment.NewLine); builder.AppendFormat("multiline{0}", Environment.NewLine); builder.AppendFormat("script{0}", Environment.NewLine); builder.AppendFormat("with{0}", Environment.NewLine); builder.AppendFormat("UP{0}", Environment.NewLine); builder.AppendFormat("marker{0}", Environment.NewLine); builder.AppendFormat("{0}", Environment.NewLine); return builder.ToString(); } } public string DownScript { get { var builder = new StringBuilder(); builder.AppendFormat("{0}", Environment.NewLine); builder.AppendFormat("some{0}", Environment.NewLine); builder.AppendFormat("multiline{0}", Environment.NewLine); builder.AppendFormat("script{0}", Environment.NewLine); builder.AppendFormat("with{0}", Environment.NewLine); builder.AppendFormat("DOWN{0}", Environment.NewLine); builder.AppendFormat("marker{0}", Environment.NewLine); builder.AppendFormat("{0}", Environment.NewLine); return builder.ToString(); } } public string ReadScriptWithBothUpAndDownMarkers { get { var builder = new StringBuilder(); builder.AppendFormat("/* MIGRATE UP */"); builder.AppendFormat("{0}", UpScript); builder.AppendFormat("/* MIGRATE DOWN */"); builder.AppendFormat("{0}", DownScript); return builder.ToString(); } } public string ReadScriptWithUpMarkerOnly { get { var builder = new StringBuilder(); builder.AppendFormat("/* MIGRATE UP */"); builder.AppendFormat("{0}", UpScript); return builder.ToString(); } } public string ReadScriptWithDownMarkerOnly { get { var builder = new StringBuilder(); builder.AppendFormat("/* MIGRATE DOWN */"); builder.AppendFormat("{0}", DownScript); return builder.ToString(); } } public override void Setup() { base.Setup(); _migrationPath = @"C:\Migration.sql"; _migrationReference = new MigrationReference(1, "", _migrationPath); } [Test] public void CreateMigration_when_called_will_read_the_contents_of_the_file_from_MigrationReference_Path() { using (_mocks.Record()) { Expect.Call(_fileSystem.ReadAllText(_migrationPath)).Repeat.Once().Return(""); } using (_mocks.Playback()) { _target.CreateMigration(_migrationReference); } _mocks.VerifyAll(); } [Test] public void CreateMigration_reading_empty_file_will_return_a_SqlScriptMigration_with_empty_Up_and_Down_scripts() { using (_mocks.Record()) { SetupResult.For(_fileSystem.ReadAllText(_migrationPath)).Repeat.Once().Return(""); } using (_mocks.Playback()) { resultingMigration = _target.CreateMigration(_migrationReference); } var sqlScriptMigration = resultingMigration as SqlScriptMigration; if (sqlScriptMigration == null) Assert.Fail("Returned migration should be SqlScriptMigration!"); Assert.That(sqlScriptMigration.UpScript == ""); Assert.That(sqlScriptMigration.DownScript == ""); _mocks.VerifyAll(); } [Test] public void CreateMigration_reading_a_file_without_markers_will_initialize_SqlScriptMigration_with_Up_script_only() { using (_mocks.Record()) { SetupResult.For(_fileSystem.ReadAllText(_migrationPath)).Repeat.Once().Return(ReadScriptWithoutMarkers); } using (_mocks.Playback()) { resultingMigration = _target.CreateMigration(_migrationReference); } var sqlScriptMigration = resultingMigration as SqlScriptMigration; Assert.That(sqlScriptMigration.UpScript == ReadScriptWithoutMarkers); Assert.That(sqlScriptMigration.DownScript == ""); _mocks.VerifyAll(); } [Test] public void CreateMigration_reading_a_file_with_both_Up_and_Down_markers_will_initialize_SqlScriptMigration_with_both_Up_and_Down_scripts() { using (_mocks.Record()) { SetupResult.For(_fileSystem.ReadAllText(_migrationPath)).Repeat.Once().Return(ReadScriptWithBothUpAndDownMarkers); } using (_mocks.Playback()) { resultingMigration = _target.CreateMigration(_migrationReference); } var sqlScriptMigration = resultingMigration as SqlScriptMigration; Assert.That(sqlScriptMigration.UpScript == UpScript); Assert.That(sqlScriptMigration.DownScript == DownScript); _mocks.VerifyAll(); } [Test] public void CreateMigration_reading_a_file_with_Up_marker_only_will_initialize_SqlScriptMigration_with_Up_scripts_only() { using (_mocks.Record()) { SetupResult.For(_fileSystem.ReadAllText(_migrationPath)).Repeat.Once().Return(ReadScriptWithUpMarkerOnly); } using (_mocks.Playback()) { resultingMigration = _target.CreateMigration(_migrationReference); } var sqlScriptMigration = resultingMigration as SqlScriptMigration; Assert.That(sqlScriptMigration.UpScript == UpScript); Assert.That(sqlScriptMigration.DownScript == ""); _mocks.VerifyAll(); } [Test] public void CreateMigration_reading_a_file_with_Down_marker_only_will_initialize_SqlScriptMigration_with_Down_scripts_only() { using (_mocks.Record()) { SetupResult.For(_fileSystem.ReadAllText(_migrationPath)).Repeat.Once().Return(ReadScriptWithDownMarkerOnly); } using (_mocks.Playback()) { resultingMigration = _target.CreateMigration(_migrationReference); } var sqlScriptMigration = resultingMigration as SqlScriptMigration; Assert.That(sqlScriptMigration.UpScript == ""); Assert.That(sqlScriptMigration.DownScript == DownScript); _mocks.VerifyAll(); } } }
/* * Copyright 2013 Monoscape * * 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. * * History: * 2011/11/10 Imesh Gunaratne <imesh@monoscape.org> Created. */ using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.Threading; using Monoscape.ApplicationGridController.Api.Services.Dashboard; using Monoscape.ApplicationGridController.Api.Services.Dashboard.Model; using Monoscape.ApplicationGridController.Runtime; using Monoscape.Common; using Monoscape.Common.Exceptions; using Monoscape.Common.Model; using Monoscape.LoadBalancerController.Api.Services.ApplicationGrid.Model; namespace Monoscape.ApplicationGridController.Scaling { internal class ScalingManager { private int monitoringInterval = 5000; // Monitoring interval 5 sec public void MonitorRequestQueue() { Log.Info(this, "Scaling Manager started"); while (Thread.CurrentThread.IsAlive) { LbGetRequestQueueResponse response = null; try { Log.Info(this, "Checking request queue status..."); LbGetRequestQueueRequest request = new LbGetRequestQueueRequest(Settings.Credentials); response = EndPoints.GetLbApplicationGridService().GetRequestQueue(request); } catch (Exception e) { Log.Error(this, e); } try { if (response != null) ScaleApplications(response.RequestQueue); Thread.Sleep(monitoringInterval); } catch (Exception e) { Log.Error(this, e); } } Log.Info(this, "Scaling Manager stopped"); } private void ScaleApplications(List<ApplicationHttpRequest> requestQueue) { if ((requestQueue == null) || (requestQueue.Count == 0)) { // No requests found in the queue // Stop all extra application instances foreach (Application application in Database.GetInstance().Applications) { foreach (Tenant tenant in application.Tenants) { int reqScale = 1; int currentScale = FindCurrentScale(application.Id, tenant.Id); int diff = currentScale - reqScale; if (diff == -1) { // Scale Up: Start initial instance of each application tenant if (ScaleUp(application.Id, tenant.Name, 1)) AddScalingHistory(application.Id, tenant.Id, 0, reqScale); } else if (diff > 0) { // Scale Down: Stop extra application instances if(ScaleDown(application.Id, tenant.Name, diff)) AddScalingHistory(application.Id, tenant.Id, 0, reqScale); } } } } else { foreach (ApplicationHttpRequest request in requestQueue) { Application app = Database.GetInstance().Applications.Find(x => x.Id == request.ApplicationId); if (app != null) { Tenant tenant = app.Tenants.Find(y => y.Id.Equals(request.TenantId)); if (tenant != null) { // Check tenant upper scale limit int upperScaleLimit = tenant.UpperScaleLimit; // Check scaling factor for the application tenant // Scaling Factor is the number of requests served by an application tenant instance int scalingFactor = tenant.ScalingFactor; // Check request count for the application tenant int requestCount = requestQueue.Count(x => x.ApplicationId == request.ApplicationId); if (requestCount > scalingFactor) { int reqScale = (int)Math.Ceiling((double)requestCount / scalingFactor); int currentScale = FindCurrentScale(request.ApplicationId, request.TenantId); if (reqScale > currentScale) { if (reqScale > upperScaleLimit) reqScale = upperScaleLimit; // Scale Up: Start new application instances int diff = reqScale - currentScale; if (diff > 0) { if (ScaleUp(request.ApplicationId, tenant.Name, diff)) AddScalingHistory(request, requestCount, reqScale); } } else { // Scale Down: Stop extra application instances int diff = currentScale - reqScale; if (diff > 0) { if (ScaleDown(request.ApplicationId, tenant.Name, diff)) AddScalingHistory(request, requestCount, reqScale); } } } else { int reqScale = 1; int currentScale = FindCurrentScale(request.ApplicationId, request.TenantId); // Scale Down: Stop extra application instances int diff = currentScale - reqScale; if (diff > 0) { if (ScaleDown(request.ApplicationId, tenant.Name, diff)) AddScalingHistory(request, requestCount, reqScale); } } } } } } } private static void AddScalingHistory(ApplicationHttpRequest request, int requestCount, int reqScale) { AddScalingHistory(request.ApplicationId, request.TenantId, requestCount, reqScale); } private static void AddScalingHistory(int applicationId, int tenantId, int requestCount, int reqScale) { ScalingHistoryItem item = new ScalingHistoryItem(); item.Time = DateTime.Now; item.ApplicationId = applicationId; item.TenantId = tenantId; item.RequestCount = requestCount; item.Scale = reqScale; Database.GetInstance().ScalingHistory.Add(item); } private bool ScaleUp(int applicationId, string tenantName, int scale) { Log.Info(this, "Scaling up application: " + applicationId); ApStartApplicationRequest request = new ApStartApplicationRequest(Settings.Credentials); request.ApplicationId = applicationId; request.TenantName = tenantName; request.NumberOfInstances = scale; GetApDashboardService().StartApplication(request); return true; } private bool ScaleDown(int applicationId, string tenantName, int scale) { Log.Info(this, "Scaling down application: " + applicationId); LbGetApplicationInstancesRequest request_ = new LbGetApplicationInstancesRequest(Settings.Credentials); request_.NodeId = -1; request_.ApplicationId = applicationId; LbGetApplicationInstancesResponse response_ = EndPoints.GetLbApplicationGridService().GetApplicationInstances(request_); List<ApplicationInstance> list = response_.ApplicationInstances.OrderBy(x => x.Id).ToList(); if ((list != null) && (list.Count >= scale)) { // Stop idling application instances List<ApplicationInstance> idlingInstances = list.FindAll(x => x.RequestCount == 0); // Keep one instance alive if (idlingInstances.Count == list.Count) idlingInstances.Remove(idlingInstances.Last()); if (idlingInstances.Count > 0) { foreach (ApplicationInstance instance in idlingInstances) { ApStopApplicationInstanceRequest request = new ApStopApplicationInstanceRequest(Settings.Credentials); request.NodeId = instance.NodeId; request.ApplicationId = instance.ApplicationId; request.InstanceId = instance.Id; GetApDashboardService().StopApplicationInstance(request); } return true; } } return false; } private int FindCurrentScale(int applicationId, int tenantId) { LbGetApplicationScaleRequest request = new LbGetApplicationScaleRequest(Settings.Credentials); request.ApplicationId = applicationId; request.TenantId = tenantId; LbGetApplicationScaleResponse response = EndPoints.GetLbApplicationGridService().GetApplicationScale(request); return response.Scale; } public IApDashboardService GetApDashboardService() { try { string serviceUrl = Settings.DashboardServiceURL; Log.Debug(typeof(EndPoints), "Creating IApDashboardService channel: " + serviceUrl); var binding = MonoscapeServiceHost.GetBinding(); var address = new EndpointAddress(serviceUrl); ChannelFactory<IApDashboardService> factory = new ChannelFactory<IApDashboardService>(binding, address); IApDashboardService channel = factory.CreateChannel(); return channel; } catch (Exception e) { MonoscapeException me = new MonoscapeException("Could not connect to the Load Balancer", e); Log.Error(typeof(EndPoints), me); throw me; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using Microsoft.Xunit.Performance; using System; using System.Diagnostics; using Xunit; [assembly: OptimizeForBenchmarks] [assembly: MeasureInstructionsRetired] namespace ConsoleMandel { public static class Program { private const int Pass = 100; private const int Fail = -1; private static bool s_silent = false; private static void DoNothing(int x, int y, int count) { } private static void DrawDot(int x, int y, int count) { if (x == 0) Console.WriteLine(); Console.Write((count < 1000) ? ' ' : '*'); } private static Algorithms.FractalRenderer.Render GetRenderer(Action<int, int, int> draw, int which) { return Algorithms.FractalRenderer.SelectRender(draw, Abort, IsVector(which), IsDouble(which), IsMulti(which), UsesADT(which), !UseIntTypes(which)); } private static bool Abort() { return false; } private static bool UseIntTypes(int num) { return (num & 8) == 0; } private static bool IsVector(int num) { return num > 7; } private static bool IsDouble(int num) { return (num & 4) != 0; } private static bool IsMulti(int num) { return (num & 2) != 0; } private static bool UsesADT(int num) { return (num & 1) != 0; } private static void PrintDescription(int i) { Console.WriteLine("{0}: {1} {2}-Precision {3}Threaded using {4} and {5} int types", i, IsVector(i) ? "Vector" : "Scalar", IsDouble(i) ? "Double" : "Single", IsMulti(i) ? "Multi" : "Single", UsesADT(i) ? "ADT" : "Raw Values", UseIntTypes(i) ? "using" : "not using any"); } private static void PrintUsage() { Console.WriteLine("Usage:\n ConsoleMandel [0-23] -[bench #] where # is the number of iterations."); for (int i = 0; i < 24; i++) { PrintDescription(i); } Console.WriteLine("The numeric argument selects the implementation number;"); Console.WriteLine("If not specified, all are run."); Console.WriteLine("In non-benchmark mode, dump a text view of the Mandelbrot set."); Console.WriteLine("In benchmark mode, a larger set is computed but nothing is dumped."); } private static int Main(string[] args) { try { int which = -1; bool verbose = false; bool bench = false; int iters = 1; int argNum = 0; while (argNum < args.Length) { if (args[argNum].ToUpperInvariant() == "-BENCH") { bench = true; if ((args.Length <= (argNum + 1)) || !Int32.TryParse(args[argNum + 1], out iters)) { iters = 5; } argNum++; } else if (args[argNum].ToUpperInvariant() == "-V") { verbose = true; } else if (args[argNum].ToUpperInvariant() == "-S") { s_silent = true; } else if (!Int32.TryParse(args[argNum], out which)) { PrintUsage(); return Fail; } argNum++; } if (bench) { Bench(iters, which); return Pass; } if (which == -1) { PrintUsage(); return Pass; } if (verbose) { PrintDescription(which); } if (IsVector(which)) { if (verbose) { Console.WriteLine(" Vector Count is {0}", IsDouble(which) ? System.Numerics.Vector<Double>.Count : System.Numerics.Vector<Single>.Count); Console.WriteLine(" {0} Accelerated.", System.Numerics.Vector.IsHardwareAccelerated ? "IS" : "IS NOT"); } } var render = GetRenderer(DrawDot, which); render(-1.5f, .5f, -1f, 1f, 2.0f / 60.0f); return Pass; } catch (System.Exception) { return Fail; } } public static void Bench(int iters, int which) { float XC = -1.248f; float YC = -.0362f; float Range = .001f; float xmin = XC - Range; float xmax = XC + Range; float ymin = YC - Range; float ymax = YC + Range; float step = Range / 1000f; // This will render one million pixels float warm = Range / 100f; // To warm up, just render 10000 pixels :-) Algorithms.FractalRenderer.Render[] renderers = new Algorithms.FractalRenderer.Render[24]; // Warm up each renderer if (!s_silent) { Console.WriteLine("Warming up..."); } Stopwatch timer = new Stopwatch(); int firstRenderer = (which == -1) ? 0 : which; int lastRenderer = (which == -1) ? (renderers.Length - 1) : which; for (int i = firstRenderer; i <= lastRenderer; i++) { renderers[i] = GetRenderer(DoNothing, i); timer.Restart(); renderers[i](xmin, xmax, ymin, ymax, warm); timer.Stop(); if (!s_silent) { Console.WriteLine("{0}{1}{2}{3}{4} Complete [{5} ms]", UseIntTypes(i) ? "IntBV " : "Strict ", IsVector(i) ? "Vector " : "Scalar ", IsDouble(i) ? "Double " : "Single ", UsesADT(i) ? "ADT " : "Raw ", IsMulti(i) ? "Multi " : "Single ", timer.ElapsedMilliseconds); } } if (!s_silent) { Console.WriteLine(" Run Type : Min Max Average Std-Dev"); } for (int i = firstRenderer; i <= lastRenderer; i++) { long totalTime = 0; long min = long.MaxValue; long max = long.MinValue; for (int count = 0; count < iters; count++) { timer.Restart(); renderers[i](xmin, xmax, ymin, ymax, step); timer.Stop(); long time = timer.ElapsedMilliseconds; max = Math.Max(time, max); min = Math.Min(time, min); totalTime += time; } double avg = totalTime / (double)iters; double stdDev = Math.Sqrt(totalTime / (iters - 1.0)) / avg; if (s_silent) { Console.WriteLine("Average: {0,0:0.0}", avg); } else { Console.WriteLine("{0}{1}{2}{3}{4}: {5,8} {6,8} {7,10:0.0} {8,10:P}", UseIntTypes(i) ? "IntBV " : "Strict ", IsVector(i) ? "Vector " : "Scalar ", IsDouble(i) ? "Double " : "Single ", UsesADT(i) ? "ADT " : "Raw ", IsMulti(i) ? "Multi " : "Single ", min, max, avg, stdDev); } } } public static void XBench(int iters, int which) { float XC = -1.248f; float YC = -.0362f; float Range = .001f; float xmin = XC - Range; float xmax = XC + Range; float ymin = YC - Range; float ymax = YC + Range; float step = Range / 100f; Algorithms.FractalRenderer.Render renderer = GetRenderer(DoNothing, which); for (int count = 0; count < iters; count++) { renderer(xmin, xmax, ymin, ymax, step); } } [Benchmark] public static void VectorFloatSinglethreadRawNoInt() { foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { XBench(10, 8); } } } [Benchmark] public static void VectorFloatSinglethreadADTNoInt() { foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { XBench(10, 9); } } } } }
using System; using System.Collections.Generic; using System.Linq; using AutoMapper; using Moq; using NUnit.Framework; using ReMi.Common.Constants; using ReMi.Common.Constants.Subscriptions; using ReMi.Common.Utils.Enums; using ReMi.Common.Utils.Repository; using ReMi.TestUtils.UnitTests; using ReMi.DataAccess.BusinessEntityGateways.Subscriptions; using ReMi.DataAccess.Exceptions; using ReMi.DataAccess.Exceptions.Subscriptions; using ReMi.DataEntities.Auth; using ReMi.DataEntities.Products; using ReMi.DataEntities.Subscriptions; using Account = ReMi.DataEntities.Auth.Account; namespace ReMi.DataAccess.Tests.Subscriptions { public class AccountNotificationGatewayTests : TestClassFor<AccountNotificationGateway> { private Account _account; private AccountNotification _accountNotification; private Mock<IMappingEngine> _mapperMock; private Mock<IRepository<Account>> _accountRepositoryMock; private Mock<IRepository<AccountNotification>> _accountNotificationRepositoryMock; protected override AccountNotificationGateway ConstructSystemUnderTest() { return new AccountNotificationGateway { Mapper = _mapperMock.Object, AccountRepository = _accountRepositoryMock.Object, AccountNotificationRepository = _accountNotificationRepositoryMock.Object }; } protected override void TestInitialize() { _mapperMock = new Mock<IMappingEngine>(); _accountNotificationRepositoryMock = new Mock<IRepository<AccountNotification>>(); _accountRepositoryMock = new Mock<IRepository<Account>>(); var account = new Account { ExternalId = Guid.NewGuid(), AccountId = RandomData.RandomInt(1, 77), AccountProducts = new List<AccountProduct> { new AccountProduct { Product = new Product { Description = "prod1" } } } }; _accountNotification = new AccountNotification { AccountId = account.AccountId, NotificationType = NotificationType.ApiChange, Account = account }; _account = account; _account.AccountNotifications = new List<AccountNotification> {_accountNotification}; _accountRepositoryMock.SetupEntities(new []{_account}); _accountNotificationRepositoryMock.SetupEntities(new[] {_accountNotification}); base.TestInitialize(); } [Test] [ExpectedException(typeof(AccountNotFoundException))] public void GetAccountNotifications_ShouldThrowException_WhenAccountNotFound() { Sut.GetAccountNotifications(Guid.NewGuid()); } [Test] public void GetAccountNotifications_ShouldReturnCorrectResult_WhenAccountIsPresent() { var result = Sut.GetAccountNotifications(_account.ExternalId); Assert.AreEqual(8, result.Count()); Assert.True( result.Any( x => x.Subscribed && x.NotificationName == EnumDescriptionHelper.GetDescription(NotificationType.ApiChange))); Assert.True( result.Any( x => !x.Subscribed && x.NotificationName == EnumDescriptionHelper.GetDescription(NotificationType.ReleaseWindowsSchedule))); Assert.True( result.Any( x => !x.Subscribed && x.NotificationName == EnumDescriptionHelper.GetDescription(NotificationType.Signing))); Assert.True( result.Any( x => !x.Subscribed && x.NotificationName == EnumDescriptionHelper.GetDescription(NotificationType.Closing))); Assert.True( result.Any( x => !x.Subscribed && x.NotificationName == EnumDescriptionHelper.GetDescription(NotificationType.Approvement))); Assert.True( result.Any( x => !x.Subscribed && x.NotificationName == EnumDescriptionHelper.GetDescription(NotificationType.ReleaseTasks))); } [Test] public void GetSubscribers_ShouldCallAutomapper_WhenInvoked() { Sut.GetSubscribers(NotificationType.ApiChange); _mapperMock.Verify( x => x.Map<List<Account>, List<BusinessEntities.Auth.Account>>( It.Is<List<Account>>(l => l.Count == 1 && l[0].AccountId == _account.AccountId))); } [Test] public void GetSubscribers_ShouldCallAutomapper_WhenInvokedWithproductParameter() { Sut.GetSubscribers(NotificationType.ApiChange, new[] {"prod1"}); _mapperMock.Verify( x => x.Map<List<Account>, List<BusinessEntities.Auth.Account>>( It.Is<List<Account>>(l => l.Count == 1 && l[0].AccountId == _account.AccountId))); } [Test] [ExpectedException(typeof(AccountNotFoundException))] public void RemoveNotificationSubscriptions_ShouldThrowException_WhenAccountNotFound() { Sut.RemoveNotificationSubscriptions(Guid.NewGuid(), null); } [Test] [ExpectedException(typeof(NotificationSubscriptionNotFoundException))] public void RemoveNotificationSubscriptions_ShouldThrowException_WhenSubscriptionNotFound() { Sut.RemoveNotificationSubscriptions(_account.ExternalId, new[] {NotificationType.ReleaseWindowsSchedule}); } [Test] public void RemoveNotificationSubscriptions_ShouldCallRepositoryDelete_WhenSubscriptionExists() { Sut.RemoveNotificationSubscriptions(_account.ExternalId, new[] {NotificationType.ApiChange}); _accountNotificationRepositoryMock.Verify( x => x.Delete( It.Is<AccountNotification>( a => a.AccountId == _account.AccountId && a.NotificationType == NotificationType.ApiChange))); } [Test] [ExpectedException(typeof(AccountNotFoundException))] public void AddNotificationSubscriptions_ShouldThrowException_WhenAccountNotFound() { Sut.AddNotificationSubscriptions(Guid.NewGuid(), null); } [Test] [ExpectedException(typeof(DuplicatedNotificationSubscriptionException))] public void AddNotificationSubscriptions_ShouldThrowException_WhenSubscriptionAlreadyExists() { Sut.AddNotificationSubscriptions(_account.ExternalId, new[] { NotificationType.ApiChange }); } [Test] public void AddNotificationSubscriptions_ShouldCallRepositoryInsert_WhenSubscriptionDoesNotExist() { Sut.AddNotificationSubscriptions(_account.ExternalId, new[] {NotificationType.ReleaseWindowsSchedule}); _accountNotificationRepositoryMock.Verify( x => x.Insert( It.Is<AccountNotification>( a => a.AccountId == _account.AccountId && a.NotificationType == NotificationType.ReleaseWindowsSchedule))); } [Test] public void Dispose_ShouldCallDisposeForAllRepos_WhenInvoked() { Sut.Dispose(); _accountNotificationRepositoryMock.Verify(x => x.Dispose()); _accountRepositoryMock.Verify(x => x.Dispose()); } } }
using Signum.Entities.Basics; using Signum.Entities.Files; using Signum.Utilities.Reflection; using System.Collections; using System.IO; namespace Signum.Engine.Files; public static class FilePathEmbeddedLogic { public static void AssertStarted(SchemaBuilder sb) { sb.AssertDefined(ReflectionTools.GetMethodInfo(() => FilePathEmbeddedLogic.Start(null!))); } public static void Start(SchemaBuilder sb) { if (sb.NotDefined(MethodInfo.GetCurrentMethod())) { FileTypeLogic.Start(sb); FilePathEmbedded.CloneFunc = fp => new FilePathEmbedded(fp.FileType, fp.FileName, fp.GetByteArray()); FilePathEmbedded.OnPreSaving += efp => { if(efp.BinaryFile != null) //First time { var task = efp.SaveFileAsync(); Transaction.PreRealCommit += data => { var a = efp; //For debugging task.Wait(); }; } }; FilePathEmbedded.CalculatePrefixPair += CalculatePrefixPair; sb.Schema.SchemaCompleted += Schema_SchemaCompleted; } } public static FilePathEmbedded ToFilePathEmbedded(this FileContent fileContent, FileTypeSymbol fileType) { return new FilePathEmbedded(fileType, fileContent.FileName, fileContent.Bytes); } private static void Schema_SchemaCompleted() { foreach (var table in Schema.Current.Tables.Values) { var fields = table.FindFields(f => f.FieldType == typeof(FilePathEmbedded)).ToList(); if (fields.Any()) { foreach (var field in fields) { giAddBinding.GetInvoker(table.Type)(field.Route); } } giOnSaved.GetInvoker(table.Type)(fields.Select(a => a.Route).ToList()); } } static GenericInvoker<Action<List<PropertyRoute>>> giOnSaved = new(prs => OnSaved<Entity>(prs)); static void OnSaved<T>(List<PropertyRoute> array) where T : Entity { var updaters = array.Select(pr => GetUpdater<T>(pr)).ToList(); Schema.Current.EntityEvents<T>().Saved += (e, args)=> { foreach (var update in updaters) { update(e); } }; } static Action<T> GetUpdater<T>(PropertyRoute route) where T : Entity { string propertyPath = route.PropertyString(); string rootType = TypeLogic.GetCleanName(route.RootType); var mlistRoute = route.GetMListItemsRoute(); if (mlistRoute == null) { var exp = route.GetLambdaExpression<T, FilePathEmbedded?>(true); var func = exp.Compile(); return (e) => { var fpe = func(e); if (fpe != null) { fpe.EntityId = e.Id; fpe.MListRowId = null; fpe.PropertyRoute = route.PropertyString(); fpe.RootType = rootType; } }; } else { var mlistExpr = mlistRoute.Parent!.GetLambdaExpression<T, IMListPrivate>(true); var mlistFunc = mlistExpr.Compile(); var fileExpr = route.GetLambdaExpression<ModifiableEntity, FilePathEmbedded>(true, mlistRoute); var fileFunc = fileExpr.Compile(); return (e) => { var mlist = mlistFunc(e); if(mlist != null) { var list = (IList)mlist; for (int i = 0; i < list.Count; i++) { var mod = (ModifiableEntity)list[i]!; var fpe = fileFunc(mod); if(fpe != null) { fpe.EntityId = e.Id; fpe.MListRowId = mlist.GetRowId(i); fpe.PropertyRoute = route.PropertyString(); fpe.RootType = rootType; } } } }; } } static GenericInvoker<Action<PropertyRoute>> giAddBinding = new(pr => AddBinding<Entity>(pr)); static void AddBinding<T>(PropertyRoute route) where T : Entity { var entityEvents = Schema.Current.EntityEvents<T>(); entityEvents.RegisterBinding<PrimaryKey>(route.Add(nameof(FilePathEmbedded.EntityId)), () => true, (t, rowId) => t.Id, (t, rowId, retriever) => t.Id); entityEvents.RegisterBinding<PrimaryKey?>(route.Add(nameof(FilePathEmbedded.MListRowId)), () => true, (t, rowId) => rowId, (t, rowId, retriever) => rowId); var routeType = TypeLogic.GetCleanName(route.RootType); entityEvents.RegisterBinding<string>(route.Add(nameof(FilePathEmbedded.RootType)), () => true, (t, rowId) => routeType, (t, rowId, retriever) => routeType); var propertyRoute = route.PropertyString(); entityEvents.RegisterBinding<string>(route.Add(nameof(FilePathEmbedded.PropertyRoute)), () => true, (t, rowId) => propertyRoute, (t, rowId, retriever) => propertyRoute); } static PrefixPair CalculatePrefixPair(this FilePathEmbedded efp) { using (new EntityCache(EntityCacheType.ForceNew)) return efp.FileType.GetAlgorithm().GetPrefixPair(efp); } public static byte[] GetByteArray(this FilePathEmbedded efp) { return efp.BinaryFile ?? efp.FileType.GetAlgorithm().ReadAllBytes(efp); } public static Stream OpenRead(this FilePathEmbedded efp) { return efp.FileType.GetAlgorithm().OpenRead(efp); } public static FilePathEmbedded SaveFile(this FilePathEmbedded efp) { var alg = efp.FileType.GetAlgorithm(); alg.ValidateFile(efp); alg.SaveFile(efp); return efp; } public static Task SaveFileAsync(this FilePathEmbedded efp) { var alg = efp.FileType.GetAlgorithm(); alg.ValidateFile(efp); return alg.SaveFileAsync(efp); } public static void DeleteFileOnCommit(this FilePathEmbedded efp) { Transaction.PostRealCommit += dic => { efp.FileType.GetAlgorithm().DeleteFiles(new List<IFilePath> { efp }); }; } }
using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Text.RegularExpressions; using System.Windows.Forms; using KojtoCAD.Utilities; #if !bcad using Autodesk.AutoCAD.PlottingServices; using Application = Autodesk.AutoCAD.ApplicationServices.Application; using Exception = Autodesk.AutoCAD.Runtime.Exception; #else using Application = Bricscad.ApplicationServices.Application; using Bricscad.PlottingServices; using Exception = Teigha.Runtime.Exception; #endif namespace KojtoCAD.Plotter { public partial class PlotterForm : Form { #region fields and properties // current layout publish info private PublishInfo _curPubInfo = null; // unchecked layout publish info private List<PublishInfo> _removed = new List<PublishInfo>(); private bool _publish = false; public bool Publish { set { _publish = value; } get { return _publish; } } public string SavePath { get { return textBoxSavePath.Text; } } public string SourcePath { get { return textBoxSavePath.Text; } } public bool WillPlotDWF { get { return checkBoxDWF.Checked; } } public bool WillPlotPDF { get { return checkBoxPDF.Checked; } } public bool WillReadDWG { get { return checkBoxDWG.Checked; } } public bool WillReadDXF { get { return checkBoxDXF.Checked; } } public bool PlotAllDWGsInSource { get { return checkBoxPlotAllDWGs.Checked; } } public bool PlotMultiSheet { get { return checkBoxMultiSheet.Checked; } } public bool Print { get { return checkBoxPrint.Checked; } } public string PlotStyleTable { get { return cmbPlotStyleTables.Text; } } public string DevicePlot { get { return cmbPlotDevicePrinter.Text; } } public string DevicePDF { get { return cmbPlotDevicePDF.Text; } } public string DeviceDWF { get { return cmbPlotDeviceDWF.Text; } } public string PaperSize { get { return cmbPaperSizePrint.Text; } } public bool IgnoreModelSpace { get { return checkBoxIgnoreModelSpace.Checked; } } public static Regex CanonicalMediaNamesFilter = new Regex(@"\d+\.\d+"); private bool _authorizedCheckDwg; private bool _authorizedCheckLayout; private bool _checkedChangedWithoutAuthorizationDwg; private bool _checkedChangedWithoutAuthorizationLayout; private bool _layoutWasChackedManualy; #endregion #region constructors and onLoad public PlotterForm() { InitializeComponent(); } private void PlotterForm_Load(object sender, EventArgs e) { #region load default settings try { cmbPlotDevicePrinter.Text = Properties.Settings.Default.plotDevicePrinter; cmbPlotDeviceDWF.Text = Properties.Settings.Default.plotDeviceDwf; cmbPlotDevicePDF.Text = Properties.Settings.Default.plotDevicePdf; cmbPaperSizePrint.Text = Properties.Settings.Default.plotPaperSizePrint; cmbPaperSizePDF.Text = Properties.Settings.Default.plotPaperSizePdf; cmbPaperSizeDWF.Text = Properties.Settings.Default.plotPaperSizeDwf; cmbPlotStyleTables.Text = Properties.Settings.Default.plotStyleTable; checkBoxDWG.Checked = Properties.Settings.Default.plotReadDwg; checkBoxDXF.Checked = Properties.Settings.Default.plotReadDxf; checkBoxPrint.Checked = Properties.Settings.Default.plotMakePrint; checkBoxDWF.Checked = Properties.Settings.Default.plotMakeDwf; checkBoxPDF.Checked = Properties.Settings.Default.plotMakePdf; checkBoxPlotAllDWGs.Checked = Properties.Settings.Default.plotPlotAllDWGs; checkBoxIgnoreModelSpace.Checked = Properties.Settings.Default.plotIgnoreModelSpace; checkBoxMultiSheet.Checked = Properties.Settings.Default.plotMultiSheet; textBoxSourcePath.Text = Properties.Settings.Default.plotSourcePath; textBoxSavePath.Text = Properties.Settings.Default.plotSavePath; checkBoxTurnOnViewPorts.Checked = Properties.Settings.Default.plotTurnOnViewPorts; checkBoxCenterPlot.Checked = Properties.Settings.Default.plotCenterPlot; textBoxDynamicBlockFrameName.Text = Properties.Settings.Default.plotDrawingFrameName; textBoxFrameLayout.Text = Properties.Settings.Default.plotDrawingFrameLayer; Properties.Settings.Default.Save(); if (!Directory.Exists(textBoxSourcePath.Text)) { textBoxSourcePath.Text = "Select source directory."; } if (!Directory.Exists(textBoxSavePath.Text)) { textBoxSavePath.Text = "Select destination directory."; } } catch (Exception ex) { MessageBox.Show(ex.Message + "\n" + ex.Source); //buttonPlot.Enabled = false; } buttonPlot.Enabled = true; #endregion #region load devices, paper sizes LoadPlotDevicePrinter(); LoadPlotDevicePDF(); LoadPlotDeviceDWF(); LoadPlotStylesTables(); #endregion } #endregion #region checkboxes actions private void checkBoxDWG_CheckedChanged(object sender, EventArgs e) { if (this.checkBoxDWG.Checked) { foreach (PublishInfo info in KojtoCAD.Plotter.Plotter.PubInfos) { if (Same(Path.GetExtension(info.DwgName), ".DWG")) { // Make sure not to add if its skipped if (_removed.Contains(info)) { _removed.Remove(info); } this._checkedChangedWithoutAuthorizationDwg = true; DwgNameList.Items.Add(info, !info.SkipDwg); this._checkedChangedWithoutAuthorizationDwg = false; } } } else { foreach (object obj in DwgNameList.Items) { PublishInfo info = (PublishInfo)obj; if (Same(Path.GetExtension(info.DwgName), ".DWG")) { _removed.Add(info); } } foreach (PublishInfo info in _removed) { DwgNameList.Items.Remove(info); } } if (DwgNameList.Items.Count > 0) { DwgNameList.SelectedIndex = 0; } } private void checkBoxDXF_CheckedChanged(object sender, EventArgs e) { if (this.checkBoxDXF.Checked) { foreach (PublishInfo info in KojtoCAD.Plotter.Plotter.PubInfos) { if (Same(Path.GetExtension(info.DwgName), ".DXF")) { if (_removed.Contains(info)) { _removed.Remove(info); } this._checkedChangedWithoutAuthorizationDwg = true; DwgNameList.Items.Add(info, !info.SkipDwg); this._checkedChangedWithoutAuthorizationDwg = false; } } } else { foreach (object obj in DwgNameList.Items) { PublishInfo info = (PublishInfo)obj; if (Same(Path.GetExtension(info.DwgName), ".DXF")) { _removed.Add(info); } } foreach (PublishInfo info in _removed) { DwgNameList.Items.Remove(info); } } if (DwgNameList.Items.Count > 0) { DwgNameList.SelectedIndex = 0; } } #endregion #region textBox actions private void textBoxSourcePath_TextChanged(object sender, EventArgs e) { if (!Directory.Exists(textBoxSourcePath.Text)) { DwgNameList.ClearSelected(); LayoutNameList.ClearSelected(); textBoxSourcePath.Focus(); return; } if ( !KojtoCAD.Plotter.Plotter.BuildList( textBoxSourcePath.Text, checkBoxDWG.Checked, checkBoxDXF.Checked, checkBoxPlotAllDWGs.Checked)) { //throw new Exception("The plotter failed to build the drawing list. Maybe you have to select different source directory."); return; } // Refreshing the list boxes the ugly way if (this.checkBoxDWG.Checked) { this.checkBoxDWG.Checked = false; this.checkBoxDWG.Checked = true; } if (this.checkBoxDXF.Checked) { this.checkBoxDXF.Checked = false; this.checkBoxDXF.Checked = true; } } #endregion #region comboBox action private void cmbPlotDevice_SelectedIndexChanged(object sender, EventArgs e) { Properties.Settings.Default.plotDevicePrinter = cmbPlotDevicePrinter.Text; UpdatePaperListbox(cmbPlotDevicePrinter, cmbPaperSizePrint, cmbPlotDevicePrinter.Text); } private void cmbPlotDevicePDF_SelectedIndexChanged(object sender, EventArgs e) { Properties.Settings.Default.plotDevicePdf = cmbPlotDevicePDF.Text; UpdatePaperListbox(cmbPlotDevicePDF, cmbPaperSizePDF, cmbPlotDevicePDF.Text); } private void cmbPlotDeviceDWF_SelectedIndexChanged(object sender, EventArgs e) { Properties.Settings.Default.plotDeviceDwf = cmbPlotDeviceDWF.Text; UpdatePaperListbox(cmbPlotDeviceDWF, cmbPaperSizeDWF, cmbPlotDeviceDWF.Text); } public void UpdatePaperListbox(ComboBox aCmbPlotDevice, ComboBox aCmbPaperSize, string aDeviceName) { aCmbPaperSize.Items.Clear(); if (aCmbPlotDevice.Text == "None" || string.IsNullOrEmpty(aCmbPlotDevice.Text)) { return; } try { PlotConfig pc = PlotConfigManager.SetCurrentConfig(aDeviceName); if (pc.IsPlotToFile || pc.PlotToFileCapability == PlotToFileCapability.MustPlotToFile || pc.PlotToFileCapability == PlotToFileCapability.PlotToFileAllowed) { aCmbPaperSize.Items.Add("Auto"); } foreach (string str in pc.CanonicalMediaNames) { if (CanonicalMediaNamesFilter.IsMatch(str)) { #if !bcad aCmbPaperSize.Items.Add(pc.GetLocalMediaName(str)); #else aCmbPaperSize.Items.Add(str); #endif } } aCmbPaperSize.Text = aCmbPaperSize.Items[0].ToString(); } catch (Exception Ex) { MessageBox.Show(Ex.Message + "\n" + Ex.Source + "\n" + Ex.StackTrace); } } public void LoadPlotDevicePrinter() { bool deviceSelected = false; // Plot devices var deviceNames = new UtilityClass().PlotDevicesNames(); foreach (var deviceName in deviceNames) { cmbPlotDevicePrinter.Items.Add(deviceName); if (string.Compare(deviceName, Properties.Settings.Default.plotDevicePrinter) == 0) { deviceSelected = true; } } if (deviceSelected) { cmbPlotDevicePrinter.Text = Properties.Settings.Default.plotDevicePrinter; UpdatePaperListbox( cmbPlotDevicePrinter, cmbPaperSizePrint, Properties.Settings.Default.plotDevicePrinter); } else { cmbPlotDevicePrinter.Text = cmbPlotDevicePrinter.Items[0].ToString(); UpdatePaperListbox(cmbPlotDevicePrinter, cmbPaperSizePrint, cmbPlotDevicePrinter.Items[0].ToString()); } cmbPaperSizePrint.Items.Add("Auto"); } public void LoadPlotDevicePDF() { bool deviceSelected = false; // Plot devices var deviceNames = new UtilityClass().PlotDevicesNames(); foreach (var deviceName in deviceNames) { cmbPlotDevicePDF.Items.Add(deviceName); if (string.Compare(deviceName, Properties.Settings.Default.plotDevicePdf) == 0) { deviceSelected = true; } } if (deviceSelected) { cmbPlotDevicePDF.Text = Properties.Settings.Default.plotDevicePdf; UpdatePaperListbox(cmbPlotDevicePDF, cmbPaperSizePDF, Properties.Settings.Default.plotDevicePdf); } else { cmbPlotDevicePDF.Text = cmbPlotDevicePDF.Items[0].ToString(); UpdatePaperListbox(cmbPlotDevicePDF, cmbPaperSizePDF, cmbPlotDevicePDF.Items[0].ToString()); } } public void LoadPlotDeviceDWF() { bool deviceSelected = false; // Plot devices var deviceNames = new UtilityClass().PlotDevicesNames(); foreach (var deviceName in deviceNames) { cmbPlotDevicePDF.Items.Add(deviceName); if (string.Compare(deviceName, Properties.Settings.Default.plotDevicePdf) == 0) { deviceSelected = true; } } if (deviceSelected) { cmbPlotDeviceDWF.Text = Properties.Settings.Default.plotDeviceDwf; UpdatePaperListbox(cmbPlotDeviceDWF, cmbPaperSizeDWF, Properties.Settings.Default.plotDeviceDwf); } else { cmbPlotDeviceDWF.Text = cmbPlotDeviceDWF.Items[0].ToString(); UpdatePaperListbox(cmbPlotDeviceDWF, cmbPaperSizeDWF, cmbPlotDeviceDWF.Items[0].ToString()); } } public void LoadPlotStylesTables() { bool deviceSelected = false; // Plot style tables var ctbNames = new UtilityClass().PltoStylesNames(); foreach (string str in ctbNames) { string[] tempStrArray = str.Split('\\'); cmbPlotStyleTables.Items.Add(tempStrArray[tempStrArray.Length - 1]); if (string.Compare(tempStrArray[tempStrArray.Length - 1], Properties.Settings.Default.plotStyleTable) == 0) { deviceSelected = true; } } cmbPlotStyleTables.Text = deviceSelected ? Properties.Settings.Default.plotStyleTable : cmbPlotStyleTables.Items[0].ToString(); } #endregion #region buttons actions private void buttonSelect_Unselect_Click(object sender, EventArgs e) { bool allAreChecked = DwgNameList.CheckedItems.Count == DwgNameList.Items.Count; int count = DwgNameList.Items.Count; for (int i = 0; i < count; i++) { PublishInfo info = (PublishInfo)DwgNameList.Items[i]; _checkedChangedWithoutAuthorizationDwg = true; DwgNameList.SetItemChecked(DwgNameList.Items.IndexOf(info), !allAreChecked); _checkedChangedWithoutAuthorizationDwg = false; } if (_curPubInfo != null) { int nCount = LayoutNameList.Items.Count; for (int i = 0; i < nCount; i++) { LayoutInfo info = (LayoutInfo)LayoutNameList.Items[i]; _checkedChangedWithoutAuthorizationLayout = true; LayoutNameList.SetItemChecked(LayoutNameList.Items.IndexOf(info), !allAreChecked); _checkedChangedWithoutAuthorizationLayout = false; } } } private void buttonSelect_UnselectLayouts_Click(object sender, EventArgs e) { bool allAreChecked = LayoutNameList.CheckedItems.Count == LayoutNameList.Items.Count; int nCount = LayoutNameList.Items.Count; for (int i = 0; i < nCount; i++) { LayoutInfo info = (LayoutInfo)LayoutNameList.Items[i]; _checkedChangedWithoutAuthorizationLayout = true; LayoutNameList.SetItemChecked(LayoutNameList.Items.IndexOf(info), !allAreChecked); _checkedChangedWithoutAuthorizationLayout = false; } } private void buttonPlot_Click(object sender, EventArgs e) { #region check textBoxSourcePath // Check for all the inputs... if (!Directory.Exists(this.textBoxSourcePath.Text)) { // Show error message and return... Application.ShowAlertDialog("Specify the DWG/DXF source directory."); this.textBoxSourcePath.Focus(); return; } #endregion #region check textBoxSavePath // Setting the focus based on the check box selection (if not set) if (checkBoxDWF.Checked || checkBoxPDF.Checked) { if (textBoxSavePath.Text.Length == 0) { // Show error message and return... Application.ShowAlertDialog( "Please specify destination directory."); textBoxSavePath.Focus(); return; } if (!Directory.Exists(this.textBoxSavePath.Text)) { // Show error message and return... Application.ShowAlertDialog( "Specified directory " + this.textBoxSavePath.Text + " not present."); textBoxSavePath.Focus(); return; } } #endregion #region check PDF device if (checkBoxPDF.Checked) { if (cmbPlotDevicePDF.Text.Length < 4) { cmbPlotDevicePDF.Text = "Select PDF device!"; cmbPlotDevicePDF.Focus(); } } #endregion #region check DWF device if (checkBoxPDF.Checked) { if (cmbPlotDevicePDF.Text.Length < 4) { cmbPlotDeviceDWF.Text = "Select DWF device!"; cmbPlotDeviceDWF.Focus(); } } #endregion if (textBoxDynamicBlockFrameName.Text.Length < 1) { MessageBox.Show( "Provide dynamic block frame name.", "No dynamic block frame name", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } if (checkBoxPrint.Checked) { if ( MessageBox.Show( "Are you shure you want to REALLY PRINT all these DWGs ? If otherwise click NO, unckeck 'Print' option and try again.", "Real print confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; } } if (checkBoxMultiSheet.Checked && (cmbPaperSizePDF.Text.Equals("Auto", StringComparison.CurrentCultureIgnoreCase) || cmbPaperSizeDWF.Text.Equals("Auto", StringComparison.CurrentCultureIgnoreCase))) { DialogResult warning = MessageBox.Show( "Multi sheet PDF with different frame format is not allowed. If your drawings have different frames press Cancel and separate them by frame.", "KojtoCADPlotter", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning); if (warning == DialogResult.Cancel) { cmbPlotDevicePDF.Focus(); return; } //return; } _publish = true; this.DialogResult = DialogResult.OK; // Save the current inputs to the Winforms properties SaveSettings(); } private void buttonExit_Click(object sender, EventArgs e) { SaveSettings(); Publish = false; Close(); } private void buttonSourcePath_Click(object sender, EventArgs e) { // Changed from FolderBrowserDialog to OpenFileDialog, because // if you manage to click on drive letter C: for example (by mistake) and // you have chosen to 'plot all drawings in the source directory' // the program starts traversing the whole drive and freezes! // To avoid this we ask the user to chose a file // and then we get only the current drawing folder and traverse it. /* //folderBrowserDialog = new FolderBrowserDialog(); openFileDialog = new OpenFileDialog(); if (openFileDialog.ShowDialog() == DialogResult.OK) { textBoxSourcePath.Text = openFileDialog.FileName.Remove(openFileDialog.FileName.LastIndexOf('\\')); } if (!Directory.Exists(textBoxSourcePath.Text)) { // Show error message and return... textBoxSourcePath.Focus(); return; } * */ folderBrowserDialog = new FolderBrowserDialog(); folderBrowserDialog.SelectedPath = Properties.Settings.Default.plotSourcePath; if (folderBrowserDialog.ShowDialog() == DialogResult.OK) { if (folderBrowserDialog.SelectedPath.Length == 3) { textBoxSourcePath.Text = "You cannot select a whole drive."; textBoxSourcePath.Focus(); return; } textBoxSourcePath.Text = folderBrowserDialog.SelectedPath; //textBoxSavePath.Text = folderBrowserDialog.SelectedPath; textBoxSavePath.Text = textBoxSourcePath.Text; } } private void buttonSavePath_Click(object sender, EventArgs e) { folderBrowserDialog = new FolderBrowserDialog(); if (folderBrowserDialog.ShowDialog() == DialogResult.OK) { textBoxSavePath.Text = folderBrowserDialog.SelectedPath; } } private void cmbPlotStyleTables_SelectedIndexChanged(object sender, EventArgs e) { Properties.Settings.Default.plotStyleTable = cmbPlotStyleTables.Text; } private void cmbPaperSize_SelectedIndexChanged(object sender, EventArgs e) { Properties.Settings.Default.plotPaperSizePrint = cmbPaperSizePrint.Text; } #endregion #region checkList actions private void DwgNameList_SelectedIndexChanged(object sender, EventArgs e) { LayoutNameList.Items.Clear(); if (DwgNameList.SelectedIndex < 0) { _curPubInfo = null; return; } _curPubInfo = (PublishInfo)DwgNameList.Items[DwgNameList.SelectedIndex]; foreach (LayoutInfo layoutInfo in _curPubInfo.LayoutInfos) { _checkedChangedWithoutAuthorizationLayout = true; LayoutNameList.Items.Add(layoutInfo, layoutInfo.Publish); _checkedChangedWithoutAuthorizationLayout = false; } } private void DwgNameList_ItemCheck(object sender, ItemCheckEventArgs e) { if (e.Index < 0) { return; } if (!this._checkedChangedWithoutAuthorizationDwg) { if (!this._authorizedCheckDwg) { e.NewValue = e.CurrentValue; //check state change was not through authorized actions return; } } PublishInfo info = (PublishInfo)DwgNameList.Items[e.Index]; if (e.NewValue == CheckState.Checked) { info.SkipDwg = false; if (info != null) { foreach (LayoutInfo layoutInfo in info.LayoutInfos) { if (!_layoutWasChackedManualy) { layoutInfo.Publish = true; } } } //LayoutNameList.Enabled = true; } else { info.SkipDwg = true; //update the layouts.... if (info != null) { foreach (LayoutInfo layoutInfo in info.LayoutInfos) { layoutInfo.Publish = false; } } //LayoutNameList.Enabled = false; } } private void LayoutNames_ItemCheck(object sender, ItemCheckEventArgs e) { if (e.Index < 0) { return; } if (this._curPubInfo == null) { return; } if (!_checkedChangedWithoutAuthorizationLayout) { if (!this._authorizedCheckLayout) { e.NewValue = e.CurrentValue; //check state change was not through authorized actions return; } } var layoutInfo = (LayoutInfo)this.LayoutNameList.Items[e.Index]; layoutInfo.Publish = e.NewValue == CheckState.Checked; var checkedItemsCount = this.LayoutNameList.CheckedItems.Count + (e.NewValue == CheckState.Checked ? 1 : -1); if (checkedItemsCount < LayoutNameList.Items.Count) { _layoutWasChackedManualy = true; } this._checkedChangedWithoutAuthorizationDwg = true; this.DwgNameList.SetItemChecked(this.DwgNameList.SelectedIndex, checkedItemsCount != 0); this._checkedChangedWithoutAuthorizationDwg = false; _layoutWasChackedManualy = false; } #endregion #region settings functions public void SaveSettings() { try { Properties.Settings.Default.plotDevicePrinter = cmbPlotDevicePrinter.Text; Properties.Settings.Default.plotDevicePdf = cmbPlotDevicePDF.Text; Properties.Settings.Default.plotDeviceDwf = cmbPlotDeviceDWF.Text; Properties.Settings.Default.plotPaperSizePrint = cmbPaperSizePrint.Text; Properties.Settings.Default.plotPaperSizePdf = cmbPaperSizePDF.Text; Properties.Settings.Default.plotPaperSizeDwf = cmbPaperSizeDWF.Text; Properties.Settings.Default.plotStyleTable = cmbPlotStyleTables.Text; Properties.Settings.Default.plotReadDwg = checkBoxDWG.Checked; Properties.Settings.Default.plotReadDxf = checkBoxDXF.Checked; Properties.Settings.Default.plotMakePrint = checkBoxPrint.Checked; Properties.Settings.Default.plotMakeDwf = checkBoxDWF.Checked; Properties.Settings.Default.plotMakePdf = checkBoxPDF.Checked; Properties.Settings.Default.plotSourcePath = textBoxSourcePath.Text; Properties.Settings.Default.plotSavePath = textBoxSavePath.Text; Properties.Settings.Default.plotPlotAllDWGs = checkBoxPlotAllDWGs.Checked; Properties.Settings.Default.plotIgnoreModelSpace = checkBoxIgnoreModelSpace.Checked; Properties.Settings.Default.plotMultiSheet = checkBoxMultiSheet.Checked; Properties.Settings.Default.plotTurnOnViewPorts = checkBoxTurnOnViewPorts.Checked; Properties.Settings.Default.plotCenterPlot = checkBoxCenterPlot.Checked; Properties.Settings.Default.plotDrawingFrameName = textBoxDynamicBlockFrameName.Text; Properties.Settings.Default.plotDrawingFrameLayer = textBoxFrameLayout.Text; Properties.Settings.Default.plotTransparency = checkBoxPlotTransparency.Checked; Properties.Settings.Default.Save(); } catch { throw new System.Exception("Failed to save plot settings."); } } #endregion #region string functions internal static bool Same(string first, string second) { return (string.Compare(first, second, true) == 0); } #endregion #region KeyPressFunctions private void PlotterForm_KeyPress(object sender, KeyPressEventArgs e) { // The user pressed ESC - then close the form. if (e.KeyChar == (char)27) { Close(); } } private void DwgNameList_MouseDown(object sender, MouseEventArgs e) { var cursorPosition = new Point(e.X, e.Y); for (int i = 0; i < this.DwgNameList.Items.Count; i++) { Rectangle rec = this.DwgNameList.GetItemRectangle(i); rec.Width = 16; //checkbox itself has a default width of about 16 pixels if (!rec.Contains(cursorPosition)) { continue; } this._authorizedCheckDwg = true; bool newValue = !this.DwgNameList.GetItemChecked(i); this.DwgNameList.SetItemChecked(i, newValue); //check this._authorizedCheckDwg = false; return; } } private void LayoutNameList_MouseDown(object sender, MouseEventArgs e) { var cursorPosition = new Point(e.X, e.Y); for (int i = 0; i < this.LayoutNameList.Items.Count; i++) { Rectangle rec = this.LayoutNameList.GetItemRectangle(i); rec.Width = 16; //checkbox itself has a default width of about 16 pixels if (!rec.Contains(cursorPosition)) { continue; } this._authorizedCheckLayout = true; bool newValue = !this.LayoutNameList.GetItemChecked(i); this.LayoutNameList.SetItemChecked(i, newValue); //check this._authorizedCheckLayout = false; return; } } #endregion } }
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Globalization; using System.Threading; using NUnit.Framework; namespace ZXing.Client.Result.Test { /// <summary> /// Tests <see cref="CalendarParsedResult" />. /// /// <author>Sean Owen</author> /// </summary> [TestFixture] public sealed class CalendarParsedResultTestCase { private const double EPSILON = 1.0E-10; private const string DATE_TIME_FORMAT = "yyyyMMdd'T'HHmmss'Z'"; [SetUp] public void SetUp() { // Locale.setDefault(Locale.ENGLISH); // TimeZone.setDefault(TimeZone.getTimeZone("GMT")); Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); } [Test] public void testStartEnd() { doTest( "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\n" + "DTSTART:20080504T123456Z\r\n" + "DTEND:20080505T234555Z\r\n" + "END:VEVENT\r\nEND:VCALENDAR", null, null, null, "20080504T123456Z", "20080505T234555Z"); } [Test] public void testNoVCalendar() { doTest( "BEGIN:VEVENT\r\n" + "DTSTART:20080504T123456Z\r\n" + "DTEND:20080505T234555Z\r\n" + "END:VEVENT", null, null, null, "20080504T123456Z", "20080505T234555Z"); } [Test] public void testStart() { doTest( "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\n" + "DTSTART:20080504T123456Z\r\n" + "END:VEVENT\r\nEND:VCALENDAR", null, null, null, "20080504T123456Z", null); } [Test] public void testDuration() { doTest( "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\n" + "DTSTART:20080504T123456Z\r\n" + "DURATION:P1D\r\n" + "END:VEVENT\r\nEND:VCALENDAR", null, null, null, "20080504T123456Z", "20080505T123456Z"); doTest( "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\n" + "DTSTART:20080504T123456Z\r\n" + "DURATION:P1DT2H3M4S\r\n" + "END:VEVENT\r\nEND:VCALENDAR", null, null, null, "20080504T123456Z", "20080505T143800Z"); } [Test] public void testSummary() { doTest( "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\n" + "SUMMARY:foo\r\n" + "DTSTART:20080504T123456Z\r\n" + "END:VEVENT\r\nEND:VCALENDAR", null, "foo", null, "20080504T123456Z", null); } [Test] public void testLocation() { doTest( "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\n" + "LOCATION:Miami\r\n" + "DTSTART:20080504T123456Z\r\n" + "END:VEVENT\r\nEND:VCALENDAR", null, null, "Miami", "20080504T123456Z", null); } [Test] public void testDescription() { doTest( "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\n" + "DTSTART:20080504T123456Z\r\n" + "DESCRIPTION:This is a test\r\n" + "END:VEVENT\r\nEND:VCALENDAR", "This is a test", null, null, "20080504T123456Z", null); doTest( "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\n" + "DTSTART:20080504T123456Z\r\n" + "DESCRIPTION:This is a test\r\n\t with a continuation\r\n" + "END:VEVENT\r\nEND:VCALENDAR", "This is a test with a continuation", null, null, "20080504T123456Z", null); } [Test] public void testGeo() { doTest( "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\n" + "DTSTART:20080504T123456Z\r\n" + "GEO:-12.345;-45.678\r\n" + "END:VEVENT\r\nEND:VCALENDAR", null, null, null, "20080504T123456Z", null, null, null, -12.345, -45.678); } [Test] public void testBadGeo() { // Not parsed as VEVENT var fakeResult = new ZXing.Result("BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\n" + "GEO:-12.345\r\n" + "END:VEVENT\r\nEND:VCALENDAR", null, null, BarcodeFormat.QR_CODE); var result = ResultParser.parseResult(fakeResult); Assert.AreEqual(ParsedResultType.URI, result.Type); } [Test] public void testOrganizer() { doTest( "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\n" + "DTSTART:20080504T123456Z\r\n" + "ORGANIZER:mailto:bob@example.org\r\n" + "END:VEVENT\r\nEND:VCALENDAR", null, null, null, "20080504T123456Z", null, "bob@example.org", null, Double.NaN, Double.NaN); } [Test] public void testAttendees() { doTest( "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\n" + "DTSTART:20080504T123456Z\r\n" + "ATTENDEE:mailto:bob@example.org\r\n" + "ATTENDEE:mailto:alice@example.org\r\n" + "END:VEVENT\r\nEND:VCALENDAR", null, null, null, "20080504T123456Z", null, null, new String[] { "bob@example.org", "alice@example.org" }, Double.NaN, Double.NaN); } [Test] public void testVEventEscapes() { doTest("BEGIN:VEVENT\n" + "CREATED:20111109T110351Z\n" + "LAST-MODIFIED:20111109T170034Z\n" + "DTSTAMP:20111109T170034Z\n" + "UID:0f6d14ef-6cb7-4484-9080-61447ccdf9c2\n" + "SUMMARY:Summary line\n" + "CATEGORIES:Private\n" + "DTSTART;TZID=Europe/Vienna:20111110T110000\n" + "DTEND;TZID=Europe/Vienna:20111110T120000\n" + "LOCATION:Location\\, with\\, escaped\\, commas\n" + "DESCRIPTION:Meeting with a friend\\nlook at homepage first\\n\\n\n" + " \\n\n" + "SEQUENCE:1\n" + "X-MOZ-GENERATION:1\n" + "END:VEVENT", "Meeting with a friend\nlook at homepage first\n\n\n \n", "Summary line", "Location, with, escaped, commas", "20111110T110000Z", "20111110T120000Z"); } [Test] public void testAllDayValueDate() { doTest("BEGIN:VEVENT\n" + "DTSTART;VALUE=DATE:20111110\n" + "DTEND;VALUE=DATE:20111110\n" + "END:VEVENT", null, null, null, "20111110T000000Z", "20111110T000000Z"); } private static void doTest(String contents, String description, String summary, String location, String startString, String endString) { doTest(contents, description, summary, location, startString, endString, null, null, Double.NaN, Double.NaN); } private static void doTest(String contents, String description, String summary, String location, String startString, String endString, String organizer, String[] attendees, double latitude, double longitude) { var fakeResult = new ZXing.Result(contents, null, null, BarcodeFormat.QR_CODE); var result = ResultParser.parseResult(fakeResult); Assert.AreEqual(ParsedResultType.CALENDAR, result.Type); var calResult = (CalendarParsedResult)result; Assert.AreEqual(description, calResult.Description); Assert.AreEqual(summary, calResult.Summary); Assert.AreEqual(location, calResult.Location); Assert.AreEqual(startString, calResult.Start.ToString(DATE_TIME_FORMAT)); Assert.AreEqual(endString, calResult.End == null ? null : calResult.End.Value.ToString(DATE_TIME_FORMAT)); Assert.AreEqual(organizer, calResult.Organizer); Assert.IsTrue(AddressBookParsedResultTestCase.AreEqual(attendees, calResult.Attendees)); assertEqualOrNaN(latitude, calResult.Latitude); assertEqualOrNaN(longitude, calResult.Longitude); } private static void assertEqualOrNaN(double expected, double actual) { if (Double.IsNaN(expected)) { Assert.IsTrue(Double.IsNaN(actual)); } else { Assert.AreEqual(expected, actual, EPSILON); } } } }
using UnityEngine; using System; using System.Collections; public enum VertexAnimationDirection { Forward, Backward, ForwardBackward, BackwardForward, } /// <summary> /// Interpolates between 2 meshes in the shader. /// </summary> [RequireComponent(typeof(MeshFilter))] public class VertexAnimationBehavior : MonoBehaviour { #region variables for looping animation /// <summary> /// The direction of the looped animation /// </summary> public VertexAnimationDirection m_directon = VertexAnimationDirection.Forward; /// <summary> /// The duration of one loop /// </summary> public float m_loopDuration; /// <summary> /// How often the animation should loop. 0 means looping infinitely /// </summary> public int m_loopNTimes; private System.Func<float, float> m_easingFunction; private System.Func<float, float> m_easingFunction2; private float m_startTime; #endregion /// <summary> /// The second keyframe to interpolate between /// </summary> public Mesh m_otherKeyframe; // Use this for initialization void Awake () { if (null != m_otherKeyframe) SetKeyframe2(m_otherKeyframe.vertices, m_otherKeyframe.normals); } // Update is called once per frame void Update () { } void Start () { // Start a looping animation if one has been configured in the inspector if (m_loopDuration > .0001f) { if (m_loopNTimes > 0) LoopNTimes(m_directon, m_loopDuration, m_loopNTimes); else LoopForever(m_directon, m_loopDuration); } } private static Color PackNormal(Vector3 normal) { normal.Normalize(); normal = normal * .5f + new Vector3(.5f, .5f, .5f); Color packed = new Color(normal.x, normal.y, normal.z, 0.0f); return packed; } private static Color[] PackNormals(Vector3[] normals) { Color[] packed = new Color[normals.Length]; for (int i=0; i < normals.Length; ++i) { packed[i] = PackNormal(normals[i]); } return packed; } /// <summary> /// Sets new vertex data for keyframe 1. /// Don't use this too often since new vetex data has to be uploaded to the GPU. /// </summary> public void SetKeyframe1(Mesh mesh) { SetKeyframe1(mesh.vertices, mesh.normals); } /// <summary> /// Sets new vertex data for keyframe 1. /// Don't use this too often since new vetex data has to be uploaded to the GPU. /// </summary> public void SetKeyframe1(Vector3[] vertexPositions, Vector3[] vertexNormals) { var myMesh = GetComponent<MeshFilter>().mesh; if (myMesh.vertices.Length != vertexPositions.Length) { Debug.LogError("#vertices of the two keyframes is not equal."); return; } myMesh.vertices = vertexPositions; myMesh.normals = vertexNormals; } /// <summary> /// Sets new vertex data for keyframe 2. /// Don't use this too often since new vetex data has to be uploaded to the GPU. /// </summary> public void SetKeyframe2(Mesh mesh) { SetKeyframe2(mesh.vertices, mesh.normals); } /// <summary> /// Sets new vertex data for keyframe 2. /// Don't use this too often since new vetex data has to be uploaded to the GPU. /// </summary> public void SetKeyframe2(Vector3[] vertexPositions, Vector3[] vertexNormals) { var myMesh = GetComponent<MeshFilter>().mesh; if (myMesh.vertices.Length != vertexPositions.Length) { Debug.LogError("#vertices of the two keyframes is not equal."); return; } // Store the vertices of the second mesh on the GPU => in the tangent Vector4[] data = new Vector4[myMesh.vertices.Length]; for (int i=0; i < data.Length; ++i) { data[i] = new Vector4(vertexPositions[i].x, vertexPositions[i].y, vertexPositions[i].z); } myMesh.tangents = data; // Store the normals of the second mesh on the GPU => in the vertex-colors myMesh.colors = PackNormals(vertexNormals); } /// <summary> /// Stops the looping animation, regardless of whether it was a forever-loop or a n-times-loop /// </summary> public void StopAnimation() { StopAllCoroutines(); } /// <summary> /// Loops the animation forever /// </summary> /// <param name='direction'> /// Direction of the animation /// </param> /// <param name='loopDuration'> /// How many seconds 1 loop takes /// </param> /// <param name='easingFunction'> /// Easing function for the animation, or for the first part of the animation, respectively, if ForwardBackward or BackwardForward animation /// </param> /// <param name='easingFunctionBack'> /// Easing function for the second part of an ForwardBackward or BackwardForward animation /// </param> public void LoopForever( VertexAnimationDirection direction, float loopDuration, System.Func<float, float> easingFunction = null, System.Func<float, float> easingFunctionBack = null) { StopAnimation(); m_directon = direction; m_loopDuration = loopDuration; if (null != easingFunction) m_easingFunction = easingFunction; else m_easingFunction = (x) => { return x; }; if (null != easingFunctionBack) m_easingFunction2 = easingFunctionBack; else m_easingFunction2 = m_easingFunction; StartCoroutine(DoLoop()); } /// <summary> /// Loops the animation n times /// </summary> /// <param name='direction'> /// Direction of the animation /// </param> /// <param name='loopDuration'> /// How many seconds 1 loop takes /// </param> /// <param name='loopCount'> /// the n /// </para> /// <param name='easingFunction'> /// Easing function for the animation, or for the first part of the animation, respectively, if ForwardBackward or BackwardForward animation /// </param> /// <param name='easingFunctionBack'> /// Easing function for the second part of an ForwardBackward or BackwardForward animation /// </param> public void LoopNTimes( VertexAnimationDirection direction, float loopDuration, int loopCount, System.Func<float, float> easingFunction = null, System.Func<float, float> easingFunctionBack = null) { StopAnimation(); m_directon = direction; m_loopDuration = loopDuration; m_loopNTimes = loopCount; if (null != easingFunction) m_easingFunction = easingFunction; else m_easingFunction = (x) => { return x; }; if (null != easingFunctionBack) m_easingFunction2 = easingFunctionBack; else m_easingFunction2 = m_easingFunction; StartCoroutine(DoLoop()); } /// <summary> /// The coroutine which calculates the animation's ratio-property /// </summary> private IEnumerator DoLoop() { m_startTime = Time.time; while (true) { float running = Time.time - m_startTime; int loops = (int)(running / m_loopDuration); if (m_loopNTimes > 0) { // set animation's final position and break out of looping animation if (loops >= m_loopNTimes) { switch (m_directon) { case VertexAnimationDirection.Forward: GetComponent<Renderer>().material.SetFloat("_Ratio", 1f); break; case VertexAnimationDirection.Backward: GetComponent<Renderer>().material.SetFloat("_Ratio", 0f); break; case VertexAnimationDirection.ForwardBackward: GetComponent<Renderer>().material.SetFloat("_Ratio", 0f); break; case VertexAnimationDirection.BackwardForward: GetComponent<Renderer>().material.SetFloat("_Ratio", 1f); break; } yield break; } } float ratio = (running - loops * m_loopDuration) / m_loopDuration; switch (m_directon) { case VertexAnimationDirection.Forward: ratio = m_easingFunction(ratio); break; case VertexAnimationDirection.Backward: ratio = m_easingFunction(1.0f - ratio); break; case VertexAnimationDirection.ForwardBackward: ratio *= 2.0f; if (ratio < 1.0f) ratio = m_easingFunction(ratio); else ratio = m_easingFunction2(2.0f - ratio); break; case VertexAnimationDirection.BackwardForward: ratio = 1.0f - 2.0f * ratio; if (ratio > 0.0f) ratio = m_easingFunction(ratio); else ratio = m_easingFunction2(-ratio); break; } GetComponent<Renderer>().material.SetFloat("_Ratio", ratio); yield return null; } } }