context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using System.Collections.ObjectModel; using OpenQA.Selenium.Internal; using Moq; namespace OpenQA.Selenium.Support.Events { [TestFixture] public class EventFiringWebDriverTest { private Mock<IWebDriver> mockDriver; private Mock<IWebElement> mockElement; private Mock<INavigation> mockNavigation; private IWebDriver stubDriver; private StringBuilder log; [SetUp] public void Setup() { mockDriver = new Mock<IWebDriver>(); mockElement = new Mock<IWebElement>(); mockNavigation = new Mock<INavigation>(); log = new StringBuilder(); } [Test] public void ShouldFireNavigationEvents() { mockDriver.SetupSet(_ => _.Url = It.Is<string>(x => x == "http://www.get.com")); mockDriver.Setup(_ => _.Navigate()).Returns(mockNavigation.Object); mockNavigation.Setup(_ => _.GoToUrl(It.Is<string>(x => x == "http://www.navigate-to.com"))); mockNavigation.Setup(_ => _.Back()); mockNavigation.Setup(_ => _.Forward()); EventFiringWebDriver firingDriver = new EventFiringWebDriver(mockDriver.Object); firingDriver.Navigating += new EventHandler<WebDriverNavigationEventArgs>(firingDriver_Navigating); firingDriver.Navigated += new EventHandler<WebDriverNavigationEventArgs>(firingDriver_Navigated); firingDriver.NavigatingBack += new EventHandler<WebDriverNavigationEventArgs>(firingDriver_NavigatingBack); firingDriver.NavigatedBack += new EventHandler<WebDriverNavigationEventArgs>(firingDriver_NavigatedBack); firingDriver.NavigatingForward += new EventHandler<WebDriverNavigationEventArgs>(firingDriver_NavigatingForward); firingDriver.NavigatedForward += new EventHandler<WebDriverNavigationEventArgs>(firingDriver_NavigatedForward); firingDriver.Url = "http://www.get.com"; firingDriver.Navigate().GoToUrl("http://www.navigate-to.com"); firingDriver.Navigate().Back(); firingDriver.Navigate().Forward(); string expectedLog = @"Navigating http://www.get.com Navigated http://www.get.com Navigating http://www.navigate-to.com Navigated http://www.navigate-to.com Navigating back Navigated back Navigating forward Navigated forward "; mockDriver.VerifySet(x => x.Url = "http://www.get.com", Times.Once); mockDriver.Verify(x => x.Navigate(), Times.Exactly(3)); mockNavigation.Verify(x => x.GoToUrl("http://www.navigate-to.com"), Times.Once); mockNavigation.Verify(x => x.Back(), Times.Once); mockNavigation.Verify(x => x.Forward(), Times.Once); Assert.AreEqual(expectedLog, log.ToString()); } [Test] public void ShouldFireClickEvent() { mockDriver.Setup(_ => _.FindElement(It.IsAny<By>())).Returns(mockElement.Object); mockElement.Setup(_ => _.Click()); EventFiringWebDriver firingDriver = new EventFiringWebDriver(mockDriver.Object); firingDriver.ElementClicking += new EventHandler<WebElementEventArgs>(firingDriver_ElementClicking); firingDriver.ElementClicked += new EventHandler<WebElementEventArgs>(firingDriver_ElementClicked); firingDriver.FindElement(By.Name("foo")).Click(); string expectedLog = @"Clicking Clicked "; Assert.AreEqual(expectedLog, log.ToString()); } [Test] public void ShouldFireFindByEvent() { IList<IWebElement> driverElements = new List<IWebElement>(); IList<IWebElement> subElements = new List<IWebElement>(); Mock<IWebElement> ignored = new Mock<IWebElement>(); mockDriver.Setup(_ => _.FindElement(It.Is<By>(x => x.Equals(By.Id("foo"))))).Returns(mockElement.Object); mockElement.Setup(_ => _.FindElement(It.IsAny<By>())).Returns(ignored.Object); mockElement.Setup(_ => _.FindElements(It.Is<By>(x => x.Equals(By.Name("xyz"))))).Returns(new ReadOnlyCollection<IWebElement>(driverElements)); mockDriver.Setup(_ => _.FindElements(It.Is<By>(x => x.Equals(By.XPath("//link[@type = 'text/css']"))))).Returns(new ReadOnlyCollection<IWebElement>(subElements)); EventFiringWebDriver firingDriver = new EventFiringWebDriver(mockDriver.Object); firingDriver.FindingElement += new EventHandler<FindElementEventArgs>(firingDriver_FindingElement); firingDriver.FindElementCompleted += new EventHandler<FindElementEventArgs>(firingDriver_FindElementCompleted); IWebElement element = firingDriver.FindElement(By.Id("foo")); element.FindElement(By.LinkText("bar")); element.FindElements(By.Name("xyz")); firingDriver.FindElements(By.XPath("//link[@type = 'text/css']")); string expectedLog = @"FindingElement from IWebDriver By.Id: foo FindElementCompleted from IWebDriver By.Id: foo FindingElement from IWebElement By.LinkText: bar FindElementCompleted from IWebElement By.LinkText: bar FindingElement from IWebElement By.Name: xyz FindElementCompleted from IWebElement By.Name: xyz FindingElement from IWebDriver By.XPath: //link[@type = 'text/css'] FindElementCompleted from IWebDriver By.XPath: //link[@type = 'text/css'] "; Assert.AreEqual(expectedLog, log.ToString()); } [Test] public void ShouldCallListenerOnException() { NoSuchElementException exception = new NoSuchElementException("argh"); mockDriver.Setup(_ => _.FindElement(It.Is<By>(x => x.Equals(By.Id("foo"))))).Throws(exception); EventFiringWebDriver firingDriver = new EventFiringWebDriver(mockDriver.Object); firingDriver.ExceptionThrown += new EventHandler<WebDriverExceptionEventArgs>(firingDriver_ExceptionThrown); try { firingDriver.FindElement(By.Id("foo")); Assert.Fail("Expected exception to be propogated"); } catch (NoSuchElementException) { // Fine } Assert.IsTrue(log.ToString().Contains(exception.Message)); } [Test] public void ShouldUnwrapElementArgsWhenCallingScripts() { Mock<IExecutingDriver> executingDriver = new Mock<IExecutingDriver>(); executingDriver.Setup(_ => _.FindElement(It.Is<By>(x => x.Equals(By.Id("foo"))))).Returns(mockElement.Object); executingDriver.Setup(_ => _.ExecuteScript(It.IsAny<string>(), It.IsAny<object[]>())).Returns("foo"); EventFiringWebDriver testedDriver = new EventFiringWebDriver(executingDriver.Object); IWebElement element = testedDriver.FindElement(By.Id("foo")); try { testedDriver.ExecuteScript("foo", element); } catch (Exception e) { // This is the error we're trying to fix throw e; } } [Test] public void ShouldBeAbleToWrapSubclassesOfSomethingImplementingTheWebDriverInterface() { // We should get this far EventFiringWebDriver testDriver = new EventFiringWebDriver(new ChildDriver()); } [Test] public void ShouldBeAbleToAccessWrappedInstanceFromEventCalls() { stubDriver = new StubDriver(); EventFiringWebDriver testDriver = new EventFiringWebDriver(stubDriver); StubDriver wrapped = ((IWrapsDriver)testDriver).WrappedDriver as StubDriver; Assert.AreEqual(stubDriver, wrapped); testDriver.Navigating += new EventHandler<WebDriverNavigationEventArgs>(testDriver_Navigating); testDriver.Url = "http://example.org"; } void testDriver_Navigating(object sender, WebDriverNavigationEventArgs e) { Assert.AreEqual(e.Driver, stubDriver); } void firingDriver_ExceptionThrown(object sender, WebDriverExceptionEventArgs e) { log.AppendLine(e.ThrownException.Message); } void firingDriver_FindingElement(object sender, FindElementEventArgs e) { log.Append("FindingElement from ").Append(e.Element == null ? "IWebDriver " : "IWebElement ").AppendLine(e.FindMethod.ToString()); } void firingDriver_FindElementCompleted(object sender, FindElementEventArgs e) { log.Append("FindElementCompleted from ").Append(e.Element == null ? "IWebDriver " : "IWebElement ").AppendLine(e.FindMethod.ToString()); } void firingDriver_ElementClicking(object sender, WebElementEventArgs e) { log.AppendLine("Clicking"); } void firingDriver_ElementClicked(object sender, WebElementEventArgs e) { log.AppendLine("Clicked"); } void firingDriver_Navigating(object sender, WebDriverNavigationEventArgs e) { log.Append("Navigating ").Append(e.Url).AppendLine(); } void firingDriver_Navigated(object sender, WebDriverNavigationEventArgs e) { log.Append("Navigated ").Append(e.Url).AppendLine(); } void firingDriver_NavigatingBack(object sender, WebDriverNavigationEventArgs e) { log.AppendLine("Navigating back"); } void firingDriver_NavigatedBack(object sender, WebDriverNavigationEventArgs e) { log.AppendLine("Navigated back"); } void firingDriver_NavigatingForward(object sender, WebDriverNavigationEventArgs e) { log.AppendLine("Navigating forward"); } void firingDriver_NavigatedForward(object sender, WebDriverNavigationEventArgs e) { log.AppendLine("Navigated forward"); } public interface IExecutingDriver : IWebDriver, IJavaScriptExecutor { } public class ChildDriver : StubDriver { } } }
#region File Description //----------------------------------------------------------------------------- // Game.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Storage; #endregion namespace PerPixelCollision { /// <summary> /// This is the main type for your game /// </summary> public class PerPixelCollisionGame : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; // The images we will draw Texture2D personTexture; Texture2D blockTexture; // The color data for the images; used for per pixel collision Color[] personTextureData; Color[] blockTextureData; // The images will be drawn with this SpriteBatch SpriteBatch spriteBatch; // Person Vector2 personPosition; const int PersonMoveSpeed = 5; // Blocks List<Vector2> blockPositions = new List<Vector2>(); float BlockSpawnProbability = 0.01f; const int BlockFallSpeed = 2; Random random = new Random(); // For when a collision is detected bool personHit = false; // The sub-rectangle of the drawable area which should be visible on all TVs Rectangle safeBounds; // Percentage of the screen on every side is the safe area const float SafeAreaPortion = 0.05f; public PerPixelCollisionGame() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to /// run. This is where it can query for any required services and load any /// non-graphic related content. Calling base.Initialize will enumerate through /// any components and initialize them as well. /// </summary> protected override void Initialize() { base.Initialize(); // Calculate safe bounds based on current resolution Viewport viewport = graphics.GraphicsDevice.Viewport; safeBounds = new Rectangle( (int)(viewport.Width * SafeAreaPortion), (int)(viewport.Height * SafeAreaPortion), (int)(viewport.Width * (1 - 2 * SafeAreaPortion)), (int)(viewport.Height * (1 - 2 * SafeAreaPortion))); // Start the player in the center along the bottom of the screen personPosition.X = (safeBounds.Width - personTexture.Width) / 2; personPosition.Y = safeBounds.Height - personTexture.Height; } /// <summary> /// Load your graphics content. /// </summary> protected override void LoadContent() { // Load textures blockTexture = Content.Load<Texture2D>("Block"); personTexture = Content.Load<Texture2D>("Person"); // Extract collision data blockTextureData = new Color[blockTexture.Width * blockTexture.Height]; blockTexture.GetData(blockTextureData); personTextureData = new Color[personTexture.Width * personTexture.Height]; personTexture.GetData(personTextureData); // Create a sprite batch to draw those textures spriteBatch = new SpriteBatch(graphics.GraphicsDevice); } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Get input KeyboardState keyboard = Keyboard.GetState(); GamePadState gamePad = GamePad.GetState(PlayerIndex.One); // Allows the game to exit if (gamePad.Buttons.Back == ButtonState.Pressed || keyboard.IsKeyDown(Keys.Escape)) { this.Exit(); } // Move the player left and right with arrow keys or d-pad if (keyboard.IsKeyDown(Keys.Left) || gamePad.DPad.Left == ButtonState.Pressed) { personPosition.X -= PersonMoveSpeed; } if (keyboard.IsKeyDown(Keys.Right) || gamePad.DPad.Right == ButtonState.Pressed) { personPosition.X += PersonMoveSpeed; } // Prevent the person from moving off of the screen personPosition.X = MathHelper.Clamp(personPosition.X, safeBounds.Left, safeBounds.Right - personTexture.Width); // Spawn new falling blocks if (random.NextDouble() < BlockSpawnProbability) { float x = (float)random.NextDouble() * (Window.ClientBounds.Width - blockTexture.Width); blockPositions.Add(new Vector2(x, -blockTexture.Height)); } // Get the bounding rectangle of the person Rectangle personRectangle = new Rectangle((int)personPosition.X, (int)personPosition.Y, personTexture.Width, personTexture.Height); // Update each block personHit = false; for (int i = 0; i < blockPositions.Count; i++) { // Animate this block falling blockPositions[i] = new Vector2(blockPositions[i].X, blockPositions[i].Y + BlockFallSpeed); // Get the bounding rectangle of this block Rectangle blockRectangle = new Rectangle((int)blockPositions[i].X, (int)blockPositions[i].Y, blockTexture.Width, blockTexture.Height); // Check collision with person if (IntersectPixels(personRectangle, personTextureData, blockRectangle, blockTextureData)) { personHit = true; } // Remove this block if it have fallen off the screen if (blockPositions[i].Y > Window.ClientBounds.Height) { blockPositions.RemoveAt(i); // When removing a block, the next block will have the same index // as the current block. Decrement i to prevent skipping a block. i--; } } base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice device = graphics.GraphicsDevice; // Change the background to red when the person was hit by a block if (personHit) { device.Clear(Color.Red); } else { device.Clear(Color.CornflowerBlue); } spriteBatch.Begin(); // Draw person spriteBatch.Draw(personTexture, personPosition, Color.White); // Draw blocks foreach (Vector2 blockPosition in blockPositions) spriteBatch.Draw(blockTexture, blockPosition, Color.White); spriteBatch.End(); base.Draw(gameTime); } /// <summary> /// Determines if there is overlap of the non-transparent pixels /// between two sprites. /// </summary> /// <param name="rectangleA">Bounding rectangle of the first sprite</param> /// <param name="dataA">Pixel data of the first sprite</param> /// <param name="rectangleB">Bouding rectangle of the second sprite</param> /// <param name="dataB">Pixel data of the second sprite</param> /// <returns>True if non-transparent pixels overlap; false otherwise</returns> static bool IntersectPixels(Rectangle rectangleA, Color[] dataA, Rectangle rectangleB, Color[] dataB) { // Find the bounds of the rectangle intersection int top = Math.Max(rectangleA.Top, rectangleB.Top); int bottom = Math.Min(rectangleA.Bottom, rectangleB.Bottom); int left = Math.Max(rectangleA.Left, rectangleB.Left); int right = Math.Min(rectangleA.Right, rectangleB.Right); // Check every point within the intersection bounds for (int y = top; y < bottom; y++) { for (int x = left; x < right; x++) { // Get the color of both pixels at this point Color colorA = dataA[(x - rectangleA.Left) + (y - rectangleA.Top) * rectangleA.Width]; Color colorB = dataB[(x - rectangleB.Left) + (y - rectangleB.Top) * rectangleB.Width]; // If both pixels are not completely transparent, if (colorA.A != 0 && colorB.A != 0) { // then an intersection has been found return true; } } } // No intersection found return false; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Surface.cs" company=""> // // </copyright> // <summary> // The surface. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Surfaces { using System.Windows; using System.Windows.Media.Media3D; /// <summary> /// The surface. /// </summary> public abstract class Surface : ModelVisual3D { /// <summary> /// The _content. /// </summary> private readonly GeometryModel3D _content = new GeometryModel3D(); /// <summary> /// Initializes a new instance of the <see cref="Surface"/> class. /// </summary> protected Surface() { this.Content = this._content; this._content.Geometry = this.CreateMesh(); } /// <summary> /// Gets or sets the material. /// </summary> public Material Material { get { return MaterialProperty.Get(this); } set { MaterialProperty.Set(this, value); } } /// <summary> /// Gets or sets the back material. /// </summary> public Material BackMaterial { get { return BackMaterialProperty.Get(this); } set { BackMaterialProperty.Set(this, value); } } /// <summary> /// Gets or sets a value indicating whether visible. /// </summary> public bool Visible { get { return VisibleProperty.Get(this); } set { VisibleProperty.Set(this, value); } } /// <summary> /// The on material changed. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> private static void OnMaterialChanged(object sender, DependencyPropertyChangedEventArgs e) { ((Surface)sender).OnMaterialChanged(); } /// <summary> /// The on back material changed. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> private static void OnBackMaterialChanged(object sender, DependencyPropertyChangedEventArgs e) { ((Surface)sender).OnBackMaterialChanged(); } /// <summary> /// The on visible changed. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> private static void OnVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) { ((Surface)sender).OnVisibleChanged(); } /// <summary> /// The on geometry changed. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected static void OnGeometryChanged(object sender, DependencyPropertyChangedEventArgs e) { ((Surface)sender).OnGeometryChanged(); } /// <summary> /// The on material changed. /// </summary> private void OnMaterialChanged() { this.SetContentMaterial(); } /// <summary> /// The on back material changed. /// </summary> private void OnBackMaterialChanged() { this.SetContentBackMaterial(); } /// <summary> /// The on visible changed. /// </summary> private void OnVisibleChanged() { this.SetContentMaterial(); this.SetContentBackMaterial(); } /// <summary> /// The set content material. /// </summary> private void SetContentMaterial() { this._content.Material = this.Visible ? this.Material : null; } /// <summary> /// The set content back material. /// </summary> private void SetContentBackMaterial() { this._content.BackMaterial = this.Visible ? this.BackMaterial : null; } /// <summary> /// The on geometry changed. /// </summary> private void OnGeometryChanged() { this._content.Geometry = this.CreateMesh(); } /// <summary> /// The create mesh. /// </summary> /// <returns> /// The <see cref="Geometry3D"/>. /// </returns> protected abstract Geometry3D CreateMesh(); /// <summary> /// The material property. /// </summary> public static readonly PropertyHolder<Material, Surface> MaterialProperty = new PropertyHolder<Material, Surface>("Material", null, OnMaterialChanged); /// <summary> /// The back material property. /// </summary> public static readonly PropertyHolder<Material, Surface> BackMaterialProperty = new PropertyHolder<Material, Surface>("BackMaterial", null, OnBackMaterialChanged); /// <summary> /// The visible property. /// </summary> public static readonly PropertyHolder<bool, Surface> VisibleProperty = new PropertyHolder<bool, Surface>("Visible", true, OnVisibleChanged); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //----------------------------------------------------------------------- // </copyright> // <summary>Test the ProjectTargetElement class.</summary> //----------------------------------------------------------------------- using System; using System.IO; using System.Xml; using Microsoft.Build.Construction; using Microsoft.VisualStudio.TestTools.UnitTesting; using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException; namespace Microsoft.Build.UnitTests.OM.Construction { /// <summary> /// Test the ProjectTargetElement class /// </summary> [TestClass] public class ProjectTargetElement_Tests { /// <summary> /// Create target with invalid name /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentException))] public void AddTargetInvalidName() { ProjectRootElement project = ProjectRootElement.Create(); project.CreateTargetElement("@#$invalid@#$"); } /// <summary> /// Read targets in an empty project /// </summary> [TestMethod] public void ReadNoTarget() { ProjectRootElement project = ProjectRootElement.Create(); Assert.AreEqual(null, project.Targets.GetEnumerator().Current); } /// <summary> /// Read an empty target /// </summary> [TestMethod] public void ReadEmptyTarget() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='t'/> </Project> "; ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); ProjectTargetElement target = (ProjectTargetElement)Helpers.GetFirst(project.Children); Assert.AreEqual(0, Helpers.Count(target.Children)); Assert.AreEqual(true, project.HasUnsavedChanges); } /// <summary> /// Read attributes on the target element /// </summary> [TestMethod] public void ReadParameters() { ProjectTargetElement target = GetTargetXml(); Assert.AreEqual("i", target.Inputs); Assert.AreEqual("o", target.Outputs); Assert.AreEqual("d", target.DependsOnTargets); Assert.AreEqual("c", target.Condition); } /// <summary> /// Set attributes on the target element /// </summary> [TestMethod] public void SetParameters() { ProjectTargetElement target = GetTargetXml(); target.Inputs = "ib"; target.Outputs = "ob"; target.DependsOnTargets = "db"; target.Condition = "cb"; Assert.AreEqual("ib", target.Inputs); Assert.AreEqual("ob", target.Outputs); Assert.AreEqual("db", target.DependsOnTargets); Assert.AreEqual("cb", target.Condition); } /// <summary> /// Set null inputs on the target element /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void SetInvalidNullInputs() { ProjectTargetElement target = GetTargetXml(); target.Inputs = null; } /// <summary> /// Set null outputs on the target element /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void SetInvalidNullOutputs() { ProjectTargetElement target = GetTargetXml(); target.Outputs = null; } /// <summary> /// Set null dependsOnTargets on the target element /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void SetInvalidNullDependsOnTargets() { ProjectTargetElement target = GetTargetXml(); target.DependsOnTargets = null; } /// <summary> /// Set null dependsOnTargets on the target element /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void SetInvalidNullKeepDuplicateOutputs() { ProjectTargetElement target = GetTargetXml(); target.KeepDuplicateOutputs = null; } /// <summary> /// Set null condition on the target element /// </summary> [TestMethod] public void SetNullCondition() { ProjectTargetElement target = GetTargetXml(); target.Condition = null; Assert.AreEqual(String.Empty, target.Condition); } /// <summary> /// Read a target with a missing name /// </summary> [TestMethod] [ExpectedException(typeof(InvalidProjectFileException))] public void ReadInvalidMissingName() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target/> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } /// <summary> /// Read a target with an invalid attribute /// </summary> [TestMethod] [ExpectedException(typeof(InvalidProjectFileException))] public void ReadInvalidAttribute() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target XX='YY'/> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } /// <summary> /// Read an target with two task children /// </summary> [TestMethod] public void ReadTargetTwoTasks() { ProjectTargetElement target = GetTargetXml(); var tasks = Helpers.MakeList(target.Children); Assert.AreEqual(2, tasks.Count); ProjectTaskElement task1 = (ProjectTaskElement)tasks[0]; ProjectTaskElement task2 = (ProjectTaskElement)tasks[1]; Assert.AreEqual("t1", task1.Name); Assert.AreEqual("t2", task2.Name); } /// <summary> /// Set name /// </summary> [TestMethod] public void SetName() { ProjectRootElement project = ProjectRootElement.Create(); ProjectTargetElement target = project.AddTarget("t"); Helpers.ClearDirtyFlag(project); target.Name = "t2"; Assert.AreEqual("t2", target.Name); Assert.AreEqual(true, project.HasUnsavedChanges); } /// <summary> /// Set inputs /// </summary> [TestMethod] public void SetInputs() { ProjectRootElement project = ProjectRootElement.Create(); ProjectTargetElement target = project.AddTarget("t"); Helpers.ClearDirtyFlag(project); target.Inputs = "in"; Assert.AreEqual("in", target.Inputs); Assert.AreEqual(true, project.HasUnsavedChanges); } /// <summary> /// Set outputs /// </summary> [TestMethod] public void SetOutputs() { ProjectRootElement project = ProjectRootElement.Create(); ProjectTargetElement target = project.AddTarget("t"); Helpers.ClearDirtyFlag(project); target.Outputs = "out"; Assert.AreEqual("out", target.Outputs); Assert.AreEqual(true, project.HasUnsavedChanges); } /// <summary> /// Set dependsontargets /// </summary> [TestMethod] public void SetDependsOnTargets() { ProjectRootElement project = ProjectRootElement.Create(); ProjectTargetElement target = project.AddTarget("t"); Helpers.ClearDirtyFlag(project); target.DependsOnTargets = "dot"; Assert.AreEqual("dot", target.DependsOnTargets); Assert.AreEqual(true, project.HasUnsavedChanges); } /// <summary> /// Set condition /// </summary> [TestMethod] public void SetCondition() { ProjectRootElement project = ProjectRootElement.Create(); ProjectTargetElement target = project.AddTarget("t"); Helpers.ClearDirtyFlag(project); target.Condition = "c"; Assert.AreEqual("c", target.Condition); Assert.AreEqual(true, project.HasUnsavedChanges); } /// <summary> /// Set KeepDuplicateOutputs attribute /// </summary> [TestMethod] public void SetKeepDuplicateOutputs() { ProjectRootElement project = ProjectRootElement.Create(); ProjectTargetElement target = project.AddTarget("t"); Helpers.ClearDirtyFlag(project); target.KeepDuplicateOutputs = "true"; Assert.AreEqual("true", target.KeepDuplicateOutputs); Assert.AreEqual(true, project.HasUnsavedChanges); } /// <summary> /// Set return value. Verify that setting to the empty string and null are /// both allowed and have distinct behaviour. /// </summary> [TestMethod] public void SetReturns() { ProjectRootElement project = ProjectRootElement.Create(); ProjectTargetElement target = project.AddTarget("t"); Helpers.ClearDirtyFlag(project); target.Returns = "@(a)"; Assert.AreEqual("@(a)", target.Returns); Assert.AreEqual(true, project.HasUnsavedChanges); Helpers.ClearDirtyFlag(project); target.Returns = String.Empty; Assert.AreEqual(String.Empty, target.Returns); Assert.AreEqual(true, project.HasUnsavedChanges); Helpers.ClearDirtyFlag(project); target.Returns = null; Assert.IsNull(target.Returns); Assert.AreEqual(true, project.HasUnsavedChanges); } /// <summary> /// Helper to get an empty ProjectTargetElement with various attributes and two tasks /// </summary> private static ProjectTargetElement GetTargetXml() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Target Name='t' Inputs='i' Outputs='o' DependsOnTargets='d' Condition='c'> <t1/> <t2/> </Target> </Project> "; ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); ProjectTargetElement target = (ProjectTargetElement)Helpers.GetFirst(project.Children); return target; } } }
using System.Diagnostics; using Autofac; using BuildIt; using System; using System.Threading.Tasks; using BuildIt.Lifecycle; using BuildIt.Lifecycle.Regions; using BuildIt.Lifecycle.States; using BuildIt.Lifecycle.States.ViewModel; using BuildIt.States; using BuildIt.States.Completion; namespace StateByState { public enum MainRegionView { Base, Main, Second, Third, Fourth } public enum MainRegionTransition { Base, MainToSecond, AnyToMain, ThirdToMain } public enum SimpleTest { Base, Test1, Test2 } public class MainRegion : StateAwareApplicationRegion { public MainRegion() { #region State Definitions var group = StateManager.Group<SimpleTest>(); StateManager.Group<MainRegionView>().WithHistory() .DefineStateWithData<MainRegionView, MainViewModel>(MainRegionView.Main) .OnCompleteWithData(MainCompletion.Page2, vm => vm.TickCount) .ChangeState(MainRegionView.Second) .OnEvent((vm, a) => vm.UnableToComplete += a, (vm, a) => vm.UnableToComplete -= a) .ChangeState(MainRegionView.Third) .OnComplete(MainCompletion.NewRegion) .LaunchRegion(this, TypeRef.Get<SecondaryApplication>()) .OnCompleteWithDataEvent<MainRegionView, MainViewModel, MainCompletion, int>(MainCompletion.Page4) .ChangeState(MainRegionView.Fourth) .InitializeNewState<MainRegionView, MainViewModel, FourthViewModel, int>( (vm, d, cancel) => vm.InitValue = $"Started with {d}") .Initialise(async (vm, cancel) => { "VM State: Init".Log(); await vm.Init(); }) .WhenChangedTo(async (vm, cancel) => { "VM State: When Changed To".Log(); // vm.Completed += State_Completed; //vm.UnableToComplete += State_UnableToCompleted; //vm.SpawnNewRegion += Vm_SpawnNewRegion; await vm.StartViewModel(); }) .WhenAboutToChange((vm, cancel) => $"VM State: About to Change - {cancel.Cancel}".Log()) .WhenChangingFrom(vm => { "VM State: When Changing From".Log(); //vm.Completed -= State_Completed; //vm.UnableToComplete -= State_UnableToCompleted; }) // .AsState() .WhenAboutToChangeFrom(cancel => $"State: About to Change - {cancel.Cancel}".Log()) #pragma warning disable 1998 .WhenChangingFrom(async (cancel) => "State: Changing".Log()) #pragma warning restore 1998 .WhenChangedTo((cancel) => Debug.WriteLine("State: Changing")) // .AsStateWithStateData<MainRegionView, MainViewModel>() // .EndState() .DefineStateWithData<MainRegionView, SecondViewModel>(MainRegionView.Second) .OnComplete(DefaultCompletion.Complete) .ChangeToPreviousState() .Initialise(async (vm, cancel) => await vm.InitSecond()) .WhenChangedTo((vm, cancel) => { //vm.SecondCompleted += SecondCompleted; Task.Run(async () => { await Task.Delay(5000); await vm.UIContext.RunAsync(() => { Debug.WriteLine("test"); }); }); }) .WhenChangedToWithData<MainRegionView, SecondViewModel, int>((vm, data, cancel) => { vm.ExtraData = data; }) .WhenChangingFrom((vm, cancel) => { //vm.SecondCompleted -= SecondCompleted; }) //.EndState() .DefineStateWithData<MainRegionView, ThirdViewModel>(MainRegionView.Third) .WhenChangedTo((vm, cancel) => { vm.ThirdCompleted += ThirdCompleted; }) .WhenChangingFrom((vm, cancel) => { vm.ThirdCompleted -= ThirdCompleted; }); //.EndState(); //sm.DefineTransition(MainRegionTransition.MainToSecond) // .From(MainRegionView.Main) // .To(MainRegionView.Second); //sm.DefineTransition(MainRegionTransition.AnyToMain) // .To(MainRegionView.Main); //sm.DefineTransition(MainRegionTransition.ThirdToMain) // .From(MainRegionView.Third) // .To(MainRegionView.Main); #endregion } private void Vm_SpawnNewRegion(object sender, EventArgs e) { Manager.CreateRegion<SecondaryApplication>(); } //public override void RegisterDependencies(IContainer container) //{ // base.RegisterDependencies(container); // foreach (var stateGroup in StateManager.StateGroups) // { // (stateGroup.Value as ICanRegisterDependencies)?.RegisterDependencies(container); // } // // (StateManager as ICanRegisterDependencies)?.RegisterDependencies(container); // //RegionManager?.RegisterDependencies(container); //} //public override void RegisterForUIAccess(IUIExecutionContext context) //{ // base.RegisterForUIAccess(context); // (StateManager as IRegisterForUIAccess)?.RegisterForUIAccess(this); //} protected override async Task CompleteStartup() { await base.CompleteStartup(); await StateManager.GoToState(MainRegionView.Main, false); } //private async void State_Completed(object sender, EventArgs e) //{ // await StateManager.GoToState(MainRegionView.Second); // // await StateManager.Transition(MainRegionTransition.MainToSecond); //} //private async void State_UnableToCompleted(object sender, EventArgs e) //{ // await StateManager.GoToState(MainRegionView.Third); // //await StateManager.Transition(MainRegionView.Third); //} private async void SecondCompleted(object sender, EventArgs e) { await StateManager.GoBackToPreviousState(); //await StateManager.GoToState(MainRegionView.Main); // await StateManager.Transition(MainRegionTransition.AnyToMain); } private async void ThirdCompleted(object sender, EventArgs e) { await StateManager.GoToState(MainRegionView.Main); // await StateManager.Transition(MainRegionTransition.ThirdToMain); } } }
using System.Diagnostics; namespace CleanSqlite { public partial class Sqlite3 { /* ** 2007 August 27 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains code used to implement mutexes on Btree objects. ** This code really belongs in btree.c. But btree.c is getting too ** big and we want to break it down some. This packaged seemed like ** a good breakout. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e ** ************************************************************************* */ //#include "btreeInt.h" #if !SQLITE_OMIT_SHARED_CACHE #if SQLITE_THREADSAFE /* ** Obtain the BtShared mutex associated with B-Tree handle p. Also, ** set BtShared.db to the database handle associated with p and the ** p->locked boolean to true. */ static void lockBtreeMutex(Btree *p){ assert( p->locked==0 ); assert( sqlite3_mutex_notheld(p->pBt->mutex) ); assert( sqlite3_mutex_held(p->db->mutex) ); sqlite3_mutex_enter(p->pBt->mutex); p->pBt->db = p->db; p->locked = 1; } /* ** Release the BtShared mutex associated with B-Tree handle p and ** clear the p->locked boolean. */ static void unlockBtreeMutex(Btree *p){ BtShared *pBt = p->pBt; assert( p->locked==1 ); assert( sqlite3_mutex_held(pBt->mutex) ); assert( sqlite3_mutex_held(p->db->mutex) ); assert( p->db==pBt->db ); sqlite3_mutex_leave(pBt->mutex); p->locked = 0; } /* ** Enter a mutex on the given BTree object. ** ** If the object is not sharable, then no mutex is ever required ** and this routine is a no-op. The underlying mutex is non-recursive. ** But we keep a reference count in Btree.wantToLock so the behavior ** of this interface is recursive. ** ** To avoid deadlocks, multiple Btrees are locked in the same order ** by all database connections. The p->pNext is a list of other ** Btrees belonging to the same database connection as the p Btree ** which need to be locked after p. If we cannot get a lock on ** p, then first unlock all of the others on p->pNext, then wait ** for the lock to become available on p, then relock all of the ** subsequent Btrees that desire a lock. */ void sqlite3BtreeEnter(Btree *p){ Btree *pLater; /* Some basic sanity checking on the Btree. The list of Btrees ** connected by pNext and pPrev should be in sorted order by ** Btree.pBt value. All elements of the list should belong to ** the same connection. Only shared Btrees are on the list. */ assert( p->pNext==0 || p->pNext->pBt>p->pBt ); assert( p->pPrev==0 || p->pPrev->pBt<p->pBt ); assert( p->pNext==0 || p->pNext->db==p->db ); assert( p->pPrev==0 || p->pPrev->db==p->db ); assert( p->sharable || (p->pNext==0 && p->pPrev==0) ); /* Check for locking consistency */ assert( !p->locked || p->wantToLock>0 ); assert( p->sharable || p->wantToLock==0 ); /* We should already hold a lock on the database connection */ assert( sqlite3_mutex_held(p->db->mutex) ); /* Unless the database is sharable and unlocked, then BtShared.db ** should already be set correctly. */ assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db ); if( !p->sharable ) return; p->wantToLock++; if( p->locked ) return; /* In most cases, we should be able to acquire the lock we ** want without having to go throught the ascending lock ** procedure that follows. Just be sure not to block. */ if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){ p->pBt->db = p->db; p->locked = 1; return; } /* To avoid deadlock, first release all locks with a larger ** BtShared address. Then acquire our lock. Then reacquire ** the other BtShared locks that we used to hold in ascending ** order. */ for(pLater=p->pNext; pLater; pLater=pLater->pNext){ assert( pLater->sharable ); assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt ); assert( !pLater->locked || pLater->wantToLock>0 ); if( pLater->locked ){ unlockBtreeMutex(pLater); } } lockBtreeMutex(p); for(pLater=p->pNext; pLater; pLater=pLater->pNext){ if( pLater->wantToLock ){ lockBtreeMutex(pLater); } } } /* ** Exit the recursive mutex on a Btree. */ void sqlite3BtreeLeave(Btree *p){ if( p->sharable ){ assert( p->wantToLock>0 ); p->wantToLock--; if( p->wantToLock==0 ){ unlockBtreeMutex(p); } } } #if NDEBUG /* ** Return true if the BtShared mutex is held on the btree, or if the ** B-Tree is not marked as sharable. ** ** This routine is used only from within assert() statements. */ int sqlite3BtreeHoldsMutex(Btree *p){ assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 ); assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db ); assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) ); assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) ); return (p->sharable==0 || p->locked); } #endif #if SQLITE_OMIT_INCRBLOB /* ** Enter and leave a mutex on a Btree given a cursor owned by that ** Btree. These entry points are used by incremental I/O and can be ** omitted if that module is not used. */ void sqlite3BtreeEnterCursor(BtCursor *pCur){ sqlite3BtreeEnter(pCur->pBtree); } void sqlite3BtreeLeaveCursor(BtCursor *pCur){ sqlite3BtreeLeave(pCur->pBtree); } #endif //* SQLITE_OMIT_INCRBLOB */ /* ** Enter the mutex on every Btree associated with a database ** connection. This is needed (for example) prior to parsing ** a statement since we will be comparing table and column names ** against all schemas and we do not want those schemas being ** reset out from under us. ** ** There is a corresponding leave-all procedures. ** ** Enter the mutexes in accending order by BtShared pointer address ** to avoid the possibility of deadlock when two threads with ** two or more btrees in common both try to lock all their btrees ** at the same instant. */ void sqlite3BtreeEnterAll(sqlite3 db){ int i; Btree *p; assert( sqlite3_mutex_held(db->mutex) ); for(i=0; i<db->nDb; i++){ p = db->aDb[i].pBt; if( p ) sqlite3BtreeEnter(p); } } void sqlite3BtreeLeaveAll(sqlite3 db){ int i; Btree *p; assert( sqlite3_mutex_held(db->mutex) ); for(i=0; i<db->nDb; i++){ p = db->aDb[i].pBt; if( p ) sqlite3BtreeLeave(p); } } /* ** Return true if a particular Btree requires a lock. Return FALSE if ** no lock is ever required since it is not sharable. */ int sqlite3BtreeSharable(Btree *p){ return p->sharable; } #if NDEBUG /* ** Return true if the current thread holds the database connection ** mutex and all required BtShared mutexes. ** ** This routine is used inside assert() statements only. */ int sqlite3BtreeHoldsAllMutexes(sqlite3 db){ int i; if( !sqlite3_mutex_held(db->mutex) ){ return 0; } for(i=0; i<db->nDb; i++){ Btree *p; p = db->aDb[i].pBt; if( p && p->sharable && (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){ return 0; } } return 1; } #endif //* NDEBUG */ #if NDEBUG /* ** Return true if the correct mutexes are held for accessing the ** db->aDb[iDb].pSchema structure. The mutexes required for schema ** access are: ** ** (1) The mutex on db ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt. ** ** If pSchema is not NULL, then iDb is computed from pSchema and ** db using sqlite3SchemaToIndex(). */ int sqlite3SchemaMutexHeld(sqlite3 db, int iDb, Schema *pSchema){ Btree *p; assert( db!=0 ); if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema); assert( iDb>=0 && iDb<db->nDb ); if( !sqlite3_mutex_held(db->mutex) ) return 0; if( iDb==1 ) return 1; p = db->aDb[iDb].pBt; assert( p!=0 ); return p->sharable==0 || p->locked==1; } #endif //* NDEBUG */ #else //* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */ /* ** The following are special cases for mutex enter routines for use ** in single threaded applications that use shared cache. Except for ** these two routines, all mutex operations are no-ops in that case and ** are null #defines in btree.h. ** ** If shared cache is disabled, then all btree mutex routines, including ** the ones below, are no-ops and are null #defines in btree.h. */ void sqlite3BtreeEnter(Btree *p){ p->pBt->db = p->db; } void sqlite3BtreeEnterAll(sqlite3 db){ int i; for(i=0; i<db->nDb; i++){ Btree *p = db->aDb[i].pBt; if( p ){ p->pBt->db = p->db; } } } #endif //* if SQLITE_THREADSAFE */ #endif //* ifndef SQLITE_OMIT_SHARED_CACHE */ } }
// 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.Generic; using Microsoft.Build.Framework; using Microsoft.Build.BackEnd.Logging; using Microsoft.Build.Shared; using InternalLoggerException = Microsoft.Build.Exceptions.InternalLoggerException; using Xunit; namespace Microsoft.Build.UnitTests.Logging { /// <summary> /// Verify the event source sink functions correctly. /// </summary> public class EventSourceSink_Tests { /// <summary> /// Verify the properties on EventSourceSink properly work /// </summary> [Fact] public void PropertyTests() { EventSourceSink sink = new EventSourceSink(); Assert.Null(sink.Name); string name = "Test Name"; sink.Name = name; Assert.Equal(0, string.Compare(sink.Name, name, StringComparison.OrdinalIgnoreCase)); } /// <summary> /// Test out events /// </summary> [Fact] public void ConsumeEventsGoodEvents() { EventSourceSink sink = new EventSourceSink(); RaiseEventHelper eventHelper = new RaiseEventHelper(sink); EventHandlerHelper testHandlers = new EventHandlerHelper(sink, null); VerifyRegisteredHandlers(RaiseEventHelper.BuildStarted, eventHelper, testHandlers); VerifyRegisteredHandlers(RaiseEventHelper.BuildFinished, eventHelper, testHandlers); VerifyRegisteredHandlers(RaiseEventHelper.NormalMessage, eventHelper, testHandlers); VerifyRegisteredHandlers(RaiseEventHelper.TaskFinished, eventHelper, testHandlers); VerifyRegisteredHandlers(RaiseEventHelper.CommandLine, eventHelper, testHandlers); VerifyRegisteredHandlers(RaiseEventHelper.Warning, eventHelper, testHandlers); VerifyRegisteredHandlers(RaiseEventHelper.Error, eventHelper, testHandlers); VerifyRegisteredHandlers(RaiseEventHelper.TargetStarted, eventHelper, testHandlers); VerifyRegisteredHandlers(RaiseEventHelper.TargetFinished, eventHelper, testHandlers); VerifyRegisteredHandlers(RaiseEventHelper.ProjectStarted, eventHelper, testHandlers); VerifyRegisteredHandlers(RaiseEventHelper.ProjectFinished, eventHelper, testHandlers); VerifyRegisteredHandlers(RaiseEventHelper.ExternalStartedEvent, eventHelper, testHandlers); VerifyRegisteredHandlers(RaiseEventHelper.BuildStarted, eventHelper, testHandlers); VerifyRegisteredHandlers(RaiseEventHelper.GenericStatusEvent, eventHelper, testHandlers); } /// <summary> /// Test out events when no event handlers are registered /// </summary> [Fact] public void ConsumeEventsGoodEventsNoHandlers() { EventSourceSink sink = new EventSourceSink(); RaiseEventHelper eventHelper = new RaiseEventHelper(sink); eventHelper.RaiseBuildEvent(RaiseEventHelper.BuildStarted); eventHelper.RaiseBuildEvent(RaiseEventHelper.BuildFinished); eventHelper.RaiseBuildEvent(RaiseEventHelper.NormalMessage); eventHelper.RaiseBuildEvent(RaiseEventHelper.TaskFinished); eventHelper.RaiseBuildEvent(RaiseEventHelper.CommandLine); eventHelper.RaiseBuildEvent(RaiseEventHelper.Warning); eventHelper.RaiseBuildEvent(RaiseEventHelper.Error); eventHelper.RaiseBuildEvent(RaiseEventHelper.TargetStarted); eventHelper.RaiseBuildEvent(RaiseEventHelper.TargetFinished); eventHelper.RaiseBuildEvent(RaiseEventHelper.ProjectStarted); eventHelper.RaiseBuildEvent(RaiseEventHelper.ProjectFinished); eventHelper.RaiseBuildEvent(RaiseEventHelper.ExternalStartedEvent); eventHelper.RaiseBuildEvent(RaiseEventHelper.ExternalStartedEvent); eventHelper.RaiseBuildEvent(RaiseEventHelper.GenericStatusEvent); } #region TestsThrowingLoggingExceptions /// <summary> /// Verify when exceptions are thrown in the event handler, they are properly handled /// </summary> [Fact] public void LoggerExceptionInEventHandler() { List<Exception> exceptionList = new List<Exception>(); exceptionList.Add(new LoggerException()); exceptionList.Add(new ArgumentException()); exceptionList.Add(new StackOverflowException()); foreach (Exception exception in exceptionList) { RaiseExceptionInEventHandler(RaiseEventHelper.BuildStarted, exception); RaiseExceptionInEventHandler(RaiseEventHelper.BuildFinished, exception); RaiseExceptionInEventHandler(RaiseEventHelper.NormalMessage, exception); RaiseExceptionInEventHandler(RaiseEventHelper.TaskFinished, exception); RaiseExceptionInEventHandler(RaiseEventHelper.CommandLine, exception); RaiseExceptionInEventHandler(RaiseEventHelper.Warning, exception); RaiseExceptionInEventHandler(RaiseEventHelper.Error, exception); RaiseExceptionInEventHandler(RaiseEventHelper.TargetStarted, exception); RaiseExceptionInEventHandler(RaiseEventHelper.TargetFinished, exception); RaiseExceptionInEventHandler(RaiseEventHelper.ProjectStarted, exception); RaiseExceptionInEventHandler(RaiseEventHelper.ProjectFinished, exception); RaiseExceptionInEventHandler(RaiseEventHelper.ExternalStartedEvent, exception); RaiseExceptionInEventHandler(RaiseEventHelper.GenericStatusEvent, exception); } } /// <summary> /// Verify raising a generic event derived from BuildEventArgs rather than CustomBuildEventArgs causes an internalErrorException /// </summary> [Fact] public void RaiseGenericBuildEventArgs() { Assert.Throws<InternalErrorException>(() => { EventSourceSink sink = new EventSourceSink(); RaiseEventHelper eventHelper = new RaiseEventHelper(sink); eventHelper.RaiseBuildEvent(RaiseEventHelper.GenericBuildEvent); } ); } /// <summary> /// Verify that shutdown un registers all of the event handlers /// </summary> [Fact] public void VerifyShutdown() { EventSourceSink sink = new EventSourceSink(); // Registers event handlers onto the event source EventHandlerHelper handlerHelper = new EventHandlerHelper(sink, null); RaiseEventHelper raiseEventHelper = new RaiseEventHelper(sink); raiseEventHelper.RaiseBuildEvent(RaiseEventHelper.ProjectStarted); Assert.True(handlerHelper.EnteredEventHandler); Assert.True(handlerHelper.EnteredAnyEventHandler); Assert.True(handlerHelper.EnteredStatusEventHandler); Assert.Equal(handlerHelper.RaisedEvent, RaiseEventHelper.ProjectStarted); Assert.Equal(handlerHelper.RaisedAnyEvent, RaiseEventHelper.ProjectStarted); Assert.Equal(handlerHelper.RaisedStatusEvent, RaiseEventHelper.ProjectStarted); sink.ShutDown(); handlerHelper.ResetRaisedEvent(); raiseEventHelper.RaiseBuildEvent(RaiseEventHelper.ProjectStarted); Assert.False(handlerHelper.EnteredEventHandler); Assert.False(handlerHelper.EnteredAnyEventHandler); Assert.False(handlerHelper.EnteredStatusEventHandler); Assert.Null(handlerHelper.RaisedEvent); Assert.Null(handlerHelper.RaisedAnyEvent); Assert.Null(handlerHelper.RaisedStatusEvent); } /// <summary> /// Verify aggregate exceptions are caught as critical if they contain critical exceptions /// </summary> [Fact] public void VerifyAggregateExceptionHandling() { try { // A simple non-critical exception throw new Exception(); } catch (Exception e) { Assert.False(ExceptionHandling.IsCriticalException(e)); } try { // An empty aggregate exception - non-critical throw new AggregateException(); } catch (Exception e) { Assert.False(ExceptionHandling.IsCriticalException(e)); } try { // Aggregate exception containing two non-critical exceptions - non-critical Exception[] exceptionArray = new Exception[] { new IndexOutOfRangeException(), new Exception() }; //// two non-critical exceptions throw new AggregateException(exceptionArray); } catch (Exception e) { Assert.False(ExceptionHandling.IsCriticalException(e)); } try { // Nested aggregate exception containing non-critical exceptions - non-critical Exception[] exceptionArray1 = new Exception[] { new IndexOutOfRangeException(), new Exception() }; //// two non-critical exceptions AggregateException ae1 = new AggregateException(exceptionArray1); Exception[] exceptionArray2 = new Exception[] { ae1, new Exception() }; //// two non-critical exceptions (ae1 contains nested exceptions) throw new AggregateException(exceptionArray2); } catch (Exception e) { Assert.False(ExceptionHandling.IsCriticalException(e)); } try { // A simple critical exception throw new OutOfMemoryException(); } catch (Exception e) { Assert.True(ExceptionHandling.IsCriticalException(e)); } try { // An aggregate exception containing one critical exception - critical Exception[] exceptionArray = new Exception[] { new OutOfMemoryException(), new IndexOutOfRangeException(), new Exception() }; //// two non-critical exceptions, one critical throw new AggregateException(exceptionArray); } catch (Exception e) { Assert.True(ExceptionHandling.IsCriticalException(e)); } try { // Nested aggregate exception containing non-critical exceptions - non-critical Exception[] exceptionArray1 = new Exception[] { new OutOfMemoryException(), new IndexOutOfRangeException(), new Exception() }; //// two non-critical exceptions, one critical AggregateException ae1 = new AggregateException(exceptionArray1); Exception[] exceptionArray2 = new Exception[] { ae1, new Exception() }; //// one critical one non-critical (ae1 contains nested critical exception) throw new AggregateException(exceptionArray2); } catch (Exception e) { Assert.True(ExceptionHandling.IsCriticalException(e)); } } #region Private methods /// <summary> /// Take an event and an exception to raise, create a new sink and raise the event on it. /// In the event handler registered on the sink, the exception will be thrown. /// </summary> /// <param name="buildEventToRaise">BuildEvent to raise on the </param> /// <param name="exceptionToRaise">Exception to throw in the event handler </param> private static void RaiseExceptionInEventHandler(BuildEventArgs buildEventToRaise, Exception exceptionToRaise) { EventSourceSink sink = new EventSourceSink(); RaiseEventHelper eventHelper = new RaiseEventHelper(sink); EventHandlerHelper testHandlers = new EventHandlerHelper(sink, exceptionToRaise); try { eventHelper.RaiseBuildEvent(buildEventToRaise); } catch (Exception e) { // Logger exceptions should be rethrown as is with no wrapping if (exceptionToRaise is LoggerException) { Assert.Equal(e, exceptionToRaise); // "Expected Logger exception to be raised in event handler and re-thrown by event source" } else { if (ExceptionHandling.IsCriticalException(e)) { Assert.Equal(e, exceptionToRaise); // "Expected Logger exception to be raised in event handler and re-thrown by event source" } else { // All other exceptions should be wrapped in an InternalLoggerException, with the original exception as the inner exception Assert.True(e is InternalLoggerException); // "Expected general exception to be raised in event handler and re-thrown by event source as a InternalLoggerException" } } } } /// <summary> /// Verify when an is raised the handlers which are registered to handle the event should handle them /// </summary> /// <param name="buildEventToRaise">A buildEventArgs to raise on the event source</param> /// <param name="eventHelper">Helper class which events are raised on</param> /// <param name="testHandlers">Class which contains a set of event handlers registered on the event source</param> private static void VerifyRegisteredHandlers(BuildEventArgs buildEventToRaise, RaiseEventHelper eventHelper, EventHandlerHelper testHandlers) { try { eventHelper.RaiseBuildEvent(buildEventToRaise); if (buildEventToRaise.GetType() != typeof(GenericBuildStatusEventArgs)) { Assert.Equal(testHandlers.RaisedEvent, buildEventToRaise); // "Expected buildevent in handler to match buildevent raised on event source" Assert.Equal(testHandlers.RaisedEvent, testHandlers.RaisedAnyEvent); // "Expected RaisedEvent and RaisedAnyEvent to match" Assert.True(testHandlers.EnteredEventHandler); // "Expected to enter into event handler" } Assert.Equal(testHandlers.RaisedAnyEvent, buildEventToRaise); // "Expected buildEvent in any event handler to match buildevent raised on event source" Assert.True(testHandlers.EnteredAnyEventHandler); // "Expected to enter into AnyEvent handler" if (buildEventToRaise is BuildStatusEventArgs) { Assert.Equal(testHandlers.RaisedStatusEvent, buildEventToRaise); // "Expected buildevent in handler to match buildevent raised on event source" Assert.True(testHandlers.EnteredStatusEventHandler); // "Expected to enter into Status event handler" } else { Assert.Null(testHandlers.RaisedStatusEvent); Assert.False(testHandlers.EnteredStatusEventHandler); } } finally { testHandlers.ResetRaisedEvent(); } } #endregion #region HelperClasses /// <summary> /// Generic class derived from BuildEventArgs which is used to test the case /// where the event is not a well known event, or a custom event /// </summary> internal class GenericBuildEventArgs : BuildEventArgs { /// <summary> /// Default constructor /// </summary> internal GenericBuildEventArgs() : base() { } } /// <summary> /// Generic class derived from BuildStatusEvent which is used to test the case /// where a status event is raised but it is not a well known status event (build started ...) /// </summary> internal class GenericBuildStatusEventArgs : BuildStatusEventArgs { /// <summary> /// Default constructor /// </summary> internal GenericBuildStatusEventArgs() : base() { } } /// <summary> /// Create a test class which will register to the event source and have event handlers /// which can act normally or throw exceptions. /// </summary> internal class EventHandlerHelper { #region Data /// <summary> /// When an event handler raises an event it will /// set this to the event which was raised /// This can then be asserted upon to verify the event /// which was raised on the sink was the one received /// by the event handler /// </summary> private BuildEventArgs _raisedEvent; /// <summary> /// The any event handler will get all events, even if they are raised to another event handler /// We need to verify that both the event handler and the any event handler both get the events /// </summary> private BuildEventArgs _raisedAnyEvent; /// <summary> /// A status event message, this is set when status events are raised on the event handler /// </summary> private BuildEventArgs _raisedStatusEvent; /// <summary> /// To test the exception mechanism of the event source, we may want to /// throw certain exceptions in the event handlers. This can be null if /// no exception is to be thrown. /// </summary> private Exception _exceptionInHandlers; /// <summary> /// Was the event handler entered into, this tells us whether or not the event /// was actually raised /// </summary> private bool _enteredEventHandler; /// <summary> /// The any event handler will get all events, even if they are raised to another event handler /// We need to verify that both the event handler and the any event handler both get the events /// </summary> private bool _enteredAnyEventHandler; /// <summary> /// Events such as BuildStarted, ProjectStarted/Finished, ... are status events. /// In addition to being raised on their own events, they are also raised on the status event and any event. /// </summary> private bool _enteredStatusEventHandler; #endregion #region Constructors /// <summary> /// Default Constructor, registered event handlers for all the well know event types on the passed in event source /// </summary> /// <param name="source">Event source to register to for events</param> /// <param name="exceptionToThrow">What exception should be thrown from the event handler, this can be null</param> internal EventHandlerHelper(IEventSource source, Exception exceptionToThrow) { _exceptionInHandlers = exceptionToThrow; source.AnyEventRaised += Source_AnyEventRaised; source.BuildFinished += Source_BuildFinished; source.BuildStarted += Source_BuildStarted; source.CustomEventRaised += Source_CustomEventRaised; source.ErrorRaised += Source_ErrorRaised; source.MessageRaised += Source_MessageRaised; source.ProjectFinished += Source_ProjectFinished; source.ProjectStarted += Source_ProjectStarted; source.StatusEventRaised += Source_StatusEventRaised; source.TargetFinished += Source_TargetFinished; source.TargetStarted += Source_TargetStarted; source.TaskFinished += Source_TaskFinished; source.TaskStarted += Source_TaskStarted; source.WarningRaised += Source_WarningRaised; } #endregion #region Properties /// <summary> /// Was an event handler entered into /// </summary> public bool EnteredEventHandler { get { return _enteredEventHandler; } } /// <summary> /// Was the Any event handler /// </summary> public bool EnteredAnyEventHandler { get { return _enteredAnyEventHandler; } } /// <summary> /// Was the Status event handler /// </summary> public bool EnteredStatusEventHandler { get { return _enteredStatusEventHandler; } } /// <summary> /// Which event was raised on the event source, this can be asserted upon /// to verify the event passed to the event source is the same one which was /// received by the event handlers /// </summary> public BuildEventArgs RaisedEvent { get { return _raisedEvent; } } /// <summary> /// Check the event raised by the AnyEventHandler /// </summary> public BuildEventArgs RaisedAnyEvent { get { return _raisedAnyEvent; } } /// <summary> /// Check the event raised by the StatusEventHandler /// </summary> public BuildEventArgs RaisedStatusEvent { get { return _raisedStatusEvent; } } #endregion #region Public Methods /// <summary> /// Reset the per event variables so that we can raise another /// event and capture the information for it. /// </summary> public void ResetRaisedEvent() { _raisedEvent = null; _raisedAnyEvent = null; _raisedStatusEvent = null; _enteredAnyEventHandler = false; _enteredEventHandler = false; _enteredStatusEventHandler = false; } #endregion #region EventHandlers /// <summary> /// Do the test work for all of the event handlers. /// </summary> /// <param name="e">Event which was raised by an event source this class was listening to</param> private void HandleEvent(BuildEventArgs e) { _enteredEventHandler = true; _raisedEvent = e; if (_exceptionInHandlers != null) { throw _exceptionInHandlers; } } /// <summary> /// Handle a warning event /// </summary> /// <param name="sender">Who sent the event</param> /// <param name="e">Event raised on the event source</param> private void Source_WarningRaised(object sender, BuildWarningEventArgs e) { HandleEvent(e); } /// <summary> /// Handle a task started event /// </summary> /// <param name="sender">Who sent the event</param> /// <param name="e">Event raised on the event source</param> private void Source_TaskStarted(object sender, TaskStartedEventArgs e) { HandleEvent(e); } /// <summary> /// Handle a task finished event /// </summary> /// <param name="sender">Who sent the event</param> /// <param name="e">Event raised on the event source</param> private void Source_TaskFinished(object sender, TaskFinishedEventArgs e) { HandleEvent(e); } /// <summary> /// Handle a target started event /// </summary> /// <param name="sender">Who sent the event</param> /// <param name="e">Event raised on the event source</param> private void Source_TargetStarted(object sender, TargetStartedEventArgs e) { HandleEvent(e); } /// <summary> /// Handle a target finished event /// </summary> /// <param name="sender">Who sent the event</param> /// <param name="e">Event raised on the event source</param> private void Source_TargetFinished(object sender, TargetFinishedEventArgs e) { HandleEvent(e); } /// <summary> /// Handle a status event /// </summary> /// <param name="sender">Who sent the event</param> /// <param name="e">Event raised on the event source</param> private void Source_StatusEventRaised(object sender, BuildStatusEventArgs e) { _enteredStatusEventHandler = true; _raisedStatusEvent = e; if (_exceptionInHandlers != null) { throw _exceptionInHandlers; } } /// <summary> /// Handle a project started event /// </summary> /// <param name="sender">Who sent the event</param> /// <param name="e">Event raised on the event source</param> private void Source_ProjectStarted(object sender, ProjectStartedEventArgs e) { HandleEvent(e); } /// <summary> /// Handle a project finished event /// </summary> /// <param name="sender">Who sent the event</param> /// <param name="e">Event raised on the event source</param> private void Source_ProjectFinished(object sender, ProjectFinishedEventArgs e) { HandleEvent(e); } /// <summary> /// Handle a message event /// </summary> /// <param name="sender">Who sent the event</param> /// <param name="e">Event raised on the event source</param> private void Source_MessageRaised(object sender, BuildMessageEventArgs e) { HandleEvent(e); } /// <summary> /// Handle a error event /// </summary> /// <param name="sender">Who sent the event</param> /// <param name="e">Event raised on the event source</param> private void Source_ErrorRaised(object sender, BuildErrorEventArgs e) { HandleEvent(e); } /// <summary> /// Handle a custom event, these are mostly user created events /// </summary> /// <param name="sender">Who sent the event</param> /// <param name="e">Event raised on the event source</param> private void Source_CustomEventRaised(object sender, CustomBuildEventArgs e) { HandleEvent(e); } /// <summary> /// Handle a build started event /// </summary> /// <param name="sender">Who sent the event</param> /// <param name="e">Event raised on the event source</param> private void Source_BuildStarted(object sender, BuildStartedEventArgs e) { HandleEvent(e); } /// <summary> /// Handle a build finished event /// </summary> /// <param name="sender">Who sent the event</param> /// <param name="e">Event raised on the event source</param> private void Source_BuildFinished(object sender, BuildFinishedEventArgs e) { HandleEvent(e); } /// <summary> /// Handle a events raised from the any event source. This source will /// raise all events no matter the type. /// </summary> /// <param name="sender">Who sent the event</param> /// <param name="e">Event raised on the event source</param> private void Source_AnyEventRaised(object sender, BuildEventArgs e) { _enteredAnyEventHandler = true; _raisedAnyEvent = e; } #endregion } /// <summary> /// Helper for the test, this class has methods /// individual types of events or a set of all well known events. /// The Events can be raised in multiple tests. The helper class keeps the code cleaner /// by not having to instantiate new objects everywhere and /// all the fields are set in one place which makes it more maintainable /// </summary> internal class RaiseEventHelper { #region Data /// <summary> /// Build Started Event /// </summary> private static BuildStartedEventArgs s_buildStarted = new BuildStartedEventArgs("Message", "Help"); /// <summary> /// Generic Build Event /// </summary> private static GenericBuildEventArgs s_genericBuild = new GenericBuildEventArgs(); /// <summary> /// Generic Build Status Event /// </summary> private static GenericBuildStatusEventArgs s_genericBuildStatus = new GenericBuildStatusEventArgs(); /// <summary> /// Build Finished Event /// </summary> private static BuildFinishedEventArgs s_buildFinished = new BuildFinishedEventArgs("Message", "Keyword", true); /// <summary> /// Build Message Event /// </summary> private static BuildMessageEventArgs s_buildMessage = new BuildMessageEventArgs("Message2", "help", "sender", MessageImportance.Normal); /// <summary> /// Task Started Event /// </summary> private static TaskStartedEventArgs s_taskStarted = new TaskStartedEventArgs("message", "help", "projectFile", "taskFile", "taskName"); /// <summary> /// Task Finished Event /// </summary> private static TaskFinishedEventArgs s_taskFinished = new TaskFinishedEventArgs("message", "help", "projectFile", "taskFile", "taskName", true); /// <summary> /// Task Command Line Event /// </summary> private static TaskCommandLineEventArgs s_taskCommandLine = new TaskCommandLineEventArgs("commandLine", "taskName", MessageImportance.Low); /// <summary> /// Build Warning Event /// </summary> private static BuildWarningEventArgs s_buildWarning = new BuildWarningEventArgs("SubCategoryForSchemaValidationErrors", "MSB4000", "file", 1, 2, 3, 4, "message", "help", "sender") { BuildEventContext = new BuildEventContext(1, 2, 3, 4, 5, 6) }; /// <summary> /// Build Error Event /// </summary> private static BuildErrorEventArgs s_buildError = new BuildErrorEventArgs("SubCategoryForSchemaValidationErrors", "MSB4000", "file", 1, 2, 3, 4, "message", "help", "sender"); /// <summary> /// Target Started Event /// </summary> private static TargetStartedEventArgs s_targetStarted = new TargetStartedEventArgs("message", "help", "targetName", "ProjectFile", "targetFile"); /// <summary> /// Target Finished Event /// </summary> private static TargetFinishedEventArgs s_targetFinished = new TargetFinishedEventArgs("message", "help", "targetName", "ProjectFile", "targetFile", true); /// <summary> /// Project Started Event /// </summary> private static ProjectStartedEventArgs s_projectStarted = new ProjectStartedEventArgs(-1, "message", "help", "ProjectFile", "targetNames", null, null, null); /// <summary> /// Project Finished Event /// </summary> private static ProjectFinishedEventArgs s_projectFinished = new ProjectFinishedEventArgs("message", "help", "ProjectFile", true) { BuildEventContext = s_buildWarning.BuildEventContext }; /// <summary> /// External Project Started Event /// </summary> private static ExternalProjectStartedEventArgs s_externalProjectStarted = new ExternalProjectStartedEventArgs("message", "help", "senderName", "projectFile", "targetNames"); /// <summary> /// Event source on which the events will be raised. /// </summary> private EventSourceSink _sourceForEvents; #endregion #region Constructor /// <summary> /// Constructor /// </summary> /// <param name="eventSource">Event source on which the events will be raised</param> internal RaiseEventHelper(EventSourceSink eventSource) { _sourceForEvents = eventSource; } #endregion #region Properties /// <summary> /// Event which can be raised in multiple tests. /// </summary> internal static BuildStartedEventArgs BuildStarted { get { return s_buildStarted; } } /// <summary> /// Event which can be raised in multiple tests. /// </summary> internal static GenericBuildEventArgs GenericBuildEvent { get { return s_genericBuild; } } /// <summary> /// Event which can be raised in multiple tests. /// </summary> internal static GenericBuildStatusEventArgs GenericStatusEvent { get { return s_genericBuildStatus; } } /// <summary> /// Event which can be raised in multiple tests. /// </summary> internal static BuildFinishedEventArgs BuildFinished { get { return s_buildFinished; } } /// <summary> /// Event which can be raised in multiple tests. /// </summary> internal static BuildMessageEventArgs NormalMessage { get { return s_buildMessage; } } /// <summary> /// Event which can be raised in multiple tests. /// </summary> internal static TaskStartedEventArgs TaskStarted { get { return s_taskStarted; } } /// <summary> /// Event which can be raised in multiple tests. /// </summary> internal static TaskFinishedEventArgs TaskFinished { get { return s_taskFinished; } } /// <summary> /// Event which can be raised in multiple tests. /// </summary> internal static TaskCommandLineEventArgs CommandLine { get { return s_taskCommandLine; } } /// <summary> /// Event which can be raised in multiple tests. /// </summary> internal static BuildWarningEventArgs Warning { get { return s_buildWarning; } } /// <summary> /// Event which can be raised in multiple tests. /// </summary> internal static BuildErrorEventArgs Error { get { return s_buildError; } } /// <summary> /// Event which can be raised in multiple tests. /// </summary> internal static TargetStartedEventArgs TargetStarted { get { return s_targetStarted; } } /// <summary> /// Event which can be raised in multiple tests. /// </summary> internal static TargetFinishedEventArgs TargetFinished { get { return s_targetFinished; } } /// <summary> /// Event which can be raised in multiple tests. /// </summary> internal static ProjectStartedEventArgs ProjectStarted { get { return s_projectStarted; } } /// <summary> /// Event which can be raised in multiple tests. /// </summary> internal static ProjectFinishedEventArgs ProjectFinished { get { return s_projectFinished; } } /// <summary> /// Event which can be raised in multiple tests. /// </summary> internal static ExternalProjectStartedEventArgs ExternalStartedEvent { get { return s_externalProjectStarted; } } #endregion /// <summary> /// Raise a build event on the event source /// </summary> internal void RaiseBuildEvent(BuildEventArgs buildEvent) { _sourceForEvents.Consume(buildEvent); if (buildEvent is BuildStartedEventArgs) { Assert.True(_sourceForEvents.HaveLoggedBuildStartedEvent); _sourceForEvents.HaveLoggedBuildStartedEvent = false; Assert.False(_sourceForEvents.HaveLoggedBuildStartedEvent); } else if (buildEvent is BuildFinishedEventArgs) { Assert.True(_sourceForEvents.HaveLoggedBuildFinishedEvent); _sourceForEvents.HaveLoggedBuildFinishedEvent = false; Assert.False(_sourceForEvents.HaveLoggedBuildFinishedEvent); } } } #endregion #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editing { /// <summary> /// An editor for making changes to symbol source declarations. /// </summary> public sealed class SymbolEditor { private readonly Solution _originalSolution; private Solution _currentSolution; private SymbolEditor(Solution solution) { _originalSolution = solution; _currentSolution = solution; } /// <summary> /// Creates a new <see cref="SymbolEditor"/> instance. /// </summary> public static SymbolEditor Create(Solution solution) { if (solution == null) { throw new ArgumentNullException(nameof(solution)); } return new SymbolEditor(solution); } /// <summary> /// Creates a new <see cref="SymbolEditor"/> instance. /// </summary> public static SymbolEditor Create(Document document) { if (document == null) { throw new ArgumentNullException(nameof(document)); } return new SymbolEditor(document.Project.Solution); } /// <summary> /// The original solution. /// </summary> public Solution OriginalSolution { get { return _originalSolution; } } /// <summary> /// The solution with the edits applied. /// </summary> public Solution ChangedSolution { get { return _currentSolution; } } /// <summary> /// The documents changed since the <see cref="SymbolEditor"/> was constructed. /// </summary> public IEnumerable<Document> GetChangedDocuments() { var solutionChanges = _currentSolution.GetChanges(_originalSolution); foreach (var projectChanges in solutionChanges.GetProjectChanges()) { foreach (var id in projectChanges.GetAddedDocuments()) { yield return _currentSolution.GetDocument(id); } foreach (var id in projectChanges.GetChangedDocuments()) { yield return _currentSolution.GetDocument(id); } } foreach (var project in solutionChanges.GetAddedProjects()) { foreach (var id in project.DocumentIds) { yield return project.GetDocument(id); } } } /// <summary> /// Gets the current symbol for a source symbol. /// </summary> public async Task<ISymbol> GetCurrentSymbolAsync(ISymbol symbol, CancellationToken cancellationToken = default(CancellationToken)) { var symbolId = DocumentationCommentId.CreateDeclarationId(symbol); // check to see if symbol is from current solution var project = _currentSolution.GetProject(symbol.ContainingAssembly, cancellationToken); if (project != null) { return await GetSymbolAsync(_currentSolution, project.Id, symbolId, cancellationToken).ConfigureAwait(false); } // check to see if it is from original solution project = _originalSolution.GetProject(symbol.ContainingAssembly, cancellationToken); if (project != null) { return await GetSymbolAsync(_currentSolution, project.Id, symbolId, cancellationToken).ConfigureAwait(false); } // try to find symbol from any project (from current solution) with matching assembly name foreach (var projectId in this.GetProjectsForAssembly(symbol.ContainingAssembly)) { var currentSymbol = await GetSymbolAsync(_currentSolution, projectId, symbolId, cancellationToken).ConfigureAwait(false); if (currentSymbol != null) { return currentSymbol; } } return null; } private ImmutableDictionary<string, ImmutableArray<ProjectId>> _assemblyNameToProjectIdMap; private ImmutableArray<ProjectId> GetProjectsForAssembly(IAssemblySymbol assembly) { if (_assemblyNameToProjectIdMap == null) { _assemblyNameToProjectIdMap = _originalSolution.Projects .ToLookup(p => p.AssemblyName, p => p.Id) .ToImmutableDictionary(g => g.Key, g => ImmutableArray.CreateRange(g)); } ImmutableArray<ProjectId> projectIds; if (!_assemblyNameToProjectIdMap.TryGetValue(assembly.Name, out projectIds)) { projectIds = ImmutableArray<ProjectId>.Empty; } return projectIds; } private async Task<ISymbol> GetSymbolAsync(Solution solution, ProjectId projectId, string symbolId, CancellationToken cancellationToken) { var comp = await solution.GetProject(projectId).GetCompilationAsync(cancellationToken).ConfigureAwait(false); var symbols = DocumentationCommentId.GetSymbolsForDeclarationId(symbolId, comp).ToList(); if (symbols.Count == 1) { return symbols[0]; } else if (symbols.Count > 1) { #if false // if we have multiple matches, use the same index that it appeared as in the original solution. var originalComp = await this.originalSolution.GetProject(projectId).GetCompilationAsync(cancellationToken).ConfigureAwait(false); var originalSymbols = DocumentationCommentId.GetSymbolsForDeclarationId(symbolId, originalComp).ToList(); var index = originalSymbols.IndexOf(originalSymbol); if (index >= 0 && index <= symbols.Count) { return symbols[index]; } #else return symbols[0]; #endif } return null; } /// <summary> /// Gets the current declarations for the specified symbol. /// </summary> public async Task<IReadOnlyList<SyntaxNode>> GetCurrentDeclarationsAsync(ISymbol symbol, CancellationToken cancellationToken = default(CancellationToken)) { var currentSymbol = await this.GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false); return this.GetDeclarations(currentSymbol).ToImmutableReadOnlyListOrEmpty(); } /// <summary> /// Gets the declaration syntax nodes for a given symbol. /// </summary> private IEnumerable<SyntaxNode> GetDeclarations(ISymbol symbol) { return symbol.DeclaringSyntaxReferences .Select(sr => sr.GetSyntax()) .Select(n => SyntaxGenerator.GetGenerator(_originalSolution.Workspace, n.Language).GetDeclaration(n)) .Where(d => d != null); } /// <summary> /// Gets the best declaration node for adding members. /// </summary> private bool TryGetBestDeclarationForSingleEdit(ISymbol symbol, out SyntaxNode declaration) { declaration = GetDeclarations(symbol).FirstOrDefault(); return declaration != null; } /// <summary> /// An action that make changes to a declaration node within a <see cref="SyntaxTree"/>. /// </summary> /// <param name="editor">The <see cref="DocumentEditor"/> to apply edits to.</param> /// <param name="declaration">The declaration to edit.</param> /// <returns></returns> public delegate void DeclarationEditAction(DocumentEditor editor, SyntaxNode declaration); /// <summary> /// An action that make changes to a declaration node within a <see cref="SyntaxTree"/>. /// </summary> /// <param name="editor">The <see cref="DocumentEditor"/> to apply edits to.</param> /// <param name="declaration">The declaration to edit.</param> /// <param name="cancellationToken">A cancellation token.</param> /// <returns></returns> public delegate Task AsyncDeclarationEditAction(DocumentEditor editor, SyntaxNode declaration, CancellationToken cancellationToken); /// <summary> /// Enables editing the definition of one of the symbol's declarations. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to edit.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public async Task<ISymbol> EditOneDeclarationAsync( ISymbol symbol, AsyncDeclarationEditAction editAction, CancellationToken cancellationToken = default(CancellationToken)) { var currentSymbol = await this.GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false); CheckSymbolArgument(currentSymbol, symbol); SyntaxNode declaration; if (TryGetBestDeclarationForSingleEdit(currentSymbol, out declaration)) { return await this.EditDeclarationAsync(currentSymbol, declaration, editAction, cancellationToken).ConfigureAwait(false); } return null; } /// <summary> /// Enables editing the definition of one of the symbol's declarations. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to edit.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public Task<ISymbol> EditOneDeclarationAsync( ISymbol symbol, DeclarationEditAction editAction, CancellationToken cancellationToken = default(CancellationToken)) { return this.EditOneDeclarationAsync( symbol, (e, d, c) => { editAction(e, d); return SpecializedTasks.EmptyTask; }, cancellationToken); } private void CheckSymbolArgument(ISymbol currentSymbol, ISymbol argSymbol) { if (currentSymbol == null) { throw new ArgumentException(string.Format(WorkspacesResources.The_symbol_0_cannot_be_located_within_the_current_solution, argSymbol.Name)); } } private async Task<ISymbol> EditDeclarationAsync( ISymbol currentSymbol, SyntaxNode declaration, AsyncDeclarationEditAction editAction, CancellationToken cancellationToken) { var doc = _currentSolution.GetDocument(declaration.SyntaxTree); var editor = await DocumentEditor.CreateAsync(doc, cancellationToken).ConfigureAwait(false); editor.TrackNode(declaration); await editAction(editor, declaration, cancellationToken).ConfigureAwait(false); var newDoc = editor.GetChangedDocument(); _currentSolution = newDoc.Project.Solution; // try to find new symbol by looking up via original declaration var model = await newDoc.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var newDeclaration = model.SyntaxTree.GetRoot(cancellationToken).GetCurrentNode(declaration); if (newDeclaration != null) { var newSymbol = model.GetDeclaredSymbol(newDeclaration, cancellationToken); if (newSymbol != null) { return newSymbol; } } // otherwise fallback to rebinding with original symbol return await this.GetCurrentSymbolAsync(currentSymbol, cancellationToken).ConfigureAwait(false); } /// <summary> /// Enables editing the definition of one of the symbol's declarations. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to edit.</param> /// <param name="location">A location within one of the symbol's declarations.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public async Task<ISymbol> EditOneDeclarationAsync( ISymbol symbol, Location location, AsyncDeclarationEditAction editAction, CancellationToken cancellationToken = default(CancellationToken)) { var sourceTree = location.SourceTree; var doc = _currentSolution.GetDocument(sourceTree); if (doc != null) { return await this.EditOneDeclarationAsync(symbol, doc.Id, location.SourceSpan.Start, editAction, cancellationToken).ConfigureAwait(false); } doc = _originalSolution.GetDocument(sourceTree); if (doc != null) { return await this.EditOneDeclarationAsync(symbol, doc.Id, location.SourceSpan.Start, editAction, cancellationToken).ConfigureAwait(false); } throw new ArgumentException("The location specified is not part of the solution.", nameof(location)); } /// <summary> /// Enables editing the definition of one of the symbol's declarations. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to edit.</param> /// <param name="location">A location within one of the symbol's declarations.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public Task<ISymbol> EditOneDeclarationAsync( ISymbol symbol, Location location, DeclarationEditAction editAction, CancellationToken cancellationToken = default(CancellationToken)) { return this.EditOneDeclarationAsync( symbol, location, (e, d, c) => { editAction(e, d); return SpecializedTasks.EmptyTask; }, cancellationToken); } private async Task<ISymbol> EditOneDeclarationAsync( ISymbol symbol, DocumentId documentId, int position, AsyncDeclarationEditAction editAction, CancellationToken cancellationToken = default(CancellationToken)) { var currentSymbol = await this.GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false); CheckSymbolArgument(currentSymbol, symbol); var decl = this.GetDeclarations(currentSymbol).FirstOrDefault(d => { var doc = _currentSolution.GetDocument(d.SyntaxTree); return doc != null && doc.Id == documentId && d.FullSpan.IntersectsWith(position); }); if (decl == null) { throw new ArgumentNullException(WorkspacesResources.The_position_is_not_within_the_symbol_s_declaration, nameof(position)); } return await this.EditDeclarationAsync(currentSymbol, decl, editAction, cancellationToken).ConfigureAwait(false); } /// <summary> /// Enables editing the symbol's declaration where the member is also declared. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to edit.</param> /// <param name="member">A symbol whose declaration is contained within one of the primary symbol's declarations.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public async Task<ISymbol> EditOneDeclarationAsync( ISymbol symbol, ISymbol member, AsyncDeclarationEditAction editAction, CancellationToken cancellationToken = default(CancellationToken)) { var currentSymbol = await this.GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false); CheckSymbolArgument(currentSymbol, symbol); var currentMember = await this.GetCurrentSymbolAsync(member, cancellationToken).ConfigureAwait(false); CheckSymbolArgument(currentMember, member); // get first symbol declaration that encompasses at least one of the member declarations var memberDecls = this.GetDeclarations(currentMember).ToList(); var declaration = this.GetDeclarations(currentSymbol).FirstOrDefault(d => memberDecls.Any(md => md.SyntaxTree == d.SyntaxTree && d.FullSpan.IntersectsWith(md.FullSpan))); if (declaration == null) { throw new ArgumentException(string.Format(WorkspacesResources.The_member_0_is_not_declared_within_the_declaration_of_the_symbol, member.Name)); } return await this.EditDeclarationAsync(currentSymbol, declaration, editAction, cancellationToken).ConfigureAwait(false); } /// <summary> /// Enables editing the symbol's declaration where the member is also declared. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to edit.</param> /// <param name="member">A symbol whose declaration is contained within one of the primary symbol's declarations.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public Task<ISymbol> EditOneDeclarationAsync( ISymbol symbol, ISymbol member, DeclarationEditAction editAction, CancellationToken cancellationToken = default(CancellationToken)) { return this.EditOneDeclarationAsync( symbol, member, (e, d, c) => { editAction(e, d); return SpecializedTasks.EmptyTask; }, cancellationToken); } /// <summary> /// Enables editing all the symbol's declarations. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to be edited.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public async Task<ISymbol> EditAllDeclarationsAsync( ISymbol symbol, AsyncDeclarationEditAction editAction, CancellationToken cancellationToken = default(CancellationToken)) { var currentSymbol = await this.GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false); CheckSymbolArgument(currentSymbol, symbol); var declsByDocId = this.GetDeclarations(currentSymbol).ToLookup(d => _currentSolution.GetDocument(d.SyntaxTree).Id); var solutionEditor = new SolutionEditor(_currentSolution); foreach (var declGroup in declsByDocId) { var docId = declGroup.Key; var editor = await solutionEditor.GetDocumentEditorAsync(docId, cancellationToken).ConfigureAwait(false); foreach (var decl in declGroup) { editor.TrackNode(decl); // ensure the declaration gets tracked await editAction(editor, decl, cancellationToken).ConfigureAwait(false); } } _currentSolution = solutionEditor.GetChangedSolution(); // try to find new symbol by looking up via original declarations foreach (var declGroup in declsByDocId) { var doc = _currentSolution.GetDocument(declGroup.Key); var model = await doc.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); foreach (var decl in declGroup) { var newDeclaration = model.SyntaxTree.GetRoot(cancellationToken).GetCurrentNode(decl); if (newDeclaration != null) { var newSymbol = model.GetDeclaredSymbol(newDeclaration); if (newSymbol != null) { return newSymbol; } } } } // otherwise fallback to rebinding with original symbol return await GetCurrentSymbolAsync(symbol, cancellationToken).ConfigureAwait(false); } /// <summary> /// Enables editing all the symbol's declarations. /// Partial types and methods may have more than one declaration. /// </summary> /// <param name="symbol">The symbol to be edited.</param> /// <param name="editAction">The action that makes edits to the declaration.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/>.</param> /// <returns>The new symbol including the changes.</returns> public Task<ISymbol> EditAllDeclarationsAsync( ISymbol symbol, DeclarationEditAction editAction, CancellationToken cancellationToken = default(CancellationToken)) { return this.EditAllDeclarationsAsync( symbol, (e, d, c) => { editAction(e, d); return SpecializedTasks.EmptyTask; }, cancellationToken); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Net.Http; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.OperationalInsights; namespace Microsoft.Azure.Management.OperationalInsights { /// <summary> /// .Net client wrapper for the REST API for Azure Operational Insights /// </summary> public partial class OperationalInsightsManagementClient : ServiceClient<OperationalInsightsManagementClient>, IOperationalInsightsManagementClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private IDataSourceOperations _dataSources; /// <summary> /// Operations for managing data sources under Workspaces. /// </summary> public virtual IDataSourceOperations DataSources { get { return this._dataSources; } } private ISearchOperations _search; /// <summary> /// Operations for using Operational Insights search. /// </summary> public virtual ISearchOperations Search { get { return this._search; } } private IStorageInsightOperations _storageInsights; /// <summary> /// Operations for managing storage insights. /// </summary> public virtual IStorageInsightOperations StorageInsights { get { return this._storageInsights; } } private IWorkspaceOperations _workspaces; /// <summary> /// Operations for managing Operational Insights workspaces. /// </summary> public virtual IWorkspaceOperations Workspaces { get { return this._workspaces; } } /// <summary> /// Initializes a new instance of the /// OperationalInsightsManagementClient class. /// </summary> public OperationalInsightsManagementClient() : base() { this._dataSources = new DataSourceOperations(this); this._search = new SearchOperations(this); this._storageInsights = new StorageInsightOperations(this); this._workspaces = new WorkspaceOperations(this); this._apiVersion = "2015-03-20"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(120); } /// <summary> /// Initializes a new instance of the /// OperationalInsightsManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> public OperationalInsightsManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the /// OperationalInsightsManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> public OperationalInsightsManagementClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the /// OperationalInsightsManagementClient class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> public OperationalInsightsManagementClient(HttpClient httpClient) : base(httpClient) { this._dataSources = new DataSourceOperations(this); this._search = new SearchOperations(this); this._storageInsights = new StorageInsightOperations(this); this._workspaces = new WorkspaceOperations(this); this._apiVersion = "2015-03-20"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(120); } /// <summary> /// Initializes a new instance of the /// OperationalInsightsManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public OperationalInsightsManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the /// OperationalInsightsManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public OperationalInsightsManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// OperationalInsightsManagementClient instance /// </summary> /// <param name='client'> /// Instance of OperationalInsightsManagementClient to clone to /// </param> protected override void Clone(ServiceClient<OperationalInsightsManagementClient> client) { base.Clone(client); if (client is OperationalInsightsManagementClient) { OperationalInsightsManagementClient clonedClient = ((OperationalInsightsManagementClient)client); clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } } }
// 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; namespace System.ServiceModel.Dispatcher { public sealed class DispatchOperation { private readonly string _action; private readonly SynchronizedCollection<FaultContractInfo> _faultContractInfos; private IDispatchMessageFormatter _formatter; private IDispatchFaultFormatter _faultFormatter; private IOperationInvoker _invoker; private bool _isSessionOpenNotificationEnabled; private readonly string _name; private readonly SynchronizedCollection<IParameterInspector> _parameterInspectors; private readonly DispatchRuntime _parent; private readonly string _replyAction; private bool _deserializeRequest = true; private bool _serializeReply = true; private readonly bool _isOneWay; private bool _autoDisposeParameters = true; private bool _hasNoDisposableParameters; private bool _isFaultFormatterSetExplicit; public DispatchOperation(DispatchRuntime parent, string name, string action) { if (parent == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parent"); if (name == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("name"); _parent = parent; _name = name; _action = action; _faultContractInfos = parent.NewBehaviorCollection<FaultContractInfo>(); _parameterInspectors = parent.NewBehaviorCollection<IParameterInspector>(); _isOneWay = true; } public DispatchOperation(DispatchRuntime parent, string name, string action, string replyAction) : this(parent, name, action) { _replyAction = replyAction; _isOneWay = false; } public bool IsOneWay { get { return _isOneWay; } } public string Action { get { return _action; } } public SynchronizedCollection<FaultContractInfo> FaultContractInfos { get { return _faultContractInfos; } } public bool AutoDisposeParameters { get { return _autoDisposeParameters; } set { lock (_parent.ThisLock) { _parent.InvalidateRuntime(); _autoDisposeParameters = value; } } } internal IDispatchMessageFormatter Formatter { get { return _formatter; } set { lock (_parent.ThisLock) { _parent.InvalidateRuntime(); _formatter = value; } } } internal IDispatchFaultFormatter FaultFormatter { get { if (_faultFormatter == null) { _faultFormatter = new DataContractSerializerFaultFormatter(_faultContractInfos); } return _faultFormatter; } set { lock (_parent.ThisLock) { _parent.InvalidateRuntime(); _faultFormatter = value; _isFaultFormatterSetExplicit = true; } } } internal bool IsFaultFormatterSetExplicit { get { return _isFaultFormatterSetExplicit; } } internal bool HasNoDisposableParameters { get { return _hasNoDisposableParameters; } set { _hasNoDisposableParameters = value; } } internal IDispatchMessageFormatter InternalFormatter { get { return _formatter; } set { _formatter = value; } } internal IOperationInvoker InternalInvoker { get { return _invoker; } set { _invoker = value; } } public IOperationInvoker Invoker { get { return _invoker; } set { lock (_parent.ThisLock) { _parent.InvalidateRuntime(); _invoker = value; } } } internal bool IsSessionOpenNotificationEnabled { get { return _isSessionOpenNotificationEnabled; } set { lock (_parent.ThisLock) { _parent.InvalidateRuntime(); _isSessionOpenNotificationEnabled = value; } } } public string Name { get { return _name; } } public SynchronizedCollection<IParameterInspector> ParameterInspectors { get { return _parameterInspectors; } } public DispatchRuntime Parent { get { return _parent; } } public string ReplyAction { get { return _replyAction; } } public bool DeserializeRequest { get { return _deserializeRequest; } set { lock (_parent.ThisLock) { _parent.InvalidateRuntime(); _deserializeRequest = value; } } } public bool SerializeReply { get { return _serializeReply; } set { lock (_parent.ThisLock) { _parent.InvalidateRuntime(); _serializeReply = value; } } } } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Cluster.Codecs { public class ConsensusModuleEncoder { public const ushort BLOCK_LENGTH = 28; public const ushort TEMPLATE_ID = 105; public const ushort SCHEMA_ID = 111; public const ushort SCHEMA_VERSION = 7; private ConsensusModuleEncoder _parentMessage; private IMutableDirectBuffer _buffer; protected int _offset; protected int _limit; public ConsensusModuleEncoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IMutableDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public ConsensusModuleEncoder Wrap(IMutableDirectBuffer buffer, int offset) { this._buffer = buffer; this._offset = offset; Limit(offset + BLOCK_LENGTH); return this; } public ConsensusModuleEncoder WrapAndApplyHeader( IMutableDirectBuffer buffer, int offset, MessageHeaderEncoder headerEncoder) { headerEncoder .Wrap(buffer, offset) .BlockLength(BLOCK_LENGTH) .TemplateId(TEMPLATE_ID) .SchemaId(SCHEMA_ID) .Version(SCHEMA_VERSION); return Wrap(buffer, offset + MessageHeaderEncoder.ENCODED_LENGTH); } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int NextSessionIdEncodingOffset() { return 0; } public static int NextSessionIdEncodingLength() { return 8; } public static long NextSessionIdNullValue() { return -9223372036854775808L; } public static long NextSessionIdMinValue() { return -9223372036854775807L; } public static long NextSessionIdMaxValue() { return 9223372036854775807L; } public ConsensusModuleEncoder NextSessionId(long value) { _buffer.PutLong(_offset + 0, value, ByteOrder.LittleEndian); return this; } public static int NextServiceSessionIdEncodingOffset() { return 8; } public static int NextServiceSessionIdEncodingLength() { return 8; } public static long NextServiceSessionIdNullValue() { return -9223372036854775808L; } public static long NextServiceSessionIdMinValue() { return -9223372036854775807L; } public static long NextServiceSessionIdMaxValue() { return 9223372036854775807L; } public ConsensusModuleEncoder NextServiceSessionId(long value) { _buffer.PutLong(_offset + 8, value, ByteOrder.LittleEndian); return this; } public static int LogServiceSessionIdEncodingOffset() { return 16; } public static int LogServiceSessionIdEncodingLength() { return 8; } public static long LogServiceSessionIdNullValue() { return -9223372036854775808L; } public static long LogServiceSessionIdMinValue() { return -9223372036854775807L; } public static long LogServiceSessionIdMaxValue() { return 9223372036854775807L; } public ConsensusModuleEncoder LogServiceSessionId(long value) { _buffer.PutLong(_offset + 16, value, ByteOrder.LittleEndian); return this; } public static int PendingMessageCapacityEncodingOffset() { return 24; } public static int PendingMessageCapacityEncodingLength() { return 4; } public static int PendingMessageCapacityNullValue() { return 0; } public static int PendingMessageCapacityMinValue() { return -2147483647; } public static int PendingMessageCapacityMaxValue() { return 2147483647; } public ConsensusModuleEncoder PendingMessageCapacity(int value) { _buffer.PutInt(_offset + 24, value, ByteOrder.LittleEndian); return this; } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { ConsensusModuleDecoder writer = new ConsensusModuleDecoder(); writer.Wrap(_buffer, _offset, BLOCK_LENGTH, SCHEMA_VERSION); return writer.AppendTo(builder); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Numerics; using System.Linq; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp { /// <summary> /// A vector of type T with 2 components. /// </summary> [Serializable] [DataContract(Namespace = "vec")] [StructLayout(LayoutKind.Sequential)] public struct gvec2<T> : IReadOnlyList<T>, IEquatable<gvec2<T>> { #region Fields /// <summary> /// x-component /// </summary> [DataMember] public T x; /// <summary> /// y-component /// </summary> [DataMember] public T y; #endregion #region Constructors /// <summary> /// Component-wise constructor /// </summary> public gvec2(T x, T y) { this.x = x; this.y = y; } /// <summary> /// all-same-value constructor /// </summary> public gvec2(T v) { this.x = v; this.y = v; } /// <summary> /// from-vector constructor /// </summary> public gvec2(gvec2<T> v) { this.x = v.x; this.y = v.y; } /// <summary> /// from-vector constructor (additional fields are truncated) /// </summary> public gvec2(gvec3<T> v) { this.x = v.x; this.y = v.y; } /// <summary> /// from-vector constructor (additional fields are truncated) /// </summary> public gvec2(gvec4<T> v) { this.x = v.x; this.y = v.y; } /// <summary> /// From-array/list constructor (superfluous values are ignored, missing values are zero-filled). /// </summary> public gvec2(IReadOnlyList<T> v) { var c = v.Count; this.x = c < 0 ? default(T) : v[0]; this.y = c < 1 ? default(T) : v[1]; } /// <summary> /// Generic from-array constructor (superfluous values are ignored, missing values are zero-filled). /// </summary> public gvec2(Object[] v) { var c = v.Length; this.x = c < 0 ? default(T) : (T)v[0]; this.y = c < 1 ? default(T) : (T)v[1]; } /// <summary> /// From-array constructor (superfluous values are ignored, missing values are zero-filled). /// </summary> public gvec2(T[] v) { var c = v.Length; this.x = c < 0 ? default(T) : v[0]; this.y = c < 1 ? default(T) : v[1]; } /// <summary> /// From-array constructor with base index (superfluous values are ignored, missing values are zero-filled). /// </summary> public gvec2(T[] v, int startIndex) { var c = v.Length; this.x = c + startIndex < 0 ? default(T) : v[0 + startIndex]; this.y = c + startIndex < 1 ? default(T) : v[1 + startIndex]; } /// <summary> /// From-IEnumerable constructor (superfluous values are ignored, missing values are zero-filled). /// </summary> public gvec2(IEnumerable<T> v) : this(v.ToArray()) { } #endregion #region Explicit Operators /// <summary> /// Explicitly converts this to a gvec3. (Higher components are zeroed) /// </summary> public static explicit operator gvec3<T>(gvec2<T> v) => new gvec3<T>((T)v.x, (T)v.y, default(T)); /// <summary> /// Explicitly converts this to a gvec4. (Higher components are zeroed) /// </summary> public static explicit operator gvec4<T>(gvec2<T> v) => new gvec4<T>((T)v.x, (T)v.y, default(T), default(T)); /// <summary> /// Explicitly converts this to a T array. /// </summary> public static explicit operator T[](gvec2<T> v) => new [] { v.x, v.y }; /// <summary> /// Explicitly converts this to a generic object array. /// </summary> public static explicit operator Object[](gvec2<T> v) => new Object[] { v.x, v.y }; #endregion #region Indexer /// <summary> /// Gets/Sets a specific indexed component (a bit slower than direct access). /// </summary> public T this[int index] { get { switch (index) { case 0: return x; case 1: return y; default: throw new ArgumentOutOfRangeException("index"); } } set { switch (index) { case 0: x = value; break; case 1: y = value; break; default: throw new ArgumentOutOfRangeException("index"); } } } #endregion #region Properties /// <summary> /// Returns an object that can be used for arbitrary swizzling (e.g. swizzle.zy) /// </summary> public swizzle_gvec2<T> swizzle => new swizzle_gvec2<T>(x, y); /// <summary> /// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property. /// </summary> public gvec2<T> xy { get { return new gvec2<T>(x, y); } set { x = value.x; y = value.y; } } /// <summary> /// Gets or sets the specified subset of components. For more advanced (read-only) swizzling, use the .swizzle property. /// </summary> public gvec2<T> rg { get { return new gvec2<T>(x, y); } set { x = value.x; y = value.y; } } /// <summary> /// Gets or sets the specified RGBA component. For more advanced (read-only) swizzling, use the .swizzle property. /// </summary> public T r { get { return x; } set { x = value; } } /// <summary> /// Gets or sets the specified RGBA component. For more advanced (read-only) swizzling, use the .swizzle property. /// </summary> public T g { get { return y; } set { y = value; } } /// <summary> /// Returns an array with all values /// </summary> public T[] Values => new[] { x, y }; /// <summary> /// Returns the number of components (2). /// </summary> public int Count => 2; #endregion #region Static Properties /// <summary> /// Predefined all-zero vector /// </summary> public static gvec2<T> Zero { get; } = new gvec2<T>(default(T), default(T)); #endregion #region Operators /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public static bool operator==(gvec2<T> lhs, gvec2<T> rhs) => lhs.Equals(rhs); /// <summary> /// Returns true iff this does not equal rhs (component-wise). /// </summary> public static bool operator!=(gvec2<T> lhs, gvec2<T> rhs) => !lhs.Equals(rhs); #endregion #region Functions /// <summary> /// Returns an enumerator that iterates through all components. /// </summary> public IEnumerator<T> GetEnumerator() { yield return x; yield return y; } /// <summary> /// Returns an enumerator that iterates through all components. /// </summary> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); /// <summary> /// Returns a string representation of this vector using ', ' as a seperator. /// </summary> public override string ToString() => ToString(", "); /// <summary> /// Returns a string representation of this vector using a provided seperator. /// </summary> public string ToString(string sep) => (x + sep + y); /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public bool Equals(gvec2<T> rhs) => (EqualityComparer<T>.Default.Equals(x, rhs.x) && EqualityComparer<T>.Default.Equals(y, rhs.y)); /// <summary> /// Returns true iff this equals rhs type- and component-wise. /// </summary> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is gvec2<T> && Equals((gvec2<T>) obj); } /// <summary> /// Returns a hash code for this instance. /// </summary> public override int GetHashCode() { unchecked { return ((EqualityComparer<T>.Default.GetHashCode(x)) * 397) ^ EqualityComparer<T>.Default.GetHashCode(y); } } #endregion #region Component-Wise Static Functions /// <summary> /// Returns a bvec2 from component-wise application of Equal (EqualityComparer&lt;T&gt;.Default.Equals(lhs, rhs)). /// </summary> public static bvec2 Equal(gvec2<T> lhs, gvec2<T> rhs) => new bvec2(EqualityComparer<T>.Default.Equals(lhs.x, rhs.x), EqualityComparer<T>.Default.Equals(lhs.y, rhs.y)); /// <summary> /// Returns a bvec2 from component-wise application of Equal (EqualityComparer&lt;T&gt;.Default.Equals(lhs, rhs)). /// </summary> public static bvec2 Equal(gvec2<T> lhs, T rhs) => new bvec2(EqualityComparer<T>.Default.Equals(lhs.x, rhs), EqualityComparer<T>.Default.Equals(lhs.y, rhs)); /// <summary> /// Returns a bvec2 from component-wise application of Equal (EqualityComparer&lt;T&gt;.Default.Equals(lhs, rhs)). /// </summary> public static bvec2 Equal(T lhs, gvec2<T> rhs) => new bvec2(EqualityComparer<T>.Default.Equals(lhs, rhs.x), EqualityComparer<T>.Default.Equals(lhs, rhs.y)); /// <summary> /// Returns a bvec from the application of Equal (EqualityComparer&lt;T&gt;.Default.Equals(lhs, rhs)). /// </summary> public static bvec2 Equal(T lhs, T rhs) => new bvec2(EqualityComparer<T>.Default.Equals(lhs, rhs)); /// <summary> /// Returns a bvec2 from component-wise application of NotEqual (!EqualityComparer&lt;T&gt;.Default.Equals(lhs, rhs)). /// </summary> public static bvec2 NotEqual(gvec2<T> lhs, gvec2<T> rhs) => new bvec2(!EqualityComparer<T>.Default.Equals(lhs.x, rhs.x), !EqualityComparer<T>.Default.Equals(lhs.y, rhs.y)); /// <summary> /// Returns a bvec2 from component-wise application of NotEqual (!EqualityComparer&lt;T&gt;.Default.Equals(lhs, rhs)). /// </summary> public static bvec2 NotEqual(gvec2<T> lhs, T rhs) => new bvec2(!EqualityComparer<T>.Default.Equals(lhs.x, rhs), !EqualityComparer<T>.Default.Equals(lhs.y, rhs)); /// <summary> /// Returns a bvec2 from component-wise application of NotEqual (!EqualityComparer&lt;T&gt;.Default.Equals(lhs, rhs)). /// </summary> public static bvec2 NotEqual(T lhs, gvec2<T> rhs) => new bvec2(!EqualityComparer<T>.Default.Equals(lhs, rhs.x), !EqualityComparer<T>.Default.Equals(lhs, rhs.y)); /// <summary> /// Returns a bvec from the application of NotEqual (!EqualityComparer&lt;T&gt;.Default.Equals(lhs, rhs)). /// </summary> public static bvec2 NotEqual(T lhs, T rhs) => new bvec2(!EqualityComparer<T>.Default.Equals(lhs, rhs)); #endregion } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNet.Mvc; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Text; using Microsoft.Framework.Logging; using OmniSharp.Models.V2; using OmniSharp.Services; namespace OmniSharp.Api.V2 { public class CodeActionController { private readonly OmnisharpWorkspace _workspace; private readonly IEnumerable<ICodeActionProvider> _codeActionProviders; private Document _originalDocument; private readonly ILogger _logger; public CodeActionController(OmnisharpWorkspace workspace, IEnumerable<ICodeActionProvider> providers, ILoggerFactory loggerFactory) { _workspace = workspace; _codeActionProviders = providers; _logger = loggerFactory.CreateLogger<CodeActionController>(); } [HttpPost("v2/getcodeactions")] public async Task<GetCodeActionsResponse> GetCodeActions(GetCodeActionsRequest request) { var actions = await GetActions(request); return new GetCodeActionsResponse { CodeActions = actions.Select(a => new OmniSharpCodeAction(a.GetIdentifier(), a.Title)) }; } [HttpPost("v2/runcodeaction")] public async Task<RunCodeActionResponse> RunCodeAction(RunCodeActionRequest request) { var actions = await GetActions(request); var action = actions.FirstOrDefault(a => a.GetIdentifier().Equals(request.Identifier)); if (action == null) { return new RunCodeActionResponse(); } _logger.LogInformation("Applying " + action); var operations = await action.GetOperationsAsync(CancellationToken.None); var solution = _workspace.CurrentSolution; foreach (var o in operations) { o.Apply(_workspace, CancellationToken.None); } var response = new RunCodeActionResponse(); var directoryName = Path.GetDirectoryName(request.FileName); var changes = await FileChanges.GetFileChangesAsync(_workspace.CurrentSolution, solution, directoryName, request.WantsTextChanges); response.Changes = changes; _workspace.TryApplyChanges(_workspace.CurrentSolution); return response; } private async Task<IEnumerable<CodeAction>> GetActions(ICodeActionRequest request) { var actions = new List<CodeAction>(); _originalDocument = _workspace.GetDocument(request.FileName); if (_originalDocument == null) { return actions; } var refactoringContext = await GetRefactoringContext(request, actions); var codeFixContext = await GetCodeFixContext(request, actions); await CollectRefactoringActions(refactoringContext); await CollectCodeFixActions(codeFixContext); actions.Reverse(); return actions; } private async Task<CodeRefactoringContext?> GetRefactoringContext(ICodeActionRequest request, List<CodeAction> actionsDestination) { var sourceText = await _originalDocument.GetTextAsync(); var location = GetTextSpan(request, sourceText); return new CodeRefactoringContext(_originalDocument, location, (a) => actionsDestination.Add(a), CancellationToken.None); } private async Task<CodeFixContext?> GetCodeFixContext(ICodeActionRequest request, List<CodeAction> actionsDestination) { var sourceText = await _originalDocument.GetTextAsync(); var semanticModel = await _originalDocument.GetSemanticModelAsync(); var diagnostics = semanticModel.GetDiagnostics(); var location = GetTextSpan(request, sourceText); var pointDiagnostics = diagnostics.Where(d => d.Location.SourceSpan.Contains(location)).ToImmutableArray(); if (pointDiagnostics.Any()) { return new CodeFixContext(_originalDocument, pointDiagnostics.First().Location.SourceSpan, pointDiagnostics, (a, d) => actionsDestination.Add(a), CancellationToken.None); } return null; } private static TextSpan GetTextSpan(ICodeActionRequest request, SourceText sourceText) { if (request.Selection != null) { var startPosition = sourceText.Lines.GetPosition(new LinePosition(request.Selection.Start.Line - 1, request.Selection.Start.Column - 1)); var endPosition = sourceText.Lines.GetPosition(new LinePosition(request.Selection.End.Line - 1, request.Selection.End.Column - 1)); return TextSpan.FromBounds(startPosition, endPosition); } var position = sourceText.Lines.GetPosition(new LinePosition(request.Line - 1, request.Column - 1)); return new TextSpan(position, 1); } private static readonly HashSet<string> _blacklist = new HashSet<string> { // This list is horrible but will be temporary "Microsoft.CodeAnalysis.CSharp.CodeFixes.AddMissingReference.AddMissingReferenceCodeFixProvider", "Microsoft.CodeAnalysis.CSharp.CodeFixes.Async.CSharpConvertToAsyncMethodCodeFixProvider", "Microsoft.CodeAnalysis.CSharp.CodeFixes.Iterator.CSharpChangeToIEnumerableCodeFixProvider", "Microsoft.CodeAnalysis.CSharp.CodeRefactorings.ChangeSignature.ChangeSignatureCodeRefactoringProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CreateMethodDeclarationAction", "ICSharpCode.NRefactory6.CSharp.Refactoring.UseStringFormatAction", "ICSharpCode.NRefactory6.CSharp.Refactoring.UseAsAndNullCheckAction", "ICSharpCode.NRefactory6.CSharp.Refactoring.SplitStringAction", "ICSharpCode.NRefactory6.CSharp.Refactoring.SplitIfAction", "ICSharpCode.NRefactory6.CSharp.Refactoring.SplitDeclarationListAction", "ICSharpCode.NRefactory6.CSharp.Refactoring.SplitDeclarationAndAssignmentAction", "ICSharpCode.NRefactory6.CSharp.Refactoring.SimplifyIfInLoopsFlowAction", "ICSharpCode.NRefactory6.CSharp.Refactoring.SimplifyIfFlowAction", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReverseDirectionForForLoopAction", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithOperatorAssignmentAction", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantCaseLabelFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.LocalVariableNotUsedFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.PartialTypeWithSinglePartFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantBaseConstructorCallFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantDefaultFieldInitializerFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantOverridenMemberFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantParamsFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.UnusedLabelFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.UnusedParameterFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ConstantNullCoalescingConditionFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantArgumentDefaultValueFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantBoolCompareFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantCatchClauseFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantCheckBeforeAssignmentFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantCommaInArrayInitializerFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantComparisonWithNullFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantDelegateCreationFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantEmptyFinallyBlockFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantEnumerableCastCallFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantObjectCreationArgumentListFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantExplicitArrayCreationFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantExplicitArraySizeFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantExplicitNullableCreationFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantExtendsListEntryFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantIfElseBlockFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantLambdaParameterTypeFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantLambdaSignatureParenthesesFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantLogicalConditionalExpressionOperandFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantObjectOrCollectionInitializerFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantStringToCharArrayCallFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantToStringCallForValueTypesFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantToStringCallFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantUnsafeContextFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantUsingDirectiveFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RemoveRedundantOrStatementFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.UnusedAnonymousMethodSignatureFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.AccessToStaticMemberViaDerivedTypeFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ConvertIfToOrExpressionFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ConvertToConstantFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.MemberCanBeMadeStaticFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ParameterCanBeDeclaredWithBaseTypeFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.PossibleMistakenCallToGetTypeFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.PublicConstructorInAbstractClassFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReferenceEqualsWithValueTypeFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithFirstOrDefaultFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithLastOrDefaultFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithOfTypeAnyFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithOfTypeCountFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithOfTypeFirstFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithOfTypeFirstOrDefaultFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithOfTypeFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithOfTypeLastFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithOfTypeLastOrDefaultFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithOfTypeLongCountFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithOfTypeSingleFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithOfTypeSingleOrDefaultFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithOfTypeWhereFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithSingleCallToAnyFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithSingleCallToCountFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithSingleCallToFirstFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithSingleCallToFirstOrDefaultFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithSingleCallToLastFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithSingleCallToLastOrDefaultFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithSingleCallToLongCountFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithSingleCallToSingleFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithSingleCallToSingleOrDefaultFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ReplaceWithStringIsNullOrEmptyFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.SimplifyConditionalTernaryExpressionFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.SimplifyLinqExpressionFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.StringCompareIsCultureSpecificFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.StringCompareToIsCultureSpecificFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.StringEndsWithIsCultureSpecificFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.StringLastIndexOfIsCultureSpecificFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.StringIndexOfIsCultureSpecificFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.StringStartsWithIsCultureSpecificFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.UseArrayCreationExpressionFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.UseIsOperatorFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.UseMethodAnyFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.UseMethodIsInstanceOfTypeFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ConvertIfStatementToNullCoalescingExpressionFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ConvertIfStatementToSwitchStatementFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ConvertNullableToShortFormFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ConvertToAutoPropertyFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ConvertToLambdaExpressionFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ForCanBeConvertedToForeachFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RewriteIfReturnToReturnFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.SuggestUseVarKeywordEvidentFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CS0183ExpressionIsAlwaysOfProvidedTypeFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CS1573ParameterHasNoMatchingParamTagFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CS1717AssignmentMadeToSameVariableFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.UnassignedReadonlyFieldFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ProhibitedModifiersFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CanBeReplacedWithTryCastAndCheckForNullFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.EqualExpressionComparisonFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ForControlVariableIsNeverModifiedFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.FormatStringProblemFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.FunctionNeverReturnsFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.LocalVariableHidesMemberFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.LongLiteralEndingLowerLFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.MemberHidesStaticFromOuterClassFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.MethodOverloadWithOptionalParameterFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.NotResolvedInTextIssueFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.OperatorIsCanBeUsedIssueFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.OptionalParameterHierarchyMismatchFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ParameterHidesMemberFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.PartialMethodParameterNameMismatchFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.PolymorphicFieldLikeEventInvocationFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.PossibleAssignmentToReadonlyFieldFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.PossibleMultipleEnumerationFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.StaticFieldInGenericTypeFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ThreadStaticAtInstanceFieldFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ValueParameterNotUsedFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.AdditionalOfTypeFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CastExpressionOfIncompatibleTypeFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CheckNamespaceFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ConstantConditionFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ConvertIfToAndExpressionFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.LockThisFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.NegativeRelationalExpressionFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ParameterOnlyAssignedFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.RedundantAssignmentFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.StaticEventSubscriptionFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.XmlDocFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CS0029InvalidConversionFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CS0126ReturnMustBeFollowedByAnyExpressionFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CS0127ReturnMustNotBeFollowedByAnyExpressionFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CS0152DuplicateCaseLabelValueFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CS0169FieldIsNeverUsedFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CS0618UsageOfObsoleteMemberFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CS0659ClassOverrideEqualsWithoutGetHashCodeFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CS0759RedundantPartialMethodIssueFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.CS1729TypeHasNoConstructorWithNArgumentsFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ExpressionIsNeverOfProvidedTypeFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.MissingInterfaceMemberImplementationFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.InconsistentNamingIssueFixProvider", "ICSharpCode.NRefactory6.CSharp.Refactoring.ConditionIsAlwaysTrueOrFalseFixProvider" }; private async Task CollectCodeFixActions(CodeFixContext? fixContext) { if (!fixContext.HasValue) return; foreach (var provider in _codeActionProviders) { foreach (var codeFix in provider.CodeFixes) { if (_blacklist.Contains(codeFix.ToString())) { continue; } try { await codeFix.RegisterCodeFixesAsync(fixContext.Value); } catch { _logger.LogError("Error registering code fixes " + codeFix); } } } } private async Task CollectRefactoringActions(CodeRefactoringContext? refactoringContext) { if (!refactoringContext.HasValue) return; foreach (var provider in _codeActionProviders) { foreach (var refactoring in provider.Refactorings) { if (_blacklist.Contains(refactoring.ToString())) { continue; } try { await refactoring.ComputeRefactoringsAsync(refactoringContext.Value); } catch { _logger.LogError("Error computing refactorings for " + refactoring); } } } } } }
using Lucene.Net.Util; using System; using System.Collections.Generic; using System.IO; using Console = Lucene.Net.Util.SystemConsole; namespace Lucene.Net.Index { /* * 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 CommandLineUtil = Lucene.Net.Util.CommandLineUtil; using Constants = Lucene.Net.Util.Constants; using Directory = Lucene.Net.Store.Directory; using FSDirectory = Lucene.Net.Store.FSDirectory; using InfoStream = Lucene.Net.Util.InfoStream; /// <summary> /// This is an easy-to-use tool that upgrades all segments of an index from previous Lucene versions /// to the current segment file format. It can be used from command line: /// <code> /// java -cp lucene-core.jar Lucene.Net.Index.IndexUpgrader [-delete-prior-commits] [-verbose] indexDir /// </code> /// Alternatively this class can be instantiated and <see cref="Upgrade()"/> invoked. It uses <see cref="UpgradeIndexMergePolicy"/> /// and triggers the upgrade via an <see cref="IndexWriter.ForceMerge(int)"/> request to <see cref="IndexWriter"/>. /// <para/> /// This tool keeps only the last commit in an index; for this /// reason, if the incoming index has more than one commit, the tool /// refuses to run by default. Specify <c>-delete-prior-commits</c> /// to override this, allowing the tool to delete all but the last commit. /// From .NET code this can be enabled by passing <c>true</c> to /// <see cref="IndexUpgrader(Directory, LuceneVersion, TextWriter, bool)"/>. /// <para/> /// <b>Warning:</b> this tool may reorder documents if the index was partially /// upgraded before execution (e.g., documents were added). If your application relies /// on &quot;monotonicity&quot; of doc IDs (which means that the order in which the documents /// were added to the index is preserved), do a full ForceMerge instead. /// The <see cref="MergePolicy"/> set by <see cref="IndexWriterConfig"/> may also reorder /// documents. /// </summary> public sealed class IndexUpgrader { private static void PrintUsage() { // LUCENENET specific - our wrapper console shows the correct usage throw new ArgumentException(); //Console.Error.WriteLine("Upgrades an index so all segments created with a previous Lucene version are rewritten."); //Console.Error.WriteLine("Usage:"); //Console.Error.WriteLine(" java " + typeof(IndexUpgrader).Name + " [-delete-prior-commits] [-verbose] [-dir-impl X] indexDir"); //Console.Error.WriteLine("this tool keeps only the last commit in an index; for this"); //Console.Error.WriteLine("reason, if the incoming index has more than one commit, the tool"); //Console.Error.WriteLine("refuses to run by default. Specify -delete-prior-commits to override"); //Console.Error.WriteLine("this, allowing the tool to delete all but the last commit."); //Console.Error.WriteLine("Specify a " + typeof(FSDirectory).Name + " implementation through the -dir-impl option to force its use. If no package is specified the " + typeof(FSDirectory).Namespace + " package will be used."); //Console.Error.WriteLine("WARNING: this tool may reorder document IDs!"); //Environment.FailFast("1"); } /// <summary> /// Main method to run <see cref="IndexUpgrader"/> from the /// command-line. /// </summary> public static void Main(string[] args) { ParseArgs(args).Upgrade(); } public static IndexUpgrader ParseArgs(string[] args) { string path = null; bool deletePriorCommits = false; TextWriter @out = null; string dirImpl = null; int i = 0; while (i < args.Length) { string arg = args[i]; if ("-delete-prior-commits".Equals(arg, StringComparison.Ordinal)) { deletePriorCommits = true; } else if ("-verbose".Equals(arg, StringComparison.Ordinal)) { @out = Console.Out; } else if ("-dir-impl".Equals(arg, StringComparison.Ordinal)) { if (i == args.Length - 1) { throw new ArgumentException("ERROR: missing value for -dir option"); //Console.WriteLine("ERROR: missing value for -dir-impl option"); //Environment.FailFast("1"); } i++; dirImpl = args[i]; } else if (path == null) { path = arg; } else { PrintUsage(); } i++; } if (path == null) { PrintUsage(); } Directory dir/* = null*/; // LUCENENET: IDE0059: Remove unnecessary value assignment if (dirImpl == null) { dir = FSDirectory.Open(new DirectoryInfo(path)); } else { dir = CommandLineUtil.NewFSDirectory(dirImpl, new DirectoryInfo(path)); } #pragma warning disable 612, 618 return new IndexUpgrader(dir, LuceneVersion.LUCENE_CURRENT, @out, deletePriorCommits); #pragma warning restore 612, 618 } internal readonly Directory dir; // LUCENENET specific - made internal for testing CLI arguments internal readonly IndexWriterConfig iwc; // LUCENENET specific - made internal for testing CLI arguments internal readonly bool deletePriorCommits; // LUCENENET specific - made internal for testing CLI arguments /// <summary> /// Creates index upgrader on the given directory, using an <see cref="IndexWriter"/> using the given /// <paramref name="matchVersion"/>. The tool refuses to upgrade indexes with multiple commit points. /// </summary> public IndexUpgrader(Directory dir, LuceneVersion matchVersion) : this(dir, new IndexWriterConfig(matchVersion, null), false) { } /// <summary> /// Creates index upgrader on the given directory, using an <see cref="IndexWriter"/> using the given /// <paramref name="matchVersion"/>. You have the possibility to upgrade indexes with multiple commit points by removing /// all older ones. If <paramref name="infoStream"/> is not <c>null</c>, all logging output will be sent to this stream. /// </summary> public IndexUpgrader(Directory dir, LuceneVersion matchVersion, TextWriter infoStream, bool deletePriorCommits) : this(dir, new IndexWriterConfig(matchVersion, null), deletePriorCommits) { if (null != infoStream) { this.iwc.SetInfoStream(infoStream); } } /// <summary> /// Creates index upgrader on the given directory, using an <see cref="IndexWriter"/> using the given /// config. You have the possibility to upgrade indexes with multiple commit points by removing /// all older ones. /// </summary> public IndexUpgrader(Directory dir, IndexWriterConfig iwc, bool deletePriorCommits) { this.dir = dir; this.iwc = iwc; this.deletePriorCommits = deletePriorCommits; } /// <summary> /// Perform the upgrade. </summary> public void Upgrade() { if (!DirectoryReader.IndexExists(dir)) { throw new IndexNotFoundException(dir.ToString()); } if (!deletePriorCommits) { ICollection<IndexCommit> commits = DirectoryReader.ListCommits(dir); if (commits.Count > 1) { throw new ArgumentException("this tool was invoked to not delete prior commit points, but the following commits were found: " + commits); } } IndexWriterConfig c = (IndexWriterConfig)iwc.Clone(); c.MergePolicy = new UpgradeIndexMergePolicy(c.MergePolicy); c.IndexDeletionPolicy = new KeepOnlyLastCommitDeletionPolicy(); IndexWriter w = new IndexWriter(dir, c); try { InfoStream infoStream = c.InfoStream; if (infoStream.IsEnabled("IndexUpgrader")) { infoStream.Message("IndexUpgrader", "Upgrading all pre-" + Constants.LUCENE_MAIN_VERSION + " segments of index directory '" + dir + "' to version " + Constants.LUCENE_MAIN_VERSION + "..."); } w.ForceMerge(1); if (infoStream.IsEnabled("IndexUpgrader")) { infoStream.Message("IndexUpgrader", "All segments upgraded to version " + Constants.LUCENE_MAIN_VERSION); } } finally { w.Dispose(); } } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Tools.OpenFileParam // Description: Double Parameters returned by an ITool allows the tool to specify a range and default value // // ******************************************************************************************************** // // The Original Code is Toolbox.dll for the DotSpatial 4.6/6 ToolManager project // // The Initial Developer of this Original Code is Teva Veluppillai. Created in Feb, 2010. // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Windows.Forms; using DotSpatial.Modeling.Forms.Parameters; namespace DotSpatial.Modeling.Forms.Elements { /// <summary> /// Open File Element /// </summary> public class OpenFileElement : DialogElement { #region Class Variables private readonly List<DataSetArray> _dataSets; private DataSetArray _addedTextFile; private bool _refreshCombo = true; private Button _btnAddData; private ComboBox _comboFile; #endregion #region Constructor /// <summary> /// Create an instance of the dialog /// </summary> /// <param name="param"></param> /// <param name="text"></param> public OpenFileElement(FileParam param, string text) { InitializeComponent(); Param = param; //_fileName = text; // textBox1.Text = param.Value; GroupBox.Text = param.Name; DoRefresh(); //Populates the dialog with the default parameter value if (param.Value != null && param.DefaultSpecified) { //_fileName = param.ModelName; base.Status = ToolStatus.Ok; LightTipText = ModelingMessageStrings.FeaturesetValid; } } /// <summary> /// Creates an instance of the dialog /// </summary> /// <param name="inputParam">The parameter this element represents</param> /// <param name="dataSets">An array of available data</param> public OpenFileElement(FileParam inputParam, List<DataSetArray> dataSets) { //Needed by the designer InitializeComponent(); //We save the parameters passed in Param = inputParam; _dataSets = dataSets; //Saves the label GroupBox.Text = Param.Name; DoRefresh(); } #endregion private void DoRefresh() { //Disable the combo box temporarily _refreshCombo = false; //We set the combo boxes status to empty to start base.Status = ToolStatus.Empty; LightTipText = ModelingMessageStrings.FeaturesetMissing; _comboFile.Items.Clear(); //If the user added a text file if (_addedTextFile != null) { _comboFile.Items.Add(_addedTextFile); if (Param.Value != null && Param.DefaultSpecified && _addedTextFile.DataSet == Param.Value) { _comboFile.SelectedItem = _addedTextFile; base.Status = ToolStatus.Ok; LightTipText = ModelingMessageStrings.FeaturesetValid; } } //Add all the dataSets back to the combo box if (_dataSets != null) { foreach (DataSetArray dsa in _dataSets) { TextFile aTextFile = dsa.DataSet as TextFile; if (aTextFile != null && !_comboFile.Items.Contains(dsa)) { //If the featureset is the correct type and isn't already in the combo box we add it _comboFile.Items.Add(dsa); if (Param.Value != null && Param.DefaultSpecified && dsa.DataSet == Param.Value) { _comboFile.SelectedItem = dsa; base.Status = ToolStatus.Ok; LightTipText = ModelingMessageStrings.FeaturesetValid; } } } } _refreshCombo = true; } /// <summary> /// updates the param if something's been changed /// </summary> public override void Refresh() { DoRefresh(); } private void btnAddData_Click(object sender, EventArgs e) { using (OpenFileDialog dialog = new OpenFileDialog()) { dialog.Title = ModelingMessageStrings.OpenFileElement_btnAddDataClick_SelectFileName; if (Param == null) Param = new FileParam("open filename"); FileParam p = Param as FileParam; if (p != null) dialog.Filter = p.DialogFilter; if (dialog.ShowDialog() == DialogResult.OK) { TextFile tmpTextFile = new TextFile(dialog.FileName); _addedTextFile = new DataSetArray(Path.GetFileNameWithoutExtension(dialog.FileName), tmpTextFile); Param.ModelName = _addedTextFile.Name; Param.Value = _addedTextFile.DataSet; Refresh(); base.Status = ToolStatus.Ok; } } } private void comboFile_SelectedValueChanged(object sender, EventArgs e) { if (_refreshCombo) { DataSetArray dsa = _comboFile.SelectedItem as DataSetArray; if (dsa != null) { Param.ModelName = dsa.Name; Param.Value = dsa.DataSet; } } } #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._btnAddData = new Button(); this._comboFile = new ComboBox(); this.GroupBox.SuspendLayout(); this.SuspendLayout(); // // GroupBox // this.GroupBox.Controls.Add(this._btnAddData); this.GroupBox.Controls.Add(this._comboFile); this.GroupBox.Controls.SetChildIndex(this._comboFile, 0); this.GroupBox.Controls.SetChildIndex(this._btnAddData, 0); // // btnAddData // this._btnAddData.Image = Images.AddLayer; this._btnAddData.Location = new Point(450, 10); this._btnAddData.Name = "_btnAddData"; this._btnAddData.Size = new Size(26, 26); this._btnAddData.TabIndex = 9; this._btnAddData.UseVisualStyleBackColor = true; this._btnAddData.Click += new EventHandler(this.btnAddData_Click); // // comboFile // this._comboFile.DropDownStyle = ComboBoxStyle.DropDownList; this._comboFile.FormattingEnabled = true; this._comboFile.Location = new Point(34, 12); this._comboFile.Name = "_comboFile"; this._comboFile.Size = new Size(410, 21); this._comboFile.TabIndex = 10; this._comboFile.SelectedValueChanged += new EventHandler(this.comboFile_SelectedValueChanged); // // OpenFileElement // this.AutoScaleDimensions = new SizeF(6F, 13F); this.Name = "OpenFileElement"; this.GroupBox.ResumeLayout(false); this.ResumeLayout(false); } #endregion } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// Beach. /// </summary> public class Beach_Core : TypeCore, ICivicStructure { public Beach_Core() { this._TypeId = 34; this._Id = "Beach"; this._Schema_Org_Url = "http://schema.org/Beach"; string label = ""; GetLabel(out label, "Beach", typeof(Beach_Core)); this._Label = label; this._Ancestors = new int[]{266,206,62}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{62}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,152}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code>&lt;time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\&gt;Tuesdays and Thursdays 4-8pm&lt;/time&gt;</code>. <br/>- If a business is open 7 days a week, then it can be specified as <code>&lt;time itemprop=\openingHours\ datetime=\Mo-Su\&gt;Monday through Sunday, all day&lt;/time&gt;</code>. /// </summary> private OpeningHours_Core openingHours; public OpeningHours_Core OpeningHours { get { return openingHours; } set { openingHours = value; SetPropertyInstance(openingHours); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
using System; using System.Windows.Input; using Prism.Commands; using Xunit; namespace Prism.Tests.Commands { public class CompositeCommandFixture { [Fact] public void RegisterACommandShouldRaiseCanExecuteEvent() { TestableCompositeCommand multiCommand = new TestableCompositeCommand(); TestCommand testCommand = new TestCommand(); multiCommand.RegisterCommand(new TestCommand()); Assert.True(multiCommand.CanExecuteChangedRaised); } [Fact] public void ShouldDelegateExecuteToSingleRegistrant() { TestableCompositeCommand multiCommand = new TestableCompositeCommand(); TestCommand testCommand = new TestCommand(); multiCommand.RegisterCommand(testCommand); Assert.False(testCommand.ExecuteCalled); multiCommand.Execute(null); Assert.True(testCommand.ExecuteCalled); } [Fact] public void ShouldDelegateExecuteToMultipleRegistrants() { TestableCompositeCommand multiCommand = new TestableCompositeCommand(); TestCommand testCommandOne = new TestCommand(); TestCommand testCommandTwo = new TestCommand(); multiCommand.RegisterCommand(testCommandOne); multiCommand.RegisterCommand(testCommandTwo); Assert.False(testCommandOne.ExecuteCalled); Assert.False(testCommandTwo.ExecuteCalled); multiCommand.Execute(null); Assert.True(testCommandOne.ExecuteCalled); Assert.True(testCommandTwo.ExecuteCalled); } [Fact] public void ShouldDelegateCanExecuteToSingleRegistrant() { TestableCompositeCommand multiCommand = new TestableCompositeCommand(); TestCommand testCommand = new TestCommand(); multiCommand.RegisterCommand(testCommand); Assert.False(testCommand.CanExecuteCalled); multiCommand.CanExecute(null); Assert.True(testCommand.CanExecuteCalled); } [Fact] public void ShouldDelegateCanExecuteToMultipleRegistrants() { TestableCompositeCommand multiCommand = new TestableCompositeCommand(); TestCommand testCommandOne = new TestCommand(); TestCommand testCommandTwo = new TestCommand(); multiCommand.RegisterCommand(testCommandOne); multiCommand.RegisterCommand(testCommandTwo); Assert.False(testCommandOne.CanExecuteCalled); Assert.False(testCommandTwo.CanExecuteCalled); multiCommand.CanExecute(null); Assert.True(testCommandOne.CanExecuteCalled); Assert.True(testCommandTwo.CanExecuteCalled); } [Fact] public void CanExecuteShouldReturnTrueIfAllRegistrantsTrue() { TestableCompositeCommand multiCommand = new TestableCompositeCommand(); TestCommand testCommandOne = new TestCommand() { CanExecuteValue = true }; TestCommand testCommandTwo = new TestCommand() { CanExecuteValue = true }; multiCommand.RegisterCommand(testCommandOne); multiCommand.RegisterCommand(testCommandTwo); Assert.True(multiCommand.CanExecute(null)); } [Fact] public void CanExecuteShouldReturnFalseIfASingleRegistrantsFalse() { TestableCompositeCommand multiCommand = new TestableCompositeCommand(); TestCommand testCommandOne = new TestCommand() { CanExecuteValue = true }; TestCommand testCommandTwo = new TestCommand() { CanExecuteValue = false }; multiCommand.RegisterCommand(testCommandOne); multiCommand.RegisterCommand(testCommandTwo); Assert.False(multiCommand.CanExecute(null)); } [Fact] public void ShouldReraiseCanExecuteChangedEvent() { TestableCompositeCommand multiCommand = new TestableCompositeCommand(); TestCommand testCommandOne = new TestCommand() { CanExecuteValue = true }; Assert.False(multiCommand.CanExecuteChangedRaised); multiCommand.RegisterCommand(testCommandOne); multiCommand.CanExecuteChangedRaised = false; testCommandOne.FireCanExecuteChanged(); Assert.True(multiCommand.CanExecuteChangedRaised); } [Fact] public void ShouldReraiseCanExecuteChangedEventAfterCollect() { TestableCompositeCommand multiCommand = new TestableCompositeCommand(); TestCommand testCommandOne = new TestCommand() { CanExecuteValue = true }; Assert.False(multiCommand.CanExecuteChangedRaised); multiCommand.RegisterCommand(testCommandOne); multiCommand.CanExecuteChangedRaised = false; GC.Collect(); testCommandOne.FireCanExecuteChanged(); Assert.True(multiCommand.CanExecuteChangedRaised); } [Fact] public void ShouldReraiseDelegateCommandCanExecuteChangedEventAfterCollect() { TestableCompositeCommand multiCommand = new TestableCompositeCommand(); DelegateCommand<object> delegateCommand = new DelegateCommand<object>(delegate { }); Assert.False(multiCommand.CanExecuteChangedRaised); multiCommand.RegisterCommand(delegateCommand); multiCommand.CanExecuteChangedRaised = false; GC.Collect(); delegateCommand.RaiseCanExecuteChanged(); Assert.True(multiCommand.CanExecuteChangedRaised); } [Fact] public void UnregisteringCommandWithNullThrows() { Assert.Throws<ArgumentNullException>(() => { var compositeCommand = new CompositeCommand(); compositeCommand.UnregisterCommand(null); }); } [Fact] public void UnregisterCommandRemovesFromExecuteDelegation() { TestableCompositeCommand multiCommand = new TestableCompositeCommand(); TestCommand testCommandOne = new TestCommand() { CanExecuteValue = true }; multiCommand.RegisterCommand(testCommandOne); multiCommand.UnregisterCommand(testCommandOne); Assert.False(testCommandOne.ExecuteCalled); multiCommand.Execute(null); Assert.False(testCommandOne.ExecuteCalled); } [Fact] public void UnregisterCommandShouldRaiseCanExecuteEvent() { TestableCompositeCommand multiCommand = new TestableCompositeCommand(); TestCommand testCommandOne = new TestCommand(); multiCommand.RegisterCommand(testCommandOne); multiCommand.CanExecuteChangedRaised = false; multiCommand.UnregisterCommand(testCommandOne); Assert.True(multiCommand.CanExecuteChangedRaised); } [Fact] public void ExecuteDoesNotThrowWhenAnExecuteCommandModifiesTheCommandsCollection() { TestableCompositeCommand multiCommand = new TestableCompositeCommand(); SelfUnregisterableCommand commandOne = new SelfUnregisterableCommand(multiCommand); SelfUnregisterableCommand commandTwo = new SelfUnregisterableCommand(multiCommand); multiCommand.RegisterCommand(commandOne); multiCommand.RegisterCommand(commandTwo); multiCommand.Execute(null); Assert.True(commandOne.ExecutedCalled); Assert.True(commandTwo.ExecutedCalled); } [Fact] public void UnregisterCommandDisconnectsCanExecuteChangedDelegate() { TestableCompositeCommand multiCommand = new TestableCompositeCommand(); TestCommand testCommandOne = new TestCommand() { CanExecuteValue = true }; multiCommand.RegisterCommand(testCommandOne); multiCommand.UnregisterCommand(testCommandOne); multiCommand.CanExecuteChangedRaised = false; testCommandOne.FireCanExecuteChanged(); Assert.False(multiCommand.CanExecuteChangedRaised); } [Fact] public void UnregisterCommandDisconnectsIsActiveChangedDelegate() { CompositeCommand activeAwareCommand = new CompositeCommand(true); MockActiveAwareCommand commandOne = new MockActiveAwareCommand() { IsActive = true, IsValid = true }; MockActiveAwareCommand commandTwo = new MockActiveAwareCommand() { IsActive = false, IsValid = false }; activeAwareCommand.RegisterCommand(commandOne); activeAwareCommand.RegisterCommand(commandTwo); Assert.True(activeAwareCommand.CanExecute(null)); activeAwareCommand.UnregisterCommand(commandOne); Assert.False(activeAwareCommand.CanExecute(null)); } [Fact] public void ShouldBubbleException() { Assert.Throws<DivideByZeroException>(() => { TestableCompositeCommand multiCommand = new TestableCompositeCommand(); BadDivisionCommand testCommand = new BadDivisionCommand(); multiCommand.RegisterCommand(testCommand); multiCommand.Execute(null); }); } [Fact] public void CanExecuteShouldReturnFalseWithNoCommandsRegistered() { TestableCompositeCommand multiCommand = new TestableCompositeCommand(); Assert.False(multiCommand.CanExecute(null)); } [Fact] public void MultiDispatchCommandExecutesActiveRegisteredCommands() { CompositeCommand activeAwareCommand = new CompositeCommand(); MockActiveAwareCommand command = new MockActiveAwareCommand(); command.IsActive = true; activeAwareCommand.RegisterCommand(command); activeAwareCommand.Execute(null); Assert.True(command.WasExecuted); } [Fact] public void MultiDispatchCommandDoesNotExecutesInactiveRegisteredCommands() { CompositeCommand activeAwareCommand = new CompositeCommand(true); MockActiveAwareCommand command = new MockActiveAwareCommand(); command.IsActive = false; activeAwareCommand.RegisterCommand(command); activeAwareCommand.Execute(null); Assert.False(command.WasExecuted); } [Fact] public void DispatchCommandDoesNotIncludeInactiveRegisteredCommandInVoting() { CompositeCommand activeAwareCommand = new CompositeCommand(true); MockActiveAwareCommand command = new MockActiveAwareCommand(); activeAwareCommand.RegisterCommand(command); command.IsValid = true; command.IsActive = false; Assert.False(activeAwareCommand.CanExecute(null), "Registered Click is inactive so should not participate in CanExecute vote"); command.IsActive = true; Assert.True(activeAwareCommand.CanExecute(null)); command.IsValid = false; Assert.False(activeAwareCommand.CanExecute(null)); } [Fact] public void DispatchCommandShouldIgnoreInactiveCommandsInCanExecuteVote() { CompositeCommand activeAwareCommand = new CompositeCommand(true); MockActiveAwareCommand commandOne = new MockActiveAwareCommand() { IsActive = false, IsValid = false }; MockActiveAwareCommand commandTwo = new MockActiveAwareCommand() { IsActive = true, IsValid = true }; activeAwareCommand.RegisterCommand(commandOne); activeAwareCommand.RegisterCommand(commandTwo); Assert.True(activeAwareCommand.CanExecute(null)); } [Fact] public void ActivityCausesActiveAwareCommandToRequeryCanExecute() { CompositeCommand activeAwareCommand = new CompositeCommand(true); MockActiveAwareCommand command = new MockActiveAwareCommand(); activeAwareCommand.RegisterCommand(command); command.IsActive = true; bool globalCanExecuteChangeFired = false; activeAwareCommand.CanExecuteChanged += delegate { globalCanExecuteChangeFired = true; }; Assert.False(globalCanExecuteChangeFired); command.IsActive = false; Assert.True(globalCanExecuteChangeFired); } [Fact] public void ShouldNotMonitorActivityIfUseActiveMonitoringFalse() { var mockCommand = new MockActiveAwareCommand(); mockCommand.IsValid = true; mockCommand.IsActive = true; var nonActiveAwareCompositeCommand = new CompositeCommand(false); bool canExecuteChangedRaised = false; nonActiveAwareCompositeCommand.RegisterCommand(mockCommand); nonActiveAwareCompositeCommand.CanExecuteChanged += delegate { canExecuteChangedRaised = true; }; mockCommand.IsActive = false; Assert.False(canExecuteChangedRaised); nonActiveAwareCompositeCommand.Execute(null); Assert.True(mockCommand.WasExecuted); } [Fact] public void ShouldRemoveCanExecuteChangedHandler() { bool canExecuteChangedRaised = false; var compositeCommand = new CompositeCommand(); var commmand = new DelegateCommand(() => { }); compositeCommand.RegisterCommand(commmand); EventHandler handler = (s, e) => canExecuteChangedRaised = true; compositeCommand.CanExecuteChanged += handler; commmand.RaiseCanExecuteChanged(); Assert.True(canExecuteChangedRaised); canExecuteChangedRaised = false; compositeCommand.CanExecuteChanged -= handler; commmand.RaiseCanExecuteChanged(); Assert.False(canExecuteChangedRaised); } [Fact] public void ShouldIgnoreChangesToIsActiveDuringExecution() { var firstCommand = new MockActiveAwareCommand { IsActive = true }; var secondCommand = new MockActiveAwareCommand { IsActive = true }; // During execution set the second command to inactive, this should not affect the currently // executed selection. firstCommand.ExecuteAction += new Action<object>((object parameter) => secondCommand.IsActive = false); var compositeCommand = new CompositeCommand(true); compositeCommand.RegisterCommand(firstCommand); compositeCommand.RegisterCommand(secondCommand); compositeCommand.Execute(null); Assert.True(secondCommand.WasExecuted); } [Fact] public void RegisteringCommandInItselfThrows() { Assert.Throws<ArgumentException>(() => { var compositeCommand = new CompositeCommand(); compositeCommand.RegisterCommand(compositeCommand); }); } [Fact] public void RegisteringCommandWithNullThrows() { Assert.Throws<ArgumentNullException>(() => { var compositeCommand = new CompositeCommand(); compositeCommand.RegisterCommand(null); }); } [Fact] public void RegisteringCommandTwiceThrows() { Assert.Throws<InvalidOperationException>(() => { var compositeCommand = new CompositeCommand(); var duplicateCommand = new TestCommand(); compositeCommand.RegisterCommand(duplicateCommand); compositeCommand.RegisterCommand(duplicateCommand); }); } [Fact] public void ShouldGetRegisteredCommands() { var firstCommand = new TestCommand(); var secondCommand = new TestCommand(); var compositeCommand = new CompositeCommand(); compositeCommand.RegisterCommand(firstCommand); compositeCommand.RegisterCommand(secondCommand); var commands = compositeCommand.RegisteredCommands; Assert.True(commands.Count > 0); } } internal class MockActiveAwareCommand : IActiveAware, ICommand { private bool _isActive; public Action<object> ExecuteAction; #region IActiveAware Members public bool IsActive { get { return _isActive; } set { if (_isActive != value) { _isActive = value; OnActiveChanged(this, EventArgs.Empty); } } } public event EventHandler IsActiveChanged = delegate { }; #endregion virtual protected void OnActiveChanged(object sender, EventArgs e) { IsActiveChanged(sender, e); } public bool WasExecuted { get; set; } public bool IsValid { get; set; } #region ICommand Members public bool CanExecute(object parameter) { return IsValid; } public event EventHandler CanExecuteChanged = delegate { }; public void Execute(object parameter) { WasExecuted = true; if (ExecuteAction != null) ExecuteAction(parameter); } #endregion } internal class TestableCompositeCommand : CompositeCommand { public bool CanExecuteChangedRaised; private EventHandler handler; public TestableCompositeCommand() { this.handler = ((sender, e) => CanExecuteChangedRaised = true); CanExecuteChanged += this.handler; } } internal class TestCommand : ICommand { public bool CanExecuteCalled { get; set; } public bool ExecuteCalled { get; set; } public int ExecuteCallCount { get; set; } public bool CanExecuteValue = true; public void FireCanExecuteChanged() { CanExecuteChanged(this, EventArgs.Empty); } #region ICommand Members public bool CanExecute(object parameter) { CanExecuteCalled = true; return CanExecuteValue; } public event EventHandler CanExecuteChanged = delegate { }; public void Execute(object parameter) { ExecuteCalled = true; ExecuteCallCount += 1; } #endregion } internal class BadDivisionCommand : ICommand { #region ICommand Members public bool CanExecute(object parameter) { return true; } public event EventHandler CanExecuteChanged = delegate { }; public void Execute(object parameter) { throw new DivideByZeroException("Test Divide By Zero"); } #endregion } internal class SelfUnregisterableCommand : ICommand { public CompositeCommand Command; public bool ExecutedCalled = false; public SelfUnregisterableCommand(CompositeCommand command) { Command = command; } #region ICommand Members public bool CanExecute(object parameter) { throw new NotImplementedException(); } public event EventHandler CanExecuteChanged; public void Execute(object parameter) { Command.UnregisterCommand(this); ExecutedCalled = true; } #endregion } }
// Copyright (c) Russlan Akiev. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace IdentityBase.Actions.Login { using System; using System.Linq; using System.Threading.Tasks; using IdentityBase.Configuration; using IdentityBase.Forms; using IdentityBase.Models; using IdentityBase.Mvc; using IdentityBase.Services; using IdentityServer4.Models; using IdentityServer4.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using ServiceBase.Mvc; public class LoginController : WebController { private readonly ApplicationOptions _applicationOptions; private readonly IUserAccountStore _userAccountStore; private readonly AuthenticationService _authenticationService; private readonly UserAccountService _userAccountService; public LoginController( IIdentityServerInteractionService interaction, IStringLocalizer localizer, ILogger<LoginController> logger, IdentityBaseContext identityBaseContext, ApplicationOptions applicationOptions, IUserAccountStore userAccountStore, AuthenticationService authenticationService, UserAccountService userAccountService) { this.InteractionService = interaction; this.Localizer = localizer; this.Logger = logger; this.IdentityBaseContext = identityBaseContext; this._applicationOptions = applicationOptions; this._userAccountStore = userAccountStore; this._authenticationService = authenticationService; this._userAccountService = userAccountService; } /// <summary> /// Shows the login page with local and external logins. /// </summary> [HttpGet("/login", Name = "Login")] [RestoreModelState] public async Task<IActionResult> LoginGet(string returnUrl) { LoginViewModel vm = await this.CreateViewModelAsync(returnUrl); // If local authentication is disbaled and there is only one // external provider provided so do just external authentication // without showing the login page if (vm.IsExternalLoginOnly) { return this.RedirectToRoute( "External", new { provider = vm.ExternalProviders .First().AuthenticationScheme, returnUrl = returnUrl } ); } vm.FormModel = await this.CreateFormViewModelAsync <ILoginCreateViewModelAction>(vm); return this.View("Login", vm); } /// <summary> /// Handle postback from username/password login /// </summary> [HttpPost("/login", Name = "Login")] [ValidateAntiForgeryToken] [StoreModelState] public async Task<IActionResult> LoginPost(LoginInputModel model) { // TODO: extract in own controller and not add it if (!this._applicationOptions.EnableAccountLogin) { return this.NotFound(); } BindInputModelResult formResult = await this .BindFormInputModelAsync<ILoginBindInputModelAction>(); // invalid input (return to same login) if (!this.ModelState.IsValid) { return this.RedirectToLogin(model.ReturnUrl); } ( UserAccount userAccount, bool isLocalAccount, bool isAccountActive, bool isPasswordValid, bool needChangePassword, bool needEmailVerification, string[] hints ) = await this.VerifyByEmailAndPasswordAsync( model.Email, model.Password); // user not present (wrong email) if (userAccount == null) { // Show email or password is invalid this.AddModelStateError(ErrorMessages.InvalidCredentials); return this.RedirectToLogin(model.ReturnUrl); } // User is not active if (!isAccountActive) { this.AddModelStateError( nameof(LoginViewModel.Email), ErrorMessages.UserAccountIsInactive); return this.RedirectToLogin(model.ReturnUrl); } if (needEmailVerification) { this.AddModelStateError( nameof(LoginViewModel.Email), ErrorMessages.UserAccountNeedsConfirmation); return this.RedirectToLogin(model.ReturnUrl); } // User has to change password (password change is required) if (needChangePassword) { throw new NotImplementedException( "Changing passwords not implemented yet."); } // User has invalid password (handle penalty) if (!isPasswordValid) { this.AddModelStateError(ErrorMessages.InvalidCredentials); this._userAccountService.SetFailedSignIn(userAccount); await this._userAccountStore.WriteAsync(userAccount); // TODO: emit user updated event return this.RedirectToLogin(model.ReturnUrl); } await this._authenticationService.SignInAsync( userAccount, model.ReturnUrl, model.RememberLogin); this._userAccountService.SetSuccessfullSignIn(userAccount); await this._userAccountStore.WriteAsync(userAccount); // TODO: emit user updated event // TODO: emit user authenticated event // TODO: check if 2factor auth is enabled return this.RedirectToReturnUrl(model.ReturnUrl); } [NonAction] private async Task<LoginViewModel> CreateViewModelAsync( string returnUrl) { LoginViewModel vm = new LoginViewModel { ReturnUrl = returnUrl, EnableRememberMe = this._applicationOptions .EnableRememberMe, EnableAccountRegistration = this._applicationOptions .EnableAccountRegistration, EnableAccountRecover = this._applicationOptions .EnableAccountRecovery, // TODO: expose AuthorizationRequest LoginHint = this.IdentityBaseContext .AuthorizationRequest.LoginHint, }; /* // Not yet supported if (context?.IdP != null) { // This is meant to short circuit the UI and only trigger the one external IdP vm.EnableLocalLogin = applicationOptions.EnableLocalLogin; vm.ExternalProviders = new ExternalProvider[] { new ExternalProvider { AuthenticationScheme = context.IdP } }; return vm; }*/ Client client = this.IdentityBaseContext.Client; // IEnumerable<ExternalProvider> providers = await this._clientService // .GetEnabledProvidersAsync(client); vm.ExternalProviders = await this._authenticationService .GetExternalProvidersAsync(); // TODO: remove as soon vm.EnableLocalLogin = (client != null ? client.EnableLocalLogin : false) && this._applicationOptions.EnableAccountLogin; // if (userAccount != null) // { // vm.ExternalProviderHints = userAccount?.Accounts // .Select(c => c.Provider); // } return vm; } [NonAction] private async Task<( UserAccount userAccount, bool isLocalAccount, bool isAccountActive, bool isPasswordValid, bool needChangePassword, bool needEmailVerification, string[] hints )> VerifyByEmailAndPasswordAsync( string email, string password ) { UserAccount userAccount = await this._userAccountStore .LoadByEmailAsync(email); bool isLocalAccount = false; bool isAccountActive = false; bool isPasswordValid = false; bool needChangePassword = false; bool needEmailVerification = false; string[] hints = null; // No ueser, nothing to do here if (userAccount == null) { return ( userAccount, isLocalAccount, isAccountActive, isPasswordValid, needChangePassword, needEmailVerification, hints ); } // If user has a password so it has a local account credentials if (userAccount.HasPassword()) { // It has a local account, so dont ask the user to create a // local account isLocalAccount = true; // Check if password is valid isPasswordValid = this._userAccountService.IsPasswordValid( userAccount.PasswordHash, password); // TODO: implement invalid passowrd policy } // User is disabled isAccountActive = userAccount.IsActive; // User requred to verify his email address needEmailVerification = !userAccount.IsEmailVerified && this._applicationOptions.RequireLocalAccountVerification; // TODO: Implement password invalidation policy needChangePassword = false; // TODO: implement hints if user should get help to get authenticated return ( userAccount, isLocalAccount, isAccountActive, isPasswordValid, needChangePassword, needEmailVerification, hints ); } } }
using Xunit; namespace Jint.Tests.Ecma { public class Test_15_2_3_11 : EcmaTest { [Fact] [Trait("Category", "15.2.3.11")] public void ObjectIssealedMustExistAsAFunction() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-0-1.js", false); } [Fact] [Trait("Category", "15.2.3.11")] public void ObjectIssealedMustExistAsAFunctionTaking1Parameter() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-0-2.js", false); } [Fact] [Trait("Category", "15.2.3.11")] public void ObjectIssealedThrowsTypeerrorIfTypeOfFirstParamIsNotObject() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-1.js", false); } [Fact] [Trait("Category", "15.2.3.11")] public void ObjectIssealedReturnsFalseForAllBuiltInObjectsGlobal() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-4-1.js", false); } [Fact] [Trait("Category", "15.2.3.11")] public void ObjectIssealedReturnsFalseForAllBuiltInObjectsBoolean() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-4-10.js", false); } [Fact] [Trait("Category", "15.2.3.11")] public void ObjectIssealedReturnsFalseForAllBuiltInObjectsBooleanPrototype() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-4-11.js", false); } [Fact] [Trait("Category", "15.2.3.11")] public void ObjectIssealedReturnsFalseForAllBuiltInObjectsNumber() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-4-12.js", false); } [Fact] [Trait("Category", "15.2.3.11")] public void ObjectIssealedReturnsFalseForAllBuiltInObjectsNumberPrototype() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-4-13.js", false); } [Fact] [Trait("Category", "15.2.3.11")] public void ObjectIssealedReturnsFalseForAllBuiltInObjectsMath() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-4-14.js", false); } [Fact] [Trait("Category", "15.2.3.11")] public void ObjectIssealedReturnsFalseForAllBuiltInObjectsDate() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-4-15.js", false); } [Fact] [Trait("Category", "15.2.3.11")] public void ObjectIssealedReturnsFalseForAllBuiltInObjectsDatePrototype() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-4-16.js", false); } [Fact] [Trait("Category", "15.2.3.11")] public void ObjectIssealedReturnsFalseForAllBuiltInObjectsRegexp() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-4-17.js", false); } [Fact] [Trait("Category", "15.2.3.11")] public void ObjectIssealedReturnsFalseForAllBuiltInObjectsRegexpPrototype() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-4-18.js", false); } [Fact] [Trait("Category", "15.2.3.11")] public void ObjectIssealedReturnsFalseForAllBuiltInObjectsError() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-4-19.js", false); } [Fact] [Trait("Category", "15.2.3.11")] public void ObjectIssealedReturnsFalseForAllBuiltInObjectsObject() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-4-2.js", false); } [Fact] [Trait("Category", "15.2.3.11")] public void ObjectIssealedReturnsFalseForAllBuiltInObjectsErrorPrototype() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-4-20.js", false); } [Fact] [Trait("Category", "15.2.3.11")] public void ObjectIssealedReturnsFalseForAllBuiltInObjectsEvalerror() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-4-21.js", false); } [Fact] [Trait("Category", "15.2.3.11")] public void ObjectIssealedReturnsFalseForAllBuiltInObjectsRangeerror() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-4-22.js", false); } [Fact] [Trait("Category", "15.2.3.11")] public void ObjectIssealedReturnsFalseForAllBuiltInObjectsReferenceerror() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-4-23.js", false); } [Fact] [Trait("Category", "15.2.3.11")] public void ObjectIssealedReturnsFalseForAllBuiltInObjectsSyntaxerror() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-4-24.js", false); } [Fact] [Trait("Category", "15.2.3.11")] public void ObjectIssealedReturnsFalseForAllBuiltInObjectsTypeerror() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-4-25.js", false); } [Fact] [Trait("Category", "15.2.3.11")] public void ObjectIssealedReturnsFalseForAllBuiltInObjectsUrierror() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-4-26.js", false); } [Fact] [Trait("Category", "15.2.3.11")] public void ObjectIssealedReturnsFalseForAllBuiltInObjectsJson() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-4-27.js", false); } [Fact] [Trait("Category", "15.2.3.11")] public void ObjectIssealedReturnsFalseForAllBuiltInObjectsObjectPrototype() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-4-3.js", false); } [Fact] [Trait("Category", "15.2.3.11")] public void ObjectIssealedReturnsFalseForAllBuiltInObjectsFunction() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-4-4.js", false); } [Fact] [Trait("Category", "15.2.3.11")] public void ObjectIssealedReturnsFalseForAllBuiltInObjectsFunctionPrototype() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-4-5.js", false); } [Fact] [Trait("Category", "15.2.3.11")] public void ObjectIssealedReturnsFalseForAllBuiltInObjectsArray() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-4-6.js", false); } [Fact] [Trait("Category", "15.2.3.11")] public void ObjectIssealedReturnsFalseForAllBuiltInObjectsArrayPrototype() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-4-7.js", false); } [Fact] [Trait("Category", "15.2.3.11")] public void ObjectIssealedReturnsFalseForAllBuiltInObjectsString() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-4-8.js", false); } [Fact] [Trait("Category", "15.2.3.11")] public void ObjectIssealedReturnsFalseForAllBuiltInObjectsStringPrototype() { RunTest(@"TestCases/ch15/15.2/15.2.3/15.2.3.11/15.2.3.11-4-9.js", false); } } }
using System; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Text; using System.Threading; using OpenHome.Net.Core; using OpenHome.Net.ControlPoint; namespace OpenHome.Net.ControlPoint.Proxies { public interface ICpProxyAvOpenhomeOrgExakt1 : ICpProxy, IDisposable { void SyncDeviceList(out String aList); void BeginDeviceList(CpProxy.CallbackAsyncComplete aCallback); void EndDeviceList(IntPtr aAsyncHandle, out String aList); void SyncDeviceSettings(String aDeviceId, out String aSettings); void BeginDeviceSettings(String aDeviceId, CpProxy.CallbackAsyncComplete aCallback); void EndDeviceSettings(IntPtr aAsyncHandle, out String aSettings); void SyncConnectionStatus(out String aConnectionStatus); void BeginConnectionStatus(CpProxy.CallbackAsyncComplete aCallback); void EndConnectionStatus(IntPtr aAsyncHandle, out String aConnectionStatus); void SyncSet(String aDeviceId, uint aBankId, String aFileUri, bool aMute, bool aPersist); void BeginSet(String aDeviceId, uint aBankId, String aFileUri, bool aMute, bool aPersist, CpProxy.CallbackAsyncComplete aCallback); void EndSet(IntPtr aAsyncHandle); void SyncReprogram(String aDeviceId, String aFileUri); void BeginReprogram(String aDeviceId, String aFileUri, CpProxy.CallbackAsyncComplete aCallback); void EndReprogram(IntPtr aAsyncHandle); void SyncReprogramFallback(String aDeviceId, String aFileUri); void BeginReprogramFallback(String aDeviceId, String aFileUri, CpProxy.CallbackAsyncComplete aCallback); void EndReprogramFallback(IntPtr aAsyncHandle); void SetPropertyDeviceListChanged(System.Action aDeviceListChanged); String PropertyDeviceList(); void SetPropertyConnectionStatusChanged(System.Action aConnectionStatusChanged); String PropertyConnectionStatus(); } internal class SyncDeviceListAvOpenhomeOrgExakt1 : SyncProxyAction { private CpProxyAvOpenhomeOrgExakt1 iService; private String iList; public SyncDeviceListAvOpenhomeOrgExakt1(CpProxyAvOpenhomeOrgExakt1 aProxy) { iService = aProxy; } public String List() { return iList; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndDeviceList(aAsyncHandle, out iList); } }; internal class SyncDeviceSettingsAvOpenhomeOrgExakt1 : SyncProxyAction { private CpProxyAvOpenhomeOrgExakt1 iService; private String iSettings; public SyncDeviceSettingsAvOpenhomeOrgExakt1(CpProxyAvOpenhomeOrgExakt1 aProxy) { iService = aProxy; } public String Settings() { return iSettings; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndDeviceSettings(aAsyncHandle, out iSettings); } }; internal class SyncConnectionStatusAvOpenhomeOrgExakt1 : SyncProxyAction { private CpProxyAvOpenhomeOrgExakt1 iService; private String iConnectionStatus; public SyncConnectionStatusAvOpenhomeOrgExakt1(CpProxyAvOpenhomeOrgExakt1 aProxy) { iService = aProxy; } public String ConnectionStatus() { return iConnectionStatus; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndConnectionStatus(aAsyncHandle, out iConnectionStatus); } }; internal class SyncSetAvOpenhomeOrgExakt1 : SyncProxyAction { private CpProxyAvOpenhomeOrgExakt1 iService; public SyncSetAvOpenhomeOrgExakt1(CpProxyAvOpenhomeOrgExakt1 aProxy) { iService = aProxy; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndSet(aAsyncHandle); } }; internal class SyncReprogramAvOpenhomeOrgExakt1 : SyncProxyAction { private CpProxyAvOpenhomeOrgExakt1 iService; public SyncReprogramAvOpenhomeOrgExakt1(CpProxyAvOpenhomeOrgExakt1 aProxy) { iService = aProxy; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndReprogram(aAsyncHandle); } }; internal class SyncReprogramFallbackAvOpenhomeOrgExakt1 : SyncProxyAction { private CpProxyAvOpenhomeOrgExakt1 iService; public SyncReprogramFallbackAvOpenhomeOrgExakt1(CpProxyAvOpenhomeOrgExakt1 aProxy) { iService = aProxy; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndReprogramFallback(aAsyncHandle); } }; /// <summary> /// Proxy for the av.openhome.org:Exakt:1 UPnP service /// </summary> public class CpProxyAvOpenhomeOrgExakt1 : CpProxy, IDisposable, ICpProxyAvOpenhomeOrgExakt1 { private OpenHome.Net.Core.Action iActionDeviceList; private OpenHome.Net.Core.Action iActionDeviceSettings; private OpenHome.Net.Core.Action iActionConnectionStatus; private OpenHome.Net.Core.Action iActionSet; private OpenHome.Net.Core.Action iActionReprogram; private OpenHome.Net.Core.Action iActionReprogramFallback; private PropertyString iDeviceList; private PropertyString iConnectionStatus; private System.Action iDeviceListChanged; private System.Action iConnectionStatusChanged; private Mutex iPropertyLock; /// <summary> /// Constructor /// </summary> /// <remarks>Use CpProxy::[Un]Subscribe() to enable/disable querying of state variable and reporting of their changes.</remarks> /// <param name="aDevice">The device to use</param> public CpProxyAvOpenhomeOrgExakt1(CpDevice aDevice) : base("av-openhome-org", "Exakt", 1, aDevice) { OpenHome.Net.Core.Parameter param; List<String> allowedValues = new List<String>(); iActionDeviceList = new OpenHome.Net.Core.Action("DeviceList"); param = new ParameterString("List", allowedValues); iActionDeviceList.AddOutputParameter(param); iActionDeviceSettings = new OpenHome.Net.Core.Action("DeviceSettings"); param = new ParameterString("DeviceId", allowedValues); iActionDeviceSettings.AddInputParameter(param); param = new ParameterString("Settings", allowedValues); iActionDeviceSettings.AddOutputParameter(param); iActionConnectionStatus = new OpenHome.Net.Core.Action("ConnectionStatus"); param = new ParameterString("ConnectionStatus", allowedValues); iActionConnectionStatus.AddOutputParameter(param); iActionSet = new OpenHome.Net.Core.Action("Set"); param = new ParameterString("DeviceId", allowedValues); iActionSet.AddInputParameter(param); param = new ParameterUint("BankId"); iActionSet.AddInputParameter(param); param = new ParameterString("FileUri", allowedValues); iActionSet.AddInputParameter(param); param = new ParameterBool("Mute"); iActionSet.AddInputParameter(param); param = new ParameterBool("Persist"); iActionSet.AddInputParameter(param); iActionReprogram = new OpenHome.Net.Core.Action("Reprogram"); param = new ParameterString("DeviceId", allowedValues); iActionReprogram.AddInputParameter(param); param = new ParameterString("FileUri", allowedValues); iActionReprogram.AddInputParameter(param); iActionReprogramFallback = new OpenHome.Net.Core.Action("ReprogramFallback"); param = new ParameterString("DeviceId", allowedValues); iActionReprogramFallback.AddInputParameter(param); param = new ParameterString("FileUri", allowedValues); iActionReprogramFallback.AddInputParameter(param); iDeviceList = new PropertyString("DeviceList", DeviceListPropertyChanged); AddProperty(iDeviceList); iConnectionStatus = new PropertyString("ConnectionStatus", ConnectionStatusPropertyChanged); AddProperty(iConnectionStatus); iPropertyLock = new Mutex(); } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> /// <param name="aList"></param> public void SyncDeviceList(out String aList) { SyncDeviceListAvOpenhomeOrgExakt1 sync = new SyncDeviceListAvOpenhomeOrgExakt1(this); BeginDeviceList(sync.AsyncComplete()); sync.Wait(); sync.ReportError(); aList = sync.List(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndDeviceList().</remarks> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginDeviceList(CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionDeviceList, aCallback); int outIndex = 0; invocation.AddOutput(new ArgumentString((ParameterString)iActionDeviceList.OutputParameter(outIndex++))); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> /// <param name="aList"></param> public void EndDeviceList(IntPtr aAsyncHandle, out String aList) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } uint index = 0; aList = Invocation.OutputString(aAsyncHandle, index++); } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> /// <param name="aDeviceId"></param> /// <param name="aSettings"></param> public void SyncDeviceSettings(String aDeviceId, out String aSettings) { SyncDeviceSettingsAvOpenhomeOrgExakt1 sync = new SyncDeviceSettingsAvOpenhomeOrgExakt1(this); BeginDeviceSettings(aDeviceId, sync.AsyncComplete()); sync.Wait(); sync.ReportError(); aSettings = sync.Settings(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndDeviceSettings().</remarks> /// <param name="aDeviceId"></param> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginDeviceSettings(String aDeviceId, CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionDeviceSettings, aCallback); int inIndex = 0; invocation.AddInput(new ArgumentString((ParameterString)iActionDeviceSettings.InputParameter(inIndex++), aDeviceId)); int outIndex = 0; invocation.AddOutput(new ArgumentString((ParameterString)iActionDeviceSettings.OutputParameter(outIndex++))); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> /// <param name="aSettings"></param> public void EndDeviceSettings(IntPtr aAsyncHandle, out String aSettings) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } uint index = 0; aSettings = Invocation.OutputString(aAsyncHandle, index++); } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> /// <param name="aConnectionStatus"></param> public void SyncConnectionStatus(out String aConnectionStatus) { SyncConnectionStatusAvOpenhomeOrgExakt1 sync = new SyncConnectionStatusAvOpenhomeOrgExakt1(this); BeginConnectionStatus(sync.AsyncComplete()); sync.Wait(); sync.ReportError(); aConnectionStatus = sync.ConnectionStatus(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndConnectionStatus().</remarks> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginConnectionStatus(CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionConnectionStatus, aCallback); int outIndex = 0; invocation.AddOutput(new ArgumentString((ParameterString)iActionConnectionStatus.OutputParameter(outIndex++))); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> /// <param name="aConnectionStatus"></param> public void EndConnectionStatus(IntPtr aAsyncHandle, out String aConnectionStatus) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } uint index = 0; aConnectionStatus = Invocation.OutputString(aAsyncHandle, index++); } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> /// <param name="aDeviceId"></param> /// <param name="aBankId"></param> /// <param name="aFileUri"></param> /// <param name="aMute"></param> /// <param name="aPersist"></param> public void SyncSet(String aDeviceId, uint aBankId, String aFileUri, bool aMute, bool aPersist) { SyncSetAvOpenhomeOrgExakt1 sync = new SyncSetAvOpenhomeOrgExakt1(this); BeginSet(aDeviceId, aBankId, aFileUri, aMute, aPersist, sync.AsyncComplete()); sync.Wait(); sync.ReportError(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndSet().</remarks> /// <param name="aDeviceId"></param> /// <param name="aBankId"></param> /// <param name="aFileUri"></param> /// <param name="aMute"></param> /// <param name="aPersist"></param> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginSet(String aDeviceId, uint aBankId, String aFileUri, bool aMute, bool aPersist, CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionSet, aCallback); int inIndex = 0; invocation.AddInput(new ArgumentString((ParameterString)iActionSet.InputParameter(inIndex++), aDeviceId)); invocation.AddInput(new ArgumentUint((ParameterUint)iActionSet.InputParameter(inIndex++), aBankId)); invocation.AddInput(new ArgumentString((ParameterString)iActionSet.InputParameter(inIndex++), aFileUri)); invocation.AddInput(new ArgumentBool((ParameterBool)iActionSet.InputParameter(inIndex++), aMute)); invocation.AddInput(new ArgumentBool((ParameterBool)iActionSet.InputParameter(inIndex++), aPersist)); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> public void EndSet(IntPtr aAsyncHandle) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> /// <param name="aDeviceId"></param> /// <param name="aFileUri"></param> public void SyncReprogram(String aDeviceId, String aFileUri) { SyncReprogramAvOpenhomeOrgExakt1 sync = new SyncReprogramAvOpenhomeOrgExakt1(this); BeginReprogram(aDeviceId, aFileUri, sync.AsyncComplete()); sync.Wait(); sync.ReportError(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndReprogram().</remarks> /// <param name="aDeviceId"></param> /// <param name="aFileUri"></param> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginReprogram(String aDeviceId, String aFileUri, CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionReprogram, aCallback); int inIndex = 0; invocation.AddInput(new ArgumentString((ParameterString)iActionReprogram.InputParameter(inIndex++), aDeviceId)); invocation.AddInput(new ArgumentString((ParameterString)iActionReprogram.InputParameter(inIndex++), aFileUri)); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> public void EndReprogram(IntPtr aAsyncHandle) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> /// <param name="aDeviceId"></param> /// <param name="aFileUri"></param> public void SyncReprogramFallback(String aDeviceId, String aFileUri) { SyncReprogramFallbackAvOpenhomeOrgExakt1 sync = new SyncReprogramFallbackAvOpenhomeOrgExakt1(this); BeginReprogramFallback(aDeviceId, aFileUri, sync.AsyncComplete()); sync.Wait(); sync.ReportError(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndReprogramFallback().</remarks> /// <param name="aDeviceId"></param> /// <param name="aFileUri"></param> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginReprogramFallback(String aDeviceId, String aFileUri, CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionReprogramFallback, aCallback); int inIndex = 0; invocation.AddInput(new ArgumentString((ParameterString)iActionReprogramFallback.InputParameter(inIndex++), aDeviceId)); invocation.AddInput(new ArgumentString((ParameterString)iActionReprogramFallback.InputParameter(inIndex++), aFileUri)); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> public void EndReprogramFallback(IntPtr aAsyncHandle) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } } /// <summary> /// Set a delegate to be run when the DeviceList state variable changes. /// </summary> /// <remarks>Callbacks may be run in different threads but callbacks for a /// CpProxyAvOpenhomeOrgExakt1 instance will not overlap.</remarks> /// <param name="aDeviceListChanged">The delegate to run when the state variable changes</param> public void SetPropertyDeviceListChanged(System.Action aDeviceListChanged) { lock (iPropertyLock) { iDeviceListChanged = aDeviceListChanged; } } private void DeviceListPropertyChanged() { lock (iPropertyLock) { ReportEvent(iDeviceListChanged); } } /// <summary> /// Set a delegate to be run when the ConnectionStatus state variable changes. /// </summary> /// <remarks>Callbacks may be run in different threads but callbacks for a /// CpProxyAvOpenhomeOrgExakt1 instance will not overlap.</remarks> /// <param name="aConnectionStatusChanged">The delegate to run when the state variable changes</param> public void SetPropertyConnectionStatusChanged(System.Action aConnectionStatusChanged) { lock (iPropertyLock) { iConnectionStatusChanged = aConnectionStatusChanged; } } private void ConnectionStatusPropertyChanged() { lock (iPropertyLock) { ReportEvent(iConnectionStatusChanged); } } /// <summary> /// Query the value of the DeviceList property. /// </summary> /// <remarks>This function is threadsafe and can only be called if Subscribe() has been /// called and a first eventing callback received more recently than any call /// to Unsubscribe().</remarks> /// <returns>Value of the DeviceList property</returns> public String PropertyDeviceList() { PropertyReadLock(); String val; try { val = iDeviceList.Value(); } finally { PropertyReadUnlock(); } return val; } /// <summary> /// Query the value of the ConnectionStatus property. /// </summary> /// <remarks>This function is threadsafe and can only be called if Subscribe() has been /// called and a first eventing callback received more recently than any call /// to Unsubscribe().</remarks> /// <returns>Value of the ConnectionStatus property</returns> public String PropertyConnectionStatus() { PropertyReadLock(); String val; try { val = iConnectionStatus.Value(); } finally { PropertyReadUnlock(); } return val; } /// <summary> /// Must be called for each class instance. Must be called before Core.Library.Close(). /// </summary> public void Dispose() { lock (this) { if (iHandle == IntPtr.Zero) return; DisposeProxy(); iHandle = IntPtr.Zero; } iActionDeviceList.Dispose(); iActionDeviceSettings.Dispose(); iActionConnectionStatus.Dispose(); iActionSet.Dispose(); iActionReprogram.Dispose(); iActionReprogramFallback.Dispose(); iDeviceList.Dispose(); iConnectionStatus.Dispose(); } } }
// 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 Microsoft.AspNet.Razor.Generator; using Microsoft.AspNet.Razor.Parser; using Microsoft.AspNet.Razor.Parser.SyntaxTree; using Microsoft.AspNet.Razor.Test.Framework; using Xunit; namespace Microsoft.AspNet.Razor.Test.Parser.CSharp { // Basic Tests for C# Statements: // * Basic case for each statement // * Basic case for ALL clauses // This class DOES NOT contain // * Error cases // * Tests for various types of nested statements // * Comment tests public class CSharpStatementTest : CsHtmlCodeParserTestBase { [Fact] public void ForStatement() { ParseBlockTest("@for(int i = 0; i++; i < length) { foo(); }", new StatementBlock( Factory.CodeTransition(), Factory.Code("for(int i = 0; i++; i < length) { foo(); }") .AsStatement() .Accepts(AcceptedCharacters.None) )); } [Fact] public void ForEachStatement() { ParseBlockTest("@foreach(var foo in bar) { foo(); }", new StatementBlock( Factory.CodeTransition(), Factory.Code("foreach(var foo in bar) { foo(); }") .AsStatement() .Accepts(AcceptedCharacters.None) )); } [Fact] public void WhileStatement() { ParseBlockTest("@while(true) { foo(); }", new StatementBlock( Factory.CodeTransition(), Factory.Code("while(true) { foo(); }") .AsStatement() .Accepts(AcceptedCharacters.None) )); } [Fact] public void SwitchStatement() { ParseBlockTest("@switch(foo) { foo(); }", new StatementBlock( Factory.CodeTransition(), Factory.Code("switch(foo) { foo(); }") .AsStatement() .Accepts(AcceptedCharacters.None) )); } [Fact] public void LockStatement() { ParseBlockTest("@lock(baz) { foo(); }", new StatementBlock( Factory.CodeTransition(), Factory.Code("lock(baz) { foo(); }") .AsStatement() .Accepts(AcceptedCharacters.None) )); } [Fact] public void IfStatement() { ParseBlockTest("@if(true) { foo(); }", new StatementBlock( Factory.CodeTransition(), Factory.Code("if(true) { foo(); }") .AsStatement() )); } [Fact] public void ElseIfClause() { ParseBlockTest("@if(true) { foo(); } else if(false) { foo(); } else if(!false) { foo(); }", new StatementBlock( Factory.CodeTransition(), Factory.Code("if(true) { foo(); } else if(false) { foo(); } else if(!false) { foo(); }") .AsStatement() )); } [Fact] public void ElseClause() { ParseBlockTest("@if(true) { foo(); } else { foo(); }", new StatementBlock( Factory.CodeTransition(), Factory.Code("if(true) { foo(); } else { foo(); }") .AsStatement() .Accepts(AcceptedCharacters.None) )); } [Fact] public void TryStatement() { ParseBlockTest("@try { foo(); }", new StatementBlock( Factory.CodeTransition(), Factory.Code("try { foo(); }") .AsStatement() )); } [Fact] public void CatchClause() { ParseBlockTest("@try { foo(); } catch(IOException ioex) { handleIO(); } catch(Exception ex) { handleOther(); }", new StatementBlock( Factory.CodeTransition(), Factory.Code("try { foo(); } catch(IOException ioex) { handleIO(); } catch(Exception ex) { handleOther(); }") .AsStatement() )); } [Fact] public void FinallyClause() { ParseBlockTest("@try { foo(); } finally { Dispose(); }", new StatementBlock( Factory.CodeTransition(), Factory.Code("try { foo(); } finally { Dispose(); }") .AsStatement() .Accepts(AcceptedCharacters.None) )); } [Fact] public void UsingStatement() { ParseBlockTest("@using(var foo = new Foo()) { foo.Bar(); }", new StatementBlock( Factory.CodeTransition(), Factory.Code("using(var foo = new Foo()) { foo.Bar(); }") .AsStatement() .Accepts(AcceptedCharacters.None) )); } [Fact] public void UsingTypeAlias() { ParseBlockTest("@using StringDictionary = System.Collections.Generic.Dictionary<string, string>", new DirectiveBlock( Factory.CodeTransition(), Factory.Code("using StringDictionary = System.Collections.Generic.Dictionary<string, string>") .AsNamespaceImport(" StringDictionary = System.Collections.Generic.Dictionary<string, string>", 5) .Accepts(AcceptedCharacters.AnyExceptNewline) )); } [Fact] public void UsingNamespaceImport() { ParseBlockTest("@using System.Text.Encoding.ASCIIEncoding", new DirectiveBlock( Factory.CodeTransition(), Factory.Code("using System.Text.Encoding.ASCIIEncoding") .AsNamespaceImport(" System.Text.Encoding.ASCIIEncoding", 5) .Accepts(AcceptedCharacters.AnyExceptNewline) )); } [Fact] public void DoStatement() { ParseBlockTest("@do { foo(); } while(true);", new StatementBlock( Factory.CodeTransition(), Factory.Code("do { foo(); } while(true);") .AsStatement() .Accepts(AcceptedCharacters.None) )); } [Fact] public void NonBlockKeywordTreatedAsImplicitExpression() { ParseBlockTest("@is foo", new ExpressionBlock(new ExpressionCodeGenerator(), Factory.CodeTransition(), Factory.Code("is") .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) .Accepts(AcceptedCharacters.NonWhiteSpace) )); } } }
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; using System.Text; using System.IO; using System.Collections.Generic; using DBus; using org.freedesktop.DBus; class BusMonitor { static Connection bus = null; public static int Main (string[] args) { bus = null; bool readIn = false; bool readOut = false; List<string> rules = new List<string> (); for (int i = 0 ; i != args.Length ; i++) { string arg = args[i]; if (!arg.StartsWith ("--")) { rules.Add (arg); continue; } switch (arg) { case "--stdin": readIn = true; break; case "--stdout": readOut = true; break; case "--system": bus = Bus.System; break; case "--session": bus = Bus.Session; break; default: Console.Error.WriteLine ("Usage: monitor.exe [--stdin|--stdout|--system|--session] [watch expressions]"); Console.Error.WriteLine (" If no watch expressions are provided, defaults will be used."); return 1; } } if (bus == null) bus = Bus.Session; if (rules.Count != 0) { //install custom match rules only foreach (string rule in rules) bus.AddMatch (rule); } else { //no custom match rules, install the defaults bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.Signal)); bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.MethodReturn)); bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.Error)); bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.MethodCall)); } if (readIn) { ReadIn (); return 0; } if (readOut) { ReadOut (); return 0; } PrettyPrintOut (); return 0; } static void ReadIn () { TextReader r = Console.In; while (true) { Message msg = MessageDumper.ReadMessage (r); if (msg == null) break; PrintMessage (msg); Console.WriteLine (); /* byte[] header = MessageDumper.ReadBlock (r); if (header == null) break; PrintHeader (header); byte[] body = MessageDumper.ReadBlock (r); PrintBody (header); */ } } static void ReadOut () { TextWriter w = Console.Out; DumpConn (bus, w); while (true) { Message msg = bus.Transport.ReadMessage (); if (msg == null) break; DumpMessage (msg, w); } } static void PrettyPrintOut () { while (true) { Message msg = bus.Transport.ReadMessage (); if (msg == null) break; PrintMessage (msg); Console.WriteLine (); } } static void DumpConn (Connection conn, TextWriter w) { w.WriteLine ("# This is a managed D-Bus protocol dump"); w.WriteLine (); w.WriteLine ("# Machine: " + Connection.MachineId); w.WriteLine ("# Connection: " + conn.Id); w.WriteLine ("# Date: " + DateTime.Now.ToString ("F")); w.WriteLine (); } static DateTime startTime = DateTime.Now; static void DumpMessage (Message msg, TextWriter w) { w.WriteLine ("# Message: " + msg.Header.Serial); TimeSpan delta = DateTime.Now - startTime; startTime = DateTime.Now; w.WriteLine ("# Time delta: " + delta.Ticks); w.WriteLine ("# Header"); MessageDumper.WriteBlock (msg.GetHeaderData (), w); w.WriteLine ("# Body"); MessageDumper.WriteBlock (msg.Body, w); w.WriteLine (); w.Flush (); } const string indent = " "; static void PrintMessage (Message msg) { Console.WriteLine ("Message (" + msg.Header.Endianness + " endian, v" + msg.Header.MajorVersion + "):"); Console.WriteLine (indent + "Type: " + msg.Header.MessageType); Console.WriteLine (indent + "Flags: " + msg.Header.Flags); Console.WriteLine (indent + "Serial: " + msg.Header.Serial); //foreach (HeaderField hf in msg.HeaderFields) // Console.WriteLine (indent + hf.Code + ": " + hf.Value); Console.WriteLine (indent + "Header Fields:"); foreach (KeyValuePair<byte,object> field in msg.Header.Fields) Console.WriteLine (indent + indent + field.Key + ": " + field.Value); Console.WriteLine (indent + "Body (" + msg.Header.Length + " bytes):"); if (msg.Body != null) { MessageReader reader = new MessageReader (msg); int argNum = 0; foreach (Signature sig in msg.Signature.GetParts ()) { //Console.Write (indent + indent + "arg" + argNum + " " + sig + ": "); PrintValue (reader, sig, 1); /* if (sig.IsPrimitive) { object arg = reader.ReadValue (sig[0]); Console.WriteLine (arg); } else { if (sig.IsArray) { //foreach (Signature elemSig in writer.StepInto (sig)) } reader.StepOver (sig); Console.WriteLine ("?"); } */ argNum++; } } } static void PrintValue (MessageReader reader, Signature sig, int depth) { string indent = new String (' ', depth * 2); indent += " "; //Console.Write (indent + indent + "arg" + argNum + " " + sig + ": "); Console.Write (indent); if (sig == Signature.VariantSig) { foreach (Signature elemSig in reader.StepInto (sig)) { Console.WriteLine ("Variant '{0}' (", elemSig); PrintValue (reader, elemSig, depth + 1); Console.WriteLine (indent + ")"); } } else if (sig.IsPrimitive) { object arg = reader.ReadValue (sig[0]); Type argType = sig.ToType (); if (sig == Signature.StringSig || sig == Signature.ObjectPathSig) Console.WriteLine ("{0} \"{1}\"", argType.Name, arg); else if (sig == Signature.SignatureSig) Console.WriteLine ("{0} '{1}'", argType.Name, arg); else Console.WriteLine ("{0} {1}", argType.Name, arg); } else if (sig.IsArray) { Console.WriteLine ("Array ["); foreach (Signature elemSig in reader.StepInto (sig)) PrintValue (reader, elemSig, depth + 1); Console.WriteLine (indent + "]"); } else if (sig.IsDictEntry) { Console.WriteLine ("DictEntry {"); foreach (Signature elemSig in reader.StepInto (sig)) PrintValue (reader, elemSig, depth + 1); Console.WriteLine (indent + "}"); } else if (sig.IsStruct) { Console.WriteLine ("Struct {"); foreach (Signature elemSig in reader.StepInto (sig)) PrintValue (reader, elemSig, depth + 1); Console.WriteLine (indent + "}"); } else { reader.StepOver (sig); Console.WriteLine ("'{0}'?", sig); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Configuration.Internal; using System.IO; using System.Runtime.Versioning; namespace System.Configuration { // An instance of the Configuration class represents a single level // in the configuration hierarchy. Its contents can be edited and // saved to disk. // // It is not thread safe for writing. public sealed class Configuration { private readonly MgmtConfigurationRecord _configRecord; private readonly object[] _hostInitConfigurationParams; private readonly Type _typeConfigHost; private Func<string, string> _assemblyStringTransformer; private ContextInformation _evalContext; private ConfigurationLocationCollection _locations; private ConfigurationSectionGroup _rootSectionGroup; private Stack _sectionsStack; private Func<string, string> _typeStringTransformer; internal Configuration(string locationSubPath, Type typeConfigHost, params object[] hostInitConfigurationParams) { _typeConfigHost = typeConfigHost; _hostInitConfigurationParams = hostInitConfigurationParams; IInternalConfigHost configHost = (IInternalConfigHost)TypeUtil.CreateInstance(typeConfigHost); // Wrap the host with the UpdateConfigHost to support SaveAs. UpdateConfigHost updateConfigHost = new UpdateConfigHost(configHost); // Now wrap in ImplicitMachineConfigHost so we can stub in a simple machine.config if needed. IInternalConfigHost implicitMachineConfigHost = new ImplicitMachineConfigHost(updateConfigHost); InternalConfigRoot configRoot = new InternalConfigRoot(this, updateConfigHost); ((IInternalConfigRoot)configRoot).Init(implicitMachineConfigHost, isDesignTime: true); // Set the configuration paths for this Configuration. // // We do this in a separate step so that the WebConfigurationHost // can use this object's _configRoot to get the <sites> section, // which is used in it's MapPath implementation. string configPath, locationConfigPath; implicitMachineConfigHost.InitForConfiguration( ref locationSubPath, out configPath, out locationConfigPath, configRoot, hostInitConfigurationParams); if (!string.IsNullOrEmpty(locationSubPath) && !implicitMachineConfigHost.SupportsLocation) throw ExceptionUtil.UnexpectedError("Configuration::ctor"); if (string.IsNullOrEmpty(locationSubPath) != string.IsNullOrEmpty(locationConfigPath)) throw ExceptionUtil.UnexpectedError("Configuration::ctor"); // Get the configuration record for this config file. _configRecord = (MgmtConfigurationRecord)configRoot.GetConfigRecord(configPath); // Create another MgmtConfigurationRecord for the location that is a child of the above record. // Note that this does not match the resolution hiearchy that is used at runtime. if (!string.IsNullOrEmpty(locationSubPath)) { _configRecord = MgmtConfigurationRecord.Create( configRoot, _configRecord, locationConfigPath, locationSubPath); } // Throw if the config record we created contains global errors. _configRecord.ThrowIfInitErrors(); } public AppSettingsSection AppSettings => (AppSettingsSection)GetSection("appSettings"); public ConnectionStringsSection ConnectionStrings => (ConnectionStringsSection)GetSection("connectionStrings"); public string FilePath => _configRecord.ConfigurationFilePath; public bool HasFile => _configRecord.HasStream; public ConfigurationLocationCollection Locations => _locations ?? (_locations = _configRecord.GetLocationCollection(this)); public ContextInformation EvaluationContext => _evalContext ?? (_evalContext = new ContextInformation(_configRecord)); public ConfigurationSectionGroup RootSectionGroup { get { if (_rootSectionGroup == null) { _rootSectionGroup = new ConfigurationSectionGroup(); _rootSectionGroup.RootAttachToConfigurationRecord(_configRecord); } return _rootSectionGroup; } } public ConfigurationSectionCollection Sections => RootSectionGroup.Sections; public ConfigurationSectionGroupCollection SectionGroups => RootSectionGroup.SectionGroups; // Is the namespace declared in the file or not? // // ie. xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0" // (currently this is the only one we allow) public bool NamespaceDeclared { get { return _configRecord.NamespacePresent; } set { _configRecord.NamespacePresent = value; } } public Func<string, string> TypeStringTransformer { get { return _typeStringTransformer; } set { if (_typeStringTransformer != value) { TypeStringTransformerIsSet = value != null; _typeStringTransformer = value; } } } public Func<string, string> AssemblyStringTransformer { get { return _assemblyStringTransformer; } set { if (_assemblyStringTransformer != value) { AssemblyStringTransformerIsSet = value != null; _assemblyStringTransformer = value; } } } public FrameworkName TargetFramework { get; set; } = null; internal bool TypeStringTransformerIsSet { get; private set; } internal bool AssemblyStringTransformerIsSet { get; private set; } internal Stack SectionsStack => _sectionsStack ?? (_sectionsStack = new Stack()); // Create a new instance of Configuration for the locationSubPath, // with the initialization parameters that were used to create this configuration. internal Configuration OpenLocationConfiguration(string locationSubPath) { return new Configuration(locationSubPath, _typeConfigHost, _hostInitConfigurationParams); } // public methods public ConfigurationSection GetSection(string sectionName) { ConfigurationSection section = (ConfigurationSection)_configRecord.GetSection(sectionName); return section; } public ConfigurationSectionGroup GetSectionGroup(string sectionGroupName) { ConfigurationSectionGroup sectionGroup = _configRecord.GetSectionGroup(sectionGroupName); return sectionGroup; } public void Save() { SaveAsImpl(null, ConfigurationSaveMode.Modified, false); } public void Save(ConfigurationSaveMode saveMode) { SaveAsImpl(null, saveMode, false); } public void Save(ConfigurationSaveMode saveMode, bool forceSaveAll) { SaveAsImpl(null, saveMode, forceSaveAll); } public void SaveAs(string filename) { SaveAs(filename, ConfigurationSaveMode.Modified, false); } public void SaveAs(string filename, ConfigurationSaveMode saveMode) { SaveAs(filename, saveMode, false); } public void SaveAs(string filename, ConfigurationSaveMode saveMode, bool forceSaveAll) { if (string.IsNullOrEmpty(filename)) throw ExceptionUtil.ParameterNullOrEmpty(nameof(filename)); SaveAsImpl(filename, saveMode, forceSaveAll); } private void SaveAsImpl(string filename, ConfigurationSaveMode saveMode, bool forceSaveAll) { filename = string.IsNullOrEmpty(filename) ? null : Path.GetFullPath(filename); if (forceSaveAll) ForceGroupsRecursive(RootSectionGroup); _configRecord.SaveAs(filename, saveMode, forceSaveAll); } // Force all sections and section groups to be instantiated. private void ForceGroupsRecursive(ConfigurationSectionGroup group) { foreach (ConfigurationSection configSection in group.Sections) { // Force the section to be read into the cache ConfigurationSection section = group.Sections[configSection.SectionInformation.Name]; } foreach (ConfigurationSectionGroup sectionGroup in group.SectionGroups) ForceGroupsRecursive(group.SectionGroups[sectionGroup.Name]); } } }
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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 MassTransit.NHibernateIntegration.Saga { using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Transactions; using GreenPipes; using Logging; using MassTransit.Saga; using NHibernate; using NHibernate.Exceptions; using Util; public class NHibernateSagaRepository<TSaga> : ISagaRepository<TSaga>, IQuerySagaRepository<TSaga> where TSaga : class, ISaga { static readonly ILog _log = Logger.Get<NHibernateSagaRepository<TSaga>>(); readonly ISessionFactory _sessionFactory; public NHibernateSagaRepository(ISessionFactory sessionFactory) { _sessionFactory = sessionFactory; } public NHibernateSagaRepository(ISessionFactory sessionFactory, System.Data.IsolationLevel isolationLevel) { _sessionFactory = sessionFactory; } public async Task<IEnumerable<Guid>> Find(ISagaQuery<TSaga> query) { using (var session = _sessionFactory.OpenSession()) { return await session.QueryOver<TSaga>() .Where(query.FilterExpression) .Select(x => x.CorrelationId) .ListAsync<Guid>().ConfigureAwait(false); } } void IProbeSite.Probe(ProbeContext context) { var scope = context.CreateScope("sagaRepository"); scope.Set(new { Persistence = "nhibernate", Entities = _sessionFactory.GetAllClassMetadata().Select(x => x.Value.EntityName).ToArray() }); } async Task ISagaRepository<TSaga>.Send<T>(ConsumeContext<T> context, ISagaPolicy<TSaga, T> policy, IPipe<SagaConsumeContext<TSaga, T>> next) { if (!context.CorrelationId.HasValue) throw new SagaException("The CorrelationId was not specified", typeof(TSaga), typeof(T)); var sagaId = context.CorrelationId.Value; using (var session = _sessionFactory.OpenSession()) using (var transaction = session.BeginTransaction()) { var inserted = false; if (policy.PreInsertInstance(context, out var instance)) inserted = await PreInsertSagaInstance<T>(session, instance).ConfigureAwait(false); try { if (instance == null) instance = await session.GetAsync<TSaga>(sagaId, LockMode.Upgrade).ConfigureAwait(false); if (instance == null) { var missingSagaPipe = new MissingPipe<T>(session, next); await policy.Missing(context, missingSagaPipe).ConfigureAwait(false); } else { if (_log.IsDebugEnabled) _log.DebugFormat("SAGA:{0}:{1} Used {2}", TypeMetadataCache<TSaga>.ShortName, instance.CorrelationId, TypeMetadataCache<T>.ShortName); var sagaConsumeContext = new NHibernateSagaConsumeContext<TSaga, T>(session, context, instance); await policy.Existing(sagaConsumeContext, next).ConfigureAwait(false); if (inserted && !sagaConsumeContext.IsCompleted) await session.UpdateAsync(instance).ConfigureAwait(false); } if (transaction.IsActive) await transaction.CommitAsync().ConfigureAwait(false); } catch (Exception ex) { if (_log.IsErrorEnabled) _log.Error($"SAGA:{TypeMetadataCache<TSaga>.ShortName} Exception {TypeMetadataCache<T>.ShortName}", ex); if (transaction.IsActive) await transaction.RollbackAsync().ConfigureAwait(false); throw; } } } public async Task SendQuery<T>(SagaQueryConsumeContext<TSaga, T> context, ISagaPolicy<TSaga, T> policy, IPipe<SagaConsumeContext<TSaga, T>> next) where T : class { using (var session = _sessionFactory.OpenSession()) using (var transaction = session.BeginTransaction()) { try { IList<TSaga> instances = await session.QueryOver<TSaga>() .Where(context.Query.FilterExpression) .ListAsync<TSaga>() .ConfigureAwait(false); if (instances.Count == 0) { var missingSagaPipe = new MissingPipe<T>(session, next); await policy.Missing(context, missingSagaPipe).ConfigureAwait(false); } else await Task.WhenAll(instances.Select(instance => SendToInstance(context, policy, instance, next, session))).ConfigureAwait(false); // TODO partial failure should not affect them all if (transaction.IsActive) await transaction.CommitAsync().ConfigureAwait(false); } catch (SagaException sex) { if (_log.IsErrorEnabled) _log.Error($"SAGA:{TypeMetadataCache<TSaga>.ShortName} Exception {TypeMetadataCache<T>.ShortName}", sex); if (transaction.IsActive) await transaction.RollbackAsync().ConfigureAwait(false); throw; } catch (Exception ex) { if (_log.IsErrorEnabled) _log.Error($"SAGA:{TypeMetadataCache<TSaga>.ShortName} Exception {TypeMetadataCache<T>.ShortName}", ex); if (transaction.IsActive) await transaction.RollbackAsync().ConfigureAwait(false); throw new SagaException(ex.Message, typeof(TSaga), typeof(T), Guid.Empty, ex); } } } static async Task<bool> PreInsertSagaInstance<T>(ISession session, TSaga instance) { bool inserted = false; try { await session.SaveAsync(instance).ConfigureAwait(false); await session.FlushAsync().ConfigureAwait(false); inserted = true; _log.DebugFormat("SAGA:{0}:{1} Insert {2}", TypeMetadataCache<TSaga>.ShortName, instance.CorrelationId, TypeMetadataCache<T>.ShortName); } catch (GenericADOException ex) { if (_log.IsDebugEnabled) { _log.DebugFormat("SAGA:{0}:{1} Dupe {2} - {3}", TypeMetadataCache<TSaga>.ShortName, instance.CorrelationId, TypeMetadataCache<T>.ShortName, ex.Message); } } return inserted; } static Task SendToInstance<T>(SagaQueryConsumeContext<TSaga, T> context, ISagaPolicy<TSaga, T> policy, TSaga instance, IPipe<SagaConsumeContext<TSaga, T>> next, ISession session) where T : class { try { if (_log.IsDebugEnabled) _log.DebugFormat("SAGA:{0}:{1} Used {2}", TypeMetadataCache<TSaga>.ShortName, instance.CorrelationId, TypeMetadataCache<T>.ShortName); var sagaConsumeContext = new NHibernateSagaConsumeContext<TSaga, T>(session, context, instance); return policy.Existing(sagaConsumeContext, next); } catch (SagaException) { throw; } catch (Exception ex) { throw new SagaException(ex.Message, typeof(TSaga), typeof(T), instance.CorrelationId, ex); } } /// <summary> /// Once the message pipe has processed the saga instance, add it to the saga repository /// </summary> /// <typeparam name="TMessage"></typeparam> class MissingPipe<TMessage> : IPipe<SagaConsumeContext<TSaga, TMessage>> where TMessage : class { readonly IPipe<SagaConsumeContext<TSaga, TMessage>> _next; readonly ISession _session; public MissingPipe(ISession session, IPipe<SagaConsumeContext<TSaga, TMessage>> next) { _session = session; _next = next; } void IProbeSite.Probe(ProbeContext context) { _next.Probe(context); } public async Task Send(SagaConsumeContext<TSaga, TMessage> context) { if (_log.IsDebugEnabled) { _log.DebugFormat("SAGA:{0}:{1} Added {2}", TypeMetadataCache<TSaga>.ShortName, context.Saga.CorrelationId, TypeMetadataCache<TMessage>.ShortName); } SagaConsumeContext<TSaga, TMessage> proxy = new NHibernateSagaConsumeContext<TSaga, TMessage>(_session, context, context.Saga); await _next.Send(proxy).ConfigureAwait(false); if (!proxy.IsCompleted) await _session.SaveAsync(context.Saga).ConfigureAwait(false); } } } }
using System; using System.Collections.Generic; using System.Text; using System.Drawing.Printing; using System.Drawing; using DowUtils; namespace Factotum { class RsCmpDetails : ReportSection { public RsCmpDetails(MainReport report, ReportSectionRules rules, int subsections) : base(report, rules, subsections) { } public override bool IsIncluded() { return true; } public override bool CanFitSome(PrintPageEventArgs args, float Y) { return true; } public override bool Print(PrintPageEventArgs args, float Y) { // Todo: use measurement graphics for row height? Graphics g = args.Graphics; Graphics measure = args.PageSettings.PrinterSettings.CreateMeasurementGraphics(); int leftX = args.MarginBounds.X; int centerX = (int)(leftX + args.MarginBounds.Width / 2); int rightX = leftX + args.MarginBounds.Width; int curX = leftX; int padding = 5; float startY = Y + padding; float curY = startY; float maxY = startY; // Get the dimensions table. int rows; int cols=0; string[,] dimensions = GetDimensionsArray(out rows); string[,] chrome; Font curFont = rpt.regTextFont; // Put the Schedule left-aligned . string s = rpt.eComponent.ComponentSchedule == null ? "Schedule: N/A" : rpt.eComponent.ComponentSchedule; g.DrawString(s, curFont, Brushes.Black, leftX, curY); curY += curFont.Height + padding; // Put the Dimensions table left-aligned curY = DrawTable(dimensions, rows, 4, 1, 1, g, leftX, curY, 100, 50, 2, rpt.boldRegTextFont, rpt.regTextFont, true, true); if (curY > maxY) maxY = curY; // If we have chromium data, get the chromium table and draw it right-justified. if (rpt.eComponent.ComponentPctChromeMain != null) { curY = startY + curFont.Height + padding; chrome = GetChromiumArray(out cols); curX = rightX - 60 * cols; curY = DrawTable(chrome, 2, cols, 1, 1, g, curX, curY, 60, 60, 2, rpt.boldRegTextFont, rpt.regTextFont, true, true); if (curY > maxY) maxY = curY; } else curX = 500; curY = startY; // Put the Material left-aligned with the chromium table which will follow. s = rpt.eComponent.ComponentMaterialName == null ? "Material: N/A" : "Material: " + rpt.eComponent.ComponentMaterialName; curFont = rpt.regTextFont; g.DrawString(s, curFont, Brushes.Black, curX, curY); curY += curFont.Height; if (curY > maxY) maxY = curY; this.Y = maxY; return true; } private string[,] GetDimensionsArray(out int rows) { // First make a 2D string array to contain all the data that we want to present // The following rules apply: If the downstream main dimensions are null // The row header for the first row should read "Main" and no ds main row should be shown, // otherwise the first row header should be "Upstream Main" // The branch row should only show if its values are non-null // The us ext row should only show if its values do not match the us main row // The ds ext row should only show if either the ds main dimensions are null and its values // don't match the us main values or // if the ds main dimensions are not null and its values don't match the ds main values. // The branch ext row should only show if the branch dimensions are not null string[,] table = new string[7, 4]; // Heading row int row = 0; int col = 0; table[row, col] = "Dimensions"; col++; table[row, col] = "OD"; col++; table[row, col] = "Tnom"; col++; table[row, col] = "Tscr"; // US Main/Main row col = 0; row++; table[row, col] = rpt.eComponent.ComponentDnMainOd == null ? "Main" : "U/S Main"; col++; table[row, col] = Util.GetFormattedDecimal_NA(rpt.eComponent.ComponentUpMainOd); col++; table[row, col] = Util.GetFormattedDecimal_NA(rpt.eComponent.ComponentUpMainTnom); col++; table[row, col] = Util.GetFormattedDecimal_NA(rpt.eComponent.ComponentUpMainTscr); // DS Main row if (rpt.eComponent.ComponentDnMainOd != null) { col = 0; row++; table[row, col] = "D/S Main"; col++; table[row, col] = Util.GetFormattedDecimal_NA(rpt.eComponent.ComponentDnMainOd); col++; table[row, col] = Util.GetFormattedDecimal_NA(rpt.eComponent.ComponentDnMainTnom); col++; table[row, col] = Util.GetFormattedDecimal_NA(rpt.eComponent.ComponentDnMainTscr); } // Branch row if (rpt.eComponent.ComponentBranchOd != null) { col = 0; row++; table[row, col] = "Branch"; col++; table[row, col] = Util.GetFormattedDecimal_NA(rpt.eComponent.ComponentBranchOd); col++; table[row, col] = Util.GetFormattedDecimal_NA(rpt.eComponent.ComponentBranchTnom); col++; table[row, col] = Util.GetFormattedDecimal_NA(rpt.eComponent.ComponentBranchTscr); } // Upstream extension row if (rpt.eComponent.ComponentUpExtOd != rpt.eComponent.ComponentUpMainOd || rpt.eComponent.ComponentUpExtTnom != rpt.eComponent.ComponentUpMainTnom || rpt.eComponent.ComponentUpExtTscr != rpt.eComponent.ComponentUpMainTscr ) { col = 0; row++; table[row, col] = "U/S Ext."; col++; table[row, col] = Util.GetFormattedDecimal_NA(rpt.eComponent.ComponentUpExtOd); col++; table[row, col] = Util.GetFormattedDecimal_NA(rpt.eComponent.ComponentUpExtTnom); col++; table[row, col] = Util.GetFormattedDecimal_NA(rpt.eComponent.ComponentUpExtTscr); } // Downstream extension row if ((rpt.eComponent.ComponentDnMainOd == null && (rpt.eComponent.ComponentDnExtOd != rpt.eComponent.ComponentUpMainOd || rpt.eComponent.ComponentDnExtTnom != rpt.eComponent.ComponentUpMainTnom || rpt.eComponent.ComponentDnExtTscr != rpt.eComponent.ComponentUpMainTscr)) || (rpt.eComponent.ComponentDnMainOd != null && (rpt.eComponent.ComponentDnExtOd != rpt.eComponent.ComponentDnMainOd || rpt.eComponent.ComponentDnExtTnom != rpt.eComponent.ComponentDnMainTnom || rpt.eComponent.ComponentDnExtTscr != rpt.eComponent.ComponentDnMainTscr))) { col = 0; row++; table[row, col] = "D/S Ext."; col++; table[row, col] = Util.GetFormattedDecimal_NA(rpt.eComponent.ComponentDnExtOd); col++; table[row, col] = Util.GetFormattedDecimal_NA(rpt.eComponent.ComponentDnExtTnom); col++; table[row, col] = Util.GetFormattedDecimal_NA(rpt.eComponent.ComponentDnExtTscr); } // Branch extension row if (rpt.eComponent.ComponentBranchOd != null && (rpt.eComponent.ComponentBrExtOd != rpt.eComponent.ComponentBranchOd || rpt.eComponent.ComponentBrExtTnom != rpt.eComponent.ComponentBranchTnom || rpt.eComponent.ComponentBrExtTscr != rpt.eComponent.ComponentBranchTscr)) { col = 0; row++; table[row, col] = "Branch Ext."; col++; table[row, col] = Util.GetFormattedDecimal_NA(rpt.eComponent.ComponentUpExtOd); col++; table[row, col] = Util.GetFormattedDecimal_NA(rpt.eComponent.ComponentUpExtTnom); col++; table[row, col] = Util.GetFormattedDecimal_NA(rpt.eComponent.ComponentUpExtTscr); } rows = row+1; return table; } private string[,] GetChromiumArray(out int cols) { // First make a 2D string array to contain all the data that we want to present // Before calling this function, make sure that Chromium data exists. string[,] table = new string[2, 6]; // Flag whether the component has a branch bool hasBranch = rpt.eComponent.ComponentBranchOd != null; // Heading row int row = 0; int col = 0; table[row, col] = ""; col++; table[row, col] = "Main"; col++; table[row, col] = "U/S Ext."; col++; table[row, col] = "D/S Ext."; // Only show branch data if it has a branch. if (hasBranch) { col++; table[row, col] = "Branch"; col++; table[row, col] = "Br. Ext."; } // Chromium row col = 0; row++; table[row, col] = "% Cr"; col++; table[row, col] = Util.GetFormattedDecimal_Percent_NA(rpt.eComponent.ComponentPctChromeMain); col++; table[row, col] = Util.GetFormattedDecimal_Percent_NA(rpt.eComponent.ComponentPctChromeUsExt); col++; table[row, col] = Util.GetFormattedDecimal_Percent_NA(rpt.eComponent.ComponentPctChromeDsExt); // Only show branch data if it has a branch. if (hasBranch) { col++; table[row, col] = Util.GetFormattedDecimal_Percent_NA(rpt.eComponent.ComponentPctChromeBranch); col++; table[row, col] = Util.GetFormattedDecimal_Percent_NA(rpt.eComponent.ComponentPctChromeBrExt); } cols = col + 1; return table; } } }
using System; using System.Collections.Generic; using Server; using Server.Multis; using Server.Targeting; using Server.ContextMenus; using Server.Gumps; namespace Server.Items { public interface IDyable { bool Dye( Mobile from, DyeTub sender ); } public class DyeTub : Item, ISecurable { private bool m_Redyable; private int m_DyedHue; private SecureLevel m_SecureLevel; //Ajout Charges private int m_Charges; [CommandProperty( AccessLevel.GameMaster )] public int Charges { get { return m_Charges; } set { m_Charges = value; } } public virtual CustomHuePicker CustomHuePicker{ get{ return null; } } public virtual bool AllowRunebooks { get{ return false; } } public virtual bool AllowFurniture { get{ return false; } } public virtual bool AllowStatuettes { get{ return false; } } public virtual bool AllowLeather { get{ return false; } } public virtual bool AllowDyables { get{ return true; } } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 2 ); // version writer.Write((int)m_Charges); writer.Write( (int)m_SecureLevel ); writer.Write( (bool) m_Redyable ); writer.Write( (int) m_DyedHue ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); switch ( version ) { case 2: { m_Charges = reader.ReadInt(); goto case 1; } case 1: { m_SecureLevel = (SecureLevel)reader.ReadInt(); goto case 0; } case 0: { m_Redyable = reader.ReadBool(); m_DyedHue = reader.ReadInt(); break; } } if (version < 2) m_Charges = 10; } [CommandProperty( AccessLevel.GameMaster )] public virtual bool Redyable { get { return m_Redyable; } set { m_Redyable = value; } } [CommandProperty( AccessLevel.GameMaster )] public int DyedHue { get { return m_DyedHue; } set { if ( m_Redyable ) { m_DyedHue = value; Hue = value; } } } [CommandProperty( AccessLevel.GameMaster )] public SecureLevel Level { get { return m_SecureLevel; } set { m_SecureLevel = value; } } [Constructable] public DyeTub() : base( 0xFAB ) { Weight = 10.0; Charges = 10; m_Redyable = true; } public override void GetContextMenuEntries( Mobile from, List<ContextMenuEntry> list ) { base.GetContextMenuEntries( from, list ); SetSecureLevelEntry.AddTo( from, this, list ); } public DyeTub( Serial serial ) : base( serial ) { } // Three metallic tubs now. public virtual bool MetallicHues { get { return false; } } // Select the clothing to dye. public virtual int TargetMessage{ get{ return 500859; } } // You can not dye that. public virtual int FailMessage{ get{ return 1042083; } } public override void OnDoubleClick( Mobile from ) { if (Charges <= 0) { from.SendMessage("Ce bac est vide"); return; } if ( from.InRange( this.GetWorldLocation(), 1 ) ) { from.SendLocalizedMessage( TargetMessage ); from.Target = new InternalTarget( this ); } else { from.SendLocalizedMessage( 500446 ); // That is too far away. } } public void CheckEmpty() { if (Charges<=0) { DyedHue = 0; } } private class InternalTarget : Target { private DyeTub m_Tub; public InternalTarget( DyeTub tub ) : base( 1, false, TargetFlags.None ) { m_Tub = tub; } protected override void OnTarget( Mobile from, object targeted ) { if ( targeted is Item ) { Item item = (Item)targeted; if (item.QuestItem) { from.SendLocalizedMessage(1151836); // You may not dye toggled quest items. } else if (item is IDyable && m_Tub.AllowDyables) { if ( !from.InRange( m_Tub.GetWorldLocation(), 1 ) || !from.InRange( item.GetWorldLocation(), 1 ) ) from.SendLocalizedMessage( 500446 ); // That is too far away. else if ( item.Parent is Mobile ) from.SendLocalizedMessage( 500861 ); // Can't Dye clothing that is being worn. else if ( ((IDyable)item).Dye( from, m_Tub ) ) { from.PlaySound( 0x23E ); m_Tub.Charges--; m_Tub.CheckEmpty(); } } else if ( (FurnitureAttribute.Check( item ) || (item is PotionKeg)) && m_Tub.AllowFurniture ) { if ( !from.InRange( m_Tub.GetWorldLocation(), 1 ) || !from.InRange( item.GetWorldLocation(), 1 ) ) { from.SendLocalizedMessage( 500446 ); // That is too far away. } else { bool okay = ( item.IsChildOf( from.Backpack ) ); if ( !okay ) { if ( item.Parent == null ) { BaseHouse house = BaseHouse.FindHouseAt( item ); // Scriptiz : ajout pour rendre les addon furniture dyable && !(item is AddonComponent) if ( house == null || ( !house.IsLockedDown( item ) && !house.IsSecure( item ) && !(item is AddonComponent) ) ) from.SendLocalizedMessage( 501022 ); // Furniture must be locked down to paint it. else if ( !house.IsCoOwner( from ) ) from.SendLocalizedMessage( 501023 ); // You must be the owner to use this item. else okay = true; } else { from.SendLocalizedMessage( 1048135 ); // The furniture must be in your backpack to be painted. } } if ( okay ) { item.Hue = m_Tub.DyedHue; from.PlaySound( 0x23E ); m_Tub.Charges--; m_Tub.CheckEmpty(); } } } else if ( (item is Runebook || item is RecallRune ) && m_Tub.AllowRunebooks ) { if ( !from.InRange( m_Tub.GetWorldLocation(), 1 ) || !from.InRange( item.GetWorldLocation(), 1 ) ) { from.SendLocalizedMessage( 500446 ); // That is too far away. } else if ( !item.Movable ) { from.SendLocalizedMessage( 1049776 ); // You cannot dye runes or runebooks that are locked down. } else { item.Hue = m_Tub.DyedHue; from.PlaySound( 0x23E ); m_Tub.Charges--; m_Tub.CheckEmpty(); } } else if ( item is MonsterStatuette && m_Tub.AllowStatuettes ) { if ( !from.InRange( m_Tub.GetWorldLocation(), 1 ) || !from.InRange( item.GetWorldLocation(), 1 ) ) { from.SendLocalizedMessage( 500446 ); // That is too far away. } else if ( !item.Movable ) { from.SendLocalizedMessage( 1049779 ); // You cannot dye statuettes that are locked down. } else { item.Hue = m_Tub.DyedHue; from.PlaySound( 0x23E ); m_Tub.Charges--; m_Tub.CheckEmpty(); } } else if ( (item is BaseArmor && (((BaseArmor)item).MaterialType == ArmorMaterialType.Leather || ((BaseArmor)item).MaterialType == ArmorMaterialType.Studded) || item is ElvenBoots || item is WoodlandBelt) && m_Tub.AllowLeather ) { if ( !from.InRange( m_Tub.GetWorldLocation(), 1 ) || !from.InRange( item.GetWorldLocation(), 1 ) ) { from.SendLocalizedMessage( 500446 ); // That is too far away. } else if ( !item.Movable ) { from.SendLocalizedMessage( 1042419 ); // You may not dye leather items which are locked down. } else if ( item.Parent is Mobile ) { from.SendLocalizedMessage( 500861 ); // Can't Dye clothing that is being worn. } else { item.Hue = m_Tub.DyedHue; from.PlaySound( 0x23E ); m_Tub.Charges--; m_Tub.CheckEmpty(); } } else { from.SendLocalizedMessage( m_Tub.FailMessage ); } } else { from.SendLocalizedMessage( m_Tub.FailMessage ); } } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Net; using System.Reflection; using System.Threading; using log4net; using Nini.Config; using Nwc.XmlRpc; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; /***************************************************** * * XMLRPCModule * * Module for accepting incoming communications from * external XMLRPC client and calling a remote data * procedure for a registered data channel/prim. * * * 1. On module load, open a listener port * 2. Attach an XMLRPC handler * 3. When a request is received: * 3.1 Parse into components: channel key, int, string * 3.2 Look up registered channel listeners * 3.3 Call the channel (prim) remote data method * 3.4 Capture the response (llRemoteDataReply) * 3.5 Return response to client caller * 3.6 If no response from llRemoteDataReply within * RemoteReplyScriptTimeout, generate script timeout fault * * Prims in script must: * 1. Open a remote data channel * 1.1 Generate a channel ID * 1.2 Register primid,channelid pair with module * 2. Implement the remote data procedure handler * * llOpenRemoteDataChannel * llRemoteDataReply * remote_data(integer type, key channel, key messageid, string sender, integer ival, string sval) * llCloseRemoteDataChannel * * **************************************************/ namespace OpenSim.Region.CoreModules.Scripting.XMLRPC { public class XMLRPCModule : IRegionModule, IXMLRPC { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private string m_name = "XMLRPCModule"; // <channel id, RPCChannelInfo> private Dictionary<UUID, RPCChannelInfo> m_openChannels; private Dictionary<UUID, SendRemoteDataRequest> m_pendingSRDResponses; private int m_remoteDataPort = 0; private Dictionary<UUID, RPCRequestInfo> m_rpcPending; private Dictionary<UUID, RPCRequestInfo> m_rpcPendingResponses; private List<Scene> m_scenes = new List<Scene>(); private int RemoteReplyScriptTimeout = 9000; private int RemoteReplyScriptWait = 300; private object XMLRPCListLock = new object(); #region IRegionModule Members public void Initialise(Scene scene, IConfigSource config) { // We need to create these early because the scripts might be calling // But since this gets called for every region, we need to make sure they // get called only one time (or we lose any open channels) if (null == m_openChannels) { m_openChannels = new Dictionary<UUID, RPCChannelInfo>(); m_rpcPending = new Dictionary<UUID, RPCRequestInfo>(); m_rpcPendingResponses = new Dictionary<UUID, RPCRequestInfo>(); m_pendingSRDResponses = new Dictionary<UUID, SendRemoteDataRequest>(); try { m_remoteDataPort = config.Configs["Network"].GetInt("remoteDataPort", m_remoteDataPort); } catch (Exception) { } } if (!m_scenes.Contains(scene)) { m_scenes.Add(scene); scene.RegisterModuleInterface<IXMLRPC>(this); } } public void PostInitialise() { if (IsEnabled()) { // Start http server // Attach xmlrpc handlers m_log.Info("[REMOTE_DATA]: " + "Starting XMLRPC Server on port " + m_remoteDataPort + " for llRemoteData commands."); BaseHttpServer httpServer = new BaseHttpServer((uint) m_remoteDataPort); httpServer.AddXmlRPCHandler("llRemoteData", XmlRpcRemoteData); httpServer.Start(); } } public void Close() { } public string Name { get { return m_name; } } public bool IsSharedModule { get { return true; } } public int Port { get { return m_remoteDataPort; } } #endregion #region IXMLRPC Members public bool IsEnabled() { return (m_remoteDataPort > 0); } /********************************************** * OpenXMLRPCChannel * * Generate a UUID channel key and add it and * the prim id to dictionary <channelUUID, primUUID> * * A custom channel key can be proposed. * Otherwise, passing UUID.Zero will generate * and return a random channel * * First check if there is a channel assigned for * this itemID. If there is, then someone called * llOpenRemoteDataChannel twice. Just return the * original channel. Other option is to delete the * current channel and assign a new one. * * ********************************************/ public UUID OpenXMLRPCChannel(uint localID, UUID itemID, UUID channelID) { UUID newChannel = UUID.Zero; // This should no longer happen, but the check is reasonable anyway if (null == m_openChannels) { m_log.Warn("[RemoteDataReply] Attempt to open channel before initialization is complete"); return newChannel; } //Is a dupe? foreach (RPCChannelInfo ci in m_openChannels.Values) { if (ci.GetItemID().Equals(itemID)) { // return the original channel ID for this item newChannel = ci.GetChannelID(); break; } } if (newChannel == UUID.Zero) { newChannel = (channelID == UUID.Zero) ? UUID.Random() : channelID; RPCChannelInfo rpcChanInfo = new RPCChannelInfo(localID, itemID, newChannel); lock (XMLRPCListLock) { m_openChannels.Add(newChannel, rpcChanInfo); } } return newChannel; } // Delete channels based on itemID // for when a script is deleted public void DeleteChannels(UUID itemID) { if (m_openChannels != null) { ArrayList tmp = new ArrayList(); lock (XMLRPCListLock) { foreach (RPCChannelInfo li in m_openChannels.Values) { if (li.GetItemID().Equals(itemID)) { tmp.Add(itemID); } } IEnumerator tmpEnumerator = tmp.GetEnumerator(); while (tmpEnumerator.MoveNext()) m_openChannels.Remove((UUID) tmpEnumerator.Current); } } } /********************************************** * Remote Data Reply * * Response to RPC message * *********************************************/ public void RemoteDataReply(string channel, string message_id, string sdata, int idata) { UUID message_key = new UUID(message_id); UUID channel_key = new UUID(channel); RPCRequestInfo rpcInfo = null; if (message_key == UUID.Zero) { foreach (RPCRequestInfo oneRpcInfo in m_rpcPendingResponses.Values) if (oneRpcInfo.GetChannelKey() == channel_key) rpcInfo = oneRpcInfo; } else { m_rpcPendingResponses.TryGetValue(message_key, out rpcInfo); } if (rpcInfo != null) { rpcInfo.SetStrRetval(sdata); rpcInfo.SetIntRetval(idata); rpcInfo.SetProcessed(true); m_rpcPendingResponses.Remove(message_key); } else { m_log.Warn("[RemoteDataReply]: Channel or message_id not found"); } } /********************************************** * CloseXMLRPCChannel * * Remove channel from dictionary * *********************************************/ public void CloseXMLRPCChannel(UUID channelKey) { if (m_openChannels.ContainsKey(channelKey)) m_openChannels.Remove(channelKey); } public bool hasRequests() { lock (XMLRPCListLock) { if (m_rpcPending != null) return (m_rpcPending.Count > 0); else return false; } } public IXmlRpcRequestInfo GetNextCompletedRequest() { if (m_rpcPending != null) { lock (XMLRPCListLock) { foreach (UUID luid in m_rpcPending.Keys) { RPCRequestInfo tmpReq; if (m_rpcPending.TryGetValue(luid, out tmpReq)) { if (!tmpReq.IsProcessed()) return tmpReq; } } } } return null; } public void RemoveCompletedRequest(UUID id) { lock (XMLRPCListLock) { RPCRequestInfo tmp; if (m_rpcPending.TryGetValue(id, out tmp)) { m_rpcPending.Remove(id); m_rpcPendingResponses.Add(id, tmp); } else { m_log.Error("UNABLE TO REMOVE COMPLETED REQUEST"); } } } public UUID SendRemoteData(uint localID, UUID itemID, string channel, string dest, int idata, string sdata) { SendRemoteDataRequest req = new SendRemoteDataRequest( localID, itemID, channel, dest, idata, sdata ); m_pendingSRDResponses.Add(req.GetReqID(), req); req.Process(); return req.ReqID; } public IServiceRequest GetNextCompletedSRDRequest() { if (m_pendingSRDResponses != null) { lock (XMLRPCListLock) { foreach (UUID luid in m_pendingSRDResponses.Keys) { SendRemoteDataRequest tmpReq; if (m_pendingSRDResponses.TryGetValue(luid, out tmpReq)) { if (tmpReq.Finished) return tmpReq; } } } } return null; } public void RemoveCompletedSRDRequest(UUID id) { lock (XMLRPCListLock) { SendRemoteDataRequest tmpReq; if (m_pendingSRDResponses.TryGetValue(id, out tmpReq)) { m_pendingSRDResponses.Remove(id); } } } public void CancelSRDRequests(UUID itemID) { if (m_pendingSRDResponses != null) { lock (XMLRPCListLock) { foreach (SendRemoteDataRequest li in m_pendingSRDResponses.Values) { if (li.ItemID.Equals(itemID)) m_pendingSRDResponses.Remove(li.GetReqID()); } } } } #endregion public XmlRpcResponse XmlRpcRemoteData(XmlRpcRequest request, IPEndPoint remoteClient) { XmlRpcResponse response = new XmlRpcResponse(); Hashtable requestData = (Hashtable) request.Params[0]; bool GoodXML = (requestData.Contains("Channel") && requestData.Contains("IntValue") && requestData.Contains("StringValue")); if (GoodXML) { UUID channel = new UUID((string) requestData["Channel"]); RPCChannelInfo rpcChanInfo; if (m_openChannels.TryGetValue(channel, out rpcChanInfo)) { string intVal = Convert.ToInt32(requestData["IntValue"]).ToString(); string strVal = (string) requestData["StringValue"]; RPCRequestInfo rpcInfo; lock (XMLRPCListLock) { rpcInfo = new RPCRequestInfo(rpcChanInfo.GetLocalID(), rpcChanInfo.GetItemID(), channel, strVal, intVal); m_rpcPending.Add(rpcInfo.GetMessageID(), rpcInfo); } int timeoutCtr = 0; while (!rpcInfo.IsProcessed() && (timeoutCtr < RemoteReplyScriptTimeout)) { Thread.Sleep(RemoteReplyScriptWait); timeoutCtr += RemoteReplyScriptWait; } if (rpcInfo.IsProcessed()) { Hashtable param = new Hashtable(); param["StringValue"] = rpcInfo.GetStrRetval(); param["IntValue"] = rpcInfo.GetIntRetval(); ArrayList parameters = new ArrayList(); parameters.Add(param); response.Value = parameters; rpcInfo = null; } else { response.SetFault(-1, "Script timeout"); rpcInfo = null; } } else { response.SetFault(-1, "Invalid channel"); } } return response; } } public class RPCRequestInfo: IXmlRpcRequestInfo { private UUID m_ChannelKey; private string m_IntVal; private UUID m_ItemID; private uint m_localID; private UUID m_MessageID; private bool m_processed; private int m_respInt; private string m_respStr; private string m_StrVal; public RPCRequestInfo(uint localID, UUID itemID, UUID channelKey, string strVal, string intVal) { m_localID = localID; m_StrVal = strVal; m_IntVal = intVal; m_ItemID = itemID; m_ChannelKey = channelKey; m_MessageID = UUID.Random(); m_processed = false; m_respStr = String.Empty; m_respInt = 0; } public bool IsProcessed() { return m_processed; } public UUID GetChannelKey() { return m_ChannelKey; } public void SetProcessed(bool processed) { m_processed = processed; } public void SetStrRetval(string resp) { m_respStr = resp; } public string GetStrRetval() { return m_respStr; } public void SetIntRetval(int resp) { m_respInt = resp; } public int GetIntRetval() { return m_respInt; } public uint GetLocalID() { return m_localID; } public UUID GetItemID() { return m_ItemID; } public string GetStrVal() { return m_StrVal; } public int GetIntValue() { return int.Parse(m_IntVal); } public UUID GetMessageID() { return m_MessageID; } } public class RPCChannelInfo { private UUID m_ChannelKey; private UUID m_itemID; private uint m_localID; public RPCChannelInfo(uint localID, UUID itemID, UUID channelID) { m_ChannelKey = channelID; m_localID = localID; m_itemID = itemID; } public UUID GetItemID() { return m_itemID; } public UUID GetChannelID() { return m_ChannelKey; } public uint GetLocalID() { return m_localID; } } public class SendRemoteDataRequest: IServiceRequest { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public string Channel; public string DestURL; private bool _finished; public bool Finished { get { return _finished; } set { _finished = value; } } private Thread httpThread; public int Idata; private UUID _itemID; public UUID ItemID { get { return _itemID; } set { _itemID = value; } } private uint _localID; public uint LocalID { get { return _localID; } set { _localID = value; } } private UUID _reqID; public UUID ReqID { get { return _reqID; } set { _reqID = value; } } public XmlRpcRequest Request; public int ResponseIdata; public string ResponseSdata; public string Sdata; public SendRemoteDataRequest(uint localID, UUID itemID, string channel, string dest, int idata, string sdata) { this.Channel = channel; DestURL = dest; this.Idata = idata; this.Sdata = sdata; ItemID = itemID; LocalID = localID; ReqID = UUID.Random(); } public void Process() { httpThread = new Thread(SendRequest); httpThread.Name = "HttpRequestThread"; httpThread.Priority = ThreadPriority.BelowNormal; httpThread.IsBackground = true; _finished = false; httpThread.Start(); ThreadTracker.Add(httpThread); } /* * TODO: More work on the response codes. Right now * returning 200 for success or 499 for exception */ public void SendRequest() { Hashtable param = new Hashtable(); // Check if channel is an UUID // if not, use as method name UUID parseUID; string mName = "llRemoteData"; if ((Channel != null) && (Channel != "")) if (!UUID.TryParse(Channel, out parseUID)) mName = Channel; else param["Channel"] = Channel; param["StringValue"] = Sdata; param["IntValue"] = Convert.ToString(Idata); ArrayList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req = new XmlRpcRequest(mName, parameters); try { XmlRpcResponse resp = req.Send(DestURL, 30000); if (resp != null) { Hashtable respParms; if (resp.Value.GetType().Equals(typeof(Hashtable))) { respParms = (Hashtable) resp.Value; } else { ArrayList respData = (ArrayList) resp.Value; respParms = (Hashtable) respData[0]; } if (respParms != null) { if (respParms.Contains("StringValue")) { Sdata = (string) respParms["StringValue"]; } if (respParms.Contains("IntValue")) { Idata = Convert.ToInt32((string) respParms["IntValue"]); } if (respParms.Contains("faultString")) { Sdata = (string) respParms["faultString"]; } if (respParms.Contains("faultCode")) { Idata = Convert.ToInt32(respParms["faultCode"]); } } } } catch (Exception we) { Sdata = we.Message; m_log.Warn("[SendRemoteDataRequest]: Request failed"); m_log.Warn(we.StackTrace); } _finished = true; } public void Stop() { try { httpThread.Abort(); } catch (Exception) { } } public UUID GetReqID() { return ReqID; } } }
using J2N.Threading; using J2N.Threading.Atomic; using Lucene.Net.Index; using Lucene.Net.Index.Extensions; using NUnit.Framework; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Console = Lucene.Net.Util.SystemConsole; namespace Lucene.Net.Search { /* * 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 Directory = Lucene.Net.Store.Directory; using DirectoryReader = Lucene.Net.Index.DirectoryReader; using Document = Documents.Document; using IndexReader = Lucene.Net.Index.IndexReader; using IndexWriter = Lucene.Net.Index.IndexWriter; using IndexWriterConfig = Lucene.Net.Index.IndexWriterConfig; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using Term = Lucene.Net.Index.Term; using TestUtil = Lucene.Net.Util.TestUtil; using ThreadedIndexingAndSearchingTestCase = Lucene.Net.Index.ThreadedIndexingAndSearchingTestCase; [SuppressCodecs("SimpleText", "Memory", "Direct")] [TestFixture] public class TestSearcherManager : ThreadedIndexingAndSearchingTestCase { internal bool warmCalled; private SearcherLifetimeManager.IPruner pruner; [Test] [Slow] public virtual void TestSearcherManager_Mem() { pruner = new SearcherLifetimeManager.PruneByAge(TestNightly ? TestUtil.NextInt32(Random, 1, 20) : 1); RunTest("TestSearcherManager"); } protected override IndexSearcher GetFinalSearcher() { if (!isNRT) { m_writer.Commit(); } assertTrue(mgr.MaybeRefresh() || mgr.IsSearcherCurrent()); return mgr.Acquire(); } private SearcherManager mgr; private SearcherLifetimeManager lifetimeMGR; private readonly IList<long> pastSearchers = new List<long>(); private bool isNRT; protected override void DoAfterWriter(TaskScheduler es) { SearcherFactory factory = new SearcherFactoryAnonymousInnerClassHelper(this, es); if (Random.NextBoolean()) { // TODO: can we randomize the applyAllDeletes? But // somehow for final searcher we must apply // deletes... mgr = new SearcherManager(m_writer, true, factory); isNRT = true; } else { // SearcherManager needs to see empty commit: m_writer.Commit(); mgr = new SearcherManager(m_dir, factory); isNRT = false; m_assertMergedSegmentsWarmed = false; } lifetimeMGR = new SearcherLifetimeManager(); } private class SearcherFactoryAnonymousInnerClassHelper : SearcherFactory { private readonly TestSearcherManager outerInstance; private TaskScheduler es; public SearcherFactoryAnonymousInnerClassHelper(TestSearcherManager outerInstance, TaskScheduler es) { this.outerInstance = outerInstance; this.es = es; } public override IndexSearcher NewSearcher(IndexReader r) { IndexSearcher s = new IndexSearcher(r, es); outerInstance.warmCalled = true; s.Search(new TermQuery(new Term("body", "united")), 10); return s; } } protected override void DoSearching(TaskScheduler es, long stopTime) { ThreadJob reopenThread = new ThreadAnonymousInnerClassHelper(this, stopTime); reopenThread.IsBackground = (true); reopenThread.Start(); RunSearchThreads(stopTime); reopenThread.Join(); } private class ThreadAnonymousInnerClassHelper : ThreadJob { private readonly TestSearcherManager outerInstance; private long stopTime; public ThreadAnonymousInnerClassHelper(TestSearcherManager outerInstance, long stopTime) { this.outerInstance = outerInstance; this.stopTime = stopTime; } public override void Run() { try { if (Verbose) { Console.WriteLine("[" + Thread.CurrentThread.Name + "]: launch reopen thread"); } while (Environment.TickCount < stopTime) { Thread.Sleep(TestUtil.NextInt32(Random, 1, 100)); outerInstance.m_writer.Commit(); Thread.Sleep(TestUtil.NextInt32(Random, 1, 5)); bool block = Random.NextBoolean(); if (block) { outerInstance.mgr.MaybeRefreshBlocking(); outerInstance.lifetimeMGR.Prune(outerInstance.pruner); } else if (outerInstance.mgr.MaybeRefresh()) { outerInstance.lifetimeMGR.Prune(outerInstance.pruner); } } } catch (Exception t) { if (Verbose) { Console.WriteLine("TEST: reopen thread hit exc"); Console.Out.Write(t.StackTrace); } outerInstance.m_failed.Value = (true); throw new Exception(t.ToString(), t); } } } protected override IndexSearcher GetCurrentSearcher() { if (Random.Next(10) == 7) { // NOTE: not best practice to call maybeReopen // synchronous to your search threads, but still we // test as apps will presumably do this for // simplicity: if (mgr.MaybeRefresh()) { lifetimeMGR.Prune(pruner); } } IndexSearcher s = null; lock (pastSearchers) { while (pastSearchers.Count != 0 && Random.NextDouble() < 0.25) { // 1/4 of the time pull an old searcher, ie, simulate // a user doing a follow-on action on a previous // search (drilling down/up, clicking next/prev page, // etc.) long token = pastSearchers[Random.Next(pastSearchers.Count)]; s = lifetimeMGR.Acquire(token); if (s == null) { // Searcher was pruned pastSearchers.Remove(token); } else { break; } } } if (s == null) { s = mgr.Acquire(); if (s.IndexReader.NumDocs != 0) { long token = lifetimeMGR.Record(s); lock (pastSearchers) { if (!pastSearchers.Contains(token)) { pastSearchers.Add(token); } } } } return s; } protected override void ReleaseSearcher(IndexSearcher s) { s.IndexReader.DecRef(); } protected override void DoClose() { assertTrue(warmCalled); if (Verbose) { Console.WriteLine("TEST: now close SearcherManager"); } mgr.Dispose(); lifetimeMGR.Dispose(); } [Test] public virtual void TestIntermediateClose() { Directory dir = NewDirectory(); // Test can deadlock if we use SMS: IConcurrentMergeScheduler scheduler; #if !FEATURE_CONCURRENTMERGESCHEDULER scheduler = new TaskMergeScheduler(); #else scheduler = new ConcurrentMergeScheduler(); #endif IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMergeScheduler(scheduler)); writer.AddDocument(new Document()); writer.Commit(); CountdownEvent awaitEnterWarm = new CountdownEvent(1); CountdownEvent awaitClose = new CountdownEvent(1); AtomicBoolean triedReopen = new AtomicBoolean(false); //TaskScheduler es = Random().NextBoolean() ? null : Executors.newCachedThreadPool(new NamedThreadFactory("testIntermediateClose")); TaskScheduler es = Random.NextBoolean() ? null : TaskScheduler.Default; SearcherFactory factory = new SearcherFactoryAnonymousInnerClassHelper2(this, awaitEnterWarm, awaitClose, triedReopen, es); SearcherManager searcherManager = Random.NextBoolean() ? new SearcherManager(dir, factory) : new SearcherManager(writer, Random.NextBoolean(), factory); if (Verbose) { Console.WriteLine("sm created"); } IndexSearcher searcher = searcherManager.Acquire(); try { assertEquals(1, searcher.IndexReader.NumDocs); } finally { searcherManager.Release(searcher); } writer.AddDocument(new Document()); writer.Commit(); AtomicBoolean success = new AtomicBoolean(false); Exception[] exc = new Exception[1]; ThreadJob thread = new ThreadJob(() => new RunnableAnonymousInnerClassHelper(this, triedReopen, searcherManager, success, exc).Run()); thread.Start(); if (Verbose) { Console.WriteLine("THREAD started"); } awaitEnterWarm.Wait(); if (Verbose) { Console.WriteLine("NOW call close"); } searcherManager.Dispose(); awaitClose.Signal(); thread.Join(); try { searcherManager.Acquire(); fail("already closed"); } #pragma warning disable 168 catch (ObjectDisposedException ex) #pragma warning restore 168 { // expected } assertFalse(success); assertTrue(triedReopen); assertNull("" + exc[0], exc[0]); writer.Dispose(); dir.Dispose(); //if (es != null) //{ // es.shutdown(); // es.awaitTermination(1, TimeUnit.SECONDS); //} } private class SearcherFactoryAnonymousInnerClassHelper2 : SearcherFactory { private readonly TestSearcherManager outerInstance; private CountdownEvent awaitEnterWarm; private CountdownEvent awaitClose; private AtomicBoolean triedReopen; private TaskScheduler es; public SearcherFactoryAnonymousInnerClassHelper2(TestSearcherManager outerInstance, CountdownEvent awaitEnterWarm, CountdownEvent awaitClose, AtomicBoolean triedReopen, TaskScheduler es) { this.outerInstance = outerInstance; this.awaitEnterWarm = awaitEnterWarm; this.awaitClose = awaitClose; this.triedReopen = triedReopen; this.es = es; } public override IndexSearcher NewSearcher(IndexReader r) { #if FEATURE_THREAD_INTERRUPT try { #endif if (triedReopen) { awaitEnterWarm.Signal(); awaitClose.Wait(); } #if FEATURE_THREAD_INTERRUPT } #pragma warning disable 168 catch (ThreadInterruptedException e) #pragma warning restore 168 { // } #endif return new IndexSearcher(r, es); } } private class RunnableAnonymousInnerClassHelper //: IThreadRunnable { private readonly TestSearcherManager outerInstance; private AtomicBoolean triedReopen; private SearcherManager searcherManager; private AtomicBoolean success; private Exception[] exc; public RunnableAnonymousInnerClassHelper(TestSearcherManager outerInstance, AtomicBoolean triedReopen, SearcherManager searcherManager, AtomicBoolean success, Exception[] exc) { this.outerInstance = outerInstance; this.triedReopen = triedReopen; this.searcherManager = searcherManager; this.success = success; this.exc = exc; } public void Run() { try { triedReopen.Value = (true); if (Verbose) { Console.WriteLine("NOW call maybeReopen"); } searcherManager.MaybeRefresh(); success.Value = (true); } catch (ObjectDisposedException) { // expected } catch (Exception e) { if (Verbose) { Console.WriteLine("FAIL: unexpected exc"); Console.Out.Write(e.StackTrace); } exc[0] = e; // use success as the barrier here to make sure we see the write success.Value = (false); } } } [Test] public virtual void TestCloseTwice() { // test that we can close SM twice (per IDisposable's contract). Directory dir = NewDirectory(); using (var iw = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, null))) { } SearcherManager sm = new SearcherManager(dir, null); sm.Dispose(); sm.Dispose(); dir.Dispose(); } [Test] public virtual void TestReferenceDecrementIllegally([ValueSource(typeof(ConcurrentMergeSchedulerFactories), "Values")]Func<IConcurrentMergeScheduler> newScheduler) { Directory dir = NewDirectory(); var config = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)) .SetMergeScheduler(newScheduler()); IndexWriter writer = new IndexWriter(dir, config); SearcherManager sm = new SearcherManager(writer, false, new SearcherFactory()); writer.AddDocument(new Document()); writer.Commit(); sm.MaybeRefreshBlocking(); IndexSearcher acquire = sm.Acquire(); IndexSearcher acquire2 = sm.Acquire(); sm.Release(acquire); sm.Release(acquire2); acquire = sm.Acquire(); acquire.IndexReader.DecRef(); sm.Release(acquire); Assert.Throws<InvalidOperationException>(() => sm.Acquire(), "acquire should have thrown an InvalidOperationException since we modified the refCount outside of the manager"); // sm.Dispose(); -- already closed writer.Dispose(); dir.Dispose(); } [Test] public virtual void TestEnsureOpen() { Directory dir = NewDirectory(); (new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, null))).Dispose(); SearcherManager sm = new SearcherManager(dir, null); IndexSearcher s = sm.Acquire(); sm.Dispose(); // this should succeed; sm.Release(s); try { // this should fail sm.Acquire(); } #pragma warning disable 168 catch (ObjectDisposedException e) #pragma warning restore 168 { // ok } try { // this should fail sm.MaybeRefresh(); } #pragma warning disable 168 catch (ObjectDisposedException e) #pragma warning restore 168 { // ok } dir.Dispose(); } [Test] public virtual void TestListenerCalled() { Directory dir = NewDirectory(); IndexWriter iw = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, null)); AtomicBoolean afterRefreshCalled = new AtomicBoolean(false); SearcherManager sm = new SearcherManager(iw, false, new SearcherFactory()); sm.AddListener(new RefreshListenerAnonymousInnerClassHelper(this, afterRefreshCalled)); iw.AddDocument(new Document()); iw.Commit(); assertFalse(afterRefreshCalled); sm.MaybeRefreshBlocking(); assertTrue(afterRefreshCalled); sm.Dispose(); iw.Dispose(); dir.Dispose(); } private class RefreshListenerAnonymousInnerClassHelper : ReferenceManager.IRefreshListener { private readonly TestSearcherManager outerInstance; private AtomicBoolean afterRefreshCalled; public RefreshListenerAnonymousInnerClassHelper(TestSearcherManager outerInstance, AtomicBoolean afterRefreshCalled) { this.outerInstance = outerInstance; this.afterRefreshCalled = afterRefreshCalled; } public void BeforeRefresh() { } public void AfterRefresh(bool didRefresh) { if (didRefresh) { afterRefreshCalled.Value = (true); } } } [Test] public virtual void TestEvilSearcherFactory() { Random random = Random; Directory dir = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif random, dir); w.Commit(); IndexReader other = DirectoryReader.Open(dir); SearcherFactory theEvilOne = new SearcherFactoryAnonymousInnerClassHelper3(this, other); try { new SearcherManager(dir, theEvilOne); } #pragma warning disable 168 catch (InvalidOperationException ise) #pragma warning restore 168 { // expected } try { new SearcherManager(w.IndexWriter, random.NextBoolean(), theEvilOne); } #pragma warning disable 168 catch (InvalidOperationException ise) #pragma warning restore 168 { // expected } w.Dispose(); other.Dispose(); dir.Dispose(); } private class SearcherFactoryAnonymousInnerClassHelper3 : SearcherFactory { private readonly TestSearcherManager outerInstance; private IndexReader other; public SearcherFactoryAnonymousInnerClassHelper3(TestSearcherManager outerInstance, IndexReader other) { this.outerInstance = outerInstance; this.other = other; } public override IndexSearcher NewSearcher(IndexReader ignored) { return LuceneTestCase.NewSearcher( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION outerInstance, #endif other); } } [Test] public virtual void TestMaybeRefreshBlockingLock() { // make sure that maybeRefreshBlocking releases the lock, otherwise other // threads cannot obtain it. Directory dir = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, dir); w.Dispose(); SearcherManager sm = new SearcherManager(dir, null); ThreadJob t = new ThreadAnonymousInnerClassHelper2(this, sm); t.Start(); t.Join(); // if maybeRefreshBlocking didn't release the lock, this will fail. assertTrue("failde to obtain the refreshLock!", sm.MaybeRefresh()); sm.Dispose(); dir.Dispose(); } private class ThreadAnonymousInnerClassHelper2 : ThreadJob { private readonly TestSearcherManager outerInstance; private SearcherManager sm; public ThreadAnonymousInnerClassHelper2(TestSearcherManager outerInstance, SearcherManager sm) { this.outerInstance = outerInstance; this.sm = sm; } public override void Run() { try { // this used to not release the lock, preventing other threads from obtaining it. sm.MaybeRefreshBlocking(); } catch (Exception e) { throw new Exception(e.ToString(), e); } } } } }
using System; using System.Collections.Generic; using Microsoft.Data.Entity.Migrations; namespace AllReady.Migrations { public partial class SplitNamePropertyOnApplicationUserIntoFirstNameAndLastName : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey(name: "FK_AllReadyTask_Event_EventId", table: "AllReadyTask"); migrationBuilder.DropForeignKey(name: "FK_Campaign_Organization_ManagingOrganizationId", table: "Campaign"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_Event_Campaign_CampaignId", table: "Event"); migrationBuilder.DropForeignKey(name: "FK_EventSignup_Event_EventId", table: "EventSignup"); migrationBuilder.DropForeignKey(name: "FK_EventSkill_Event_EventId", table: "EventSkill"); migrationBuilder.DropForeignKey(name: "FK_EventSkill_Skill_SkillId", table: "EventSkill"); migrationBuilder.DropForeignKey(name: "FK_Itinerary_Event_EventId", table: "Itinerary"); migrationBuilder.DropForeignKey(name: "FK_ItineraryRequest_Itinerary_ItineraryId", table: "ItineraryRequest"); migrationBuilder.DropForeignKey(name: "FK_ItineraryRequest_Request_RequestId", table: "ItineraryRequest"); migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Contact_ContactId", table: "OrganizationContact"); migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Organization_OrganizationId", table: "OrganizationContact"); migrationBuilder.DropForeignKey(name: "FK_Request_Event_EventId", table: "Request"); migrationBuilder.DropForeignKey(name: "FK_TaskSignup_AllReadyTask_TaskId", table: "TaskSignup"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_Skill_SkillId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles"); migrationBuilder.DropColumn(name: "Name", table: "AspNetUsers"); migrationBuilder.AddColumn<string>( name: "FirstName", table: "AspNetUsers", nullable: true); migrationBuilder.AddColumn<string>( name: "LastName", table: "AspNetUsers", nullable: true); migrationBuilder.AddForeignKey( name: "FK_AllReadyTask_Event_EventId", table: "AllReadyTask", column: "EventId", principalTable: "Event", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Campaign_Organization_ManagingOrganizationId", table: "Campaign", column: "ManagingOrganizationId", principalTable: "Organization", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Event_Campaign_CampaignId", table: "Event", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_EventSignup_Event_EventId", table: "EventSignup", column: "EventId", principalTable: "Event", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_EventSkill_Event_EventId", table: "EventSkill", column: "EventId", principalTable: "Event", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_EventSkill_Skill_SkillId", table: "EventSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Itinerary_Event_EventId", table: "Itinerary", column: "EventId", principalTable: "Event", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_ItineraryRequest_Itinerary_ItineraryId", table: "ItineraryRequest", column: "ItineraryId", principalTable: "Itinerary", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_ItineraryRequest_Request_RequestId", table: "ItineraryRequest", column: "RequestId", principalTable: "Request", principalColumn: "RequestId", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_OrganizationContact_Contact_ContactId", table: "OrganizationContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_OrganizationContact_Organization_OrganizationId", table: "OrganizationContact", column: "OrganizationId", principalTable: "Organization", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Request_Event_EventId", table: "Request", column: "EventId", principalTable: "Event", principalColumn: "Id", onDelete: ReferentialAction.SetNull); migrationBuilder.AddForeignKey( name: "FK_TaskSignup_AllReadyTask_TaskId", table: "TaskSignup", column: "TaskId", principalTable: "AllReadyTask", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill", column: "TaskId", principalTable: "AllReadyTask", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_UserSkill_Skill_SkillId", table: "UserSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey(name: "FK_AllReadyTask_Event_EventId", table: "AllReadyTask"); migrationBuilder.DropForeignKey(name: "FK_Campaign_Organization_ManagingOrganizationId", table: "Campaign"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_Event_Campaign_CampaignId", table: "Event"); migrationBuilder.DropForeignKey(name: "FK_EventSignup_Event_EventId", table: "EventSignup"); migrationBuilder.DropForeignKey(name: "FK_EventSkill_Event_EventId", table: "EventSkill"); migrationBuilder.DropForeignKey(name: "FK_EventSkill_Skill_SkillId", table: "EventSkill"); migrationBuilder.DropForeignKey(name: "FK_Itinerary_Event_EventId", table: "Itinerary"); migrationBuilder.DropForeignKey(name: "FK_ItineraryRequest_Itinerary_ItineraryId", table: "ItineraryRequest"); migrationBuilder.DropForeignKey(name: "FK_ItineraryRequest_Request_RequestId", table: "ItineraryRequest"); migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Contact_ContactId", table: "OrganizationContact"); migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Organization_OrganizationId", table: "OrganizationContact"); migrationBuilder.DropForeignKey(name: "FK_Request_Event_EventId", table: "Request"); migrationBuilder.DropForeignKey(name: "FK_TaskSignup_AllReadyTask_TaskId", table: "TaskSignup"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_Skill_SkillId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles"); migrationBuilder.DropColumn(name: "FirstName", table: "AspNetUsers"); migrationBuilder.DropColumn(name: "LastName", table: "AspNetUsers"); migrationBuilder.AddColumn<string>( name: "Name", table: "AspNetUsers", nullable: true); migrationBuilder.AddForeignKey( name: "FK_AllReadyTask_Event_EventId", table: "AllReadyTask", column: "EventId", principalTable: "Event", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Campaign_Organization_ManagingOrganizationId", table: "Campaign", column: "ManagingOrganizationId", principalTable: "Organization", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Event_Campaign_CampaignId", table: "Event", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_EventSignup_Event_EventId", table: "EventSignup", column: "EventId", principalTable: "Event", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_EventSkill_Event_EventId", table: "EventSkill", column: "EventId", principalTable: "Event", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_EventSkill_Skill_SkillId", table: "EventSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Itinerary_Event_EventId", table: "Itinerary", column: "EventId", principalTable: "Event", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_ItineraryRequest_Itinerary_ItineraryId", table: "ItineraryRequest", column: "ItineraryId", principalTable: "Itinerary", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_ItineraryRequest_Request_RequestId", table: "ItineraryRequest", column: "RequestId", principalTable: "Request", principalColumn: "RequestId", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_OrganizationContact_Contact_ContactId", table: "OrganizationContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_OrganizationContact_Organization_OrganizationId", table: "OrganizationContact", column: "OrganizationId", principalTable: "Organization", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Request_Event_EventId", table: "Request", column: "EventId", principalTable: "Event", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_TaskSignup_AllReadyTask_TaskId", table: "TaskSignup", column: "TaskId", principalTable: "AllReadyTask", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill", column: "TaskId", principalTable: "AllReadyTask", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_UserSkill_Skill_SkillId", table: "UserSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); } } }
/****************************************************************************** * Spine Runtimes Software License v2.5 * * Copyright (c) 2013-2016, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable, and * non-transferable license to use, install, execute, and perform the Spine * Runtimes software and derivative works solely for personal or internal * use. Without the written permission of Esoteric Software (see Section 2 of * the Spine Software License Agreement), you may not (a) modify, translate, * adapt, or develop new applications using the Spine Runtimes or otherwise * create derivative works or improvements of the Spine Runtimes or (b) remove, * delete, alter, or obscure any trademarks or any copyright, trademark, patent, * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF * USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ // Contributed by: Mitch Thompson and John Dy using UnityEngine; using Spine; namespace Spine.Unity { public static class SkeletonExtensions { #region Colors const float ByteToFloat = 1f / 255f; public static Color GetColor (this Skeleton s) { return new Color(s.r, s.g, s.b, s.a); } public static Color GetColor (this RegionAttachment a) { return new Color(a.r, a.g, a.b, a.a); } public static Color GetColor (this MeshAttachment a) { return new Color(a.r, a.g, a.b, a.a); } public static void SetColor (this Skeleton skeleton, Color color) { skeleton.A = color.a; skeleton.R = color.r; skeleton.G = color.g; skeleton.B = color.b; } public static void SetColor (this Skeleton skeleton, Color32 color) { skeleton.A = color.a * ByteToFloat; skeleton.R = color.r * ByteToFloat; skeleton.G = color.g * ByteToFloat; skeleton.B = color.b * ByteToFloat; } public static void SetColor (this Slot slot, Color color) { slot.A = color.a; slot.R = color.r; slot.G = color.g; slot.B = color.b; } public static void SetColor (this Slot slot, Color32 color) { slot.A = color.a * ByteToFloat; slot.R = color.r * ByteToFloat; slot.G = color.g * ByteToFloat; slot.B = color.b * ByteToFloat; } public static void SetColor (this RegionAttachment attachment, Color color) { attachment.A = color.a; attachment.R = color.r; attachment.G = color.g; attachment.B = color.b; } public static void SetColor (this RegionAttachment attachment, Color32 color) { attachment.A = color.a * ByteToFloat; attachment.R = color.r * ByteToFloat; attachment.G = color.g * ByteToFloat; attachment.B = color.b * ByteToFloat; } public static void SetColor (this MeshAttachment attachment, Color color) { attachment.A = color.a; attachment.R = color.r; attachment.G = color.g; attachment.B = color.b; } public static void SetColor (this MeshAttachment attachment, Color32 color) { attachment.A = color.a * ByteToFloat; attachment.R = color.r * ByteToFloat; attachment.G = color.g * ByteToFloat; attachment.B = color.b * ByteToFloat; } #endregion #region Bone /// <summary>Sets the bone's (local) X and Y according to a Vector2</summary> public static void SetPosition (this Bone bone, Vector2 position) { bone.X = position.x; bone.Y = position.y; } /// <summary>Sets the bone's (local) X and Y according to a Vector3. The z component is ignored.</summary> public static void SetPosition (this Bone bone, Vector3 position) { bone.X = position.x; bone.Y = position.y; } /// <summary>Gets the bone's local X and Y as a Vector2.</summary> public static Vector2 GetLocalPosition (this Bone bone) { return new Vector2(bone.x, bone.y); } /// <summary>Gets the position of the bone in Skeleton-space.</summary> public static Vector2 GetSkeletonSpacePosition (this Bone bone) { return new Vector2(bone.worldX, bone.worldY); } /// <summary>Gets a local offset from the bone and converts it into Skeleton-space.</summary> public static Vector2 GetSkeletonSpacePosition (this Bone bone, Vector2 boneLocal) { Vector2 o; bone.LocalToWorld(boneLocal.x, boneLocal.y, out o.x, out o.y); return o; } /// <summary>Gets the bone's Unity World position using its Spine GameObject Transform. UpdateWorldTransform needs to have been called for this to return the correct, updated value.</summary> public static Vector3 GetWorldPosition (this Bone bone, UnityEngine.Transform spineGameObjectTransform) { return spineGameObjectTransform.TransformPoint(new Vector3(bone.worldX, bone.worldY)); } public static Vector3 GetWorldPosition (this Bone bone, UnityEngine.Transform spineGameObjectTransform, float positionScale) { return spineGameObjectTransform.TransformPoint(new Vector3(bone.worldX * positionScale, bone.worldY * positionScale)); } /// <summary>Gets a skeleton space UnityEngine.Quaternion representation of bone.WorldRotationX.</summary> public static Quaternion GetQuaternion (this Bone bone) { var halfRotation = Mathf.Atan2(bone.c, bone.a) * 0.5f; return new Quaternion(0, 0, Mathf.Sin(halfRotation), Mathf.Cos(halfRotation)); } /// <summary>Gets the PointAttachment's Unity World position using its Spine GameObject Transform.</summary> public static Vector3 GetWorldPosition (this PointAttachment attachment, Slot slot, Transform spineGameObjectTransform) { Vector3 skeletonSpacePosition; skeletonSpacePosition.z = 0; attachment.ComputeWorldPosition(slot.bone, out skeletonSpacePosition.x, out skeletonSpacePosition.y); return spineGameObjectTransform.TransformPoint(skeletonSpacePosition); } /// <summary>Gets the PointAttachment's Unity World position using its Spine GameObject Transform.</summary> public static Vector3 GetWorldPosition (this PointAttachment attachment, Bone bone, Transform spineGameObjectTransform) { Vector3 skeletonSpacePosition; skeletonSpacePosition.z = 0; attachment.ComputeWorldPosition(bone, out skeletonSpacePosition.x, out skeletonSpacePosition.y); return spineGameObjectTransform.TransformPoint(skeletonSpacePosition); } /// <summary>Gets the internal bone matrix as a Unity bonespace-to-skeletonspace transformation matrix.</summary> public static Matrix4x4 GetMatrix4x4 (this Bone bone) { return new Matrix4x4 { m00 = bone.a, m01 = bone.b, m03 = bone.worldX, m10 = bone.c, m11 = bone.d, m13 = bone.worldY, m33 = 1 }; } /// <summary>Calculates a 2x2 Transformation Matrix that can convert a skeleton-space position to a bone-local position.</summary> public static void GetWorldToLocalMatrix (this Bone bone, out float ia, out float ib, out float ic, out float id) { float a = bone.a, b = bone.b, c = bone.c, d = bone.d; float invDet = 1 / (a * d - b * c); ia = invDet * d; ib = invDet * -b; ic = invDet * -c; id = invDet * a; } /// <summary>UnityEngine.Vector2 override of Bone.WorldToLocal. This converts a skeleton-space position into a bone local position.</summary> public static Vector2 WorldToLocal (this Bone bone, Vector2 worldPosition) { Vector2 o; bone.WorldToLocal(worldPosition.x, worldPosition.y, out o.x, out o.y); return o; } #endregion #region Attachments public static Material GetMaterial (this Attachment a) { object rendererObject = null; var regionAttachment = a as RegionAttachment; if (regionAttachment != null) rendererObject = regionAttachment.RendererObject; var meshAttachment = a as MeshAttachment; if (meshAttachment != null) rendererObject = meshAttachment.RendererObject; if (rendererObject == null) return null; #if SPINE_TK2D return (rendererObject.GetType() == typeof(Material)) ? (Material)rendererObject : (Material)((AtlasRegion)rendererObject).page.rendererObject; #else return (Material)((AtlasRegion)rendererObject).page.rendererObject; #endif } /// <summary>Fills a Vector2 buffer with local vertices.</summary> /// <param name="va">The VertexAttachment</param> /// <param name="slot">Slot where the attachment belongs.</param> /// <param name="buffer">Correctly-sized buffer. Use attachment's .WorldVerticesLength to get the correct size. If null, a new Vector2[] of the correct size will be allocated.</param> public static Vector2[] GetLocalVertices (this VertexAttachment va, Slot slot, Vector2[] buffer) { int floatsCount = va.worldVerticesLength; int bufferTargetSize = floatsCount >> 1; buffer = buffer ?? new Vector2[bufferTargetSize]; if (buffer.Length < bufferTargetSize) throw new System.ArgumentException(string.Format("Vector2 buffer too small. {0} requires an array of size {1}. Use the attachment's .WorldVerticesLength to get the correct size.", va.Name, floatsCount), "buffer"); if (va.bones == null) { var localVerts = va.vertices; for (int i = 0; i < bufferTargetSize; i++) { int j = i * 2; buffer[i] = new Vector2(localVerts[j], localVerts[j+1]); } } else { var floats = new float[floatsCount]; va.ComputeWorldVertices(slot, floats); Bone sb = slot.bone; float ia, ib, ic, id, bwx = sb.worldX, bwy = sb.worldY; sb.GetWorldToLocalMatrix(out ia, out ib, out ic, out id); for (int i = 0; i < bufferTargetSize; i++) { int j = i * 2; float x = floats[j] - bwx, y = floats[j+1] - bwy; buffer[i] = new Vector2(x * ia + y * ib, x * ic + y * id); } } return buffer; } /// <summary>Calculates world vertices and fills a Vector2 buffer.</summary> /// <param name="a">The VertexAttachment</param> /// <param name="slot">Slot where the attachment belongs.</param> /// <param name="buffer">Correctly-sized buffer. Use attachment's .WorldVerticesLength to get the correct size. If null, a new Vector2[] of the correct size will be allocated.</param> public static Vector2[] GetWorldVertices (this VertexAttachment a, Slot slot, Vector2[] buffer) { int worldVertsLength = a.worldVerticesLength; int bufferTargetSize = worldVertsLength >> 1; buffer = buffer ?? new Vector2[bufferTargetSize]; if (buffer.Length < bufferTargetSize) throw new System.ArgumentException(string.Format("Vector2 buffer too small. {0} requires an array of size {1}. Use the attachment's .WorldVerticesLength to get the correct size.", a.Name, worldVertsLength), "buffer"); var floats = new float[worldVertsLength]; a.ComputeWorldVertices(slot, floats); for (int i = 0, n = worldVertsLength >> 1; i < n; i++) { int j = i * 2; buffer[i] = new Vector2(floats[j], floats[j + 1]); } return buffer; } #endregion } } namespace Spine { using System.Collections.Generic; public static class SkeletonExtensions { public static bool IsWeighted (this VertexAttachment va) { return va.bones != null && va.bones.Length > 0; } #region Transform Modes public static bool InheritsRotation (this TransformMode mode) { const int RotationBit = 0; return ((int)mode & (1U << RotationBit)) == 0; } public static bool InheritsScale (this TransformMode mode) { const int ScaleBit = 1; return ((int)mode & (1U << ScaleBit)) == 0; } #endregion #region Posing internal static void SetPropertyToSetupPose (this Skeleton skeleton, int propertyID) { int tt = propertyID >> 24; var timelineType = (TimelineType)tt; int i = propertyID - (tt << 24); Bone bone; IkConstraint ikc; PathConstraint pc; switch (timelineType) { // Bone case TimelineType.Rotate: bone = skeleton.bones.Items[i]; bone.rotation = bone.data.rotation; break; case TimelineType.Translate: bone = skeleton.bones.Items[i]; bone.x = bone.data.x; bone.y = bone.data.y; break; case TimelineType.Scale: bone = skeleton.bones.Items[i]; bone.scaleX = bone.data.scaleX; bone.scaleY = bone.data.scaleY; break; case TimelineType.Shear: bone = skeleton.bones.Items[i]; bone.shearX = bone.data.shearX; bone.shearY = bone.data.shearY; break; // Slot case TimelineType.Attachment: skeleton.SetSlotAttachmentToSetupPose(i); break; case TimelineType.Color: skeleton.slots.Items[i].SetColorToSetupPose(); break; case TimelineType.TwoColor: skeleton.slots.Items[i].SetColorToSetupPose(); break; case TimelineType.Deform: skeleton.slots.Items[i].attachmentVertices.Clear(); break; // Skeleton case TimelineType.DrawOrder: skeleton.SetDrawOrderToSetupPose(); break; // IK Constraint case TimelineType.IkConstraint: ikc = skeleton.ikConstraints.Items[i]; ikc.mix = ikc.data.mix; ikc.bendDirection = ikc.data.bendDirection; break; // TransformConstraint case TimelineType.TransformConstraint: var tc = skeleton.transformConstraints.Items[i]; var tcData = tc.data; tc.rotateMix = tcData.rotateMix; tc.translateMix = tcData.translateMix; tc.scaleMix = tcData.scaleMix; tc.shearMix = tcData.shearMix; break; // Path Constraint case TimelineType.PathConstraintPosition: pc = skeleton.pathConstraints.Items[i]; pc.position = pc.data.position; break; case TimelineType.PathConstraintSpacing: pc = skeleton.pathConstraints.Items[i]; pc.spacing = pc.data.spacing; break; case TimelineType.PathConstraintMix: pc = skeleton.pathConstraints.Items[i]; pc.rotateMix = pc.data.rotateMix; pc.translateMix = pc.data.translateMix; break; } } /// <summary>Resets the DrawOrder to the Setup Pose's draw order</summary> public static void SetDrawOrderToSetupPose (this Skeleton skeleton) { var slotsItems = skeleton.slots.Items; int n = skeleton.slots.Count; var drawOrder = skeleton.drawOrder; drawOrder.Clear(false); drawOrder.GrowIfNeeded(n); System.Array.Copy(slotsItems, drawOrder.Items, n); } /// <summary>Resets the color of a slot to Setup Pose value.</summary> public static void SetColorToSetupPose (this Slot slot) { slot.r = slot.data.r; slot.g = slot.data.g; slot.b = slot.data.b; slot.a = slot.data.a; slot.r2 = slot.data.r2; slot.g2 = slot.data.g2; slot.b2 = slot.data.b2; } /// <summary>Sets a slot's attachment to setup pose. If you have the slotIndex, Skeleton.SetSlotAttachmentToSetupPose is faster.</summary> public static void SetAttachmentToSetupPose (this Slot slot) { var slotData = slot.data; slot.Attachment = slot.bone.skeleton.GetAttachment(slotData.name, slotData.attachmentName); } /// <summary>Resets the attachment of slot at a given slotIndex to setup pose. This is faster than Slot.SetAttachmentToSetupPose.</summary> public static void SetSlotAttachmentToSetupPose (this Skeleton skeleton, int slotIndex) { var slot = skeleton.slots.Items[slotIndex]; var attachmentName = slot.data.attachmentName; if (string.IsNullOrEmpty(attachmentName)) { slot.Attachment = null; } else { var attachment = skeleton.GetAttachment(slotIndex, attachmentName); slot.Attachment = attachment; } } /// <summary> /// Shortcut for posing a skeleton at a specific time. Time is in seconds. (frameNumber / 30f) will give you seconds. /// If you need to do this often, you should get the Animation object yourself using skeleton.data.FindAnimation. and call Apply on that.</summary> /// <param name = "skeleton">The skeleton to pose.</param> /// <param name="animationName">The name of the animation to use.</param> /// <param name = "time">The time of the pose within the animation.</param> /// <param name = "loop">Wraps the time around if it is longer than the duration of the animation.</param> public static void PoseWithAnimation (this Skeleton skeleton, string animationName, float time, bool loop = false) { // Fail loud when skeleton.data is null. Spine.Animation animation = skeleton.data.FindAnimation(animationName); if (animation == null) return; animation.Apply(skeleton, 0, time, loop, null, 1f, MixPose.Setup, MixDirection.In); } /// <summary>Pose a skeleton according to a given time in an animation.</summary> public static void PoseSkeleton (this Animation animation, Skeleton skeleton, float time, bool loop = false) { animation.Apply(skeleton, 0, time, loop, null, 1f, MixPose.Setup, MixDirection.In); } /// <summary>Resets Skeleton parts to Setup Pose according to a Spine.Animation's keyed items.</summary> public static void SetKeyedItemsToSetupPose (this Animation animation, Skeleton skeleton) { animation.Apply(skeleton, 0, 0, false, null, 0, MixPose.Setup, MixDirection.Out); } #endregion #region Skins /// <summary><see cref="Spine.Skin.FindNamesForSlot(int,List)"/></summary> public static void FindNamesForSlot (this Skin skin, string slotName, SkeletonData skeletonData, List<string> results) { int slotIndex = skeletonData.FindSlotIndex(slotName); skin.FindNamesForSlot(slotIndex, results); } /// <summary><see cref="Spine.Skin.FindAttachmentsForSlot(int,List)"/></summary> public static void FindAttachmentsForSlot (this Skin skin, string slotName, SkeletonData skeletonData, List<Attachment> results) { int slotIndex = skeletonData.FindSlotIndex(slotName); skin.FindAttachmentsForSlot(slotIndex, results); } #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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void SubtractUInt64() { var test = new SimpleBinaryOpTest__SubtractUInt64(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__SubtractUInt64 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(UInt64); private const int Op2ElementCount = VectorSize / sizeof(UInt64); private const int RetElementCount = VectorSize / sizeof(UInt64); private static UInt64[] _data1 = new UInt64[Op1ElementCount]; private static UInt64[] _data2 = new UInt64[Op2ElementCount]; private static Vector128<UInt64> _clsVar1; private static Vector128<UInt64> _clsVar2; private Vector128<UInt64> _fld1; private Vector128<UInt64> _fld2; private SimpleBinaryOpTest__DataTable<UInt64, UInt64, UInt64> _dataTable; static SimpleBinaryOpTest__SubtractUInt64() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ulong)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__SubtractUInt64() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ulong)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ulong)(random.Next(0, int.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<UInt64, UInt64, UInt64>(_data1, _data2, new UInt64[RetElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.Subtract( Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.Subtract( Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.Subtract( Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.Subtract( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr); var result = Sse2.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr)); var result = Sse2.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr)); var result = Sse2.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__SubtractUInt64(); var result = Sse2.Subtract(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.Subtract(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<UInt64> left, Vector128<UInt64> right, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] inArray2 = new UInt64[Op2ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "") { if ((ulong)(left[0] - right[0]) != result[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((ulong)(left[i] - right[i]) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Subtract)}<UInt64>(Vector128<UInt64>, Vector128<UInt64>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.3 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculus.com/licenses/LICENSE-3.3 Unless required by applicable law or agreed to in writing, the Oculus VR SDK distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ************************************************************************************/ using System; using System.Runtime.InteropServices; using System.Text.RegularExpressions; using UnityEngine; using VR = UnityEngine.VR; /// <summary> /// Manages an Oculus Rift head-mounted display (HMD). /// </summary> public class OVRDisplay { /// <summary> /// Specifies the size and field-of-view for one eye texture. /// </summary> public struct EyeRenderDesc { /// <summary> /// The horizontal and vertical size of the texture. /// </summary> public Vector2 resolution; /// <summary> /// The angle of the horizontal and vertical field of view in degrees. /// </summary> public Vector2 fov; } /// <summary> /// Contains latency measurements for a single frame of rendering. /// </summary> public struct LatencyData { /// <summary> /// The time it took to render both eyes in seconds. /// </summary> public float render; /// <summary> /// The time it took to perform TimeWarp in seconds. /// </summary> public float timeWarp; /// <summary> /// The time between the end of TimeWarp and scan-out in seconds. /// </summary> public float postPresent; public float renderError; public float timeWarpError; } private bool needsConfigureTexture; private EyeRenderDesc[] eyeDescs = new EyeRenderDesc[2]; /// <summary> /// Creates an instance of OVRDisplay. Called by OVRManager. /// </summary> public OVRDisplay() { UpdateTextures(); } /// <summary> /// Updates the internal state of the OVRDisplay. Called by OVRManager. /// </summary> public void Update() { UpdateTextures(); } /// <summary> /// Occurs when the head pose is reset. /// </summary> public event System.Action RecenteredPose; /// <summary> /// Recenters the head pose. /// </summary> public void RecenterPose() { VR.InputTracking.Recenter(); if (RecenteredPose != null) { RecenteredPose(); } } /// <summary> /// Gets the current linear acceleration of the head. /// </summary> public Vector3 acceleration { get { if (!OVRManager.isHmdPresent) return Vector3.zero; OVRPose ret = OVRPlugin.GetEyeAcceleration(OVRPlugin.Eye.None).ToOVRPose(); return ret.position; } } /// <summary> /// Gets the current angular acceleration of the head. /// </summary> public Quaternion angularAcceleration { get { if (!OVRManager.isHmdPresent) return Quaternion.identity; OVRPose ret = OVRPlugin.GetEyeAcceleration(OVRPlugin.Eye.None).ToOVRPose(); return ret.orientation; } } /// <summary> /// Gets the current linear velocity of the head. /// </summary> public Vector3 velocity { get { if (!OVRManager.isHmdPresent) return Vector3.zero; OVRPose ret = OVRPlugin.GetEyeVelocity(OVRPlugin.Eye.None).ToOVRPose(); return ret.position; } } /// <summary> /// Gets the current angular velocity of the head. /// </summary> public Quaternion angularVelocity { get { if (!OVRManager.isHmdPresent) return Quaternion.identity; OVRPose ret = OVRPlugin.GetEyeVelocity(OVRPlugin.Eye.None).ToOVRPose(); return ret.orientation; } } /// <summary> /// Gets the resolution and field of view for the given eye. /// </summary> public EyeRenderDesc GetEyeRenderDesc(VR.VRNode eye) { return eyeDescs[(int)eye]; } /// <summary> /// Gets the current measured latency values. /// </summary> public LatencyData latency { get { if (!OVRManager.isHmdPresent) return new LatencyData(); string latency = OVRPlugin.latency; var r = new Regex("Render: ([0-9]+[.][0-9]+)ms, TimeWarp: ([0-9]+[.][0-9]+)ms, PostPresent: ([0-9]+[.][0-9]+)ms", RegexOptions.None); var ret = new LatencyData(); Match match = r.Match(latency); if (match.Success) { ret.render = float.Parse(match.Groups[1].Value); ret.timeWarp = float.Parse(match.Groups[2].Value); ret.postPresent = float.Parse(match.Groups[3].Value); } return ret; } } /// <summary> /// Gets the recommended MSAA level for optimal quality/performance the current device. /// </summary> public int recommendedMSAALevel { get { return OVRPlugin.recommendedMSAALevel; } } private void UpdateTextures() { ConfigureEyeDesc(VR.VRNode.LeftEye); ConfigureEyeDesc(VR.VRNode.RightEye); } private void ConfigureEyeDesc(VR.VRNode eye) { if (!OVRManager.isHmdPresent) return; OVRPlugin.Sizei size = OVRPlugin.GetEyeTextureSize((OVRPlugin.Eye)eye); OVRPlugin.Frustumf frust = OVRPlugin.GetEyeFrustum((OVRPlugin.Eye)eye); eyeDescs[(int)eye] = new EyeRenderDesc() { resolution = new Vector2(size.w, size.h), fov = Mathf.Rad2Deg * new Vector2(frust.fovX, frust.fovY), }; } }
/* * Copyright 2010 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.Collections.Generic; using System.Text; using ZXing.Common; using ZXing.Common.ReedSolomon; namespace ZXing.Aztec.Internal { /// <summary> /// The main class which implements Aztec Code decoding -- as opposed to locating and extracting /// the Aztec Code from an image. /// </summary> /// <author>David Olivier</author> public sealed class Decoder { private enum Table { UPPER, LOWER, MIXED, DIGIT, PUNCT, BINARY } private static readonly String[] UPPER_TABLE = { "CTRL_PS", " ", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "CTRL_LL", "CTRL_ML", "CTRL_DL", "CTRL_BS" }; private static readonly String[] LOWER_TABLE = { "CTRL_PS", " ", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "CTRL_US", "CTRL_ML", "CTRL_DL", "CTRL_BS" }; private static readonly String[] MIXED_TABLE = { "CTRL_PS", " ", "\x1", "\x2", "\x3", "\x4", "\x5", "\x6", "\x7", "\b", "\t", "\n", "\xD", "\f", "\r", "\x21", "\x22", "\x23", "\x24", "\x25", "@", "\\", "^", "_", "`", "|", "~", "\xB1", "CTRL_LL", "CTRL_UL", "CTRL_PL", "CTRL_BS" }; private static readonly String[] PUNCT_TABLE = { "", "\r", "\r\n", ". ", ", ", ": ", "!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", ":", ";", "<", "=", ">", "?", "[", "]", "{", "}", "CTRL_UL" }; private static readonly String[] DIGIT_TABLE = { "CTRL_PS", " ", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ",", ".", "CTRL_UL", "CTRL_US" }; private static readonly IDictionary<Table, String[]> codeTables = new Dictionary<Table, String[]> { {Table.UPPER, UPPER_TABLE}, {Table.LOWER, LOWER_TABLE}, {Table.MIXED, MIXED_TABLE}, {Table.PUNCT, PUNCT_TABLE}, {Table.DIGIT, DIGIT_TABLE}, {Table.BINARY, null} }; private static readonly IDictionary<char, Table> codeTableMap = new Dictionary<char, Table> { {'U', Table.UPPER}, {'L', Table.LOWER}, {'M', Table.MIXED}, {'P', Table.PUNCT}, {'D', Table.DIGIT}, {'B', Table.BINARY} }; private AztecDetectorResult ddata; /// <summary> /// Decodes the specified detector result. /// </summary> /// <param name="detectorResult">The detector result.</param> /// <returns></returns> public DecoderResult decode(AztecDetectorResult detectorResult) { ddata = detectorResult; BitMatrix matrix = detectorResult.Bits; bool[] rawbits = extractBits(matrix); if (rawbits == null) return null; bool[] correctedBits = correctBits(rawbits); if (correctedBits == null) return null; String result = getEncodedData(correctedBits); if (result == null) return null; return new DecoderResult(null, result, null, null); } // This method is used for testing the high-level encoder public static String highLevelDecode(bool[] correctedBits) { return getEncodedData(correctedBits); } /// <summary> /// Gets the string encoded in the aztec code bits /// </summary> /// <param name="correctedBits">The corrected bits.</param> /// <returns>the decoded string</returns> private static String getEncodedData(bool[] correctedBits) { var endIndex = correctedBits.Length; var latchTable = Table.UPPER; // table most recently latched to var shiftTable = Table.UPPER; // table to use for the next read var strTable = UPPER_TABLE; var result = new StringBuilder(20); var index = 0; while (index < endIndex) { if (shiftTable == Table.BINARY) { if (endIndex - index < 5) { break; } int length = readCode(correctedBits, index, 5); index += 5; if (length == 0) { if (endIndex - index < 11) { break; } length = readCode(correctedBits, index, 11) + 31; index += 11; } for (int charCount = 0; charCount < length; charCount++) { if (endIndex - index < 8) { index = endIndex; // Force outer loop to exit break; } int code = readCode(correctedBits, index, 8); result.Append((char) code); index += 8; } // Go back to whatever mode we had been in shiftTable = latchTable; strTable = codeTables[shiftTable]; } else { int size = shiftTable == Table.DIGIT ? 4 : 5; if (endIndex - index < size) { break; } int code = readCode(correctedBits, index, size); index += size; String str = getCharacter(strTable, code); if (str.StartsWith("CTRL_")) { // Table changes shiftTable = getTable(str[5]); strTable = codeTables[shiftTable]; if (str[6] == 'L') { latchTable = shiftTable; } } else { result.Append(str); // Go back to whatever mode we had been in shiftTable = latchTable; strTable = codeTables[shiftTable]; } } } return result.ToString(); } /// <summary> /// gets the table corresponding to the char passed /// </summary> /// <param name="t">The t.</param> /// <returns></returns> private static Table getTable(char t) { if (!codeTableMap.ContainsKey(t)) return codeTableMap['U']; return codeTableMap[t]; } /// <summary> /// Gets the character (or string) corresponding to the passed code in the given table /// </summary> /// <param name="table">the table used</param> /// <param name="code">the code of the character</param> /// <returns></returns> private static String getCharacter(String[] table, int code) { return table[code]; } /// <summary> ///Performs RS error correction on an array of bits. /// </summary> /// <param name="rawbits">The rawbits.</param> /// <returns>the corrected array</returns> private bool[] correctBits(bool[] rawbits) { GenericGF gf; int codewordSize; if (ddata.NbLayers <= 2) { codewordSize = 6; gf = GenericGF.AZTEC_DATA_6; } else if (ddata.NbLayers <= 8) { codewordSize = 8; gf = GenericGF.AZTEC_DATA_8; } else if (ddata.NbLayers <= 22) { codewordSize = 10; gf = GenericGF.AZTEC_DATA_10; } else { codewordSize = 12; gf = GenericGF.AZTEC_DATA_12; } int numDataCodewords = ddata.NbDatablocks; int numCodewords = rawbits.Length/codewordSize; int offset = rawbits.Length%codewordSize; int numECCodewords = numCodewords - numDataCodewords; int[] dataWords = new int[numCodewords]; for (int i = 0; i < numCodewords; i++, offset += codewordSize) { dataWords[i] = readCode(rawbits, offset, codewordSize); } var rsDecoder = new ReedSolomonDecoder(gf); if (!rsDecoder.decode(dataWords, numECCodewords)) return null; // Now perform the unstuffing operation. // First, count how many bits are going to be thrown out as stuffing int mask = (1 << codewordSize) - 1; int stuffedBits = 0; for (int i = 0; i < numDataCodewords; i++) { int dataWord = dataWords[i]; if (dataWord == 0 || dataWord == mask) { return null; } else if (dataWord == 1 || dataWord == mask - 1) { stuffedBits++; } } // Now, actually unpack the bits and remove the stuffing bool[] correctedBits = new bool[numDataCodewords*codewordSize - stuffedBits]; int index = 0; for (int i = 0; i < numDataCodewords; i++) { int dataWord = dataWords[i]; if (dataWord == 1 || dataWord == mask - 1) { // next codewordSize-1 bits are all zeros or all ones SupportClass.Fill(correctedBits, index, index + codewordSize - 1, dataWord > 1); index += codewordSize - 1; } else { for (int bit = codewordSize - 1; bit >= 0; --bit) { correctedBits[index++] = (dataWord & (1 << bit)) != 0; } } } if (index != correctedBits.Length) return null; return correctedBits; } /// <summary> /// Gets the array of bits from an Aztec Code matrix /// </summary> /// <param name="matrix">The matrix.</param> /// <returns>the array of bits</returns> private bool[] extractBits(BitMatrix matrix) { bool compact = ddata.Compact; int layers = ddata.NbLayers; int baseMatrixSize = compact ? 11 + layers*4 : 14 + layers*4; // not including alignment lines int[] alignmentMap = new int[baseMatrixSize]; bool[] rawbits = new bool[totalBitsInLayer(layers, compact)]; if (compact) { for (int i = 0; i < alignmentMap.Length; i++) { alignmentMap[i] = i; } } else { int matrixSize = baseMatrixSize + 1 + 2*((baseMatrixSize/2 - 1)/15); int origCenter = baseMatrixSize/2; int center = matrixSize/2; for (int i = 0; i < origCenter; i++) { int newOffset = i + i/15; alignmentMap[origCenter - i - 1] = center - newOffset - 1; alignmentMap[origCenter + i] = center + newOffset + 1; } } for (int i = 0, rowOffset = 0; i < layers; i++) { int rowSize = compact ? (layers - i)*4 + 9 : (layers - i)*4 + 12; // The top-left most point of this layer is <low, low> (not including alignment lines) int low = i*2; // The bottom-right most point of this layer is <high, high> (not including alignment lines) int high = baseMatrixSize - 1 - low; // We pull bits from the two 2 x rowSize columns and two rowSize x 2 rows for (int j = 0; j < rowSize; j++) { int columnOffset = j*2; for (int k = 0; k < 2; k++) { // left column rawbits[rowOffset + columnOffset + k] = matrix[alignmentMap[low + k], alignmentMap[low + j]]; // bottom row rawbits[rowOffset + 2*rowSize + columnOffset + k] = matrix[alignmentMap[low + j], alignmentMap[high - k]]; // right column rawbits[rowOffset + 4*rowSize + columnOffset + k] = matrix[alignmentMap[high - k], alignmentMap[high - j]]; // top row rawbits[rowOffset + 6*rowSize + columnOffset + k] = matrix[alignmentMap[high - j], alignmentMap[low + k]]; } } rowOffset += rowSize*8; } return rawbits; } /// <summary> /// Reads a code of given length and at given index in an array of bits /// </summary> /// <param name="rawbits">The rawbits.</param> /// <param name="startIndex">The start index.</param> /// <param name="length">The length.</param> /// <returns></returns> private static int readCode(bool[] rawbits, int startIndex, int length) { int res = 0; for (int i = startIndex; i < startIndex + length; i++) { res <<= 1; if (rawbits[i]) { res++; } } return res; } private static int totalBitsInLayer(int layers, bool compact) { return ((compact ? 88 : 112) + 16*layers)*layers; } } }
using System; using Castle.Core; using Castle.Core.Internal; using Castle.Igloo.Attributes; using Castle.Igloo.ComponentActivator; using Castle.Igloo.Inspectors; using Castle.Igloo.Interceptors; using Castle.Igloo.LifestyleManager; using Castle.Igloo.Test.ScopeTest.Components; using Castle.MicroKernel; using Castle.MicroKernel.ModelBuilder; using Castle.Windsor; using NUnit.Framework; namespace Castle.Igloo.Test.ScopeTest { [TestFixture] public class ComponentActivatorTests { private IContributeComponentModelConstruction _inspector = null; private IKernel _kernel = null; private IWindsorContainer _container = null; [SetUp] public void Setup() { _kernel = new DefaultKernel(); _inspector = new IglooInspector(); _container = new WindsorContainer(); _container.AddFacility("Igloo.Facility", new IglooFacility()); } [Test] public void ProcessModel_NoScopeAttribute() { ComponentModel model = new ComponentModel("test", typeof(IComponent), typeof(SingletonScopeComponent)); _inspector.ProcessModel(_kernel, model); Assert.IsNull(model.CustomComponentActivator); } [Test] public void ProcessModel_ScopeAttributeWithProxy() { ComponentModel model = new ComponentModel("test", typeof(IComponent), typeof(SimpleComponent)); _inspector.ProcessModel(_kernel, model); Assert.IsNotNull(model.CustomComponentActivator); Assert.AreEqual(typeof(ScopeComponentActivator), model.CustomComponentActivator); ScopeAttribute scopeAttribute = (ScopeAttribute)model.ExtendedProperties[ScopeInspector.SCOPE_ATTRIBUTE]; Assert.IsTrue(scopeAttribute.UseProxy); Assert.AreEqual(ScopeType.Singleton ,scopeAttribute.Scope); } [Test] public void ProcessModel_ScopeAttributeWithoutProxy() { ComponentModel model = new ComponentModel("test", typeof(IComponent), typeof(TransientScopeComponent)); _inspector.ProcessModel(_kernel, model); Assert.IsNull(model.CustomComponentActivator); ScopeAttribute scopeAttribute = (ScopeAttribute)model.ExtendedProperties[ScopeInspector.SCOPE_ATTRIBUTE]; Assert.IsFalse(scopeAttribute.UseProxy); Assert.AreEqual(ScopeType.Transient, scopeAttribute.Scope); Assert.AreEqual(LifestyleType.Custom, model.LifestyleType); Assert.AreEqual(typeof(ScopeLifestyleManager), model.CustomLifestyle); } [Test] public void ProcessModel_ScopeConfigWithProxy() { _container.AddComponent("Simple.Component", typeof(IComponent), typeof(SimpleComponent)); IVertex[] vertices = TopologicalSortAlgo.Sort(_container.Kernel.GraphNodes); for (int i = 0; i < vertices.Length; i++) { ComponentModel model = (ComponentModel)vertices[i]; if (model.Name == "Simple.Component") { Assert.IsNotNull(model.CustomComponentActivator); Assert.AreEqual(typeof(ScopeComponentActivator), model.CustomComponentActivator); ScopeAttribute scopeAttribute = (ScopeAttribute)model.ExtendedProperties[ScopeInspector.SCOPE_ATTRIBUTE]; Assert.IsTrue(scopeAttribute.UseProxy); Assert.AreEqual(ScopeType.Singleton, scopeAttribute.Scope); } } } [Test] public void ProcessModel_ScopeConfigWithoutProxy() { _container.AddComponent("Transient.Scope.Component", typeof(IComponent), typeof(TransientScopeComponent)); IVertex[] vertices = TopologicalSortAlgo.Sort(_container.Kernel.GraphNodes); for (int i = 0; i < vertices.Length; i++) { ComponentModel model = (ComponentModel)vertices[i]; if (model.Name == "Transient.Scope.Component") { Assert.IsNull(model.CustomComponentActivator); ScopeAttribute scopeAttribute = (ScopeAttribute)model.ExtendedProperties[ScopeInspector.SCOPE_ATTRIBUTE]; Assert.IsFalse(scopeAttribute.UseProxy); Assert.AreEqual(ScopeType.Transient, scopeAttribute.Scope); Assert.AreEqual(LifestyleType.Custom, model.LifestyleType); Assert.AreEqual(typeof(ScopeLifestyleManager), model.CustomLifestyle); Assert.AreEqual(0, model.Interceptors.Count); foreach (InterceptorReference interceptorRef in model.Interceptors) { Assert.AreEqual(interceptorRef.ReferenceType, InterceptorReferenceType.Interface); Assert.AreEqual(interceptorRef.ServiceType, typeof(BijectionInterceptor)); } } } } [Test] public void ProcessModel_WithoutInjectProperties() { ComponentModel model = new ComponentModel("test", typeof(IComponent), typeof(TransientScopeComponent)); _inspector.ProcessModel(_kernel, model); Assert.AreEqual(0, model.Interceptors.Count); } [Test] public void ProcessModel_WithInjectProperties() { ComponentModel model = new ComponentModel("test", typeof(IComponent), typeof(ScopeComponentWithInject)); _inspector.ProcessModel(_kernel, model); Assert.AreEqual(1, model.Interceptors.Count); foreach (InterceptorReference interceptorRef in model.Interceptors) { Assert.AreEqual(interceptorRef.ReferenceType, InterceptorReferenceType.Interface); Assert.AreEqual(interceptorRef.ServiceType, typeof(BijectionInterceptor)); } } [Test] public void ProcessModel_WithOutjectProperties() { ComponentModel model = new ComponentModel("test", typeof(IComponent), typeof(TransientScopeComponent)); _inspector.ProcessModel(_kernel, model); Assert.AreEqual(0, model.Interceptors.Count); } [Test] public void ProcessModel_WithoutOutjectProperties() { ComponentModel model = new ComponentModel("test", typeof(IComponent), typeof(ScopeComponentWithOutject)); _inspector.ProcessModel(_kernel, model); Assert.AreEqual(1, model.Interceptors.Count); foreach (InterceptorReference interceptorRef in model.Interceptors) { Assert.AreEqual(interceptorRef.ReferenceType, InterceptorReferenceType.Interface); Assert.AreEqual(interceptorRef.ServiceType, typeof(BijectionInterceptor)); } } [Test] public void ProcessModel_WithInjectOutjectProperties() { ComponentModel model = new ComponentModel("test", typeof(IComponent), typeof(ScopeComponentWithInjectOutject)); _inspector.ProcessModel(_kernel, model); Assert.AreEqual(1, model.Interceptors.Count); foreach (InterceptorReference interceptorRef in model.Interceptors) { Assert.AreEqual(interceptorRef.ReferenceType, InterceptorReferenceType.Interface); Assert.AreEqual(interceptorRef.ServiceType, typeof(BijectionInterceptor)); } } [Scope(Scope = ScopeType.Transient)] private class ScopeComponentWithInject : IComponent { [Inject(Name="Test")] public string Name { set { throw new NotImplementedException("The method or operation is not implemented."); } } #region IComponent Members public int ID { get { throw new NotImplementedException("The method or operation is not implemented."); } } #endregion } [Scope(Scope = ScopeType.Transient)] private class ScopeComponentWithOutject : IComponent { [Outject(Name = "Test")] public string Name { get { throw new NotImplementedException("The method or operation is not implemented."); } } #region IComponent Members public int ID { get { throw new NotImplementedException("The method or operation is not implemented."); } } #endregion } [Scope(Scope = ScopeType.Transient)] private class ScopeComponentWithInjectOutject : IComponent { [Outject(Name = "Test")] [Inject(Name = "Test")] public string Name { get { throw new NotImplementedException("The method or operation is not implemented."); } set { throw new NotImplementedException("The method or operation is not implemented."); } } #region IComponent Members public int ID { get { throw new NotImplementedException("The method or operation is not implemented."); } } #endregion } } }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Copyright (c) GHI Electronics, LLC. // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using Microsoft.SPOT; using Microsoft.SPOT.Presentation.Media; namespace GHI.Glide.Display { /// <summary> /// The Window class inherits from: DisplayObjectContainer, DisplayObject /// </summary> /// <remarks>The Window represents a single screen within an application.</remarks> public class Window : DisplayObjectContainer { private bool _handleEvents = false; private bool _moving = false; private int _ignoredTouchMoves = 0; private int _maxIgnoredTouchMoves = 1; private int _lastPressY; private int _lastListY; private int _listMaxY; /// <summary> /// Creates a new Window. /// </summary> /// <remarks>If you're using this empty constructor (to extend for example), you'll need to initialize the window's graphics object yourself. <code>myWindow.Graphics = new Graphics(width, height);</code></remarks> public Window() { } /// <summary> /// Value changed event. /// </summary> public event OnRendered RenderedEvent; /// <summary> /// Triggers a rendered event. /// </summary> /// <param name="sender">Object associated with the event.</param> public void TriggerOnRenderedEvent(object sender) { if (RenderedEvent != null) RenderedEvent(sender); } /// <summary> /// Creates a new Window. /// </summary> /// <param name="name">Name of the Window.</param> /// <param name="width">Width</param> /// <param name="height">Height</param> public Window(string name, int width, int height) { Name = name; X = 0; Y = 0; Width = width; Height = height; Graphics = new Graphics(width, height); ListY = 0; AutoHeight = true; } /// <summary> /// Close event. /// </summary> public event OnClose CloseEvent; /// <summary> /// Triggers a close event. /// </summary> /// <param name="sender">Object associated with the event.</param> public void TriggerCloseEvent(object sender) { if (CloseEvent != null) CloseEvent(sender); } /// <summary> /// Tells this window to handle touch events. /// </summary> public void HandleEvents() { _handleEvents = true; GlideTouch.TouchDownEvent += new TouchEventHandler(TouchDownEvent); GlideTouch.TouchUpEvent += new TouchEventHandler(TouchUpEvent); GlideTouch.TouchMoveEvent += new TouchEventHandler(TouchMoveEvent); GlideTouch.TouchGestureEvent += new TouchGestureEventHandler(TouchGestureEvent); } /// <summary> /// Tells this window to ignore touch events. /// </summary> public void IgnoreEvents() { _handleEvents = false; GlideTouch.TouchDownEvent -= new TouchEventHandler(TouchDownEvent); GlideTouch.TouchUpEvent -= new TouchEventHandler(TouchUpEvent); GlideTouch.TouchMoveEvent -= new TouchEventHandler(TouchMoveEvent); GlideTouch.TouchGestureEvent -= new TouchGestureEventHandler(TouchGestureEvent); _moving = false; _ignoredTouchMoves = 0; } /// <summary> /// Draws this window and it's children on it's graphics. /// </summary> public override void Render() { // HACK: To fix image/color retention. Graphics.DrawRectangle(Rect, 0, 255); if (BackImage != null) Graphics.DrawImage(0, 0, BackImage, 0, 0, Width, Height); else Graphics.DrawRectangle(Rect, BackColor, Alpha); base.Render(); TriggerOnRenderedEvent(this); } /// <summary> /// Renders the window and flushes it to the screen. /// </summary> // Since windows need to flush we must override the default invalidate. public override void Invalidate() { Render(); Glide.screen.DrawImage(X, Y, Graphics.GetBitmap(), 0, ListY, Width, Height); Glide.screen.Flush(); } /// <summary> /// Disposes this container and all it's children. /// </summary> public override void Dispose() { if (BackImage != null) BackImage.Dispose(); base.Dispose(); } /// <summary> /// Pass touch down events to the children. /// </summary> /// <param name="sender">Object associated with the event.</param> /// <param name="e">Touch event arguments.</param> private void TouchDownEvent(object sender, TouchEventArgs e) { // Make sure this window is handling events. if (_handleEvents) { _lastPressY = e.Point.Y; _lastListY = ListY; // Adjust the point with the scroll offset e.Point.Y += ListY; OnTouchDown(e); } } /// <summary> /// Pass touch up events to the children. /// </summary> /// <param name="sender">Object associated with the event.</param> /// <param name="e">Touch event arguments.</param> private void TouchUpEvent(object sender, TouchEventArgs e) { if (_handleEvents) { _moving = false; e.Point.Y += ListY; OnTouchUp(e); } } /// <summary> /// Pass touch move events to the children. /// </summary> /// <param name="sender">Object associated with the event.</param> /// <param name="e">Touch event arguments.</param> private void TouchMoveEvent(object sender, TouchEventArgs e) { if (_handleEvents) { OnTouchMove(e); if (!_moving) { if (_ignoredTouchMoves < _maxIgnoredTouchMoves) _ignoredTouchMoves++; else { _ignoredTouchMoves = 0; _moving = true; } } else { int dragDistance = e.Point.Y - _lastPressY; ListY = _lastListY - dragDistance; if (Height > Glide.LCD.Height) _listMaxY = Height - Glide.LCD.Height; ListY = GlideUtils.Math.MinMax(ListY, 0, _listMaxY); Glide.screen.DrawImage(X, Y, Graphics.GetBitmap(), 0, ListY, Width, Height); Glide.screen.Flush(); } } } /// <summary> /// Pass touch gesture events to the children. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void TouchGestureEvent(object sender, TouchGestureEventArgs e) { if (_handleEvents) OnTouchGesture(e); } /// <summary> /// Fills a rectangle on this window's graphics using it's background image (if it exists) or the background color. /// </summary> /// <param name="rect">Rectangle object.</param> public void FillRect(Geom.Rectangle rect) { if (BackImage != null) Graphics.DrawImage(rect.X, rect.Y, BackImage, rect.X, rect.Y, rect.Width, rect.Height, Alpha); else Graphics.DrawRectangle(0, 0, rect.X, rect.Y, rect.Width, rect.Height, 0, 0, BackColor, 0, 0, BackColor, 0, 0, Alpha); } /// <summary> /// Background color. /// </summary> public Color BackColor { get; set; } /// <summary> /// Background image. /// </summary> public Bitmap BackImage { get; set; } /// <summary> /// List Y-axis position. /// </summary> public int ListY { get; set; } } }
// Copyright (c) Rotorz Limited. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root. using System; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; using Object = UnityEngine.Object; namespace Rotorz.Tile.Editor { /// <summary> /// Basic event handler. /// </summary> public delegate void BasicHandler(); /// <summary> /// Prefab event handler. /// </summary> /// <param name="prefab">Reference to prefab object.</param> public delegate void PrefabHandler(Object prefab); /// <summary> /// Tile system event handler. /// </summary> /// <param name="system">Tile system instance.</param> public delegate void TileSystemHandler(TileSystem system); /// <summary> /// Utility functionality for optimising tile systems. /// </summary> /// <remarks> /// <para>There are a number of events that can be used to perform additional /// processing during build process. The events occur in the following order:</para> /// <list type="bullet"> /// <item><see cref="BuildSceneStart"/> or <see cref="BuildPrefabStart"/></item> /// <item><see cref="PrepareTileSystem"/> (for each tile system)</item> /// <item><see cref="FinalizeTileSystem"/> (for each tile system)</item> /// <item><see cref="BuildSceneComplete"/> or <see cref="BuildPrefabComplete"/></item> /// </list> /// <para>Refer to <a href="https://github.com/rotorz/unity3d-tile-system/wiki/Tile-System-Optimization">Optimization</a> /// section of user guide for further information regarding the optimization of tile /// systems.</para> /// </remarks> public static class BuildUtility { #region Events /// <summary> /// Occurs when preparing to build and strip a tile system. /// </summary> /// <remarks> /// <para>This event is invoked before building a tile system to handle /// pre-build event for tile system.</para> /// </remarks> /// <seealso cref="IBuildContext"/> public static event BuildEventDelegate PrepareTileSystem; /// <summary> /// Occurs when tile system has been built and stripped. /// </summary> /// <remarks> /// <para>This event is invoked after building a tile system to handle /// post-build event for tile system.</para> /// </remarks> /// <seealso cref="IBuildContext"/> public static event BuildEventDelegate FinalizeTileSystem; /// <summary> /// Occurs before building scene. /// </summary> public static event BasicHandler BuildSceneStart; /// <summary> /// Occurs after scene has been built. /// </summary> public static event BasicHandler BuildSceneComplete; /// <summary> /// Occurs before building prefab from tile system. /// </summary> public static event TileSystemHandler BuildPrefabStart; /// <summary> /// Occurs after building prefab from tile system. /// </summary> public static event PrefabHandler BuildPrefabComplete; #endregion #region Build Tile System /// <summary> /// Build tile system and apply stripping rules. /// </summary> /// <param name="builder">Tile system builder.</param> /// <param name="system">Tile system.</param> private static void BuildTileSystemHelper(TileSystemBuilder builder, TileSystem system) { builder.SetContext(system); if (PrepareTileSystem != null) { PrepareTileSystem(builder); } builder.Build(system); if (FinalizeTileSystem != null) { FinalizeTileSystem(builder); } } /// <summary> /// Build tile system and apply stripping rules. /// </summary> /// <param name="system">Tile system.</param> /// <param name="progressHandler">Progress handler delegate.</param> /// <returns>Tile system builder that was used to build tile system.</returns> private static TileSystemBuilder BuildTileSystemHelper(TileSystem system, ProgressDelegate progressHandler = null) { var builder = new TileSystemBuilder(progressHandler); BuildTileSystemHelper(builder, system); return builder; } /// <summary> /// Build tile system and apply stripping rules. /// </summary> /// <param name="system">Tile system.</param> /// <param name="progressHandler">Progress handler delegate.</param> public static void BuildTileSystem(TileSystem system, ProgressDelegate progressHandler = null) { BuildTileSystemHelper(system, progressHandler); } #endregion #region Build Scene private static string SaveBuildSceneAs() { string currentScenePath = EditorApplication.currentScene.Replace("Assets/", Application.dataPath + "/"); int fileNameIndex = currentScenePath.LastIndexOf('/'); // Prompt user to save built scene. string outputPath; while (true) { // Prompt user to save scene. outputPath = EditorUtility.SaveFilePanel( title: TileLang.ParticularText("Action", "Save Built Scene"), directory: currentScenePath.Substring(0, fileNameIndex), defaultName: currentScenePath.Substring(fileNameIndex + 1).Replace(".unity", "_build.unity"), extension: "unity" ); // Make output path relative to project. outputPath = outputPath.Replace(Application.dataPath, "Assets"); // Attempt to save scene. if (!string.IsNullOrEmpty(outputPath)) { if (outputPath == EditorApplication.currentScene) { if (EditorUtility.DisplayDialog( TileLang.Text("Error"), TileLang.ParticularText("Error", "Cannot overwrite current scene with built scene."), TileLang.ParticularText("Action", "Choose Other"), TileLang.ParticularText("Action", "Cancel") )) { continue; } else { return null; } } // Ensure that built scene will be placed within "Assets" directory. else if (outputPath.StartsWith("Assets/", StringComparison.OrdinalIgnoreCase)) { break; } } // Allow user to retry! if (!EditorUtility.DisplayDialog( TileLang.Text("Error"), TileLang.ParticularText("Error", "Was unable to save built scene.\n\nWould you like to specify an alternative filename?"), TileLang.ParticularText("Action", "Yes"), TileLang.ParticularText("Action", "No") )) { return null; } } return outputPath; } /// <summary> /// Build all tile systems in scene. /// </summary> /// <remarks> /// <para>Each tile system in scene is built in sequence and then the built /// version of the scene is saved. Various user interfaces will appear during /// the build process.</para> /// </remarks> public static void BuildScene() { if (!EditorUtility.DisplayDialog( TileLang.ParticularText("Action", "Build Scene"), TileLang.Text("Scene must be saved before tile systems can be built.\n\nWould you like to save the scene now?"), TileLang.ParticularText("Action", "Save and Proceed"), TileLang.ParticularText("Action", "Cancel") )) { //EditorUtility.DisplayDialog(ProductInfo.name, "Could not build scene because it was not saved.", "Close"); return; } // Force user to save scene if (!EditorSceneManager.SaveOpenScenes()) { //EditorUtility.DisplayDialog(ProductInfo.name, "Could not build scene because it was not saved.", "Close"); return; } string originalScenePath = EditorApplication.currentScene; if (!EditorUtility.DisplayDialog( string.Format( /* 0: path of scene */ TileLang.Text("Building Scene '{0}'"), originalScenePath ), TileLang.Text("Open scene was saved successfully.\n\nProceed to save built variation of scene."), TileLang.ParticularText("Action", "Proceed"), TileLang.ParticularText("Action", "Cancel") )) { Debug.Log(TileLang.Text("Building of tile systems was cancelled.")); return; } // Prompt user to save built scene. string outputPath = SaveBuildSceneAs(); if (outputPath == null) { return; } // Save output scene straight away! if (!EditorApplication.SaveScene(outputPath)) { EditorUtility.DisplayDialog( TileLang.Text("Error"), string.Format( /* 0: path to output asset */ TileLang.ParticularText("Error", "Was unable to save output scene '{0}'"), outputPath ), TileLang.ParticularText("Action", "Close") ); return; } if (BuildSceneStart != null) { BuildSceneStart(); } bool hasErrors = false; // Fetch all tile systems in scene. TileSystem[] systems = GameObject.FindObjectsOfType<TileSystem>(); float overallTaskCount = 1f; float overallTaskOffset = 0f; float overallTaskRatio = 0f; TileSystemBuilder builder = new TileSystemBuilder(); builder.progressHandler = delegate (string title, string status, float percentage) { float progress = (builder.Task + overallTaskOffset) * overallTaskRatio; return EditorUtility.DisplayCancelableProgressBar(title, status, progress); }; // Count tasks in advance. foreach (TileSystem system in systems) { // Skip non-editable tile systems and output warning message to console. if (!system.IsEditable) { Debug.LogWarning(string.Format( /* 0: name of tile system */ TileLang.Text("Skipping non-editable tile system '{0}'."), system.name ), system); continue; } overallTaskCount += builder.CountTasks(system); } overallTaskRatio = 1f / overallTaskCount; try { // Build each tile system in turn. foreach (TileSystem system in systems) { // Skip non-editable tile systems. if (!system.IsEditable) { continue; } BuildTileSystemHelper(builder, system); // Adjust overall task offset. overallTaskOffset += builder.TaskCount; } builder.progressHandler( TileLang.Text("Building tile systems"), TileLang.Text("Cleaning up..."), progress: (overallTaskCount - 1f) * overallTaskRatio ); builder = null; UnityEngine.Resources.UnloadUnusedAssets(); GC.Collect(); } catch (Exception ex) { Debug.LogError(ex.ToString()); hasErrors = true; } finally { // Finished with progress bar! EditorUtility.ClearProgressBar(); } // Save output scene. if (!EditorApplication.SaveScene(outputPath)) { Debug.LogError(string.Format( /* 0: scene file path */ TileLang.ParticularText("Error", "Was unable to save output scene '{0}'"), outputPath )); } // Raise event for end of build process. if (BuildSceneComplete != null) { BuildSceneComplete(); } // Rollback changes. EditorApplication.OpenScene(originalScenePath); if (hasErrors) { EditorUtility.DisplayDialog( TileLang.Text("Warning"), TileLang.Text("Errors were encountered whilst building scene. Please check console for any additional information."), TileLang.ParticularText("Action", "Close") ); } } #endregion /// <summary> /// Build optimized prefab from a tile system. /// </summary> /// <remarks> /// <para>Presents various user interfaces.</para> /// </remarks> /// <param name="system">Tile system.</param> /// <param name="dataPath">Output path for generated data asset.</param> /// <param name="prefabPath">Output path for generated prefab asset.</param> public static void BuildPrefab(TileSystem system, string dataPath, string prefabPath) { // Destroy mesh if it already exists. AssetDatabase.DeleteAsset(dataPath); // Destroy prefab if it already exists. AssetDatabase.DeleteAsset(prefabPath); // Duplicate tile system for processing. var duplicateTileSystemGO = GameObject.Instantiate(system.gameObject); var duplicateTileSystem = duplicateTileSystemGO.GetComponent<TileSystem>(); InternalUtility.EnableProgressHandler = true; // Raise event for start of building prefab. if (BuildPrefabStart != null) { BuildPrefabStart(duplicateTileSystem); } try { string tileSystemName = duplicateTileSystem.name; var tileSystemBuilder = BuildTileSystemHelper(duplicateTileSystem, InternalUtility.CancelableProgressHandler); // Save generated meshes to asset. TileSystemPrefabAsset assetData = ScriptableObject.CreateInstance<TileSystemPrefabAsset>(); AssetDatabase.CreateAsset(assetData, dataPath); foreach (var mesh in tileSystemBuilder.GeneratedMeshes) { AssetDatabase.AddObjectToAsset(mesh, assetData); } AssetDatabase.ImportAsset(dataPath); EditorUtility.DisplayProgressBar( string.Format( /* 0: name of tile system */ TileLang.Text("Building tile system '{0}'..."), tileSystemName ), TileLang.Text("Saving prefab and data asset..."), progress: 1f ); // Create prefab output. var newPrefab = PrefabUtility.CreatePrefab(prefabPath, duplicateTileSystemGO, ReplacePrefabOptions.ConnectToPrefab); // Raise event for end of building prefab. if (BuildPrefabComplete != null) { BuildPrefabComplete(newPrefab); } } catch { throw; } finally { // Destroy duplicate tile system. Object.DestroyImmediate(duplicateTileSystemGO); // Finished with progress bar! EditorUtility.ClearProgressBar(); } } } }
// *********************************************************************** // Copyright (c) 2007 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using NUnit.Framework; #if !NETSTANDARD1_3 && !NETSTANDARD1_6 using System.Security.Principal; #endif namespace NUnit.TestData.TestFixtureTests { /// <summary> /// Classes used for testing NUnit /// </summary> [TestFixture] public class RegularFixtureWithOneTest { [Test] public void OneTest() { } } [TestFixture] public class NoDefaultCtorFixture { public NoDefaultCtorFixture(int index) { } [Test] public void OneTest() { } } [TestFixture(7,3)] public class FixtureWithArgsSupplied { public FixtureWithArgsSupplied(int x, int y) { } [Test] public void OneTest() { } } [TestFixture(7, 3)] [TestFixture(8, 4)] public class FixtureWithMultipleArgsSupplied { public FixtureWithMultipleArgsSupplied(int x, int y) { } [Test] public void OneTest() { } } [TestFixture] public class BadCtorFixture { public BadCtorFixture() { throw new Exception(); } [Test] public void OneTest() { } } [TestFixture] public class FixtureWithTestFixtureAttribute { [Test] public void SomeTest() { } } public class FixtureWithoutTestFixtureAttributeContainingTest { [Test] public void SomeTest() { } } public class FixtureWithoutTestFixtureAttributeContainingTestCase { [TestCase(42)] public void SomeTest(int x) { } } [TestFixture] public class FixtureWithParameterizedTestAndArgsSupplied { [TestCase(42, "abc")] public void SomeTest(int x, string y) { } } [TestFixture] public class FixtureWithParameterizedTestAndMultipleArgsSupplied { [TestCase(42, "abc")] [TestCase(24, "cba")] public void SomeTest(int x, string y) { } } public class FixtureWithoutTestFixtureAttributeContainingTestCaseSource { [TestCaseSource("data")] public void SomeTest(int x) { } } public class FixtureWithoutTestFixtureAttributeContainingTheory { [Theory] public void SomeTest(int x) { } } public static class StaticFixtureWithoutTestFixtureAttribute { [Test] public static void StaticTest() { } } [TestFixture] public class MultipleSetUpAttributes { [SetUp] public void Init1() { } [SetUp] public void Init2() { } [Test] public void OneTest() { } } [TestFixture] public class MultipleTearDownAttributes { [TearDown] public void Destroy1() { } [TearDown] public void Destroy2() { } [Test] public void OneTest() { } } [TestFixture] [Ignore("testing ignore a fixture")] public class FixtureUsingIgnoreAttribute { [Test] public void Success() { } } [TestFixture(Ignore = "testing ignore a fixture")] public class FixtureUsingIgnoreProperty { [Test] public void Success() { } } [TestFixture(IgnoreReason = "testing ignore a fixture")] public class FixtureUsingIgnoreReasonProperty { [Test] public void Success() { } } [TestFixture] public class OuterClass { [TestFixture] public class NestedTestFixture { [TestFixture] public class DoublyNestedTestFixture { [Test] public void Test() { } } } } [TestFixture] public abstract class AbstractTestFixture { [TearDown] public void Destroy1() { } [Test] public void SomeTest() { } } public class DerivedFromAbstractTestFixture : AbstractTestFixture { } [TestFixture] public class BaseClassTestFixture { [Test] public void Success() { } } public abstract class AbstractDerivedTestFixture : BaseClassTestFixture { [Test] public void Test() { } } public class DerivedFromAbstractDerivedTestFixture : AbstractDerivedTestFixture { } [TestFixture] public abstract class AbstractBaseFixtureWithAttribute { } [TestFixture] public abstract class AbstractDerivedFixtureWithSecondAttribute : AbstractBaseFixtureWithAttribute { } public class DoubleDerivedClassWithTwoInheritedAttributes : AbstractDerivedFixtureWithSecondAttribute { } [TestFixture] public class MultipleFixtureSetUpAttributes { [OneTimeSetUp] public void Init1() { } [OneTimeSetUp] public void Init2() { } [Test] public void OneTest() { } } [TestFixture] public class MultipleFixtureTearDownAttributes { [OneTimeTearDown] public void Destroy1() { } [OneTimeTearDown] public void Destroy2() { } [Test] public void OneTest() { } } // Base class used to ensure following classes // all have at least one test public class OneTestBase { [Test] public void OneTest() { } } [TestFixture] public class PrivateSetUp : OneTestBase { [SetUp] private void Setup() { } } [TestFixture] public class ProtectedSetUp : OneTestBase { [SetUp] protected void Setup() { } } [TestFixture] public class StaticSetUp : OneTestBase { [SetUp] public static void Setup() { } } [TestFixture] public class SetUpWithReturnValue : OneTestBase { [SetUp] public int Setup() { return 0; } } [TestFixture] public class SetUpWithParameters : OneTestBase { [SetUp] public void Setup(int j) { } } [TestFixture] public class PrivateTearDown : OneTestBase { [TearDown] private void Teardown() { } } [TestFixture] public class ProtectedTearDown : OneTestBase { [TearDown] protected void Teardown() { } } [TestFixture] public class StaticTearDown : OneTestBase { [SetUp] public static void TearDown() { } } [TestFixture] public class TearDownWithReturnValue : OneTestBase { [TearDown] public int Teardown() { return 0; } } [TestFixture] public class TearDownWithParameters : OneTestBase { [TearDown] public void Teardown(int j) { } } [TestFixture] public class PrivateFixtureSetUp : OneTestBase { [OneTimeSetUp] private void Setup() { } } [TestFixture] public class ProtectedFixtureSetUp : OneTestBase { [OneTimeSetUp] protected void Setup() { } } [TestFixture] public class StaticFixtureSetUp : OneTestBase { [OneTimeSetUp] public static void Setup() { } } [TestFixture] public class FixtureSetUpWithReturnValue : OneTestBase { [OneTimeSetUp] public int Setup() { return 0; } } [TestFixture] public class FixtureSetUpWithParameters : OneTestBase { [OneTimeSetUp] public void Setup(int j) { } } [TestFixture] public class PrivateFixtureTearDown : OneTestBase { [OneTimeTearDown] private void Teardown() { } } [TestFixture] public class ProtectedFixtureTearDown : OneTestBase { [OneTimeTearDown] protected void Teardown() { } } [TestFixture] public class StaticFixtureTearDown : OneTestBase { [OneTimeTearDown] public static void Teardown() { } } [TestFixture] public class FixtureTearDownWithReturnValue : OneTestBase { [OneTimeTearDown] public int Teardown() { return 0; } } [TestFixture] public class FixtureTearDownWithParameters : OneTestBase { [OneTimeTearDown] public void Teardown(int j) { } } #if !NETSTANDARD1_3 && !NETSTANDARD1_6 [TestFixture] public class FixtureThatChangesTheCurrentPrincipal { [Test] public void ChangeCurrentPrincipal() { WindowsIdentity identity = WindowsIdentity.GetCurrent(); GenericPrincipal principal = new GenericPrincipal( identity, new string[] { } ); System.Threading.Thread.CurrentPrincipal = principal; } } #endif [TestFixture(typeof(int))] [TestFixture(typeof(string))] public class GenericFixtureWithProperArgsProvided<T> { [Test] public void SomeTest() { } } public class GenericFixtureWithNoTestFixtureAttribute<T> { [Test] public void SomeTest() { } } [TestFixture] public class GenericFixtureWithNoArgsProvided<T> { [Test] public void SomeTest() { } } [TestFixture] public abstract class AbstractFixtureBase { [Test] public void SomeTest() { } } public class GenericFixtureDerivedFromAbstractFixtureWithNoArgsProvided<T> : AbstractFixtureBase { } [TestFixture(typeof(int))] [TestFixture(typeof(string))] public class GenericFixtureDerivedFromAbstractFixtureWithArgsProvided<T> : AbstractFixtureBase { } }
// *********************************************************************** // Copyright (c) 2007 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; using NUnit.TestUtilities.Collections; namespace NUnit.Framework.Assertions { /// <summary> /// Summary description for ArrayEqualTests. /// </summary> [TestFixture] public class ArrayEqualsFixture { #pragma warning disable 183, 184 // error number varies in different runtimes // Used to detect runtimes where ArraySegments implement IEnumerable private static readonly bool ArraySegmentImplementsIEnumerable = new ArraySegment<int>() is IEnumerable; #pragma warning restore 183, 184 [Test] public void ArrayIsEqualToItself() { string[] array = { "one", "two", "three" }; Assert.That( array, Is.SameAs(array) ); Assert.AreEqual( array, array ); } [Test] public void ArraysOfString() { string[] array1 = { "one", "two", "three" }; string[] array2 = { "one", "two", "three" }; Assert.IsFalse( array1 == array2 ); Assert.AreEqual(array1, array2); Assert.AreEqual(array2, array1); } [Test] public void ArraysOfInt() { int[] a = new int[] { 1, 2, 3 }; int[] b = new int[] { 1, 2, 3 }; Assert.AreEqual(a, b); Assert.AreEqual(b, a); } [Test] public void ArraysOfDouble() { double[] a = new double[] { 1.0, 2.0, 3.0 }; double[] b = new double[] { 1.0, 2.0, 3.0 }; Assert.AreEqual(a, b); Assert.AreEqual(b, a); } [Test] public void ArraysOfDecimal() { decimal[] a = new decimal[] { 1.0m, 2.0m, 3.0m }; decimal[] b = new decimal[] { 1.0m, 2.0m, 3.0m }; Assert.AreEqual(a, b); Assert.AreEqual(b, a); } [Test] public void ArrayOfIntAndArrayOfDouble() { int[] a = new int[] { 1, 2, 3 }; double[] b = new double[] { 1.0, 2.0, 3.0 }; Assert.AreEqual(a, b); Assert.AreEqual(b, a); } [Test] public void ArraysDeclaredAsDifferentTypes() { string[] array1 = { "one", "two", "three" }; object[] array2 = { "one", "two", "three" }; Assert.AreEqual( array1, array2, "String[] not equal to Object[]" ); Assert.AreEqual( array2, array1, "Object[] not equal to String[]" ); } [Test] public void ArraysOfMixedTypes() { DateTime now = DateTime.Now; object[] array1 = new object[] { 1, 2.0f, 3.5d, 7.000m, "Hello", now }; object[] array2 = new object[] { 1.0d, 2, 3.5, 7, "Hello", now }; Assert.AreEqual( array1, array2 ); Assert.AreEqual(array2, array1); } [Test] public void DoubleDimensionedArrays() { int[,] a = new int[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int[,] b = new int[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; Assert.AreEqual(a, b); Assert.AreEqual(b, a); } [Test] public void TripleDimensionedArrays() { int[, ,] expected = new int[,,] { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }; int[,,] actual = new int[,,] { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }; Assert.AreEqual(expected, actual); } [Test] public void FiveDimensionedArrays() { int[, , , ,] expected = new int[2, 2, 2, 2, 2] { { { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }, { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } } }, { { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }, { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } } } }; int[, , , ,] actual = new int[2, 2, 2, 2, 2] { { { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }, { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } } }, { { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }, { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } } } }; Assert.AreEqual(expected, actual); } [Test] public void ArraysOfArrays() { int[][] a = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6 }, new int[] { 7, 8, 9 } }; int[][] b = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6 }, new int[] { 7, 8, 9 } }; Assert.AreEqual(a, b); Assert.AreEqual(b, a); } [Test] public void JaggedArrays() { int[][] expected = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6, 7 }, new int[] { 8, 9 } }; int[][] actual = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6, 7 }, new int[] { 8, 9 } }; Assert.AreEqual(expected, actual); } [Test] public void ArraysPassedAsObjects() { object a = new int[] { 1, 2, 3 }; object b = new double[] { 1.0, 2.0, 3.0 }; Assert.AreEqual(a, b); Assert.AreEqual(b, a); } [Test] public void ArrayAndCollection() { int[] a = new int[] { 1, 2, 3 }; ICollection b = new SimpleObjectCollection( 1, 2, 3 ); Assert.AreEqual(a, b); Assert.AreEqual(b, a); } [Test] public void ArraysWithDifferentRanksComparedAsCollection() { int[] expected = new int[] { 1, 2, 3, 4 }; int[,] actual = new int[,] { { 1, 2 }, { 3, 4 } }; Assert.AreNotEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected).AsCollection); } [Test] public void ArraysWithDifferentDimensionsMatchedAsCollection() { int[,] expected = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } }; int[,] actual = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } }; Assert.AreNotEqual(expected, actual); Assert.That(actual, Is.EqualTo(expected).AsCollection); } private static readonly int[] underlyingArray = { 1, 2, 3, 4, 5 }; [Test] public void ArraySegmentAndArray() { Assume.That(ArraySegmentImplementsIEnumerable); Assert.That(new ArraySegment<int>(underlyingArray, 1, 3), Is.EqualTo(new int[] { 2, 3, 4 })); } [Test] public void EmptyArraySegmentAndArray() { Assume.That(ArraySegmentImplementsIEnumerable); Assert.That(new ArraySegment<int>(), Is.Not.EqualTo(new int[] { 2, 3, 4 })); } [Test] public void ArrayAndArraySegment() { Assume.That(ArraySegmentImplementsIEnumerable); Assert.That(new int[] { 2, 3, 4 }, Is.EqualTo(new ArraySegment<int>(underlyingArray, 1, 3))); } [Test] public void ArrayAndEmptyArraySegment() { Assume.That(ArraySegmentImplementsIEnumerable); Assert.That(new int[] { 2, 3, 4 }, Is.Not.EqualTo(new ArraySegment<int>())); } [Test] public void TwoArraySegments() { Assume.That(ArraySegmentImplementsIEnumerable); Assert.That(new ArraySegment<int>(underlyingArray, 1, 3), Is.EqualTo(new ArraySegment<int>(underlyingArray, 1, 3))); } [Test] public void TwoEmptyArraySegments() { Assume.That(ArraySegmentImplementsIEnumerable); Assert.That(new ArraySegment<int>(), Is.EqualTo(new ArraySegment<int>())); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Editor.CSharp.Interactive; using Microsoft.CodeAnalysis.Interactive; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Traits = Roslyn.Test.Utilities.Traits; namespace Microsoft.CodeAnalysis.UnitTests.Interactive { [Trait(Traits.Feature, Traits.Features.InteractiveHost)] public sealed class InteractiveHostTests : AbstractInteractiveHostTests { #region Utils private SynchronizedStringWriter _synchronizedOutput; private SynchronizedStringWriter _synchronizedErrorOutput; private int[] _outputReadPosition = new int[] { 0, 0 }; private readonly InteractiveHost Host; private static readonly string s_fxDir = FileUtilities.NormalizeDirectoryPath(RuntimeEnvironment.GetRuntimeDirectory()); private static readonly string s_homeDir = FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)); public InteractiveHostTests() { Host = new InteractiveHost(typeof(CSharpReplServiceProvider), GetInteractiveHostPath(), ".", millisecondsTimeout: -1); RedirectOutput(); Host.ResetAsync(new InteractiveHostOptions(initializationFile: null, culture: CultureInfo.InvariantCulture)).Wait(); var remoteService = Host.TryGetService(); Assert.NotNull(remoteService); remoteService.SetTestObjectFormattingOptions(); Host.SetPathsAsync(new[] { s_fxDir }, new[] { s_homeDir }, s_homeDir).Wait(); // assert and remove logo: var output = SplitLines(ReadOutputToEnd()); var errorOutput = ReadErrorOutputToEnd(); Assert.Equal("", errorOutput); Assert.Equal(2, output.Length); Assert.Equal("Microsoft (R) Roslyn C# Compiler version " + FileVersionInfo.GetVersionInfo(Host.GetType().Assembly.Location).FileVersion, output[0]); // "Type "#help" for more information." Assert.Equal(FeaturesResources.TypeHelpForMoreInformation, output[1]); // remove logo: ClearOutput(); } public override void Dispose() { try { Process process = Host.TryGetProcess(); DisposeInteractiveHostProcess(Host); // the process should be terminated if (process != null && !process.HasExited) { process.WaitForExit(); } } finally { // Dispose temp files only after the InteractiveHost exits, // so that assemblies are unloaded. base.Dispose(); } } private void RedirectOutput() { _synchronizedOutput = new SynchronizedStringWriter(); _synchronizedErrorOutput = new SynchronizedStringWriter(); ClearOutput(); Host.Output = _synchronizedOutput; Host.ErrorOutput = _synchronizedErrorOutput; } private bool LoadReference(string reference) { return Execute($"#r \"{reference}\""); } private bool Execute(string code) { var task = Host.ExecuteAsync(code); task.Wait(); return task.Result.Success; } private bool IsShadowCopy(string path) { return Host.TryGetService().IsShadowCopy(path); } public string ReadErrorOutputToEnd() { return ReadOutputToEnd(isError: true); } public void ClearOutput() { _outputReadPosition = new int[] { 0, 0 }; _synchronizedOutput.Clear(); _synchronizedErrorOutput.Clear(); } public void RestartHost(string rspFile = null) { ClearOutput(); var initTask = Host.ResetAsync(new InteractiveHostOptions(initializationFile: rspFile, culture: CultureInfo.InvariantCulture)); initTask.Wait(); } public string ReadOutputToEnd(bool isError = false) { var writer = isError ? _synchronizedErrorOutput : _synchronizedOutput; var markPrefix = '\uFFFF'; var mark = markPrefix + Guid.NewGuid().ToString(); // writes mark to the STDOUT/STDERR pipe in the remote process: Host.TryGetService().RemoteConsoleWrite(Encoding.UTF8.GetBytes(mark), isError); while (true) { var data = writer.Prefix(mark, ref _outputReadPosition[isError ? 0 : 1]); if (data != null) { return data; } Thread.Sleep(10); } } private class CompiledFile { public string Path; public ImmutableArray<byte> Image; } private static CompiledFile CompileLibrary(TempDirectory dir, string fileName, string assemblyName, string source, params MetadataReference[] references) { var file = dir.CreateFile(fileName); var compilation = CreateCompilation( new[] { source }, assemblyName: assemblyName, references: references.Concat(new[] { MetadataReference.CreateFromAssemblyInternal(typeof(object).Assembly) }), options: fileName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) ? TestOptions.ReleaseExe : TestOptions.ReleaseDll); var image = compilation.EmitToArray(); file.WriteAllBytes(image); return new CompiledFile { Path = file.Path, Image = image }; } #endregion [Fact] public void OutputRedirection() { Execute(@" System.Console.WriteLine(""hello-\u4567!""); System.Console.Error.WriteLine(""error-\u7890!""); 1+1 "); var output = ReadOutputToEnd(); var error = ReadErrorOutputToEnd(); Assert.Equal("hello-\u4567!\r\n2\r\n", output); Assert.Equal("error-\u7890!\r\n", error); } [Fact] public void OutputRedirection2() { Execute(@"System.Console.WriteLine(1);"); Execute(@"System.Console.Error.WriteLine(2);"); var output = ReadOutputToEnd(); var error = ReadErrorOutputToEnd(); Assert.Equal("1\r\n", output); Assert.Equal("2\r\n", error); RedirectOutput(); Execute(@"System.Console.WriteLine(3);"); Execute(@"System.Console.Error.WriteLine(4);"); output = ReadOutputToEnd(); error = ReadErrorOutputToEnd(); Assert.Equal("3\r\n", output); Assert.Equal("4\r\n", error); } [Fact] public void StackOverflow() { // Windows Server 2008 (OS v6.0), Vista (OS v6.0) and XP (OS v5.1) ignores SetErrorMode and shows crash dialog, which would hang the test: if (Environment.OSVersion.Version < new Version(6, 1, 0, 0)) { return; } Execute(@" int foo(int a0, int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9) { return foo(0,1,2,3,4,5,6,7,8,9) + foo(0,1,2,3,4,5,6,7,8,9); } foo(0,1,2,3,4,5,6,7,8,9) "); Assert.Equal("", ReadOutputToEnd()); // Hosting process exited with exit code -1073741571. Assert.Equal("Process is terminated due to StackOverflowException.\n" + string.Format(FeaturesResources.HostingProcessExitedWithExitCode, -1073741571), ReadErrorOutputToEnd().Trim()); Execute(@"1+1"); Assert.Equal("2\r\n", ReadOutputToEnd().ToString()); } private const string MethodWithInfiniteLoop = @" void foo() { int i = 0; while (true) { if (i < 10) { i = i + 1; } else if (i == 10) { System.Console.Error.WriteLine(""in the loop""); i = i + 1; } } } "; [Fact] public void AsyncExecute_InfiniteLoop() { var mayTerminate = new ManualResetEvent(false); Host.ErrorOutputReceived += (_, __) => mayTerminate.Set(); var executeTask = Host.ExecuteAsync(MethodWithInfiniteLoop + "\r\nfoo()"); Assert.True(mayTerminate.WaitOne()); RestartHost(); executeTask.Wait(); Assert.True(Execute(@"1+1")); Assert.Equal("2\r\n", ReadOutputToEnd()); } [Fact(Skip = "529027")] public void AsyncExecute_HangingForegroundThreads() { var mayTerminate = new ManualResetEvent(false); Host.OutputReceived += (_, __) => { mayTerminate.Set(); }; var executeTask = Host.ExecuteAsync(@" using System.Threading; int i1 = 0; Thread t1 = new Thread(() => { while(true) { i1++; } }); t1.Name = ""TestThread-1""; t1.IsBackground = false; t1.Start(); int i2 = 0; Thread t2 = new Thread(() => { while(true) { i2++; } }); t2.Name = ""TestThread-2""; t2.IsBackground = true; t2.Start(); Thread t3 = new Thread(() => Thread.Sleep(Timeout.Infinite)); t3.Name = ""TestThread-3""; t3.Start(); while (i1 < 2 || i2 < 2 || t3.ThreadState != System.Threading.ThreadState.WaitSleepJoin) { } System.Console.WriteLine(""terminate!""); while(true) {} "); Assert.Equal("", ReadErrorOutputToEnd()); Assert.True(mayTerminate.WaitOne()); var service = Host.TryGetService(); Assert.NotNull(service); var process = Host.TryGetProcess(); Assert.NotNull(process); service.EmulateClientExit(); // the process should terminate with exit code 0: process.WaitForExit(); Assert.Equal(0, process.ExitCode); } [Fact] public void AsyncExecuteFile_InfiniteLoop() { var file = Temp.CreateFile().WriteAllText(MethodWithInfiniteLoop + "\r\nfoo();").Path; var mayTerminate = new ManualResetEvent(false); Host.ErrorOutputReceived += (_, __) => mayTerminate.Set(); var executeTask = Host.ExecuteFileAsync(file); mayTerminate.WaitOne(); RestartHost(); executeTask.Wait(); Assert.True(Execute(@"1+1")); Assert.Equal("2\r\n", ReadOutputToEnd()); } [Fact] public void AsyncExecuteFile_SourceKind() { var file = Temp.CreateFile().WriteAllText("1 1").Path; var task = Host.ExecuteFileAsync(file); task.Wait(); Assert.False(task.Result.Success); var errorOut = ReadErrorOutputToEnd().Trim(); Assert.True(errorOut.StartsWith(file + "(1,3):", StringComparison.Ordinal), "Error output should start with file name, line and column"); Assert.True(errorOut.Contains("CS1002"), "Error output should include error CS1002"); } [Fact] public void AsyncExecuteFile_NonExistingFile() { var task = Host.ExecuteFileAsync("non existing file"); task.Wait(); Assert.False(task.Result.Success); var errorOut = ReadErrorOutputToEnd().Trim(); Assert.Contains(FeaturesResources.SpecifiedFileNotFound, errorOut, StringComparison.Ordinal); Assert.Contains(FeaturesResources.SearchedInDirectory, errorOut, StringComparison.Ordinal); } [Fact] public void AsyncExecuteFile() { var file = Temp.CreateFile().WriteAllText(@" using static System.Console; public class C { public int field = 4; public int Foo(int i) { return i; } } public int Foo(int i) { return i; } WriteLine(5); ").Path; var task = Host.ExecuteFileAsync(file); task.Wait(); Assert.True(task.Result.Success); Assert.Equal("5", ReadOutputToEnd().Trim()); Execute("Foo(2)"); Assert.Equal("2", ReadOutputToEnd().Trim()); Execute("new C().Foo(3)"); Assert.Equal("3", ReadOutputToEnd().Trim()); Execute("new C().field"); Assert.Equal("4", ReadOutputToEnd().Trim()); } [Fact] public void AsyncExecuteFile_InvalidFileContent() { var executeTask = Host.ExecuteFileAsync(typeof(Process).Assembly.Location); executeTask.Wait(); var errorOut = ReadErrorOutputToEnd().Trim(); Assert.True(errorOut.StartsWith(typeof(Process).Assembly.Location + "(1,3):", StringComparison.Ordinal), "Error output should start with file name, line and column"); Assert.True(errorOut.Contains("CS1056"), "Error output should include error CS1056"); Assert.True(errorOut.Contains("CS1002"), "Error output should include error CS1002"); } [Fact] public void AsyncExecuteFile_ScriptFileWithBuildErrors() { var file = Temp.CreateFile().WriteAllText("#load blah.csx" + "\r\n" + "class C {}"); Host.ExecuteFileAsync(file.Path).Wait(); var errorOut = ReadErrorOutputToEnd().Trim(); Assert.True(errorOut.StartsWith(file.Path + "(1,7):", StringComparison.Ordinal), "Error output should start with file name, line and column"); Assert.True(errorOut.Contains("CS7010"), "Error output should include error CS7010"); } /// <summary> /// Check that the assembly resolve event doesn't cause any harm. It shouldn't actually be /// even invoked since we resolve the assembly via Fusion. /// </summary> [Fact(Skip = "987032")] public void UserDefinedAssemblyResolve_InfiniteLoop() { var mayTerminate = new ManualResetEvent(false); Host.ErrorOutputReceived += (_, __) => mayTerminate.Set(); Host.TryGetService().HookMaliciousAssemblyResolve(); var executeTask = Host.AddReferenceAsync("nonexistingassembly" + Guid.NewGuid()); Assert.True(mayTerminate.WaitOne()); executeTask.Wait(); Assert.True(Execute(@"1+1")); var output = ReadOutputToEnd(); Assert.Equal("2\r\n", output); } [Fact] public void AddReference_Path() { Assert.False(Execute("new System.Data.DataSet()")); Assert.True(LoadReference(Assembly.Load(new AssemblyName("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")).Location)); Assert.True(Execute("new System.Data.DataSet()")); } [Fact] public void AddReference_PartialName() { Assert.False(Execute("new System.Data.DataSet()")); Assert.True(LoadReference("System.Data")); Assert.True(Execute("new System.Data.DataSet()")); } [Fact] public void AddReference_PartialName_LatestVersion() { // there might be two versions of System.Data - v2 and v4, we should get the latter: Assert.True(LoadReference("System.Data")); Assert.True(LoadReference("System")); Assert.True(LoadReference("System.Xml")); Execute(@"new System.Data.DataSet().GetType().Assembly.GetName().Version"); var output = ReadOutputToEnd(); Assert.Equal("[4.0.0.0]\r\n", output); } [Fact] public void AddReference_FullName() { Assert.False(Execute("new System.Data.DataSet()")); Assert.True(LoadReference("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")); Assert.True(Execute("new System.Data.DataSet()")); } [ConditionalFact(typeof(Framework35Installed), Skip="https://github.com/dotnet/roslyn/issues/5167")] public void AddReference_VersionUnification1() { // V3.5 unifies with the current Framework version: var result = LoadReference("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("", ReadOutputToEnd().Trim()); Assert.True(result); result = LoadReference("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("", ReadOutputToEnd().Trim()); Assert.True(result); result = LoadReference("System.Core"); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("", ReadOutputToEnd().Trim()); Assert.True(result); } [Fact] public void AddReference_AssemblyAlreadyLoaded() { var result = LoadReference("System.Core"); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("", ReadOutputToEnd().Trim()); Assert.True(result); result = LoadReference("System.Core.dll"); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("", ReadOutputToEnd().Trim()); Assert.True(result); } // Caused by submission not inheriting references. [Fact(Skip = "101161")] public void AddReference_ShadowCopy() { var dir = Temp.CreateDirectory(); // create C.dll var c = CompileLibrary(dir, "c.dll", "c", @"public class C { }"); // load C.dll: Assert.True(LoadReference(c.Path)); Assert.True(Execute("new C()")); Assert.Equal("C { }", ReadOutputToEnd().Trim()); // rewrite C.dll: File.WriteAllBytes(c.Path, new byte[] { 1, 2, 3 }); // we can still run code: var result = Execute("new C()"); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("C { }", ReadOutputToEnd().Trim()); Assert.True(result); } #if TODO /// <summary> /// Tests that a dependency is correctly resolved and loaded at runtime. /// A depends on B, which depends on C. When CallB is jitted B is loaded. When CallC is jitted C is loaded. /// </summary> [Fact(Skip = "https://github.com/dotnet/roslyn/issues/860")] public void AddReference_Dependencies() { var dir = Temp.CreateDirectory(); var c = CompileLibrary(dir, "c.dll", "c", @"public class C { }"); var b = CompileLibrary(dir, "b.dll", "b", @"public class B { public static int CallC() { new C(); return 1; } }", MetadataReference.CreateFromImage(c.Image)); var a = CompileLibrary(dir, "a.dll", "a", @"public class A { public static int CallB() { B.CallC(); return 1; } }", MetadataReference.CreateFromImage(b.Image)); AssemblyLoadResult result; result = LoadReference(a.Path); Assert.Equal(a.Path, result.OriginalPath); Assert.True(IsShadowCopy(result.Path)); Assert.True(result.IsSuccessful); Assert.True(Execute("A.CallB()")); // c.dll is loaded as a dependency, so #r should be successful: result = LoadReference(c.Path); Assert.Equal(c.Path, result.OriginalPath); Assert.True(IsShadowCopy(result.Path)); Assert.True(result.IsSuccessful); // c.dll was already loaded explicitly via #r so we should fail now: result = LoadReference(c.Path); Assert.False(result.IsSuccessful); Assert.Equal(c.Path, result.OriginalPath); Assert.True(IsShadowCopy(result.Path)); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("1", ReadOutputToEnd().Trim()); } #endif /// <summary> /// When two files of the same version are in the same directory, prefer .dll over .exe. /// </summary> [Fact] public void AddReference_Dependencies_DllExe() { var dir = Temp.CreateDirectory(); var dll = CompileLibrary(dir, "c.dll", "C", @"public class C { public static int Main() { return 1; } }"); var exe = CompileLibrary(dir, "c.exe", "C", @"public class C { public static int Main() { return 2; } }"); var main = CompileLibrary(dir, "main.exe", "Main", @"public class Program { public static int Main() { return C.Main(); } }", MetadataReference.CreateFromImage(dll.Image)); Assert.True(LoadReference(main.Path)); Assert.True(Execute("Program.Main()")); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("1", ReadOutputToEnd().Trim()); } [Fact] public void AddReference_Dependencies_Versions() { var dir1 = Temp.CreateDirectory(); var dir2 = Temp.CreateDirectory(); var dir3 = Temp.CreateDirectory(); // [assembly:AssemblyVersion("1.0.0.0")] public class C { public static int Main() { return 1; } }"); var file1 = dir1.CreateFile("c.dll").WriteAllBytes(TestResources.General.C1); // [assembly:AssemblyVersion("2.0.0.0")] public class C { public static int Main() { return 2; } }"); var file2 = dir2.CreateFile("c.dll").WriteAllBytes(TestResources.General.C2); Assert.True(LoadReference(file1.Path)); Assert.True(LoadReference(file2.Path)); var main = CompileLibrary(dir3, "main.exe", "Main", @"public class Program { public static int Main() { return C.Main(); } }", MetadataReference.CreateFromImage(TestResources.General.C2.AsImmutableOrNull())); Assert.True(LoadReference(main.Path)); Assert.True(Execute("Program.Main()")); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("2", ReadOutputToEnd().Trim()); } [Fact] public void AddReference_AlreadyLoadedDependencies() { var dir = Temp.CreateDirectory(); var lib1 = CompileLibrary(dir, "lib1.dll", "lib1", @"public interface I { int M(); }"); var lib2 = CompileLibrary(dir, "lib2.dll", "lib2", @"public class C : I { public int M() { return 1; } }", MetadataReference.CreateFromFile(lib1.Path)); Execute("#r \"" + lib1.Path + "\""); Execute("#r \"" + lib2.Path + "\""); Execute("new C().M()"); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("1", ReadOutputToEnd().Trim()); } [Fact(Skip = "101161")] public void AddReference_LoadUpdatedReference() { var dir = Temp.CreateDirectory(); var source1 = "public class C { public int X = 1; }"; var c1 = CreateCompilationWithMscorlib(source1, assemblyName: "C"); var file = dir.CreateFile("c.dll").WriteAllBytes(c1.EmitToArray()); // use: Execute($@" #r ""{file.Path}"" C foo() => new C(); new C().X "); // update: var source2 = "public class D { public int Y = 2; }"; var c2 = CreateCompilationWithMscorlib(source2, assemblyName: "C"); file.WriteAllBytes(c2.EmitToArray()); // add the reference again: Execute($@" #r ""{file.Path}"" new D().Y "); // TODO: We should report an error that assembly named 'a' was already loaded with different content. // In future we can let it load and improve error reporting around type conversions. Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal( @"1 2", ReadOutputToEnd().Trim()); } [Fact(Skip = "129388")] public void AddReference_MultipleReferencesWithSameWeakIdentity() { var dir = Temp.CreateDirectory(); var dir1 = dir.CreateDirectory("1"); var dir2 = dir.CreateDirectory("2"); var source1 = "public class C1 { }"; var c1 = CreateCompilationWithMscorlib(source1, assemblyName: "C"); var file1 = dir1.CreateFile("c.dll").WriteAllBytes(c1.EmitToArray()); var source2 = "public class C2 { }"; var c2 = CreateCompilationWithMscorlib(source2, assemblyName: "C"); var file2 = dir2.CreateFile("c.dll").WriteAllBytes(c2.EmitToArray()); Execute($@" #r ""{file1.Path}"" #r ""{file2.Path}"" "); Execute("new C1()"); Execute("new C2()"); // TODO: We should report an error that assembly named 'c' was already loaded with different content. // In future we can let it load and let the compiler report the error CS1704: "An assembly with the same simple name 'C' has already been imported". Assert.Equal( @"(2,1): error CS1704: An assembly with the same simple name 'C' has already been imported. Try removing one of the references (e.g. '" + file1.Path + @"') or sign them to enable side-by-side. (1,5): error CS0246: The type or namespace name 'C1' could not be found (are you missing a using directive or an assembly reference?) (1,5): error CS0246: The type or namespace name 'C2' could not be found (are you missing a using directive or an assembly reference?)", ReadErrorOutputToEnd().Trim()); Assert.Equal("", ReadOutputToEnd().Trim()); } [Fact(Skip = "129388")] public void AddReference_MultipleReferencesWeakVersioning() { var dir = Temp.CreateDirectory(); var dir1 = dir.CreateDirectory("1"); var dir2 = dir.CreateDirectory("2"); var source1 = @"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class C1 { }"; var c1 = CreateCompilationWithMscorlib(source1, assemblyName: "C"); var file1 = dir1.CreateFile("c.dll").WriteAllBytes(c1.EmitToArray()); var source2 = @"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class C2 { }"; var c2 = CreateCompilationWithMscorlib(source2, assemblyName: "C"); var file2 = dir2.CreateFile("c.dll").WriteAllBytes(c2.EmitToArray()); Execute($@" #r ""{file1.Path}"" #r ""{file2.Path}"" "); Execute("new C1()"); Execute("new C2()"); // TODO: We should report an error that assembly named 'c' was already loaded with different content. // In future we can let it load and improve error reporting around type conversions. Assert.Equal("TODO: error", ReadErrorOutputToEnd().Trim()); Assert.Equal("", ReadOutputToEnd().Trim()); } //// TODO (987032): //// [Fact] //// public void AsyncInitializeContextWithDotNETLibraries() //// { //// var rspFile = Temp.CreateFile(); //// var rspDisplay = Path.GetFileName(rspFile.Path); //// var initScript = Temp.CreateFile(); //// rspFile.WriteAllText(@" /////r:System.Core ////""" + initScript.Path + @""" ////"); //// initScript.WriteAllText(@" ////using static System.Console; ////using System.Linq.Expressions; ////WriteLine(Expression.Constant(123)); ////"); //// // override default "is restarting" behavior (the REPL is already initialized): //// var task = Host.InitializeContextAsync(rspFile.Path, isRestarting: false, killProcess: true); //// task.Wait(); //// var output = SplitLines(ReadOutputToEnd()); //// var errorOutput = ReadErrorOutputToEnd(); //// Assert.Equal(4, output.Length); //// Assert.Equal("Microsoft (R) Roslyn C# Compiler version " + FileVersionInfo.GetVersionInfo(typeof(Compilation).Assembly.Location).FileVersion, output[0]); //// Assert.Equal("Loading context from '" + rspDisplay + "'.", output[1]); //// Assert.Equal("Type \"#help\" for more information.", output[2]); //// Assert.Equal("123", output[3]); //// Assert.Equal("", errorOutput); //// Host.InitializeContextAsync(rspFile.Path).Wait(); //// output = SplitLines(ReadOutputToEnd()); //// errorOutput = ReadErrorOutputToEnd(); //// Assert.True(2 == output.Length, "Output is: '" + string.Join("<NewLine>", output) + "'. Expecting 2 lines."); //// Assert.Equal("Loading context from '" + rspDisplay + "'.", output[0]); //// Assert.Equal("123", output[1]); //// Assert.Equal("", errorOutput); //// } //// [Fact] //// public void AsyncInitializeContextWithBothUserDefinedAndDotNETLibraries() //// { //// var dir = Temp.CreateDirectory(); //// var rspFile = Temp.CreateFile(); //// var initScript = Temp.CreateFile(); //// var dll = CompileLibrary(dir, "c.dll", "C", @"public class C { public static int Main() { return 1; } }"); //// rspFile.WriteAllText(@" /////r:System.Numerics /////r:" + dll.Path + @" ////""" + initScript.Path + @""" ////"); //// initScript.WriteAllText(@" ////using static System.Console; ////using System.Numerics; ////WriteLine(new Complex(12, 6).Real + C.Main()); ////"); //// // override default "is restarting" behavior (the REPL is already initialized): //// var task = Host.InitializeContextAsync(rspFile.Path, isRestarting: false, killProcess: true); //// task.Wait(); //// var errorOutput = ReadErrorOutputToEnd(); //// Assert.Equal("", errorOutput); //// var output = SplitLines(ReadOutputToEnd()); //// Assert.Equal(4, output.Length); //// Assert.Equal("Microsoft (R) Roslyn C# Compiler version " + FileVersionInfo.GetVersionInfo(Host.GetType().Assembly.Location).FileVersion, output[0]); //// Assert.Equal("Loading context from '" + Path.GetFileName(rspFile.Path) + "'.", output[1]); //// Assert.Equal("Type \"#help\" for more information.", output[2]); //// Assert.Equal("13", output[3]); //// } [Fact] public void ReferencePaths() { var directory = Temp.CreateDirectory(); var assemblyName = GetUniqueName(); CompileLibrary(directory, assemblyName + ".dll", assemblyName, @"public class C { }"); var rspFile = Temp.CreateFile(); rspFile.WriteAllText("/lib:" + directory.Path); Host.ResetAsync(new InteractiveHostOptions(initializationFile: rspFile.Path, culture: CultureInfo.InvariantCulture)).Wait(); Execute( $@"#r ""{assemblyName}.dll"" typeof(C).Assembly.GetName()"); Assert.Equal("", ReadErrorOutputToEnd()); var output = SplitLines(ReadOutputToEnd()); Assert.Equal(2, output.Length); Assert.Equal("Loading context from '" + Path.GetFileName(rspFile.Path) + "'.", output[0]); Assert.Equal($"[{assemblyName}, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", output[1]); } [Fact] public void DefaultUsings() { var rspFile = Temp.CreateFile(); rspFile.WriteAllText(@" /r:System /r:System.Core /r:Microsoft.CSharp /u:System /u:System.IO /u:System.Collections.Generic /u:System.Diagnostics /u:System.Dynamic /u:System.Linq /u:System.Linq.Expressions /u:System.Text /u:System.Threading.Tasks "); Host.ResetAsync(new InteractiveHostOptions(initializationFile: rspFile.Path, culture: CultureInfo.InvariantCulture)).Wait(); Execute(@" dynamic d = new ExpandoObject(); "); Execute(@" Process p = new Process(); "); Execute(@" Expression<Func<int>> e = () => 1; "); Execute(@" var squares = from x in new[] { 1, 2, 3 } select x * x; "); Execute(@" var sb = new StringBuilder(); "); Execute(@" var list = new List<int>(); "); Execute(@" var stream = new MemoryStream(); await Task.Delay(10); p = new Process(); Console.Write(""OK"") "); AssertEx.AssertEqualToleratingWhitespaceDifferences("", ReadErrorOutputToEnd()); AssertEx.AssertEqualToleratingWhitespaceDifferences( $@"Loading context from '{Path.GetFileName(rspFile.Path)}'. OK ", ReadOutputToEnd()); } [Fact] public void InitialScript_Error() { var initFile = Temp.CreateFile(extension: ".csx").WriteAllText("1 1"); var rspFile = Temp.CreateFile(); rspFile.WriteAllText($@" /r:System /u:System.Diagnostics {initFile.Path} "); Host.ResetAsync(new InteractiveHostOptions(initializationFile: rspFile.Path, culture: CultureInfo.InvariantCulture)).Wait(); Execute("new Process()"); AssertEx.AssertEqualToleratingWhitespaceDifferences($@" {initFile.Path}(1,3): error CS1002: ; expected ", ReadErrorOutputToEnd()); AssertEx.AssertEqualToleratingWhitespaceDifferences($@" Loading context from '{Path.GetFileName(rspFile.Path)}'. [System.Diagnostics.Process] ", ReadOutputToEnd()); } [Fact] public void ScriptAndArguments() { var scriptFile = Temp.CreateFile(extension: ".csx").WriteAllText("foreach (var arg in Args) Print(arg);"); var rspFile = Temp.CreateFile(); rspFile.WriteAllText($@" {scriptFile} a b c "); Host.ResetAsync(new InteractiveHostOptions(initializationFile: rspFile.Path, culture: CultureInfo.InvariantCulture)).Wait(); Assert.Equal("", ReadErrorOutputToEnd()); AssertEx.AssertEqualToleratingWhitespaceDifferences( $@"Loading context from '{Path.GetFileName(rspFile.Path)}'. ""a"" ""b"" ""c"" ", ReadOutputToEnd()); } [Fact] public void ReferenceDirectives() { Execute(@" #r ""System.Numerics"" #r """ + typeof(System.Linq.Expressions.Expression).Assembly.Location + @""" using static System.Console; using System.Linq.Expressions; using System.Numerics; WriteLine(Expression.Constant(1)); WriteLine(new Complex(2, 6).Real); "); var output = ReadOutputToEnd(); Assert.Equal("1\r\n2\r\n", output); } [Fact] public void Script_NoHostNamespaces() { Execute("nameof(Microsoft.CodeAnalysis)"); AssertEx.AssertEqualToleratingWhitespaceDifferences(@" (1,8): error CS0234: The type or namespace name 'CodeAnalysis' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)", ReadErrorOutputToEnd()); Assert.Equal("", ReadOutputToEnd()); } [Fact] public void ExecutesOnStaThread() { Execute(@" #r ""System"" #r ""System.Xaml"" #r ""WindowsBase"" #r ""PresentationCore"" #r ""PresentationFramework"" new System.Windows.Window(); System.Console.WriteLine(""OK""); "); var error = ReadErrorOutputToEnd(); Assert.Equal("", error); var output = ReadOutputToEnd(); Assert.Equal("OK\r\n", output); } /// <summary> /// Execution of expressions should be /// sequential, even await expressions. /// </summary> [Fact] public void ExecuteSequentially() { Execute(@"using System; using System.Threading.Tasks;"); Execute(@"await Task.Delay(1000).ContinueWith(t => 1)"); Execute(@"await Task.Delay(500).ContinueWith(t => 2)"); Execute(@"3"); var output = ReadOutputToEnd(); Assert.Equal("1\r\n2\r\n3\r\n", output); } [Fact] public void MultiModuleAssembly() { var dir = Temp.CreateDirectory(); var dll = dir.CreateFile("MultiModule.dll").WriteAllBytes(TestResources.SymbolsTests.MultiModule.MultiModuleDll); dir.CreateFile("mod2.netmodule").WriteAllBytes(TestResources.SymbolsTests.MultiModule.mod2); dir.CreateFile("mod3.netmodule").WriteAllBytes(TestResources.SymbolsTests.MultiModule.mod3); Execute(@" #r """ + dll.Path + @""" new object[] { new Class1(), new Class2(), new Class3() } "); var error = ReadErrorOutputToEnd(); Assert.Equal("", error); var output = ReadOutputToEnd(); Assert.Equal("object[3] { Class1 { }, Class2 { }, Class3 { } }\r\n", output); } [Fact] public void SearchPaths1() { var dll = Temp.CreateFile(extension: ".dll").WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSInterfaces01); var srcDir = Temp.CreateDirectory(); var dllDir = Path.GetDirectoryName(dll.Path); srcDir.CreateFile("foo.csx").WriteAllText("ReferencePaths.Add(@\"" + dllDir + "\");"); Func<string, string> normalizeSeparatorsAndFrameworkFolders = (s) => s.Replace("\\", "\\\\").Replace("Framework64", "Framework"); // print default: Host.ExecuteAsync(@"ReferencePaths").Wait(); var output = ReadOutputToEnd(); Assert.Equal("SearchPaths { \"" + normalizeSeparatorsAndFrameworkFolders(string.Join("\", \"", new[] { s_fxDir })) + "\" }\r\n", output); Host.ExecuteAsync(@"SourcePaths").Wait(); output = ReadOutputToEnd(); Assert.Equal("SearchPaths { \"" + normalizeSeparatorsAndFrameworkFolders(string.Join("\", \"", new[] { s_homeDir })) + "\" }\r\n", output); // add and test if added: Host.ExecuteAsync("SourcePaths.Add(@\"" + srcDir + "\");").Wait(); Host.ExecuteAsync(@"SourcePaths").Wait(); output = ReadOutputToEnd(); Assert.Equal("SearchPaths { \"" + normalizeSeparatorsAndFrameworkFolders(string.Join("\", \"", new[] { s_homeDir, srcDir.Path })) + "\" }\r\n", output); // execute file (uses modified search paths), the file adds a reference path Host.ExecuteFileAsync("foo.csx").Wait(); Host.ExecuteAsync(@"ReferencePaths").Wait(); output = ReadOutputToEnd(); Assert.Equal("SearchPaths { \"" + normalizeSeparatorsAndFrameworkFolders(string.Join("\", \"", new[] { s_fxDir, dllDir })) + "\" }\r\n", output); Host.AddReferenceAsync(Path.GetFileName(dll.Path)).Wait(); Host.ExecuteAsync(@"typeof(Metadata.ICSProp)").Wait(); var error = ReadErrorOutputToEnd(); Assert.Equal("", error); output = ReadOutputToEnd(); Assert.Equal("[Metadata.ICSProp]\r\n", output); } [Fact, WorkItem(6457, "https://github.com/dotnet/roslyn/issues/6457")] public void MissingReferencesReuse() { var source = @" public class C { public System.Diagnostics.Process P; } "; var lib = CSharpCompilation.Create( "Lib", new[] { SyntaxFactory.ParseSyntaxTree(source) }, new[] { TestReferences.NetFx.v4_0_30319.mscorlib, TestReferences.NetFx.v4_0_30319.System }, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); var libFile = Temp.CreateFile("lib").WriteAllBytes(lib.EmitToArray()); Execute($@"#r ""{libFile.Path}"""); Execute("C c;"); Execute("c = new C()"); var error = ReadErrorOutputToEnd(); Assert.Equal("", error); var output = ReadOutputToEnd(); AssertEx.AssertEqualToleratingWhitespaceDifferences("C { P=null }", output); } [Fact, WorkItem(7280, "https://github.com/dotnet/roslyn/issues/7280")] public void AsyncContinueOnDifferentThread() { Execute(@" using System; using System.Threading; using System.Threading.Tasks; Console.Write(Task.Run(() => { Thread.CurrentThread.Join(100); return 42; }).ContinueWith(t => t.Result).Result)"); var output = ReadOutputToEnd(); var error = ReadErrorOutputToEnd(); Assert.Equal("42", output); Assert.Empty(error); } #region Submission result printing - null/void/value. [Fact] public void SubmissionResult_PrintingNull() { Execute(@" string s; s "); var output = ReadOutputToEnd(); Assert.Equal("null\r\n", output); } [Fact] public void SubmissionResult_PrintingVoid() { Execute(@"System.Console.WriteLine(2)"); var output = ReadOutputToEnd(); Assert.Equal("2\r\n", output); Execute(@" void foo() { } foo() "); output = ReadOutputToEnd(); Assert.Equal("", output); } #endregion private static ImmutableArray<string> SplitLines(string text) { return ImmutableArray.Create(text.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries)); } } }
using System.Collections.Generic; using MineLib.Network.IO; using MineLib.Network.Modern.Enums; using Org.BouncyCastle.Math; namespace MineLib.Network.Modern.Packets.Server { public interface IPlayerList { IPlayerList FromReader(IMinecraftDataReader reader); void ToStream(ref IMinecraftStream stream); } public struct Properties { public string Name; public string Value; public bool IsSigned; public string Signature; } public class PlayerListActionProperties { private readonly List<Properties> _entries; public PlayerListActionProperties() { _entries = new List<Properties>(); } public int Count { get { return _entries.Count; } } public Properties this[int index] { get { return _entries[index]; } set { _entries.Insert(index, value); } } public static PlayerListActionProperties FromReader(IMinecraftDataReader reader) { var count = reader.ReadVarInt(); var value = new PlayerListActionProperties(); for (var i = 0; i < count; i++) { var property = new Properties(); property.Name = reader.ReadString(); property.Value = reader.ReadString(); property.IsSigned = reader.ReadBoolean(); if (property.IsSigned) property.Signature = reader.ReadString(); value[i] = property; } return value; } public void ToStream(ref IMinecraftStream stream) { stream.WriteVarInt(Count); foreach (var entry in _entries) { stream.WriteString(entry.Name); stream.WriteString(entry.Value); stream.WriteBoolean(entry.IsSigned); if (entry.IsSigned) stream.WriteString(entry.Signature); } } } public struct PlayerListActionAddPlayer : IPlayerList { public string Name; public PlayerListActionProperties Properties; public int Gamemode; public int Ping; public bool HasDisplayName; public string DisplayName; public IPlayerList FromReader(IMinecraftDataReader reader) { Name = reader.ReadString(); Properties = PlayerListActionProperties.FromReader(reader); Gamemode = reader.ReadVarInt(); Ping = reader.ReadVarInt(); HasDisplayName = reader.ReadBoolean(); if (HasDisplayName) DisplayName = reader.ReadString(); return this; } public void ToStream(ref IMinecraftStream stream) { stream.WriteString(Name); Properties.ToStream(ref stream); stream.WriteVarInt(Gamemode); stream.WriteVarInt(Ping); stream.WriteBoolean(HasDisplayName); if (HasDisplayName) stream.WriteString(DisplayName); } } public struct PlayerListActionUpdateGamemode : IPlayerList { public int Gamemode; public IPlayerList FromReader(IMinecraftDataReader reader) { Gamemode = reader.ReadVarInt(); return this; } public void ToStream(ref IMinecraftStream stream) { stream.WriteVarInt(Gamemode); } } public struct PlayerListActionUpdateLatency : IPlayerList { public int Ping; public IPlayerList FromReader(IMinecraftDataReader reader) { Ping = reader.ReadVarInt(); return this; } public void ToStream(ref IMinecraftStream stream) { stream.WriteVarInt(Ping); } } public struct PlayerListActionUpdateDisplayName : IPlayerList { public bool HasDisplayName; public string DisplayName; public IPlayerList FromReader(IMinecraftDataReader reader) { HasDisplayName = reader.ReadBoolean(); DisplayName = reader.ReadString(); return this; } public void ToStream(ref IMinecraftStream stream) { stream.WriteBoolean(HasDisplayName); stream.WriteString(DisplayName); } } public struct PlayerListActionRemovePlayer : IPlayerList { public IPlayerList FromReader(IMinecraftDataReader reader) { return this; } public void ToStream(ref IMinecraftStream stream) { } } public struct PlayerListItemPacket : IPacket { public PlayerListAction Action; public int Length; public BigInteger UUID; public IPlayerList PlayerList; public byte ID { get { return 0x38; } } public IPacket ReadPacket(IMinecraftDataReader reader) { Action = (PlayerListAction) reader.ReadVarInt(); Length = reader.ReadVarInt(); UUID = reader.ReadBigInteger(); switch (Action) { case PlayerListAction.AddPlayer: PlayerList = new PlayerListActionAddPlayer().FromReader(reader); break; case PlayerListAction.UpdateGamemode: PlayerList = new PlayerListActionUpdateGamemode().FromReader(reader); break; case PlayerListAction.UpdateLatency: PlayerList = new PlayerListActionUpdateLatency().FromReader(reader); break; case PlayerListAction.UpdateDisplayName: PlayerList = new PlayerListActionUpdateDisplayName().FromReader(reader); break; case PlayerListAction.RemovePlayer: PlayerList = new PlayerListActionRemovePlayer().FromReader(reader); break; } return this; } public IPacket WritePacket(IMinecraftStream stream) { stream.WriteVarInt(ID); stream.WriteVarInt((byte) Action); stream.WriteVarInt(Length); stream.WriteBigInteger(UUID); PlayerList.ToStream(ref stream); stream.Purge(); return this; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.Tracing; #if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue https://github.com/dotnet/corefx/issues/4864 using Microsoft.Diagnostics.Tracing.Session; #endif using Xunit; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; namespace BasicEventSourceTests { public class TestEventCounter { private sealed class MyEventSource : EventSource { private EventCounter _requestCounter; private EventCounter _errorCounter; public MyEventSource() { _requestCounter = new EventCounter("Request", this); _errorCounter = new EventCounter("Error", this); } public void Request(float elapsed) { _requestCounter.WriteMetric(elapsed); } public void Error() { _errorCounter.WriteMetric(1); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, reason: "https://github.com/dotnet/corefx/issues/23661")] [ActiveIssue("https://github.com/dotnet/corefx/issues/22791", TargetFrameworkMonikers.UapAot)] public void Test_Write_Metric_EventListener() { using (var listener = new EventListenerListener()) { Test_Write_Metric(listener); } } #if USE_ETW [Fact] public void Test_Write_Metric_ETW() { using (var listener = new EtwListener()) { Test_Write_Metric(listener); } } #endif private void Test_Write_Metric(Listener listener) { TestUtilities.CheckNoEventSourcesRunning("Start"); using (var logger = new MyEventSource()) { var tests = new List<SubTest>(); /*************************************************************************/ tests.Add(new SubTest("EventCounter: Log 1 event, explicit poll at end", delegate () { listener.EnableTimer(logger, 1); // Set to poll every second, but we dont actually care because the test ends before that. logger.Request(5); listener.EnableTimer(logger, 0); }, delegate (List<Event> evts) { // There will be two events (request and error) for time 0 and 2 more at 1 second and 2 more when we shut it off. Assert.Equal(4, evts.Count); ValidateSingleEventCounter(evts[0], "Request", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[1], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[2], "Request", 1, 5, 0, 5, 5); ValidateSingleEventCounter(evts[3], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); })); /*************************************************************************/ tests.Add(new SubTest("EventCounter: Log 2 events, explicit poll at end", delegate () { listener.EnableTimer(logger, 1); // Set to poll every second, but we dont actually care because the test ends before that. logger.Request(5); logger.Request(10); listener.EnableTimer(logger, 0); // poll }, delegate (List<Event> evts) { Assert.Equal(4, evts.Count); ValidateSingleEventCounter(evts[0], "Request", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[1], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[2], "Request", 2, 7.5f, 2.5f, 5, 10); ValidateSingleEventCounter(evts[3], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); })); /*************************************************************************/ tests.Add(new SubTest("EventCounter: Log 3 events in two polling periods (explicit polling)", delegate () { listener.EnableTimer(logger, 0); /* Turn off (but also poll once) */ logger.Request(5); logger.Request(10); logger.Error(); listener.EnableTimer(logger, 0); /* Turn off (but also poll once) */ logger.Request(8); logger.Error(); logger.Error(); listener.EnableTimer(logger, 0); /* Turn off (but also poll once) */ }, delegate (List<Event> evts) { Assert.Equal(6, evts.Count); ValidateSingleEventCounter(evts[0], "Request", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[1], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[2], "Request", 2, 7.5f, 2.5f, 5, 10); ValidateSingleEventCounter(evts[3], "Error", 1, 1, 0, 1, 1); ValidateSingleEventCounter(evts[4], "Request", 1, 8, 0, 8, 8); ValidateSingleEventCounter(evts[5], "Error", 2, 1, 0, 1, 1); })); /*************************************************************************/ int num100msecTimerTicks = 0; tests.Add(new SubTest("EventCounter: Log multiple events in multiple periods", delegate () { // We have had problems with timer ticks not being called back 100% reliably. // However timers really don't have a strong guarentee (only that the happen eventually) // So what we do is create a timer callback that simply counts the number of callbacks. // This acts as a marker to show whether the timer callbacks are happening promptly. // If we don't get enough of these tick callbacks then we don't require EventCounter to // be sending periodic callbacks either. num100msecTimerTicks = 0; using (var timer = new System.Threading.Timer(delegate(object state) { num100msecTimerTicks++; EventTestHarness.LogWriteLine("Tick"); }, null, 100, 100)) { listener.EnableTimer(logger, .1); /* Poll every .1 s */ // logs at 0 seconds because of EnableTimer command Sleep(100); logger.Request(1); Sleep(100); logger.Request(2); logger.Error(); Sleep(100); logger.Request(4); Sleep(100); logger.Request(8); logger.Error(); Sleep(100); logger.Request(16); Sleep(220); listener.EnableTimer(logger, 0); } }, delegate (List<Event> evts) { int requestCount = 0; float requestSum = 0; float requestMin = float.MaxValue; float requestMax = float.MinValue; int errorCount = 0; float errorSum = 0; float errorMin = float.MaxValue; float errorMax = float.MinValue; float timeSum = 0; for (int j = 0; j < evts.Count; j += 2) { var requestPayload = ValidateEventHeaderAndGetPayload(evts[j]); Assert.Equal("Request", requestPayload["Name"]); var count = (int)requestPayload["Count"]; requestCount += count; if (count > 0) requestSum += (float)requestPayload["Mean"] * count; requestMin = Math.Min(requestMin, (float)requestPayload["Min"]); requestMax = Math.Max(requestMax, (float)requestPayload["Max"]); float requestIntevalSec = (float)requestPayload["IntervalSec"]; var errorPayload = ValidateEventHeaderAndGetPayload(evts[j + 1]); Assert.Equal("Error", errorPayload["Name"]); count = (int)errorPayload["Count"]; errorCount += count; if (count > 0) errorSum += (float)errorPayload["Mean"] * count; errorMin = Math.Min(errorMin, (float)errorPayload["Min"]); errorMax = Math.Max(errorMax, (float)errorPayload["Max"]); float errorIntevalSec = (float)requestPayload["IntervalSec"]; Assert.Equal(requestIntevalSec, errorIntevalSec); timeSum += requestIntevalSec; } EventTestHarness.LogWriteLine("Validating: Count={0} RequestSum={1:n3} TimeSum={2:n3} ", evts.Count, requestSum, timeSum); Assert.Equal(requestCount, 5); Assert.Equal(requestSum, 31); Assert.Equal(requestMin, 1); Assert.Equal(requestMax, 16); Assert.Equal(errorCount, 2); Assert.Equal(errorSum, 2); Assert.Equal(errorMin, 1); Assert.Equal(errorMax, 1); Assert.True(.4 < timeSum, $"FAILURE: .4 < {timeSum}"); // We should have at least 400 msec Assert.True(timeSum < 2, $"FAILURE: {timeSum} < 2"); // But well under 2 sec. // Do all the things that depend on the count of events last so we know everything else is sane Assert.True(4 <= evts.Count, "We expect two metrics at the beginning trigger and two at the end trigger. evts.Count = " + evts.Count); Assert.True(evts.Count % 2 == 0, "We expect two metrics for every trigger. evts.Count = " + evts.Count); ValidateSingleEventCounter(evts[0], "Request", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[1], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); // We shoudl always get the unconditional callback at the start and end of the trace. Assert.True(4 <= evts.Count, $"FAILURE EventCounter Multi-event: 4 <= {evts.Count} ticks: {num100msecTimerTicks} thread: {Thread.CurrentThread.ManagedThreadId}"); // We expect the timer to have gone off at least twice, plus the explicit poll at the begining and end. // Each one fires two events (one for requests, one for errors). so that is (2 + 2)*2 = 8 // We expect about 7 timer requests, but we don't get picky about the exact count // Putting in a generous buffer, we double 7 to say we don't expect more than 14 timer fires // so that is (2 + 14) * 2 = 32 if (num100msecTimerTicks > 3) // We seem to have problems with timer events going off 100% reliably. To avoid failures here we only check if in the 700 msec test we get at least 3 100 msec ticks. Assert.True(8 <= evts.Count, $"FAILURE: 8 <= {evts.Count}"); Assert.True(evts.Count <= 32, $"FAILURE: {evts.Count} <= 32"); })); /*************************************************************************/ #if FEATURE_EVENTCOUNTER_DISPOSE tests.Add(new SubTest("EventCounter: Dispose()", delegate () { // Creating and destroying var myCounter = new EventCounter("counter for a transient object", logger); myCounter.WriteMetric(10); listener.EnableTimer(logger, 0); /* Turn off (but also poll once) */ myCounter.Dispose(); listener.EnableTimer(logger, 0); /* Turn off (but also poll once) */ }, delegate (List<Event> evts) { // The static counters (Request and Error), should not log any counts and stay at zero. // The new counter will exist for the first poll but will not exist for the second. Assert.Equal(5, evts.Count); ValidateSingleEventCounter(evts[0], "Request", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[1], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[2], "counter for a transient object", 1, 10, 0, 10, 10); ValidateSingleEventCounter(evts[3], "Request", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); ValidateSingleEventCounter(evts[4], "Error", 0, 0, 0, float.PositiveInfinity, float.NegativeInfinity); })); #endif /*************************************************************************/ EventTestHarness.RunTests(tests, listener, logger); } TestUtilities.CheckNoEventSourcesRunning("Stop"); } // Thread.Sleep has proven unreliable, sometime sleeping much shorter than it should. // This makes sure it at least sleeps 'msec' at a miniumum. private static void Sleep(int minMSec) { var startTime = DateTime.UtcNow; for (; ; ) { DateTime endTime = DateTime.UtcNow; double delta = (endTime - startTime).TotalMilliseconds; if (delta >= minMSec) break; Thread.Sleep(1); } } private static void ValidateSingleEventCounter(Event evt, string counterName, int count, float mean, float standardDeviation, float min, float max) { ValidateEventCounter(counterName, count, mean, standardDeviation, min, max, ValidateEventHeaderAndGetPayload(evt)); } private static IDictionary<string, object> ValidateEventHeaderAndGetPayload(Event evt) { Assert.Equal("EventCounters", evt.EventName); Assert.Equal(1, evt.PayloadCount); Assert.NotNull(evt.PayloadNames); Assert.Equal(1, evt.PayloadNames.Count); Assert.Equal("Payload", evt.PayloadNames[0]); var ret = (IDictionary<string, object>)evt.PayloadValue(0, "Payload"); Assert.NotNull(ret); return ret; } private static void ValidateEventCounter(string counterName, int count, float mean, float standardDeviation, float min, float max, IDictionary<string, object> payloadContent) { Assert.Equal(counterName, (string)payloadContent["Name"]); Assert.Equal(count, (int)payloadContent["Count"]); if (count != 0) { Assert.Equal(mean, (float)payloadContent["Mean"]); Assert.Equal(standardDeviation, (float)payloadContent["StandardDeviation"]); } Assert.Equal(min, (float)payloadContent["Min"]); Assert.Equal(max, (float)payloadContent["Max"]); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace DevOpsDashboard.Web.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// ------------------------------------------------------------------------ // ======================================================================== // THIS CODE AND INFORMATION ARE GENERATED BY AUTOMATIC CODE GENERATOR // ======================================================================== // Template: ViewModel.tt using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Windows; using System.Windows.Input; using Controls=WPAppStudio.Controls; using Entities=WPAppStudio.Entities; using EntitiesBase=WPAppStudio.Entities.Base; using IServices=WPAppStudio.Services.Interfaces; using IViewModels=WPAppStudio.ViewModel.Interfaces; using Localization=WPAppStudio.Localization; using Repositories=WPAppStudio.Repositories; using Services=WPAppStudio.Services; using ViewModelsBase=WPAppStudio.ViewModel.Base; using WPAppStudio; using WPAppStudio.Shared; namespace WPAppStudio.ViewModel { /// <summary> /// Implementation of ReviewsFeed_Detail ViewModel. /// </summary> [CompilerGenerated] [GeneratedCode("Radarc", "4.0")] public partial class ReviewsFeed_DetailViewModel : ViewModelsBase.VMBase, IViewModels.IReviewsFeed_DetailViewModel, ViewModelsBase.INavigable { private readonly Repositories.ReviewsFeed_ReviewsFeed _reviewsFeed_ReviewsFeed; private readonly IServices.IDialogService _dialogService; private readonly IServices.INavigationService _navigationService; private readonly IServices.ISpeechService _speechService; private readonly IServices.IShareService _shareService; private readonly IServices.ILiveTileService _liveTileService; /// <summary> /// Initializes a new instance of the <see cref="ReviewsFeed_DetailViewModel" /> class. /// </summary> /// <param name="reviewsFeed_ReviewsFeed">The Reviews Feed_ Reviews Feed.</param> /// <param name="dialogService">The Dialog Service.</param> /// <param name="navigationService">The Navigation Service.</param> /// <param name="speechService">The Speech Service.</param> /// <param name="shareService">The Share Service.</param> /// <param name="liveTileService">The Live Tile Service.</param> public ReviewsFeed_DetailViewModel(Repositories.ReviewsFeed_ReviewsFeed reviewsFeed_ReviewsFeed, IServices.IDialogService dialogService, IServices.INavigationService navigationService, IServices.ISpeechService speechService, IServices.IShareService shareService, IServices.ILiveTileService liveTileService) { _reviewsFeed_ReviewsFeed = reviewsFeed_ReviewsFeed; _dialogService = dialogService; _navigationService = navigationService; _speechService = speechService; _shareService = shareService; _liveTileService = liveTileService; } private EntitiesBase.RssSearchResult _currentRssSearchResult; /// <summary> /// CurrentRssSearchResult property. /// </summary> public EntitiesBase.RssSearchResult CurrentRssSearchResult { get { return _currentRssSearchResult; } set { SetProperty(ref _currentRssSearchResult, value); } } private bool _hasNextpanoramaReviewsFeed_Detail0; /// <summary> /// HasNextpanoramaReviewsFeed_Detail0 property. /// </summary> public bool HasNextpanoramaReviewsFeed_Detail0 { get { return _hasNextpanoramaReviewsFeed_Detail0; } set { SetProperty(ref _hasNextpanoramaReviewsFeed_Detail0, value); } } private bool _hasPreviouspanoramaReviewsFeed_Detail0; /// <summary> /// HasPreviouspanoramaReviewsFeed_Detail0 property. /// </summary> public bool HasPreviouspanoramaReviewsFeed_Detail0 { get { return _hasPreviouspanoramaReviewsFeed_Detail0; } set { SetProperty(ref _hasPreviouspanoramaReviewsFeed_Detail0, value); } } /// <summary> /// Delegate method for the TextToSpeechReviewsFeed_DetailStaticControlCommand command. /// </summary> public void TextToSpeechReviewsFeed_DetailStaticControlCommandDelegate() { _speechService.TextToSpeech(CurrentRssSearchResult.Title + " " + CurrentRssSearchResult.Content); } private ICommand _textToSpeechReviewsFeed_DetailStaticControlCommand; /// <summary> /// Gets the TextToSpeechReviewsFeed_DetailStaticControlCommand command. /// </summary> public ICommand TextToSpeechReviewsFeed_DetailStaticControlCommand { get { return _textToSpeechReviewsFeed_DetailStaticControlCommand = _textToSpeechReviewsFeed_DetailStaticControlCommand ?? new ViewModelsBase.DelegateCommand(TextToSpeechReviewsFeed_DetailStaticControlCommandDelegate); } } /// <summary> /// Delegate method for the ShareReviewsFeed_DetailStaticControlCommand command. /// </summary> public void ShareReviewsFeed_DetailStaticControlCommandDelegate() { _shareService.Share(CurrentRssSearchResult.Title, CurrentRssSearchResult.Content, CurrentRssSearchResult.FeedUrl, CurrentRssSearchResult.ImageUrl); } private ICommand _shareReviewsFeed_DetailStaticControlCommand; /// <summary> /// Gets the ShareReviewsFeed_DetailStaticControlCommand command. /// </summary> public ICommand ShareReviewsFeed_DetailStaticControlCommand { get { return _shareReviewsFeed_DetailStaticControlCommand = _shareReviewsFeed_DetailStaticControlCommand ?? new ViewModelsBase.DelegateCommand(ShareReviewsFeed_DetailStaticControlCommandDelegate); } } /// <summary> /// Delegate method for the PinToStartReviewsFeed_DetailStaticControlCommand command. /// </summary> public void PinToStartReviewsFeed_DetailStaticControlCommandDelegate() { _liveTileService.PinToStart(typeof(IViewModels.IReviewsFeed_DetailViewModel), CreateTileInfoReviewsFeed_DetailStaticControl()); } private ICommand _pinToStartReviewsFeed_DetailStaticControlCommand; /// <summary> /// Gets the PinToStartReviewsFeed_DetailStaticControlCommand command. /// </summary> public ICommand PinToStartReviewsFeed_DetailStaticControlCommand { get { return _pinToStartReviewsFeed_DetailStaticControlCommand = _pinToStartReviewsFeed_DetailStaticControlCommand ?? new ViewModelsBase.DelegateCommand(PinToStartReviewsFeed_DetailStaticControlCommandDelegate); } } /// <summary> /// Delegate method for the GoToSourceReviewsFeed_DetailStaticControlCommand command. /// </summary> public void GoToSourceReviewsFeed_DetailStaticControlCommandDelegate() { _navigationService.NavigateTo(string.IsNullOrEmpty(CurrentRssSearchResult.FeedUrl) ? null : new Uri(CurrentRssSearchResult.FeedUrl)); } private ICommand _goToSourceReviewsFeed_DetailStaticControlCommand; /// <summary> /// Gets the GoToSourceReviewsFeed_DetailStaticControlCommand command. /// </summary> public ICommand GoToSourceReviewsFeed_DetailStaticControlCommand { get { return _goToSourceReviewsFeed_DetailStaticControlCommand = _goToSourceReviewsFeed_DetailStaticControlCommand ?? new ViewModelsBase.DelegateCommand(GoToSourceReviewsFeed_DetailStaticControlCommandDelegate); } } /// <summary> /// Delegate method for the NextpanoramaReviewsFeed_Detail0 command. /// </summary> public async void NextpanoramaReviewsFeed_Detail0Delegate() { LoadingCurrentRssSearchResult = true; var next = await _reviewsFeed_ReviewsFeed.Next(CurrentRssSearchResult); if(next != null) CurrentRssSearchResult = next; RefreshHasPrevNext(); } private bool _loadingCurrentRssSearchResult; public bool LoadingCurrentRssSearchResult { get { return _loadingCurrentRssSearchResult; } set { SetProperty(ref _loadingCurrentRssSearchResult, value); } } private ICommand _nextpanoramaReviewsFeed_Detail0; /// <summary> /// Gets the NextpanoramaReviewsFeed_Detail0 command. /// </summary> public ICommand NextpanoramaReviewsFeed_Detail0 { get { return _nextpanoramaReviewsFeed_Detail0 = _nextpanoramaReviewsFeed_Detail0 ?? new ViewModelsBase.DelegateCommand(NextpanoramaReviewsFeed_Detail0Delegate); } } /// <summary> /// Delegate method for the PreviouspanoramaReviewsFeed_Detail0 command. /// </summary> public async void PreviouspanoramaReviewsFeed_Detail0Delegate() { LoadingCurrentRssSearchResult = true; var prev = await _reviewsFeed_ReviewsFeed.Previous(CurrentRssSearchResult); if(prev != null) CurrentRssSearchResult = prev; RefreshHasPrevNext(); } private ICommand _previouspanoramaReviewsFeed_Detail0; /// <summary> /// Gets the PreviouspanoramaReviewsFeed_Detail0 command. /// </summary> public ICommand PreviouspanoramaReviewsFeed_Detail0 { get { return _previouspanoramaReviewsFeed_Detail0 = _previouspanoramaReviewsFeed_Detail0 ?? new ViewModelsBase.DelegateCommand(PreviouspanoramaReviewsFeed_Detail0Delegate); } } private async void RefreshHasPrevNext() { HasPreviouspanoramaReviewsFeed_Detail0 = await _reviewsFeed_ReviewsFeed.HasPrevious(CurrentRssSearchResult); HasNextpanoramaReviewsFeed_Detail0 = await _reviewsFeed_ReviewsFeed.HasNext(CurrentRssSearchResult); LoadingCurrentRssSearchResult = false; } public object NavigationContext { set { if (!(value is EntitiesBase.RssSearchResult)) { return; } CurrentRssSearchResult = value as EntitiesBase.RssSearchResult; RefreshHasPrevNext(); } } /// <summary> /// Initializes a <see cref="Services.TileInfo" /> object for the ReviewsFeed_DetailStaticControl control. /// </summary> /// <returns>A <see cref="Services.TileInfo" /> object.</returns> public Services.TileInfo CreateTileInfoReviewsFeed_DetailStaticControl() { var tileInfo = new Services.TileInfo { CurrentId = CurrentRssSearchResult.Title, Title = CurrentRssSearchResult.Title, BackTitle = CurrentRssSearchResult.Title, BackContent = CurrentRssSearchResult.Content, Count = 0, BackgroundImagePath = CurrentRssSearchResult.ImageUrl, BackBackgroundImagePath = CurrentRssSearchResult.ImageUrl, LogoPath = "Logo-242457de-80da-42c9-9fbb-98b5451c622c.png" }; return tileInfo; } } }
// <copyright file="ServiceCollectionExtensions.cs" company="Fubar Development Junker"> // Copyright (c) Fubar Development Junker. All rights reserved. // </copyright> using System; using System.IO; using System.Text; using System.Threading; using FubarDev.FtpServer; using FubarDev.FtpServer.AccountManagement.Directories.RootPerUser; using FubarDev.FtpServer.AccountManagement.Directories.SingleRootWithoutHome; using FubarDev.FtpServer.CommandExtensions; using FubarDev.FtpServer.Commands; using FubarDev.FtpServer.FileSystem; using FubarDev.FtpServer.FileSystem.DotNet; using FubarDev.FtpServer.FileSystem.GoogleDrive; using FubarDev.FtpServer.FileSystem.InMemory; #if NETCOREAPP using FubarDev.FtpServer.FileSystem.Unix; using FubarDev.FtpServer.MembershipProvider.Pam; using FubarDev.FtpServer.MembershipProvider.Pam.Directories; #endif using Google.Apis.Auth.OAuth2; using Google.Apis.Drive.v3; using Microsoft.DotNet.PlatformAbstractions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; #if NETCOREAPP using Mono.Unix.Native; using TestFtpServer.CommandMiddlewares; #endif using TestFtpServer.Commands; using TestFtpServer.Configuration; using TestFtpServer.Extensions; using TestFtpServer.ServerInfo; using TestFtpServer.Utilities; namespace TestFtpServer { public static class ServiceCollectionExtensions { public static IServiceCollection AddFtpServices( this IServiceCollection services, FtpOptions options) { services .Configure<AuthTlsOptions>( opt => { opt.ServerCertificate = options.GetCertificate(); opt.ImplicitFtps = options.Ftps.Implicit; }) .Configure<FtpConnectionOptions>( opt => opt.DefaultEncoding = Encoding.ASCII) .Configure<FubarDev.FtpServer.FtpServerOptions>( opt => { opt.ServerAddress = options.Server.Address; opt.Port = options.GetServerPort(); opt.MaxActiveConnections = options.Server.MaxActiveConnections ?? 0; opt.ConnectionInactivityCheckInterval = ToTimeSpan(options.Server.ConnectionInactivityCheckInterval); }) .Configure<PortCommandOptions>( opt => { if (options.Server.UseFtpDataPort) { opt.DataPort = options.GetServerPort() - 1; } }) .Configure<SimplePasvOptions>( opt => { var portRange = options.GetPasvPortRange(); if (portRange != null) { (opt.PasvMinPort, opt.PasvMaxPort) = portRange.Value; } }) .Configure<PasvCommandOptions>(opt => opt.PromiscuousPasv = options.Server.Pasv.Promiscuous) .Configure<GoogleDriveOptions>(opt => opt.UseBackgroundUpload = options.GoogleDrive.BackgroundUpload) .Configure<FileSystemAmazonS3Options>( opt => { opt.BucketName = options.AmazonS3.BucketName; opt.BucketRegion = options.AmazonS3.BucketRegion; opt.AwsAccessKeyId = options.AmazonS3.AwsAccessKeyId; opt.AwsSecretAccessKey = options.AmazonS3.AwsSecretAccessKey; }); #if NETCOREAPP services .Configure<PamMembershipProviderOptions>( opt => opt.IgnoreAccountManagement = options.Pam.NoAccountManagement); #endif // Add "Hello" service - unique per FTP connection services.AddScoped<Hello>(); // Add custom command handlers services.AddSingleton<IFtpCommandHandlerScanner>( _ => new AssemblyFtpCommandHandlerScanner(typeof(HelloFtpCommandHandler).Assembly)); // Add custom command handler extensions services.AddSingleton<IFtpCommandHandlerExtensionScanner>( sp => new AssemblyFtpCommandHandlerExtensionScanner( sp.GetRequiredService<IFtpCommandHandlerProvider>(), sp.GetService<ILogger<AssemblyFtpCommandHandlerExtensionScanner>>(), typeof(SiteHelloFtpCommandHandlerExtension).Assembly)); #if NETCOREAPP if (options.SetFileSystemId && RuntimeEnvironment.OperatingSystemPlatform != Microsoft.DotNet.PlatformAbstractions.Platform.Windows) { services.AddScoped<IFtpCommandMiddleware, FsIdChanger>(); } #endif switch (options.BackendType) { case FileSystemType.InMemory: services = services .AddFtpServer(sb => sb.ConfigureAuthentication(options).UseInMemoryFileSystem().ConfigureServer(options)) .Configure<InMemoryFileSystemOptions>( opt => opt.KeepAnonymousFileSystem = options.InMemory.KeepAnonymous); break; case FileSystemType.Unix: #if NETCOREAPP services = services .AddFtpServer(sb => sb.ConfigureAuthentication(options).UseUnixFileSystem().ConfigureServer(options)) .Configure<UnixFileSystemOptions>( opt => { opt.Root = options.Unix.Root; opt.FlushAfterWrite = options.Unix.FlushAfterWrite; }); #else services = services .AddFtpServer(sb => sb.ConfigureAuthentication(options).UseDotNetFileSystem().ConfigureServer(options)) .Configure<DotNetFileSystemOptions>( opt => { opt.RootPath = options.Unix.Root; opt.FlushAfterWrite = options.Unix.FlushAfterWrite; }); #endif break; case FileSystemType.SystemIO: services = services .AddFtpServer(sb => sb.ConfigureAuthentication(options).UseDotNetFileSystem().ConfigureServer(options)) .Configure<DotNetFileSystemOptions>( opt => { opt.RootPath = options.SystemIo.Root; opt.FlushAfterWrite = options.SystemIo.FlushAfterWrite; }); break; case FileSystemType.GoogleDriveUser: var userCredential = GetUserCredential( options.GoogleDrive.User.ClientSecrets ?? throw new ArgumentNullException( nameof(options.GoogleDrive.User.ClientSecrets), "Client secrets file not specified."), options.GoogleDrive.User.UserName ?? throw new ArgumentNullException( nameof(options.GoogleDrive.User.ClientSecrets), "User name not specified."), options.GoogleDrive.User.RefreshToken); services = services .AddFtpServer(sb => sb.ConfigureAuthentication(options).UseGoogleDrive(userCredential).ConfigureServer(options)); break; case FileSystemType.GoogleDriveService: var serviceCredential = GoogleCredential .FromFile(options.GoogleDrive.Service.CredentialFile) .CreateScoped(DriveService.Scope.Drive, DriveService.Scope.DriveFile); services = services .AddFtpServer(sb => sb.ConfigureAuthentication(options).UseGoogleDrive(serviceCredential).ConfigureServer(options)); break; case FileSystemType.AmazonS3: services = services .AddFtpServer(sb => sb.ConfigureAuthentication(options).UseS3FileSystem().ConfigureServer(options)); break; default: throw new NotSupportedException( $"Backend of type {options.Backend} cannot be run from configuration file options."); } switch (options.LayoutType) { case FileSystemLayoutType.SingleRoot: services.AddSingleton<IAccountDirectoryQuery, SingleRootWithoutHomeAccountDirectoryQuery>(); break; case FileSystemLayoutType.PamHome: #if NETCOREAPP services .AddSingleton<IAccountDirectoryQuery, PamAccountDirectoryQuery>() .Configure<PamAccountDirectoryQueryOptions>( opt => opt.AnonymousRootDirectory = Path.GetTempPath()); break; #endif case FileSystemLayoutType.PamHomeChroot: #if NETCOREAPP services .AddSingleton<IAccountDirectoryQuery, PamAccountDirectoryQuery>() .Configure<PamAccountDirectoryQueryOptions>( opt => { opt.AnonymousRootDirectory = Path.GetTempPath(); opt.UserHomeIsRoot = true; }); break; #endif case FileSystemLayoutType.RootPerUser: services .AddSingleton<IAccountDirectoryQuery, RootPerUserAccountDirectoryQuery>() .Configure<RootPerUserAccountDirectoryQueryOptions>(opt => opt.AnonymousRootPerEmail = true); break; } #if NETCOREAPP services.Decorate<IFtpServer>( (ftpServer, serviceProvider) => { /* Setting the umask is only valid for non-Windows platforms. */ if (!string.IsNullOrEmpty(options.Umask) && RuntimeEnvironment.OperatingSystemPlatform != Microsoft.DotNet.PlatformAbstractions.Platform.Windows) { var umask = options.Umask!.StartsWith("0") ? Convert.ToInt32(options.Umask, 8) : Convert.ToInt32(options.Umask, 10); Syscall.umask((FilePermissions)umask); } return ftpServer; }); #endif services.Scan( ts => ts .FromAssemblyOf<HostedFtpService>() .AddClasses(itf => itf.AssignableTo<IModuleInfo>(), true).As<IModuleInfo>() .WithSingletonLifetime()); return services; } private static IFtpServerBuilder ConfigureServer(this IFtpServerBuilder builder, FtpOptions options) { builder = builder .DisableChecks(); if (options.Connection.Inactivity.Enabled) { builder = builder .EnableIdleCheck(); builder.Services .Configure<FtpConnectionOptions>( opt => opt.InactivityTimeout = ToTimeSpan(options.Connection.Inactivity.InactivityTimeout)); } if (options.Connection.SocketState.Enabled) { builder = builder .EnableConnectionCheck(); } if (options.Ftps.Implicit) { var implicitFtpsCertificate = options.GetCertificate(); if (implicitFtpsCertificate != null) { builder = builder.UseImplicitTls(implicitFtpsCertificate); } } return builder; } private static UserCredential GetUserCredential( string clientSecretsFile, string userName, bool refreshToken) { UserCredential credential; using (var secretsSource = new FileStream(clientSecretsFile, FileMode.Open)) { var secrets = GoogleClientSecrets.Load(secretsSource); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( secrets.Secrets, new[] { DriveService.Scope.DriveFile, DriveService.Scope.Drive }, userName, CancellationToken.None).Result; } if (refreshToken) { credential.RefreshTokenAsync(CancellationToken.None).Wait(); } return credential; } private static TimeSpan? ToTimeSpan(int? seconds) { return seconds == null ? (TimeSpan?)null : TimeSpan.FromSeconds(seconds.Value); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Skahal.Infrastructure.Framework.Domain; namespace Skahal.Infrastructure.Framework.Repositories { /// <summary> /// Repository extensions. /// </summary> public static class RepositoryExtensions { #region FindAll /// <summary> /// Finds all entities. /// </summary> /// <returns>The found entities.</returns> /// <param name="repository">Repository.</param> /// <param name="filter">Filter.</param> public static IEnumerable<TEntity> FindAll<TEntity>(this IRepository<TEntity> repository) where TEntity : IAggregateRoot { return repository.FindAll(0, int.MaxValue, null); } /// <summary> /// Finds all entities that matches the filter. /// </summary> /// <returns>The found entities.</returns> /// <param name="repository">Repository.</param> /// <param name="filter">Filter.</param> public static IEnumerable<TEntity> FindAll<TEntity>(this IRepository<TEntity> repository, Expression<Func<TEntity, bool>> filter) where TEntity : IAggregateRoot { return repository.FindAll(0, int.MaxValue, filter); } /// <summary> /// Finds all entities. /// </summary> /// <returns>The found entities.</returns> /// <param name="repository">Repository.</param> /// <param name="offset">Offset.</param> /// <param name="limit">Limit.</param> public static IEnumerable<TEntity> FindAll<TEntity>(this IRepository<TEntity> repository, int offset, int limit) where TEntity : IAggregateRoot { return repository.FindAll(offset, limit, null); } /// <summary> /// Finds all entities. /// </summary> /// <returns>The found entities.</returns> /// <param name="repository">Repository.</param> /// <param name="offset">Offset.</param> /// <param name="limit">Limit.</param> public static IEnumerable<TEntity> FindAll<TEntity>(this IRepository<TEntity> repository, int offset, long limit) where TEntity : IAggregateRoot { return repository.FindAll(offset, Convert.ToInt32(limit), null); } #endregion #region FindAllAscending /// <summary> /// Finds all entities in a ascending order /// </summary> /// <returns>The found entities.</returns> /// <param name="repository">The repository.</param> /// <param name="orderBy">The order.</param> public static IEnumerable<TEntity> FindAllAscending<TEntity, TOrderByKey>(this IRepository<TEntity> repository, Expression<Func<TEntity, TOrderByKey>> orderBy) where TEntity : IAggregateRoot { return repository.FindAllAscending(0, int.MaxValue, null, orderBy); } /// <summary> /// Finds all entities that matches the filter in a ascending order /// </summary> /// <returns>The found entities.</returns> /// <param name="repository">The repository.</param> /// <param name="filter">The filter.</param> /// <param name="orderBy">The order.</param> public static IEnumerable<TEntity> FindAllAscending<TEntity, TOrderByKey>(this IRepository<TEntity> repository, Expression<Func<TEntity, bool>> filter, Expression<Func<TEntity, TOrderByKey>> orderBy) where TEntity : IAggregateRoot { return repository.FindAllAscending(0, int.MaxValue, filter, orderBy); } /// <summary> /// Finds all entities in a ascending order /// </summary> /// <returns>The found entities.</returns> /// <param name="repository">Repository.</param> /// <param name="offset">Offset.</param> /// <param name="limit">Limit.</param> /// <param name="orderBy">The order.</param> public static IEnumerable<TEntity> FindAllAscending<TEntity, TOrderByKey>(this IRepository<TEntity> repository, int offset, int limit, Expression<Func<TEntity, TOrderByKey>> orderBy) where TEntity : IAggregateRoot { return repository.FindAllAscending(offset, limit, null, orderBy); } /// <summary> /// Finds all entities in a ascending order /// </summary> /// <returns>The found entities.</returns> /// <param name="repository">Repository.</param> /// <param name="offset">Offset.</param> /// <param name="limit">Limit.</param> /// <param name="orderBy">The order.</param> public static IEnumerable<TEntity> FindAll<TEntity, TOrderByKey>(this IRepository<TEntity> repository, int offset, long limit, Expression<Func<TEntity, TOrderByKey>> orderBy) where TEntity : IAggregateRoot { return repository.FindAllAscending(offset, Convert.ToInt32(limit), null, orderBy); } #endregion #region FindAllDescending /// <summary> /// Finds all entities in a descending order /// </summary> /// <returns>The found entities.</returns> /// <param name="repository">The repository.</param> /// <param name="orderBy">The order.</param> public static IEnumerable<TEntity> FindAllDescending<TEntity, TOrderByKey>(this IRepository<TEntity> repository, Expression<Func<TEntity, TOrderByKey>> orderBy) where TEntity : IAggregateRoot { return repository.FindAllDescending(0, int.MaxValue, (f) => true, orderBy); } /// <summary> /// Finds all entities that matches the filter in a descending order /// </summary> /// <returns>The found entities.</returns> /// <param name="repository">The repository.</param> /// <param name="filter">The filter.</param> /// <param name="orderBy">The order.</param> public static IEnumerable<TEntity> FindAllDescending<TEntity, TOrderByKey>(this IRepository<TEntity> repository, Expression<Func<TEntity, bool>> filter, Expression<Func<TEntity, TOrderByKey>> orderBy) where TEntity : IAggregateRoot { return repository.FindAllDescending(0, int.MaxValue, filter, orderBy); } /// <summary> /// Finds all entities in a descending order /// </summary> /// <returns>The found entities.</returns> /// <param name="repository">Repository.</param> /// <param name="offset">Offset.</param> /// <param name="limit">Limit.</param> /// <param name="orderBy">The order.</param> public static IEnumerable<TEntity> FindAllDescending<TEntity, TOrderByKey>(this IRepository<TEntity> repository, int offset, int limit, Expression<Func<TEntity, TOrderByKey>> orderBy) where TEntity : IAggregateRoot { return repository.FindAllDescending(offset, limit, null, orderBy); } /// <summary> /// Finds all entities in a descending order /// </summary> /// <returns>The found entities.</returns> /// <param name="repository">Repository.</param> /// <param name="offset">Offset.</param> /// <param name="limit">Limit.</param> /// <param name="orderBy">The order.</param> public static IEnumerable<TEntity> FindAllDescending<TEntity, TOrderByKey>(this IRepository<TEntity> repository, int offset, long limit, Expression<Func<TEntity, TOrderByKey>> orderBy) where TEntity : IAggregateRoot { return repository.FindAllDescending(offset, Convert.ToInt32(limit), null, orderBy); } #endregion #region CountAll /// <summary> /// Counts all entities. /// </summary> /// <param name="repository">Repository.</param> /// <returns>The number of the entities that matches the filter.</returns> public static long CountAll<TEntity>(this IRepository<TEntity> repository) where TEntity : IAggregateRoot { return repository.CountAll (null); } #endregion #region FindFirst /// <summary> /// Finds the first entity. /// </summary> /// <typeparam name="TEntity">The entity type.</typeparam> /// <param name="repository">The repository.</param> /// <returns>The first entity.</returns> public static TEntity FindFirst<TEntity>(this IRepository<TEntity> repository) where TEntity : IAggregateRoot { return repository.FindAll(0, 1).FirstOrDefault(); } /// <summary> /// Finds the first entity that match the filter. /// </summary> /// <typeparam name="TEntity">The entity type.</typeparam> /// <param name="repository">The repository.</param> /// <param name="filter">The filter.</param> /// <returns>The first entity that match the filter or null if none match.</returns> public static TEntity FindFirst<TEntity>(this IRepository<TEntity> repository, Expression<Func<TEntity, bool>> filter) where TEntity : IAggregateRoot { return repository.FindAll(0, 1, filter).FirstOrDefault(); } /// <summary> /// Finds the first entity that match the filter in an ascending order. /// </summary> /// <typeparam name="TEntity">The entity type.</typeparam> /// <param name="repository">The repository.</param> /// <param name="filter">The filter.</param> /// <param name="orderBy">The order.</param> /// <returns>The first entity that match the filter or null if none match.</returns> public static TEntity FindFirstAscending<TEntity, TOrderByKey>(this IRepository<TEntity> repository, Expression<Func<TEntity, bool>> filter, Expression<Func<TEntity, TOrderByKey>> orderBy) where TEntity : IAggregateRoot { return repository.FindAllAscending(0, 1, filter, orderBy).FirstOrDefault(); } /// <summary> /// Finds the first entity that match the filter in an descending order. /// </summary> /// <typeparam name="TEntity">The entity type.</typeparam> /// <param name="repository">The repository.</param> /// <param name="filter">The filter.</param> /// <param name="orderBy">The order.</param> /// <returns>The first entity that match the filter or null if none match.</returns> public static TEntity FindFirstDescending<TEntity, TOrderByKey>(this IRepository<TEntity> repository, Expression<Func<TEntity, bool>> filter, Expression<Func<TEntity, TOrderByKey>> orderBy) where TEntity : IAggregateRoot { return repository.FindAllDescending(0, 1, filter, orderBy).FirstOrDefault(); } #endregion #region FindLast /// <summary> /// Finds the last entity. /// </summary> /// <returns>The last entity.</returns> /// <param name="repository">Repository.</param> /// <typeparam name="TEntity">The 1st type parameter.</typeparam> public static TEntity FindLast<TEntity>(this IRepository<TEntity> repository) where TEntity : IAggregateRoot { return repository.FindAll (Convert.ToInt32(repository.CountAll() - 1), 1).FirstOrDefault (); } #endregion } }
/* * Copyright (c) 2016 Robert Adams * * 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.Drawing; using System.Text; using log4net; using OpenSim.Region.CoreModules.World.LegacyMap; using OMV = OpenMetaverse; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OMVS = OpenMetaverse.StructuredData; using OMVA = OpenMetaverse.Assets; using OMVR = OpenMetaverse.Rendering; namespace org.herbal3d.BasilOS { public class BasilTerrain { private static string LogHeader = "BasilTerrain"; // Create a mesh for the terrain of the current scene public static EntityGroup CreateTerrainMesh(BasilModuleContext context, Scene scene, PrimToMesh assetMesher, IAssetFetcher assetFetcher) { ITerrainChannel terrainDef = scene.Heightmap; int XSize = terrainDef.Width; int YSize = terrainDef.Height; float[,] heightMap = new float[XSize, YSize]; if (context.parms.HalfRezTerrain) { context.log.DebugFormat("{0}: CreateTerrainMesh. creating half sized terrain sized <{1},{2}>", LogHeader, XSize/2, YSize/2); // Half resolution mesh that approximates the heightmap heightMap = new float[XSize/2, YSize/2]; for (int xx = 0; xx < XSize; xx += 2) { for (int yy = 0; yy < YSize; yy += 2) { float here = terrainDef.GetHeightAtXYZ(xx+0, yy+0, 26); float ln = terrainDef.GetHeightAtXYZ(xx+1, yy+0, 26); float ll = terrainDef.GetHeightAtXYZ(xx+0, yy+1, 26); float lr = terrainDef.GetHeightAtXYZ(xx+1, yy+1, 26); heightMap[xx/2, yy/2] = (here + ln + ll + lr) / 4; } } } else { context.log.DebugFormat("{0}: CreateTerrainMesh. creating terrain sized <{1},{2}>", LogHeader, XSize/2, YSize/2); for (int xx = 0; xx < XSize; xx++) { for (int yy = 0; yy < YSize; yy++) { heightMap[xx, yy] = terrainDef.GetHeightAtXYZ(xx, yy, 26); } } } context.log.DebugFormat("{0}: CreateTerrainMesh. calling MeshFromHeightMap", LogHeader); ExtendedPrimGroup epg = assetMesher.MeshFromHeightMap(heightMap, terrainDef.Width, terrainDef.Height); // Number found in RegionSettings.cs as DEFAULT_TERRAIN_TEXTURE_3 OMV.UUID defaultTextureID = new OMV.UUID("179cdabd-398a-9b6b-1391-4dc333ba321f"); OMV.Primitive.TextureEntry te = new OMV.Primitive.TextureEntry(defaultTextureID); if (context.parms.CreateTerrainSplat) { // Use the OpenSim maptile generator to create a texture for the terrain var terrainRenderer = new TexturedMapTileRenderer(); terrainRenderer.Initialise(scene, context.sysConfig.ConfigSource); var mapbmp = new Bitmap(terrainDef.Width, terrainDef.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb); terrainRenderer.TerrainToBitmap(mapbmp); // The built terrain mesh will have one face in the mesh OMVR.Face aFace = epg.primaryExtendePrim.fromOS.facetedMesh.Faces.First(); FaceInfo fi = new FaceInfo(0, epg.primaryExtendePrim, aFace, te.CreateFace(0)); fi.textureID = OMV.UUID.Random(); fi.faceImage = mapbmp; fi.hasAlpha = false; fi.persist = new BasilPersist(Gltf.MakeAssetURITypeImage, fi.textureID.ToString(), context); epg.primaryExtendePrim.faces.Add(fi); } else { // Fabricate a texture // The built terrain mesh will have one face in the mesh OMVR.Face aFace = epg.primaryExtendePrim.fromOS.facetedMesh.Faces.First(); FaceInfo fi = new FaceInfo(0, epg.primaryExtendePrim, aFace, te.CreateFace(0)); fi.textureID = defaultTextureID; assetFetcher.FetchTextureAsImage(new EntityHandle(defaultTextureID)) .Catch(e => { context.log.ErrorFormat("{0} CreateTerrainMesh: unable to fetch default terrain texture: id={1}: {2}", LogHeader, defaultTextureID, e); }) .Then(theImage => { // This will happen later so hopefully soon enough for anyone using the image fi.faceImage = theImage; }); fi.hasAlpha = false; epg.primaryExtendePrim.faces.Add(fi); } EntityGroup eg = new EntityGroup(); eg.Add(epg); return eg; } // A structure to hold vertex information that also includes the index for building indices. private struct Vert : IEquatable<Vert>{ public OMV.Vector3 Position; public OMV.Vector3 Normal; public OMV.Vector2 TexCoord; public uint index; // Methods so this will work in a Dictionary public override int GetHashCode() { int hash = Position.GetHashCode(); hash = hash * 31 + Normal.GetHashCode(); hash = hash * 31 + TexCoord.GetHashCode(); return hash; } public bool Equals(Vert other) { return Position == other.Position && Normal == other.Normal && TexCoord == other.TexCoord; } } // PrimMesher has a terrain mesh generator but it doesn't compute normals. // TODO: Optimize by removing vertices that are just mid points. // Having a vertex for every height is very inefficient especially for flat areas. public static OMVR.Face TerrainMesh(float[,] heights, float realSizeX, float realSizeY, ILog log) { List<ushort> indices = new List<ushort>(); int sizeX = heights.GetLength(0); int sizeY = heights.GetLength(1); // build the vertices in an array for computing normals and eventually for // optimizations. Vert[,] vertices = new Vert[sizeX, sizeY]; float stepX = (realSizeX+1f) / (float)sizeX; // the real dimension step for each heightmap step float stepY = (realSizeY+1f) / (float)sizeY; float coordStepX = 1.0f / (float)sizeX; // the coordinate dimension step for each heightmap step float coordStepY = 1.0f / (float)sizeY; uint index = 0; for (int xx = 0; xx < sizeX; xx++) { for (int yy = 0; yy < sizeY; yy++) { Vert vert = new Vert(); vert.Position = new OMV.Vector3(stepX * xx, stepY * yy, heights[xx, yy]); vert.Normal = new OMV.Vector3(0f, 1f, 0f); // normal pointing up for the moment vert.TexCoord = new OMV.Vector2(coordStepX * xx, coordStepY * yy); vert.index = index++; vertices[xx, yy] = vert; } } // Compute the normals // Take three corners of each quad and calculate the normal for the vector // a--b--e--... // | | | // d--c--h--... // The triangle a-b-d calculates the normal for a, etc for (int xx = 0; xx < sizeX-1; xx++) { for (int yy = 0; yy < sizeY-1; yy++) { vertices[xx,yy].Normal = MakeNormal(vertices[xx, yy], vertices[xx + 1, yy], vertices[xx, yy + 1]); } } // The vertices along the edges need an extra pass to compute the normals for (int xx = 0; xx < sizeX-1 ; xx++) { vertices[xx, sizeY - 1].Normal = MakeNormal(vertices[xx, sizeY - 1], vertices[xx + 1, sizeY - 1], vertices[xx, sizeY - 2]); } for (int yy = 0; yy < sizeY - 1; yy++) { vertices[sizeX -1, yy].Normal = MakeNormal(vertices[sizeX -1 , yy], vertices[sizeX - 1, yy + 1], vertices[sizeX - 2, yy]); } vertices[sizeX -1, sizeY - 1].Normal = MakeNormal(vertices[sizeX -1 , sizeY - 1], vertices[sizeX - 2, sizeY - 1], vertices[sizeX - 1, sizeY - 2]); // Convert our vertices into the format expected by the caller List<OMVR.Vertex> vertexList = new List<OMVR.Vertex>(); for (int xx = 0; xx < sizeX; xx++) { for (int yy = 0; yy < sizeY; yy++) { Vert vert = vertices[xx, yy]; OMVR.Vertex oVert = new OMVR.Vertex(); oVert.Position = vert.Position; oVert.Normal = vert.Normal; oVert.TexCoord = vert.TexCoord; vertexList.Add(oVert); } } // Make indices for all the vertices. // Pass over the matrix and create two triangles for each quad // // 00-----01 // | f1 /| // | / | // | / f2 | // 10-----11 // // Counter Clockwise for (int xx = 0; xx < sizeX - 1; xx++) { for (int yy = 0; yy < sizeY - 1; yy++) { indices.Add((ushort)vertices[xx + 0, yy + 0].index); indices.Add((ushort)vertices[xx + 1, yy + 0].index); indices.Add((ushort)vertices[xx + 0, yy + 1].index); indices.Add((ushort)vertices[xx + 0, yy + 1].index); indices.Add((ushort)vertices[xx + 1, yy + 0].index); indices.Add((ushort)vertices[xx + 1, yy + 1].index); } } OMVR.Face aface = new OMVR.Face(); aface.Vertices = vertexList; aface.Indices = indices; return aface; } // Given a root (aa) and two adjacent vertices (bb, cc), computer the normal for aa private static OMV.Vector3 MakeNormal(Vert aa, Vert bb, Vert cc) { OMV.Vector3 mm = aa.Position - bb.Position; OMV.Vector3 nn = aa.Position - cc.Position; OMV.Vector3 theNormal = OMV.Vector3.Cross(mm, nn); theNormal.Normalize(); return theNormal; } } }
// Copyright (c) Sven Groot (Ookii.org) 2006 // See license.txt for details using System; using System.ComponentModel; using System.IO; using System.Windows.Forms; using Ookii.Dialogs.Interop; namespace Ookii.Dialogs { /// <summary> /// Prompts the user to open a file. /// </summary> /// <remarks> /// <para> /// This class will use the Vista style file dialog if possible, and automatically fall back to the old-style /// dialog on versions of Windows older than Vista. /// </para> /// <para> /// As of .Net 3.5 and .Net 2.0 SP1, the regular <see cref="System.Windows.Forms.OpenFileDialog"/> class will also use /// the new Vista style dialogs. However, certain options, such as settings <see cref="System.Windows.Forms.OpenFileDialog.ShowReadOnly"/>, /// still cause that class to revert to the old style dialogs. For this reason, this class is still provided. /// It is recommended that you use the <see cref="System.Windows.Forms.FileDialog"/> class whenever possible. /// </para> /// </remarks> /// <threadsafety static="true" instance="false"/> [System.Drawing.ToolboxBitmap(typeof(System.Windows.Forms.OpenFileDialog), "OpenFileDialog.bmp"), Description("Prompts the user to open a file.")] public class VistaOpenFileDialog : VistaFileDialog { private bool _showReadOnly; private bool _readOnlyChecked; private const int _openDropDownId = 0x4002; private const int _openItemId = 0x4003; private const int _readOnlyItemId = 0x4004; /// <summary> /// Creates a new instance of <see cref="VistaOpenFileDialog" /> class. /// </summary> public VistaOpenFileDialog() : this(false) { } /// <summary> /// Creates a new instance of <see cref="VistaOpenFileDialog" /> class. /// </summary> /// <param name="forceDownlevel">When <see langword="true"/>, the old style common file dialog will always be used even if the OS supports the Vista style.</param> public VistaOpenFileDialog(bool forceDownlevel) { if (forceDownlevel || !IsVistaFileDialogSupported) DownlevelDialog = new OpenFileDialog(); } #region Public Properties /// <summary> /// Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a file name that does not exist. /// </summary> /// <value> /// <see langword="true"/> if the dialog box displays a warning if the user specifies a file name that does not exist; otherwise, <see langword="false"/>. The default value is <see langword="true"/>. /// </value> [DefaultValue(true), Description("A value indicating whether the dialog box displays a warning if the user specifies a file name that does not exist.")] public override bool CheckFileExists { get { return base.CheckFileExists; } set { base.CheckFileExists = value; } } /// <summary> /// Gets or sets a value indicating whether the dialog box allows multiple files to be selected. /// </summary> /// <value> /// <see langword="true"/> if the dialog box allows multiple files to be selected together or concurrently; otherwise, <see langword="false"/>. /// The default value is <see langword="false"/>. /// </value> [Description("A value indicating whether the dialog box allows multiple files to be selected."), DefaultValue(false), Category("Behavior")] public bool Multiselect { get { if (DownlevelDialog != null) return ((OpenFileDialog)DownlevelDialog).Multiselect; return GetOption(NativeMethods.FILEOPENDIALOGOPTIONS.FOS_ALLOWMULTISELECT); } set { if (DownlevelDialog != null) ((OpenFileDialog)DownlevelDialog).Multiselect = value; SetOption(NativeMethods.FILEOPENDIALOGOPTIONS.FOS_ALLOWMULTISELECT, value); } } /// <summary> /// Gets or sets a value indicating whether the dialog box contains a read-only check box. /// </summary> /// <value> /// <see langword="true"/> if the dialog box contains a read-only check box; otherwise, <see langword="false"/>. The default value is <see langword="false"/>. /// </value> /// <remarks> /// If the Vista style dialog is used, this property can only be used to determine whether the user chose /// Open as read-only on the dialog; setting it in code will have no effect. /// </remarks> [Description("A value indicating whether the dialog box contains a read-only check box."), Category("Behavior"), DefaultValue(false)] public bool ShowReadOnly { get { if (DownlevelDialog != null) return ((OpenFileDialog)DownlevelDialog).ShowReadOnly; return _showReadOnly; } set { if (DownlevelDialog != null) ((OpenFileDialog)DownlevelDialog).ShowReadOnly = value; else _showReadOnly = value; } } /// <summary> /// Gets or sets a value indicating whether the read-only check box is selected. /// </summary> /// <value> /// <see langword="true"/> if the read-only check box is selected; otherwise, <see langword="false"/>. The default value is <see langword="false"/>. /// </value> [DefaultValue(false), Description("A value indicating whether the read-only check box is selected."), Category("Behavior")] public bool ReadOnlyChecked { get { if (DownlevelDialog != null) return ((OpenFileDialog)DownlevelDialog).ReadOnlyChecked; return _readOnlyChecked; } set { if (DownlevelDialog != null) ((OpenFileDialog)DownlevelDialog).ReadOnlyChecked = value; else _readOnlyChecked = value; } } #endregion #region Public Methods /// <summary> /// Resets all properties to their default values. /// </summary> public override void Reset() { base.Reset(); if (DownlevelDialog == null) { CheckFileExists = true; _showReadOnly = false; _readOnlyChecked = false; } } /// <summary> /// Opens the file selected by the user, with read-only permission. The file is specified by the FileName property. /// </summary> /// <returns>A Stream that specifies the read-only file selected by the user.</returns> /// <exception cref="System.ArgumentNullException">The file name is <see langword="null"/>.</exception> public System.IO.Stream OpenFile() { if (DownlevelDialog != null) return ((OpenFileDialog)DownlevelDialog).OpenFile(); else { string fileName = FileName; if (string.IsNullOrEmpty(fileName)) throw new ArgumentNullException("FileName"); return new FileStream(fileName, FileMode.Open, FileAccess.Read); } } #endregion #region Internal Methods internal override Ookii.Dialogs.Interop.IFileDialog CreateFileDialog() { return new Interop.NativeFileOpenDialog(); } internal override void SetDialogProperties(Ookii.Dialogs.Interop.IFileDialog dialog) { base.SetDialogProperties(dialog); if (_showReadOnly) { Ookii.Dialogs.Interop.IFileDialogCustomize customize = (Ookii.Dialogs.Interop.IFileDialogCustomize)dialog; customize.EnableOpenDropDown(_openDropDownId); customize.AddControlItem(_openDropDownId, _openItemId, ComDlgResources.LoadString(ComDlgResources.ComDlgResourceId.OpenButton)); customize.AddControlItem(_openDropDownId, _readOnlyItemId, ComDlgResources.LoadString(ComDlgResources.ComDlgResourceId.ReadOnly)); } } internal override void GetResult(Ookii.Dialogs.Interop.IFileDialog dialog) { if (Multiselect) { Ookii.Dialogs.Interop.IShellItemArray results; ((Ookii.Dialogs.Interop.IFileOpenDialog)dialog).GetResults(out results); uint count; results.GetCount(out count); string[] fileNames = new string[count]; for (uint x = 0; x < count; ++x) { Ookii.Dialogs.Interop.IShellItem item; results.GetItemAt(x, out item); string name; item.GetDisplayName(NativeMethods.SIGDN.SIGDN_FILESYSPATH, out name); fileNames[x] = name; } FileNamesInternal = fileNames; } else FileNamesInternal = null; if (ShowReadOnly) { Interop.IFileDialogCustomize customize = (Interop.IFileDialogCustomize)dialog; int selected; customize.GetSelectedControlItem(_openDropDownId, out selected); _readOnlyChecked = (selected == _readOnlyItemId); } base.GetResult(dialog); } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace ClosedXML.Excel { using System.Linq; internal class XLCells : IXLCells, IXLStylized, IEnumerable<XLCell> { public Boolean StyleChanged { get; set; } #region Fields private readonly bool _includeFormats; private readonly List<XLRangeAddress> _rangeAddresses = new List<XLRangeAddress>(); private readonly bool _usedCellsOnly; private IXLStyle _style; private readonly Func<IXLCell, Boolean> _predicate; #endregion #region Constructor public XLCells(bool usedCellsOnly, bool includeFormats, Func<IXLCell, Boolean> predicate = null) { _style = new XLStyle(this, XLWorkbook.DefaultStyle); _usedCellsOnly = usedCellsOnly; _includeFormats = includeFormats; _predicate = predicate; } #endregion #region IEnumerable<XLCell> Members public IEnumerator<XLCell> GetEnumerator() { var cellsInRanges = new Dictionary<XLWorksheet, HashSet<XLSheetPoint>>(); Boolean oneRange = _rangeAddresses.Count == 1; foreach (XLRangeAddress range in _rangeAddresses) { HashSet<XLSheetPoint> hash; if (cellsInRanges.ContainsKey(range.Worksheet)) hash = cellsInRanges[range.Worksheet]; else { hash = new HashSet<XLSheetPoint>(); cellsInRanges.Add(range.Worksheet, hash); } if (_usedCellsOnly) { if (oneRange) { var cellRange = range .Worksheet .Internals .CellsCollection .GetCells( range.FirstAddress.RowNumber, range.FirstAddress.ColumnNumber, range.LastAddress.RowNumber, range.LastAddress.ColumnNumber) .Where(c => !c.IsEmpty(_includeFormats) && (_predicate == null || _predicate(c)) ); foreach(var cell in cellRange) { yield return cell; } } else { var tmpRange = range; var addressList = range.Worksheet.Internals.CellsCollection .GetSheetPoints( tmpRange.FirstAddress.RowNumber, tmpRange.FirstAddress.ColumnNumber, tmpRange.LastAddress.RowNumber, tmpRange.LastAddress.ColumnNumber); foreach (XLSheetPoint a in addressList.Where(a => !hash.Contains(a))) { hash.Add(a); } } } else { var mm = new MinMax { MinRow = range.FirstAddress.RowNumber, MaxRow = range.LastAddress.RowNumber, MinColumn = range.FirstAddress.ColumnNumber, MaxColumn = range.LastAddress.ColumnNumber }; if (mm.MaxRow > 0 && mm.MaxColumn > 0) { for (Int32 ro = mm.MinRow; ro <= mm.MaxRow; ro++) { for (Int32 co = mm.MinColumn; co <= mm.MaxColumn; co++) { if (oneRange) { var c = range.Worksheet.Cell(ro, co); if (_predicate == null || _predicate(c)) yield return c; } else { var address = new XLSheetPoint(ro, co); if (!hash.Contains(address)) hash.Add(address); } } } } } } if (!oneRange) { if (_usedCellsOnly) { var cellRange = cellsInRanges .SelectMany( cir => cir.Value.Select(a => cir.Key.Internals.CellsCollection.GetCell(a)).Where( cell => cell != null && !cell.IsEmpty(_includeFormats) && (_predicate == null || _predicate(cell)) ) ); foreach (var cell in cellRange) { yield return cell; } } else { foreach (var cir in cellsInRanges) { foreach (XLSheetPoint a in cir.Value) { var c = cir.Key.Cell(a.Row, a.Column); if (_predicate == null || _predicate(c)) yield return c; } } } } } #endregion #region IXLCells Members IEnumerator<IXLCell> IEnumerable<IXLCell>.GetEnumerator() { foreach (XLCell cell in this) yield return cell; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public IXLStyle Style { get { return _style; } set { _style = new XLStyle(this, value); this.ForEach<XLCell>(c => c.Style = _style); } } public Object Value { set { this.ForEach<XLCell>(c => c.Value = value); } } public IXLCells SetDataType(XLDataType dataType) { this.ForEach<XLCell>(c => c.DataType = dataType); return this; } public XLDataType DataType { set { this.ForEach<XLCell>(c => c.DataType = value); } } public IXLCells Clear(XLClearOptions clearOptions = XLClearOptions.ContentsAndFormats) { this.ForEach<XLCell>(c => c.Clear(clearOptions)); return this; } public void DeleteComments() { this.ForEach<XLCell>(c => c.DeleteComment()); } public String FormulaA1 { set { this.ForEach<XLCell>(c => c.FormulaA1 = value); } } public String FormulaR1C1 { set { this.ForEach<XLCell>(c => c.FormulaR1C1 = value); } } #endregion #region IXLStylized Members public IEnumerable<IXLStyle> Styles { get { UpdatingStyle = true; yield return _style; foreach (XLCell c in this) yield return c.Style; UpdatingStyle = false; } } public Boolean UpdatingStyle { get; set; } public IXLStyle InnerStyle { get { return _style; } set { _style = new XLStyle(this, value); } } public IXLRanges RangesUsed { get { var retVal = new XLRanges(); this.ForEach<XLCell>(c => retVal.Add(c.AsRange())); return retVal; } } #endregion public void Add(XLRangeAddress rangeAddress) { _rangeAddresses.Add(rangeAddress); } public void Add(XLCell cell) { _rangeAddresses.Add(new XLRangeAddress(cell.Address, cell.Address)); } //-- #region Nested type: MinMax private struct MinMax { public Int32 MaxColumn; public Int32 MaxRow; public Int32 MinColumn; public Int32 MinRow; } #endregion public void Select() { foreach (var cell in this) cell.Select(); } } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.IO; using Jovian.Tools.Support; namespace Jovian.Tools { public class JovianEdit : System.Windows.Forms.Control { private System.ComponentModel.Container components = null; private System.Timers.Timer cursorTimer; rtfDocument RTF; Pen CursorPen; Pen CursorPenDrag; bool ShowCursor; private rtfDisplayCursor curse; private VScrollBar _vertScroll; private HScrollBar _horzScroll; private int _ScrollLeft; private rtfFindBar _findBar; private System.Drawing.Printing.PrintDocument printer; private System.Windows.Forms.PrintDialog printDialog; private rtfReplace _replaceBar; private System.Windows.Forms.ContextMenu rightClickMenu; private rtfFormatting _formatPop; private AutoCompleteListBox autoPick; private int ap_Line = 0; private int ap_Caret = 0; private string ap_Hint = ""; private string ap_Grp = ""; private int ap_Param = -1; private System.Windows.Forms.Label lbAuto; private ArrayList ap_List; private bool goodHint() { return ap_Hint.Replace("(0)", "").Length > 1; } bool cssAutoHelp = false; public void SetCSSAutoHelp() { cssAutoHelp = true; RTF.MinusAllowedInGroup = true; } private void AutoSelect() { int iC = ap_Hint.IndexOf("("); string cC = ap_Hint.Substring(iC + 1).Trim(); cC = cC.Substring(0, cC.Length - 1); int oap = ap_Param; ap_Param = -1; try { ap_Param = Int32.Parse(cC); } catch (Exception erz) { string zee = erz.ToString(); } if (oap != ap_Param) { AutoInfo(); } string dbHint = ap_Hint.Replace("(0)", ""); int pP = dbHint.IndexOf("."); string grp = dbHint.Substring(0, pP); if (!grp.Equals(ap_Grp)) { HidePicker(); ShowPicker(); return; } string wrd = dbHint.Substring(pP + 1); if (wrd.Length == 0) return; string wrdL = wrd.ToLower(); int curIdx = 0; int bestIdx = -1; foreach (AutoDatabase.SimpleEntry se in ap_List) { if (se.name.Length >= wrd.Length) { if (se.name.Equals(wrd)) { bestIdx = curIdx; } else { if (bestIdx < 0) { if (se.name.Substring(0, wrd.Length).Equals(wrd)) { bestIdx = curIdx; } else if (se.name.Substring(0, wrd.Length).ToLower().Equals(wrdL)) { bestIdx = curIdx; } else if (se.name.ToLower().Equals(wrdL)) { bestIdx = curIdx; } } } } curIdx++; } if (bestIdx >= 0) { autoPick.SelectedIndex = bestIdx; AutoInfo(); } else { this.Focus(); } // this is based on the hint } private void AutoInfo() { int k = autoPick.SelectedIndex; if (k >= 0 && k < ap_List.Count) { AutoDatabase.SimpleEntry se = ap_List[k] as AutoDatabase.SimpleEntry; lbAuto.Text = se.notes; if (se.paramHelp != null) { if (0 <= ap_Param && ap_Param < se.paramHelp.Length) { lbAuto.Text += (("" + (char)13) + (char)10) + "Parameter [" + ap_Param + "] : " + se.paramHelp[ap_Param]; } } } } private bool AutoComplete() { if (autoPick.Visible) { if (goodHint()) { try { string dbHint = ap_Hint.Replace("(0)", ""); int pP = dbHint.IndexOf("."); string wrd = dbHint.Substring(pP + 1); string total = autoPick.SelectedItem as string; if (cssAutoHelp && pP == 0) { total += ":"; RTF.AutoInsert(wrd, total); HidePicker(); ShowPicker(); return true; } else { if (cssAutoHelp) total += ";"; RTF.AutoInsert(wrd, total); } } catch (Exception eRZ) { string xo = eRZ.ToString(); } } } HidePicker(); return true; } private AutoDatabase.SimpleDatabase _DataBase = null; public void SetDatabase(AutoDatabase.SimpleDatabase db) { _DataBase = db; } private void AutoPopulate() { // this will be based on the engine autoPick.Items.Clear(); if (_DataBase == null) return; string dbHint = ap_Hint.Replace("(0)", ""); int pP = dbHint.IndexOf("."); string grp = dbHint.Substring(0, pP); ap_Grp = grp; ap_List = _DataBase.GetGroup(grp); foreach (AutoDatabase.SimpleEntry se in ap_List) { autoPick.Items.Add(se.name); } } private void CharTrigger(char x) { if (!autoPick.Visible) { if (x == '.' || x == ':') ShowPicker(); } return; } private void ShowPicker() { ap_Line = RTF.GetCurrentCursor().Line; ap_Caret = RTF.GetCurrentCursor().Place; ap_Hint = RTF.GetHint(ap_Line, ap_Caret); autoPick.Left = Math.Max(50, curse.x - autoPick.Width); autoPick.Top = curse.y + curse.h; lbAuto.Left = autoPick.Left + autoPick.Width; lbAuto.Top = autoPick.Top; lbAuto.Height = autoPick.Height / 2; lbAuto.Width = Math.Max(autoPick.Width, this.Width - (lbAuto.Right + 50)); if (goodHint()) { AutoPopulate(); autoPick.SelectedIndex = -1; if (autoPick.Items.Count > 0) { AutoSelect(); autoPick.Visible = true; lbAuto.Visible = true; } } } private void AutoDelta(int x) { int M = autoPick.Items.Count; int S = autoPick.SelectedIndex; S += x; S = Math.Max(0, S); S = Math.Min(M - 1, S); autoPick.SelectedIndex = S; AutoInfo(); //autoPick.Focus(); } private void AutoHidePickerChk() { if (autoPick.Visible) { if (ap_Line != RTF.GetCurrentCursor().Line) { HidePicker(); return; } else { if (ap_Caret != RTF.GetCurrentCursor().Place) { ap_Caret = RTF.GetCurrentCursor().Place; ap_Hint = RTF.GetHint(ap_Line, ap_Caret); if (!goodHint()) HidePicker(); else AutoSelect(); } } } } private void HidePicker() { lbAuto.Visible = false; autoPick.Visible = false; this.Focus(); } private rtfOnChange _OnChange = null; public void SetOnChange(rtfOnChange roc) { _OnChange = roc; } public void Changed() { if (_OnChange != null) _OnChange.Changed(); } public void FireTxtChanged() { this.OnTextChanged(new System.EventArgs()); } public StyleEng Engine { get { return RTF.GetStyle(); } set { RTF.SetStyle(value); Invalidate(); } } public void SyncSearch() { if (_replaceBar == null) return; _replaceBar.ResetResults(RTF.SearchResults); } public void AlterSearchResults(int Sty, bool F) { RTF.AlterSearchResults(Sty, F); SyncSearch(); Invalidate(); } public void DeleteSearchResults(rtfSearchRange K) { RTF.DeleteFromSearchResults(K); SyncSearch(); Invalidate(); } public void ExecuteReplace(string x) { RTF.ExecuteReplace(x); SyncSearch(); Invalidate(); KillReplaceBar(); } public void ApplyFormatter(Formatter F) { RTF.ResetDoc(F.apply(RTF)); } public void ChangeCursor(int C) { RTF.SearchCursor = C; RTF.UpdateSearch(); Invalidate(); } public void SyncSearchCursor() { } public void InstallFormatting() { if (_formatPop == null) { _formatPop = new rtfFormatting(this); PositionScrollBars(); this.Controls.Add(_formatPop); } else { KillFormatting(); } } public void KillFormatting() { if (_formatPop != null) { this.Controls.Remove(_formatPop); _formatPop.Dispose(); _formatPop = null; } } public void InstallReplaceBar() { if (_replaceBar == null) { _replaceBar = new rtfReplace(this); PositionScrollBars(); this.Controls.Add(_replaceBar); _findBar.goodFocus(); SyncSearch(); } else { KillReplaceBar(); } } public void KillReplaceBar() { if (_replaceBar != null) { this.Controls.Remove(_replaceBar); _replaceBar.Dispose(); _replaceBar = null; PositionScrollBars(); } } public void InstallFindBar() { if (_findBar == null) { _findBar = new rtfFindBar(this); PositionScrollBars(); this.Controls.Add(_findBar); _findBar.goodFocus(); } else { KillFindBar(); } } public void KillFindBar() { KillReplaceBar(); if (_findBar != null) { this.Controls.Remove(_findBar); _findBar.Dispose(); _findBar = null; PositionScrollBars(); } this.Focus(); } public rtfSearchKey GetKey() { return RTF.GetKey(); } public int ExecuteSearch() { int r = RTF.ExecSearch(true); Invalidate(); SyncSearch(); return r; } public void SetSearchCursor(int c) { } public void ExecuteSearchNext() { RTF.SearchNext(); SyncSearchCursor(); } public void ExecuteSearchPrev() { RTF.SearchPrev(); SyncSearchCursor(); } public override string Text { get { return RTF.GetTEXT(); } set { RTF = new rtfDocument(this); if (value != null) RTF.Insert(value); else RTF.Insert(""); RTF.TrimEnd(); RTF.KillUndoStack(); } } public void Open(string filename) { StreamReader SR = new StreamReader(filename); this.Text = SR.ReadToEnd(); SR.Close(); string ext = filename.ToUpper().Substring(filename.LastIndexOf(".")); if (ext.Equals(".JS")) { this.Engine = new Styles.JavaScript(); } else if (ext.Equals(".HTML") || ext.Equals(".XML") || ext.Equals(".HTM")) { this.Engine = new Styles.XML(); } else if (ext.Equals(".SQL")) { this.Engine = new Styles.SQL(); } else { this.Engine = null; } } public void SaveTo(string filename) { StreamWriter SW = new StreamWriter(filename); SW.Write(RTF.GetTEXT()); SW.Flush(); SW.Close(); } private int botHeight() { int h = _horzScroll.Height; if (_findBar != null) h += _findBar.Height; return h; } private int rigWidth() { int w = _vertScroll.Width; if (_replaceBar != null) w += _replaceBar.Width; return w; } public void PositionScrollBars() { _vertScroll.Top = 0; _vertScroll.Left = this.Width - rigWidth(); _vertScroll.Height = this.Height - botHeight(); _horzScroll.Left = 0; _horzScroll.Top = this.Height - botHeight(); _horzScroll.Width = this.Width - rigWidth(); if (_findBar != null) { _findBar.Left = 0; _findBar.Top = this.Height - _findBar.Height; int dx = 0; if (_replaceBar != null) dx = _replaceBar.Width; _findBar.Width = this.Width - dx; } if (_replaceBar != null) { _replaceBar.TabIndex = 0; _replaceBar.Left = this.Width - _replaceBar.Width; _replaceBar.Height = this.Height; } if (_formatPop != null) { _formatPop.Left = this.Width - rigWidth() - _formatPop.Width; _formatPop.Top = this.Height - botHeight() - _formatPop.Height; } } public JovianEdit() { _DataBase = new Jovian.Tools.AutoDatabase.SimpleDatabase(); _ScrollLeft = 0; RTF = new rtfDocument(this); InitializeComponent(); curse = new rtfDisplayCursor(); CursorPen = new Pen(Color.Black, 2); CursorPenDrag = new Pen(Color.Red, 3); ShowCursor = true; this.Cursor = System.Windows.Forms.Cursors.IBeam; _vertScroll = new VScrollBar(); //_vertScroll.Dock = DockStyle.Right; _vertScroll.Enabled = true; _vertScroll.Anchor = AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom; this.Controls.Add(_vertScroll); _vertScroll.Scroll += new System.Windows.Forms.ScrollEventHandler(this.vScrollBar); _vertScroll.ValueChanged += new System.EventHandler(this.vScrollBar2); _vertScroll.Cursor = System.Windows.Forms.Cursors.Hand; _horzScroll = new HScrollBar(); _horzScroll.Enabled = true; _vertScroll.Anchor = AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Bottom; //_horzScroll.Dock = DockStyle.Bottom; this.Controls.Add(_horzScroll); _horzScroll.Scroll += new System.Windows.Forms.ScrollEventHandler(this.hScrollBar); _horzScroll.ValueChanged += new System.EventHandler(this.hScrollBar2); _horzScroll.Cursor = System.Windows.Forms.Cursors.Hand; this.Controls.Add(autoPick); autoPick.parent = this; PositionScrollBars(); _horzScroll.Invalidate(); _vertScroll.Invalidate(); this.Controls.Add(lbAuto); rightClickMenu.MenuItems.Add("Undo", new System.EventHandler(rightClick_Undo)); rightClickMenu.MenuItems.Add("-"); rightClickMenu.MenuItems.Add("Cut", new System.EventHandler(rightClick_Cut)); rightClickMenu.MenuItems.Add("Copy", new System.EventHandler(rightClick_Copy)); rightClickMenu.MenuItems.Add("Paste", new System.EventHandler(rightClick_Paste)); rightClickMenu.MenuItems.Add("Delete", new System.EventHandler(rightClick_Delete)); rightClickMenu.MenuItems.Add("-"); rightClickMenu.MenuItems.Add("Select All", new System.EventHandler(rightClick_SelectAll)); /* rightClickMenu.MenuItems.Add("Cut", new System.EventHandler(rightClick_Cut)); rightClickMenu.MenuItems.Add("Cut", new System.EventHandler(rightClick_Cut)); rightClickMenu.MenuItems.Add("Cut", new System.EventHandler(rightClick_Cut)); rightClickMenu.MenuItems.Add("Cut", new System.EventHandler(rightClick_Cut)); */ this.Text = ""; //this.hScrollBar1.ValueChanged += new System.EventHandler(this.hScrollBar1_ValueChanged); //this.hScrollBar1.Scroll += new System.Windows.Forms.ScrollEventHandler(this.hScrollBar1_Scroll); } private void rightClick_Cut(object sender, System.EventArgs e) { Cut(); } private void rightClick_Copy(object sender, System.EventArgs e) { Copy(); } private void rightClick_Paste(object sender, System.EventArgs e) { Paste(); } private void rightClick_Delete(object sender, System.EventArgs e) { Delete(); } private void rightClick_Undo(object sender, System.EventArgs e) { Undo(); } private void rightClick_SelectAll(object sender, System.EventArgs e) { SelectAll(); } protected override void OnMove(EventArgs e) { PositionScrollBars(); base.OnMove(e); } protected override void OnResize(EventArgs e) { PositionScrollBars(); base.OnResize(e); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { this.cursorTimer.Enabled = false; if (disposing) { if (components != null) components.Dispose(); } base.Dispose(disposing); } #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.cursorTimer = new System.Timers.Timer(); this.printer = new System.Drawing.Printing.PrintDocument(); this.printDialog = new System.Windows.Forms.PrintDialog(); this.rightClickMenu = new System.Windows.Forms.ContextMenu(); this.autoPick = new Jovian.Tools.Support.AutoCompleteListBox(); this.lbAuto = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.cursorTimer)).BeginInit(); // // cursorTimer // this.cursorTimer.Enabled = true; this.cursorTimer.Interval = 20; this.cursorTimer.SynchronizingObject = this; this.cursorTimer.Elapsed += new System.Timers.ElapsedEventHandler(this.cursorTimer_Elapsed); // // printer // this.printer.DocumentName = "JovianEditDoc"; this.printer.BeginPrint += new System.Drawing.Printing.PrintEventHandler(this.printer_BeginPrint); this.printer.EndPrint += new System.Drawing.Printing.PrintEventHandler(this.printer_EndPrint); this.printer.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.printer_PrintPage); // // printDialog // this.printDialog.Document = this.printer; // // autoPick // this.autoPick.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(255)), ((System.Byte)(192))); this.autoPick.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.autoPick.Cursor = System.Windows.Forms.Cursors.Arrow; this.autoPick.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.autoPick.ForeColor = System.Drawing.Color.Navy; this.autoPick.Items.AddRange(new object[] { "a", "b", "c"}); this.autoPick.Location = new System.Drawing.Point(441, 17); this.autoPick.Name = "autoPick"; this.autoPick.Size = new System.Drawing.Size(200, 160); this.autoPick.TabIndex = 0; this.autoPick.Visible = false; this.autoPick.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.autoPick_KeyPress); this.autoPick.MouseUp += new System.Windows.Forms.MouseEventHandler(this.autoPick_MouseUp); // // lbAuto // this.lbAuto.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(224)), ((System.Byte)(192))); this.lbAuto.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.lbAuto.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.lbAuto.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.lbAuto.ForeColor = System.Drawing.Color.Navy; this.lbAuto.Location = new System.Drawing.Point(534, 17); this.lbAuto.Name = "lbAuto"; this.lbAuto.TabIndex = 0; this.lbAuto.Visible = false; ((System.ComponentModel.ISupportInitialize)(this.cursorTimer)).EndInit(); } #endregion public void Copy() { string txt = RTF.ExtractSelection(); if (txt == null) txt = "" + (char)13; if (txt.Length == 0) txt = "" + (char)13; Clipboard.SetDataObject(txt, true); } public void Cut() { string txt = RTF.ExtractSelection(); if (txt == null) txt = "" + (char)13; if (txt.Length == 0) txt = "" + (char)13; Clipboard.SetDataObject(txt, true); RTF.DelCurSelUndo(); } public void Paste() { IDataObject ido = Clipboard.GetDataObject(); if (ido != null) { bool hasStr = false; string[] formats = ido.GetFormats(); foreach (string x in formats) if (x.Equals("System.String")) hasStr = true; if (hasStr) { String X = Clipboard.GetDataObject().GetData("System.String") as String; if (X != null) { RTF.Insert(X); } } } } public void SelectAll() { RTF.SelectAll(); } public void Find() { InstallFindBar(); } public void DateTimeStamp() { RTF.InsertTimeStamp(); } public void IncreaseFont() { RTF.Library.Increase(); Invalidate(); } public void DecreaseFont() { RTF.Library.Decrease(); Invalidate(); } public void AdvancedFormatting() { InstallFormatting(); } public void Replace() { InstallReplaceBar(); } public void Delete() { ProcessDialogKey(Keys.Delete); } protected override void OnKeyPress(KeyPressEventArgs e) { if ((int)e.KeyChar == 12) { string txt = new Formating.ExtractStrings().apply(RTF); if (txt.Length > 0) { Clipboard.SetDataObject(txt, true); } } if ((int)e.KeyChar == 11) { AdvancedFormatting(); } if ((int)e.KeyChar == 16) { Print(); } if ((int)e.KeyChar == 19) { RTF.SearchNext(); } if ((int)e.KeyChar == 23) { IncreaseFont(); } if ((int)e.KeyChar == 17) { DecreaseFont(); } if ((int)e.KeyChar == 3) { Copy(); } else if ((int)e.KeyChar == 26) { RTF.Undo(); } else if ((int)e.KeyChar == 20) { DateTimeStamp(); } else if ((int)e.KeyChar == 6) { Find(); } else if ((int)e.KeyChar == 25) { RTF.Redo(); } else if ((int)e.KeyChar == 24) { Cut(); } else if ((int)e.KeyChar == 22) { Paste(); } else if ((int)e.KeyChar == 1) { SelectAll(); } else { if (e.KeyChar >= 32) { if ((int)e.KeyChar != 13) RTF.OnKey(e.KeyChar, ShiftDown); } } CharTrigger(e.KeyChar); AutoHidePickerChk(); } bool ShiftDown = false; protected override void OnKeyDown(KeyEventArgs e) { //MessageBox.Show("DASD" + e.KeyData); ShiftDown = e.Shift; if (ShiftDown) { if (RTF.OnSpecial(Keys.ShiftKey | Keys.Shift, true)) return; } base.OnKeyDown(e); } protected override void OnKeyUp(KeyEventArgs e) { bool was = ShiftDown; ShiftDown = e.Shift; bool now = ShiftDown; if (was && !now) { if (RTF.OnSpecial(Keys.ShiftKey | Keys.Shift, false)) return; } base.OnKeyUp(e); } public bool ExtDialogKey(Keys keyData) { return ProcessDialogKey(keyData); } protected override bool ProcessDialogKey(Keys keyData) { if (keyData == (Keys.Control | Keys.Space)) { this.ShowPicker(); return true; } if (keyData == Keys.F2) { InstallFindBar(); return true; } if (keyData == Keys.F3) { if (_findBar == null) { InstallFindBar(); } InstallReplaceBar(); return true; } bool good = this.Focused || autoPick.Focused;// _findBar == null; if (_findBar != null) { //good = !_findBar.Focused; } if (keyData == (Keys.ShiftKey | Keys.Shift)) return base.ProcessDialogKey(keyData); if (good) { if (autoPick.Visible) { if (keyData == Keys.Down) { AutoDelta(1); return true; } else if (keyData == Keys.Up) { AutoDelta(-1); return true; } else if (keyData == Keys.PageDown) { AutoDelta(10); return true; } else if (keyData == Keys.PageUp) { AutoDelta(-10); return true; } else if (keyData == Keys.Enter) { if (!AutoComplete()) { return RTF.OnSpecial(keyData, ShiftDown); } return true; } else { bool x = RTF.OnSpecial(keyData, ShiftDown); AutoHidePickerChk(); return x; } } else { return RTF.OnSpecial(keyData, ShiftDown); } } return base.ProcessDialogKey(keyData); } bool LeftDown = false; protected override void OnMouseWheel(MouseEventArgs e) { int dC = (-e.Delta / 60); if (Math.Abs(dC) > 0) { RTF.Wheel(dC); } base.OnMouseWheel(e); } int LastX = 0; int LastY = 0; protected override void OnDoubleClick(EventArgs e) { RTF.OnDoubleClick(LastX, LastY); } private bool drag_Selection; private rtfSelectionObject drag_Start; private rtfSelectionObject drag_End; private string drag_Txt; protected override void OnMouseDown(MouseEventArgs e) { drag_Start = null; drag_End = null; drag_Selection = false; LastX = e.X; LastY = e.Y; this.Focus(); if (e.Button == MouseButtons.Left) { if (IdealDragText) { drag_Start = RTF.GetSTART(); drag_End = RTF.GetEND(); if (drag_Start != null && drag_End != null) { drag_Txt = RTF.ExtractSelection(); drag_Selection = true; this.Cursor = System.Windows.Forms.Cursors.Cross; RTF.BackupCursor(); IdealDragText = false; } //MessageBox.Show("DRAG"); } else { LeftDown = true; RTF.OnLeftMouseDown(e.X, e.Y); } } } /* * * public int CursorX() { int x = _LeftMargin - _LeftTranslation; for(int k = 0; k < _Size; k++) { if(_Cursor==k) return x; x += _Line[k].w; } return x; } */ public void FitCursor(int x) { if (x < 50 + _ScrollLeft) { _ScrollLeft = 0; _horzScroll.Value = 0; } if (x > this.Width - (rigWidth() + 50)) { _ScrollLeft = x - (this.Width - rigWidth() - 50); _horzScroll.Value = _ScrollLeft; } //_ScrollLeft //this.Width - } private bool IdealDragText = false; protected override void OnMouseMove(MouseEventArgs e) { if (drag_Selection) { RTF.OnDrag(e.X, e.Y); Invalidate(); return; } if (LeftDown) { RTF.OnLeftMouseMove(e.X, e.Y); } else { bool next = RTF.OnPassiveMouseMove(e.X, e.Y); if (next != IdealDragText) { if (next) { this.Cursor = System.Windows.Forms.Cursors.Arrow; } else { this.Cursor = System.Windows.Forms.Cursors.IBeam; } } IdealDragText = next; } } protected override void OnMouseUp(MouseEventArgs e) { if (drag_Selection) { RTF.CommitBackup(); RTF.MoveSelection2Point(drag_Start, drag_End, e.X, e.Y); this.Cursor = System.Windows.Forms.Cursors.IBeam; IdealDragText = false; drag_Selection = false; } if (LeftDown) { RTF.OnLeftMouseUp(e.X, e.Y); LeftDown = false; } if (e.Button == MouseButtons.Right) { rightClickMenu.Show(this, new Point(e.X, e.Y)); } AutoHidePickerChk(); } private Bitmap offScreenBmp = null; private Graphics offScreenDC = null; private Brush cornerBrush = new SolidBrush(Color.White); protected override void OnPaint(PaintEventArgs pe) { pe.Graphics.Clip = new Region(pe.ClipRectangle); if (this.Width <= 0) return; if (this.Height <= 0) return; if (offScreenBmp == null) { offScreenBmp = new Bitmap(this.Width, this.Height); offScreenDC = Graphics.FromImage(offScreenBmp); } else if (offScreenBmp.Width != this.Width || offScreenBmp.Height != this.Height) { offScreenBmp = new Bitmap(this.Width, this.Height); offScreenDC = Graphics.FromImage(offScreenBmp); // offScreenDC.SmoothingMode = SmoothingMode.HighSpeed; // offScreenDC.CompositingQuality = CompositingQuality.HighSpeed; // offScreenDC.InterpolationMode = InterpolationMode.Low; } /* * //offScreenDC = pe.Graphics; drawBackground(offScreenDC); drawLayer0(offScreenDC); pe.Graphics.DrawImage(offScreenBmp, 0, 0); */ offScreenDC.Clear(Color.White); RTF.Render(offScreenDC, pe.ClipRectangle, curse, _ScrollLeft, this.Height - botHeight()); pe.Graphics.DrawImage(offScreenBmp, 0, 0); if (ShowCursor && curse.h > 0) { pe.Graphics.DrawLine(CursorPen, curse.x, curse.y, curse.x, curse.y + curse.h); } if (RTF.IsCursorAlwaysOn() && curse.h > 0) { pe.Graphics.DrawLine(CursorPenDrag, curse.x, curse.y, curse.x, curse.y + curse.h); } // pe.Graphics.DrawString("" + _vertScroll.Value + ":" + _vertScroll.Maximum,new Font("Arial",12),new SolidBrush(Color.Red),100,100); int docWidth = RTF.Width(); int cliWidth = this.Width - 50 - rigWidth(); int scrWidth = docWidth - cliWidth; try { if (scrWidth > 0) { _horzScroll.Enabled = true; _horzScroll.Maximum = docWidth + 15; _horzScroll.SmallChange = 1; _horzScroll.LargeChange = cliWidth; } else { _ScrollLeft = 0; _horzScroll.Value = 0; _horzScroll.Enabled = false; } } catch (Exception zztop) { } pe.Graphics.FillRectangle(cornerBrush, this.Width - rigWidth(), this.Height - botHeight(), _vertScroll.Width, _horzScroll.Height); /* if(ShowCursor) pe.Graphics.DrawString("[",RTF.Library.TabFont,RTF.Library.LineNumberColor,this.Width - rigWidth(),this.Height - botHeight()); else pe.Graphics.DrawString("J",RTF.Library.TabFont,RTF.Library.LineNumberColor,this.Width - rigWidth(),this.Height - botHeight()); */ try { if (RTF.Height() > (this.Height - botHeight()) || RTF.Top() > 0) { _vertScroll.LargeChange = RTF.RenderedLines(); _vertScroll.Enabled = true; _vertScroll.Value = RTF.Top(); _vertScroll.Maximum = Math.Max(0, RTF.NumLines()); } else { _vertScroll.Enabled = false; //_vertScroll.Value = 0; //RTF.SetTop(0); } } catch (Exception zztop) { } /* pe.Graphics.Clear(Color.White); RTF.Render(pe.Graphics,pe.ClipRectangle,curse); if(ShowCursor && curse.h > 0) { pe.Graphics.DrawLine(CursorPen,curse.x,curse.y,curse.x,curse.y+curse.h); } */ } protected override void OnPaintBackground(PaintEventArgs pevent) { } private int Delta = 1; private void UpdateD(int d) { Delta = Math.Max(1, 30 - d / 2); } private void UpdateD2(int d) { Delta = Math.Max(1, d / 5); } private void AutoScrollLogic() { Rectangle R = this.RectangleToScreen(this.Bounds); Point P = Cursor.Position; if (P.Y < R.Y) { UpdateD2(R.Y - P.Y); if (RTF.AutoScrollUp(Delta)) { Invalidate(); RTF.RepeatSelectLogic(); _vertScroll.Value = Math.Min(_vertScroll.Maximum, RTF.Top()); } } if (P.Y > R.Y + R.Height) { UpdateD2(P.Y - (R.Y + R.Height)); if (RTF.AutoScrollDown(Delta)) { Invalidate(); RTF.RepeatSelectLogic(); _vertScroll.Value = Math.Min(_vertScroll.Maximum, RTF.Top()); } } if (P.X < R.X) { UpdateD2(R.X - P.X); _horzScroll.Value = Math.Max(0, _horzScroll.Value - Delta); } if (P.X > R.X + R.Width) { UpdateD2(P.X - (R.X + R.Width)); _horzScroll.Value = Math.Min(_horzScroll.Maximum - _horzScroll.LargeChange, _horzScroll.Value + Delta); } } int CursorChange = 0; int DeltaChange = 0; private void cursorTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { if (this.Focused || autoPick.Focused) { CursorChange++; DeltaChange++; CursorChange %= 15; if (CursorChange == 0) { ShowCursor = !ShowCursor; this.Invalidate(); } if (LeftDown) { AutoScrollLogic(); this.Invalidate(); } } else { ShowCursor = false; } } private void hScrollBar(object sender, System.Windows.Forms.ScrollEventArgs e) { _ScrollLeft = _horzScroll.Value; this.Invalidate(); } private void vScrollBar(object sender, System.Windows.Forms.ScrollEventArgs e) { } private void vScrollBar2(object sender, System.EventArgs e) { RTF.SetTop(_vertScroll.Value); this.Invalidate(); } private void hScrollBar2(object sender, System.EventArgs e) { _ScrollLeft = Math.Max(0, _horzScroll.Value); this.Invalidate(); } public void Print() { if (printDialog.ShowDialog() == DialogResult.OK) { printer.Print(); } } string _PrintTitle = "Page"; public string Title { get { return _PrintTitle; } set { _PrintTitle = value; } } int PageNumber; int PrintLineStart; private void printer_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e) { PageNumber = 1; PrintLineStart = 0; } private void printer_EndPrint(object sender, System.Drawing.Printing.PrintEventArgs e) { } private void printer_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { int Hei = e.PageBounds.Height; Size Sz = e.Graphics.MeasureString(_PrintTitle + " [" + PageNumber + "]", new Font("Arial", 14)).ToSize(); e.Graphics.DrawString(_PrintTitle + " [" + PageNumber + "]", new Font("Arial", 14), new SolidBrush(Color.Black), 50, 25); e.Graphics.DrawLine(new Pen(Color.Black), 50, 25 + Sz.Height + 1, e.PageBounds.Width - 70, 25 + Sz.Height + 1); e.Graphics.TranslateTransform(50, 25 + Sz.Height + 3); PrintLineStart += RTF.PrintPage(PageNumber, PrintLineStart, e.Graphics, Hei - (75 + Sz.Height + 3), e.PageBounds.Width - 120); e.HasMorePages = PrintLineStart < RTF.NumLines(); PageNumber++; } public void Undo() { RTF.Undo(); } public void Redo() { RTF.Redo(); } private void autoPick_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { if (e.KeyChar == 13 || e.KeyChar == 10) { this.AutoComplete(); e.Handled = true; } this.OnKeyPress(e); } private void autoPick_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) { if (autoPick.SelectedIndex >= 0) { AutoComplete(); } } private void autoPick_SelectedValueChanged(object sender, System.EventArgs e) { if (autoPick.SelectedIndex >= 0) { AutoInfo(); } } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Messages.Messages File: CandleMessage.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Messages { using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using Ecng.Common; using Ecng.Serialization; using StockSharp.Localization; /// <summary> /// Candle states. /// </summary> [System.Runtime.Serialization.DataContract] [Serializable] public enum CandleStates { /// <summary> /// Empty state (candle doesn't exist). /// </summary> [EnumMember] None, /// <summary> /// Candle active. /// </summary> [EnumMember] Active, /// <summary> /// Candle finished. /// </summary> [EnumMember] Finished, } /// <summary> /// The message contains information about the candle. /// </summary> [System.Runtime.Serialization.DataContract] [Serializable] public abstract class CandleMessage : Message { /// <summary> /// Security ID. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.SecurityIdKey)] [DescriptionLoc(LocalizedStrings.SecurityIdKey, true)] [MainCategory] public SecurityId SecurityId { get; set; } /// <summary> /// Open time. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.CandleOpenTimeKey)] [DescriptionLoc(LocalizedStrings.CandleOpenTimeKey, true)] [MainCategory] public DateTimeOffset OpenTime { get; set; } /// <summary> /// Time of candle high. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.CandleHighTimeKey)] [DescriptionLoc(LocalizedStrings.CandleHighTimeKey, true)] [MainCategory] public DateTimeOffset HighTime { get; set; } /// <summary> /// Time of candle low. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.CandleLowTimeKey)] [DescriptionLoc(LocalizedStrings.CandleLowTimeKey, true)] [MainCategory] public DateTimeOffset LowTime { get; set; } /// <summary> /// Close time. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.CandleCloseTimeKey)] [DescriptionLoc(LocalizedStrings.CandleCloseTimeKey, true)] [MainCategory] public DateTimeOffset CloseTime { get; set; } /// <summary> /// Opening price. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.Str79Key)] [DescriptionLoc(LocalizedStrings.Str80Key)] [MainCategory] public decimal OpenPrice { get; set; } /// <summary> /// Maximum price. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.Str81Key)] [DescriptionLoc(LocalizedStrings.Str82Key)] [MainCategory] public decimal HighPrice { get; set; } /// <summary> /// Minimum price. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.Str83Key)] [DescriptionLoc(LocalizedStrings.Str84Key)] [MainCategory] public decimal LowPrice { get; set; } /// <summary> /// Closing price. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.ClosingPriceKey)] [DescriptionLoc(LocalizedStrings.Str86Key)] [MainCategory] public decimal ClosePrice { get; set; } /// <summary> /// Volume at open. /// </summary> [DataMember] [Nullable] public decimal? OpenVolume { get; set; } /// <summary> /// Volume at close. /// </summary> [DataMember] [Nullable] public decimal? CloseVolume { get; set; } /// <summary> /// Volume at high. /// </summary> [DataMember] [Nullable] public decimal? HighVolume { get; set; } /// <summary> /// Minimum volume. /// </summary> [DataMember] [Nullable] public decimal? LowVolume { get; set; } /// <summary> /// Relative colume. /// </summary> [DataMember] public decimal? RelativeVolume { get; set; } /// <summary> /// Total volume. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.VolumeKey)] [DescriptionLoc(LocalizedStrings.TotalCandleVolumeKey)] [MainCategory] public decimal TotalVolume { get; set; } /// <summary> /// Open interest. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.OIKey)] [DescriptionLoc(LocalizedStrings.OpenInterestKey)] [MainCategory] public decimal? OpenInterest { get; set; } /// <summary> /// Number of ticks. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.TicksKey)] [DescriptionLoc(LocalizedStrings.TickCountKey)] [MainCategory] public int? TotalTicks { get; set; } /// <summary> /// Number of uptrending ticks. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.TickUpKey)] [DescriptionLoc(LocalizedStrings.TickUpCountKey)] [MainCategory] public int? UpTicks { get; set; } /// <summary> /// Number of downtrending ticks. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.TickDownKey)] [DescriptionLoc(LocalizedStrings.TickDownCountKey)] [MainCategory] public int? DownTicks { get; set; } /// <summary> /// State. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.StateKey)] [DescriptionLoc(LocalizedStrings.CandleStateKey)] [MainCategory] public CandleStates State { get; set; } /// <summary> /// ID of the original message <see cref="MarketDataMessage.TransactionId"/> for which this message is a response. /// </summary> [DataMember] public long OriginalTransactionId { get; set; } /// <summary> /// It is the last message in the requested batch of candles. /// </summary> [DataMember] public bool IsFinished { get; set; } /// <summary> /// Price levels. /// </summary> [DataMember] public IEnumerable<CandlePriceLevel> PriceLevels { get; set; } /// <summary> /// Candle arg. /// </summary> public abstract object Arg { get; set; } /// <summary> /// Initialize <see cref="CandleMessage"/>. /// </summary> /// <param name="type">Message type.</param> protected CandleMessage(MessageTypes type) : base(type) { } /// <summary> /// Copy parameters. /// </summary> /// <param name="copy">Copy.</param> /// <returns>Copy.</returns> protected CandleMessage CopyTo(CandleMessage copy) { if (copy == null) throw new ArgumentNullException(nameof(copy)); copy.LocalTime = LocalTime; copy.ClosePrice = ClosePrice; copy.CloseTime = CloseTime; copy.CloseVolume = CloseVolume; copy.HighPrice = HighPrice; copy.HighVolume = HighVolume; copy.LowPrice = LowPrice; copy.LowVolume = LowVolume; copy.OpenInterest = OpenInterest; copy.OpenPrice = OpenPrice; copy.OpenTime = OpenTime; copy.OpenVolume = OpenVolume; copy.SecurityId = SecurityId; copy.TotalVolume = TotalVolume; copy.RelativeVolume = RelativeVolume; copy.OriginalTransactionId = OriginalTransactionId; copy.DownTicks = DownTicks; copy.UpTicks = UpTicks; copy.TotalTicks = TotalTicks; copy.IsFinished = IsFinished; copy.PriceLevels = PriceLevels?.Select(l => l.Clone()).ToArray(); return copy; } /// <summary> /// Returns a string that represents the current object. /// </summary> /// <returns>A string that represents the current object.</returns> public override string ToString() { return $"{Type},T={OpenTime:yyyy/MM/dd HH:mm:ss.fff},O={OpenPrice},H={HighPrice},L={LowPrice},C={ClosePrice},V={TotalVolume}"; } } /// <summary> /// The message contains information about the time-frame candle. /// </summary> [System.Runtime.Serialization.DataContract] [Serializable] public class TimeFrameCandleMessage : CandleMessage { /// <summary> /// Initializes a new instance of the <see cref="TimeFrameCandleMessage"/>. /// </summary> public TimeFrameCandleMessage() : base(MessageTypes.CandleTimeFrame) { } /// <summary> /// Time-frame. /// </summary> [DataMember] public TimeSpan TimeFrame { get; set; } /// <summary> /// Create a copy of <see cref="TimeFrameCandleMessage"/>. /// </summary> /// <returns>Copy.</returns> public override Message Clone() { return CopyTo(new TimeFrameCandleMessage { TimeFrame = TimeFrame }); } /// <summary> /// Candle arg. /// </summary> public override object Arg { get { return TimeFrame; } set { TimeFrame = (TimeSpan)value; } } } /// <summary> /// The message contains information about the tick candle. /// </summary> [System.Runtime.Serialization.DataContract] [Serializable] public class TickCandleMessage : CandleMessage { /// <summary> /// Initializes a new instance of the <see cref="TickCandleMessage"/>. /// </summary> public TickCandleMessage() : base(MessageTypes.CandleTick) { } /// <summary> /// Maximum tick count. /// </summary> [DataMember] public int MaxTradeCount { get; set; } /// <summary> /// Create a copy of <see cref="TickCandleMessage"/>. /// </summary> /// <returns>Copy.</returns> public override Message Clone() { return CopyTo(new TickCandleMessage { MaxTradeCount = MaxTradeCount }); } /// <summary> /// Candle arg. /// </summary> public override object Arg { get { return MaxTradeCount; } set { MaxTradeCount = (int)value; } } } /// <summary> /// The message contains information about the volume candle. /// </summary> [System.Runtime.Serialization.DataContract] [Serializable] public class VolumeCandleMessage : CandleMessage { /// <summary> /// Initializes a new instance of the <see cref="VolumeCandleMessage"/>. /// </summary> public VolumeCandleMessage() : base(MessageTypes.CandleVolume) { } /// <summary> /// Maximum volume. /// </summary> [DataMember] public decimal Volume { get; set; } /// <summary> /// Create a copy of <see cref="VolumeCandleMessage"/>. /// </summary> /// <returns>Copy.</returns> public override Message Clone() { return CopyTo(new VolumeCandleMessage { Volume = Volume }); } /// <summary> /// Candle arg. /// </summary> public override object Arg { get { return Volume; } set { Volume = (decimal)value; } } } /// <summary> /// The message contains information about the range candle. /// </summary> [System.Runtime.Serialization.DataContract] [Serializable] public class RangeCandleMessage : CandleMessage { /// <summary> /// Initializes a new instance of the <see cref="RangeCandleMessage"/>. /// </summary> public RangeCandleMessage() : base(MessageTypes.CandleRange) { } /// <summary> /// Range of price. /// </summary> [DataMember] public Unit PriceRange { get; set; } /// <summary> /// Create a copy of <see cref="RangeCandleMessage"/>. /// </summary> /// <returns>Copy.</returns> public override Message Clone() { return CopyTo(new RangeCandleMessage { PriceRange = PriceRange }); } /// <summary> /// Candle arg. /// </summary> public override object Arg { get { return PriceRange; } set { PriceRange = (Unit)value; } } } /// <summary> /// Symbol types. /// </summary> [System.Runtime.Serialization.DataContract] [Serializable] public enum PnFTypes { /// <summary> /// X (price up). /// </summary> [EnumMember] X, /// <summary> /// 0 (price down). /// </summary> [EnumMember] O, } /// <summary> /// Point in fugure (X0) candle arg. /// </summary> [System.Runtime.Serialization.DataContract] [Serializable] public class PnFArg : Equatable<PnFArg> { private Unit _boxSize = new Unit(); /// <summary> /// Range of price above which create a new <see cref="PnFTypes.X"/> or <see cref="PnFTypes.O"/>. /// </summary> [DataMember] public Unit BoxSize { get { return _boxSize; } set { if (value == null) throw new ArgumentNullException(nameof(value)); _boxSize = value; } } /// <summary> /// The number of boxes (an <see cref="PnFTypes.X"/> or an <see cref="PnFTypes.O"/>) required to cause a reversal. /// </summary> [DataMember] public int ReversalAmount { get; set; } /// <summary> /// Returns a string that represents the current object. /// </summary> /// <returns>A string that represents the current object.</returns> public override string ToString() { return $"Box = {BoxSize} RA = {ReversalAmount}"; } /// <summary> /// Create a copy of <see cref="PnFArg"/>. /// </summary> /// <returns>Copy.</returns> public override PnFArg Clone() { return new PnFArg { BoxSize = BoxSize.Clone(), ReversalAmount = ReversalAmount, }; } /// <summary> /// Compare <see cref="PnFArg"/> on the equivalence. /// </summary> /// <param name="other">Another value with which to compare.</param> /// <returns><see langword="true" />, if the specified object is equal to the current object, otherwise, <see langword="false" />.</returns> protected override bool OnEquals(PnFArg other) { return other.BoxSize == BoxSize && other.ReversalAmount == ReversalAmount; } /// <summary> /// Get the hash code of the object <see cref="PnFArg"/>. /// </summary> /// <returns>A hash code.</returns> public override int GetHashCode() { return BoxSize.GetHashCode() ^ ReversalAmount.GetHashCode(); } } /// <summary> /// The message contains information about the XO candle. /// </summary> [System.Runtime.Serialization.DataContract] [Serializable] public class PnFCandleMessage : CandleMessage { /// <summary> /// Initializes a new instance of the <see cref="PnFCandleMessage"/>. /// </summary> public PnFCandleMessage() : base(MessageTypes.CandlePnF) { } /// <summary> /// Value of arguments. /// </summary> [DataMember] public PnFArg PnFArg { get; set; } /// <summary> /// Type of symbols. /// </summary> [DataMember] public PnFTypes PnFType { get; set; } /// <summary> /// Create a copy of <see cref="PnFCandleMessage"/>. /// </summary> /// <returns>Copy.</returns> public override Message Clone() { return CopyTo(new PnFCandleMessage { PnFArg = PnFArg, PnFType = PnFType }); } /// <summary> /// Candle arg. /// </summary> public override object Arg { get { return PnFArg; } set { PnFArg = (PnFArg)value; } } } /// <summary> /// The message contains information about the renko candle. /// </summary> [System.Runtime.Serialization.DataContract] [Serializable] public class RenkoCandleMessage : CandleMessage { /// <summary> /// Initializes a new instance of the <see cref="RenkoCandleMessage"/>. /// </summary> public RenkoCandleMessage() : base(MessageTypes.CandleRenko) { } /// <summary> /// Possible price change range. /// </summary> [DataMember] public Unit BoxSize { get; set; } /// <summary> /// Create a copy of <see cref="RenkoCandleMessage"/>. /// </summary> /// <returns>Copy.</returns> public override Message Clone() { return CopyTo(new RenkoCandleMessage { BoxSize = BoxSize }); } /// <summary> /// Candle arg. /// </summary> public override object Arg { get { return BoxSize; } set { BoxSize = (Unit)value; } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections; using System.ComponentModel; using System.Reflection; using System.Diagnostics.Contracts; namespace System.Data { // Summary: // Represents the collection of System.Data.DataRelation objects for this System.Data.DataSet. //[DefaultProperty("Table")] //[DefaultEvent("CollectionChanged")] //[Editor("Microsoft.VSDesigner.Data.Design.DataRelationCollectionEditor, Microsoft.VSDesigner, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public abstract class DataRelationCollection //: InternalDataCollectionBase { // Summary: // Initializes a new instance of the System.Data.DataRelationCollection class. //protected DataRelationCollection(); // Summary: // Gets the System.Data.DataRelation object at the specified index. // // Parameters: // index: // The zero-based index to find. // // Returns: // The System.Data.DataRelation, or a null value if the specified System.Data.DataRelation // does not exist. // // Exceptions: // System.IndexOutOfRangeException: // The index value is greater than the number of items in the collection. //public abstract DataRelation this[int index] { get; } // // Summary: // Gets the System.Data.DataRelation object specified by name. // // Parameters: // name: // The name of the relation to find. // // Returns: // The named System.Data.DataRelation, or a null value if the specified System.Data.DataRelation // does not exist. //public abstract DataRelation this[string name] { get; } // Summary: // Occurs when the collection has changed. //[ResDescription("collectionChangedEventDescr")] //public event CollectionChangeEventHandler CollectionChanged; // Summary: // Adds a System.Data.DataRelation to the System.Data.DataRelationCollection. // // Parameters: // relation: // The DataRelation to add to the collection. // // Exceptions: // System.ArgumentNullException: // The relation parameter is a null value. // // System.ArgumentException: // The relation already belongs to this collection, or it belongs to another // collection. // // System.Data.DuplicateNameException: // The collection already has a relation with the specified name. (The comparison // is not case sensitive.) // // System.Data.InvalidConstraintException: // The relation has entered an invalid state since it was created. public void Add(DataRelation relation) { Contract.Requires(relation != null); } // Summary: // Creates a System.Data.DataRelation with a specified parent and child column, // and adds it to the collection. // // Parameters: // parentColumn: // The parent column of the relation. // // childColumn: // The child column of the relation. // // Returns: // The created relation. public virtual DataRelation Add(DataColumn parentColumn, DataColumn childColumn) { Contract.Ensures(Contract.Result<DataRelation>() != null); return default(DataRelation); } // // Summary: // Creates a System.Data.DataRelation with the specified parent and child columns, // and adds it to the collection. // // Parameters: // parentColumns: // The parent columns of the relation. // // childColumns: // The child columns of the relation. // // Returns: // The created relation. // // Exceptions: // System.ArgumentNullException: // The relation argument is a null value. // // System.ArgumentException: // The relation already belongs to this collection, or it belongs to another // collection. // // System.Data.DuplicateNameException: // The collection already has a relation with the same name. (The comparison // is not case sensitive.) // // System.Data.InvalidConstraintException: // The relation has entered an invalid state since it was created. public virtual DataRelation Add(DataColumn[] parentColumns, DataColumn[] childColumns) { Contract.Ensures(Contract.Result<DataRelation>() != null); return default(DataRelation); } // // Summary: // Creates a System.Data.DataRelation with the specified name, and parent and // child columns, and adds it to the collection. // // Parameters: // name: // The name of the relation. // // parentColumn: // The parent column of the relation. // // childColumn: // The child column of the relation. // // Returns: // The created relation. public virtual DataRelation Add(string name, DataColumn parentColumn, DataColumn childColumn) { Contract.Ensures(Contract.Result<DataRelation>() != null); return default(DataRelation); } // // Summary: // Creates a System.Data.DataRelation with the specified name and arrays of // parent and child columns, and adds it to the collection. // // Parameters: // name: // The name of the DataRelation to create. // // parentColumns: // An array of parent System.Data.DataColumn objects. // // childColumns: // An array of child DataColumn objects. // // Returns: // The created DataRelation. // // Exceptions: // System.ArgumentNullException: // The relation name is a null value. // // System.ArgumentException: // The relation already belongs to this collection, or it belongs to another // collection. // // System.Data.DuplicateNameException: // The collection already has a relation with the same name. (The comparison // is not case sensitive.) // // System.Data.InvalidConstraintException: // The relation has entered an invalid state since it was created. public virtual DataRelation Add(string name, DataColumn[] parentColumns, DataColumn[] childColumns) { Contract.Requires(name != null); Contract.Ensures(Contract.Result<DataRelation>() != null); return default(DataRelation); } // // Summary: // Creates a System.Data.DataRelation with the specified name, parent and child // columns, with optional constraints according to the value of the createConstraints // parameter, and adds it to the collection. // // Parameters: // name: // The name of the relation. // // parentColumn: // The parent column of the relation. // // childColumn: // The child column of the relation. // // createConstraints: // true to create constraints; otherwise false. (The default is true). // // Returns: // The created relation. public virtual DataRelation Add(string name, DataColumn parentColumn, DataColumn childColumn, bool createConstraints) { Contract.Ensures(Contract.Result<DataRelation>() != null); return default(DataRelation); } // // Summary: // Creates a System.Data.DataRelation with the specified name, arrays of parent // and child columns, and value specifying whether to create a constraint, and // adds it to the collection. // // Parameters: // name: // The name of the DataRelation to create. // // parentColumns: // An array of parent System.Data.DataColumn objects. // // childColumns: // An array of child DataColumn objects. // // createConstraints: // true to create a constraint; otherwise false. // // Returns: // The created relation. // // Exceptions: // System.ArgumentNullException: // The relation name is a null value. // // System.ArgumentException: // The relation already belongs to this collection, or it belongs to another // collection. // // System.Data.DuplicateNameException: // The collection already has a relation with the same name. (The comparison // is not case sensitive.) // // System.Data.InvalidConstraintException: // The relation has entered an invalid state since it was created. public virtual DataRelation Add(string name, DataColumn[] parentColumns, DataColumn[] childColumns, bool createConstraints) { Contract.Requires(name != null); Contract.Ensures(Contract.Result<DataRelation>() != null); return default(DataRelation); } // // Summary: // Performs verification on the table. // // Parameters: // relation: // The relation to check. // // Exceptions: // System.ArgumentNullException: // The relation is null. // // System.ArgumentException: // The relation already belongs to this collection, or it belongs to another // collection. // // System.Data.DuplicateNameException: // The collection already has a relation with the same name. (The comparison // is not case sensitive.) protected virtual void AddCore(DataRelation relation) { Contract.Requires(relation != null); } // // Summary: // Copies the elements of the specified System.Data.DataRelation array to the // end of the collection. // // Parameters: // relations: // The array of System.Data.DataRelation objects to add to the collection. //public virtual void AddRange(DataRelation[] relations); // // // Summary: // Raises the System.Data.DataRelationCollection.CollectionChanged event. // // Parameters: // ccevent: // A System.ComponentModel.CollectionChangeEventArgs that contains the event // data. //protected virtual void OnCollectionChanged(CollectionChangeEventArgs ccevent); // // Summary: // Raises the System.Data.DataRelationCollection.CollectionChanged event. // // Parameters: // ccevent: // A System.ComponentModel.CollectionChangeEventArgs that contains the event // data. //protected virtual void OnCollectionChanging(CollectionChangeEventArgs ccevent); // // Summary: // Removes the specified relation from the collection. // // Parameters: // relation: // The relation to remove. // // Exceptions: // System.ArgumentNullException: // The relation is a null value. // // System.ArgumentException: //// The relation does not belong to the collection. //public void Remove(DataRelation relation); //// //// Summary: //// Removes the relation with the specified name from the collection. //// //// Parameters: //// name: //// The name of the relation to remove. //// //// Exceptions: //// System.IndexOutOfRangeException: //// The collection does not have a relation with the specified name. //public void Remove(string name); //// //// Summary: //// Removes the relation at the specified index from the collection. //// //// Parameters: //// index: //// The index of the relation to remove. //// //// Exceptions: //// System.ArgumentException: //// The collection does not have a relation at the specified index. //public void RemoveAt(int index); //// //// Summary: //// Performs a verification on the specified System.Data.DataRelation object. //// //// Parameters: //// relation: //// The DataRelation object to verify. //// //// Exceptions: //// System.ArgumentNullException: //// The collection does not have a relation at the specified index. //// //// System.ArgumentException: //// The specified relation does not belong to this collection, or it belongs //// to another collection. //protected virtual void RemoveCore(DataRelation relation); } }
using System.Collections.Generic; using Cake.Common.Tests.Fixtures.Tools; using Cake.Common.Tools.Fixie; using Cake.Core; using Cake.Core.IO; using Cake.Testing; using Cake.Testing.Xunit; using NSubstitute; using Xunit; namespace Cake.Common.Tests.Unit.Tools.Fixie { public sealed class FixieRunnerTests { public sealed class TheRunMethod { [Fact] public void Should_Throw_If_Assembly_Paths_Are_Null() { // Given var fixture = new FixieRunnerFixture(); fixture.AssemblyPaths = null; // When var result = Record.Exception(() => fixture.Run()); // Then Assert.IsArgumentNullException(result, "assemblyPaths"); } [Fact] public void Should_Throw_If_Fixie_Runner_Was_Not_Found() { // Given var fixture = new FixieRunnerFixture(); fixture.GivenDefaultToolDoNotExist(); // When var result = Record.Exception(() => fixture.Run()); // Then Assert.IsType<CakeException>(result); Assert.Equal("Fixie: Could not locate executable.", result.Message); } [Theory] [InlineData("/bin/tools/Fixie/Fixie.Console.exe", "/bin/tools/Fixie/Fixie.Console.exe")] [InlineData("./tools/Fixie/Fixie.Console.exe", "/Working/tools/Fixie/Fixie.Console.exe")] public void Should_Use_Fixie_Runner_From_Tool_Path_If_Provided(string toolPath, string expected) { // Given var fixture = new FixieRunnerFixture(); fixture.Settings.ToolPath = toolPath; fixture.GivenSettingsToolPathExist(); // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Path.FullPath); } [WindowsTheory] [InlineData("C:/Fixie/Fixie.Console.exe", "C:/Fixie/Fixie.Console.exe")] public void Should_Use_Fixie_Runner_From_Tool_Path_If_Provided_On_Windows(string toolPath, string expected) { // Given var fixture = new FixieRunnerFixture(); fixture.Settings.ToolPath = toolPath; fixture.GivenSettingsToolPathExist(); // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Path.FullPath); } [Fact] public void Should_Find_Fixie_Runner_If_Tool_Path_Not_Provided() { // Given var fixture = new FixieRunnerFixture(); // When var result = fixture.Run(); // Then Assert.Equal("/Working/tools/Fixie.Console.exe", result.Path.FullPath); } [Fact] public void Should_Use_Provided_Assembly_Path_In_Process_Arguments() { // Given var fixture = new FixieRunnerFixture(); // When var result = fixture.Run(); // Then Assert.Equal("\"/Working/Test1.dll\"", result.Args); } [Fact] public void Should_Use_Provided_Assembly_Paths_In_Process_Arguments() { // Given var fixture = new FixieRunnerFixture(); fixture.AssemblyPaths.Clear(); fixture.AssemblyPaths.Add("./Test1.dll"); fixture.AssemblyPaths.Add("./Test2.dll"); // When var result = fixture.Run(); // Then Assert.Equal("\"/Working/Test1.dll\" \"/Working/Test2.dll\"", result.Args); } [Fact] public void Should_Set_Working_Directory() { // Given var fixture = new FixieRunnerFixture(); // When var result = fixture.Run(); // Then Assert.Equal("/Working", result.Process.WorkingDirectory.FullPath); } [Fact] public void Should_Throw_If_Process_Was_Not_Started() { // Given var fixture = new FixieRunnerFixture(); fixture.GivenProcessCannotStart(); // When var result = Record.Exception(() => fixture.Run()); // Then Assert.IsType<CakeException>(result); Assert.Equal("Fixie: Process was not started.", result.Message); } [Fact] public void Should_Throw_If_Process_Has_A_Non_Zero_Exit_Code() { // Given var fixture = new FixieRunnerFixture(); fixture.GivenProcessExitsWithCode(1); // When var result = Record.Exception(() => fixture.Run()); // Then Assert.IsType<CakeException>(result); Assert.Equal("Fixie: Process returned an error (exit code 1).", result.Message); } [Fact] public void Should_Set_NUnitXml_Output_File() { // Given var fixture = new FixieRunnerFixture(); fixture.Settings.NUnitXml = "nunit-style-results.xml"; // When var result = fixture.Run(); // Then Assert.Equal("\"/Working/Test1.dll\" " + "--NUnitXml \"/Working/nunit-style-results.xml\"", result.Args); } [Fact] public void Should_Set_xUnitXml_Output_File() { // Given var fixture = new FixieRunnerFixture(); fixture.Settings.XUnitXml = "xunit-results.xml"; // When var result = fixture.Run(); // Then Assert.Equal("\"/Working/Test1.dll\" " + "--xUnitXml \"/Working/xunit-results.xml\"", result.Args); } [Theory] [InlineData(true, "on", "\"/Working/Test1.dll\" --TeamCity on")] [InlineData(false, "off", "\"/Working/Test1.dll\" --TeamCity off")] public void Should_Set_TeamCity_Value(bool teamCityOutput, string teamCityValue, string expected) { // Given var fixture = new FixieRunnerFixture(); fixture.Settings.TeamCity = teamCityOutput; // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Args); } [Fact] public void Should_Set_Custom_Options() { // Given var fixture = new FixieRunnerFixture(); fixture.Settings.WithOption("--include", "CategoryA"); fixture.Settings.WithOption("--include", "CategoryB"); // When var result = fixture.Run(); // Then Assert.Equal("\"/Working/Test1.dll\" " + "--include CategoryA " + "--include CategoryB", result.Args); } [Fact] public void Should_Set_Multiple_Options() { // Given var fixture = new FixieRunnerFixture(); fixture.Settings.WithOption("--type", "fast"); fixture.Settings.WithOption("--include", "CategoryA", "CategoryB"); fixture.Settings.WithOption("--output", "fixie-log.txt"); // When var result = fixture.Run(); // Then Assert.Equal("\"/Working/Test1.dll\" --type fast " + "--include CategoryA --include CategoryB " + "--output fixie-log.txt", result.Args); } } } }
// 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 Microsoft.Build.Framework; using TaskItem = Microsoft.Build.Execution.ProjectItemInstance.TaskItem; namespace Microsoft.Build.UnitTests { internal class MockTaskBase { private bool _myBoolParam = false; private bool[] _myBoolArrayParam = null; private int _myIntParam = 0; private int[] _myIntArrayParam = null; private string _myStringParam = null; private string[] _myStringArrayParam = null; private ITaskItem _myITaskItemParam = null; private ITaskItem[] _myITaskItemArrayParam = null; private bool _myRequiredBoolParam = false; private bool[] _myRequiredBoolArrayParam = null; private int _myRequiredIntParam = 0; private int[] _myRequiredIntArrayParam = null; private string _myRequiredStringParam = null; private string[] _myRequiredStringArrayParam = null; private ITaskItem _myRequiredITaskItemParam = null; private ITaskItem[] _myRequiredITaskItemArrayParam = null; internal bool myBoolParamWasSet = false; internal bool myBoolArrayParamWasSet = false; internal bool myIntParamWasSet = false; internal bool myIntArrayParamWasSet = false; internal bool myStringParamWasSet = false; internal bool myStringArrayParamWasSet = false; internal bool myITaskItemParamWasSet = false; internal bool myITaskItemArrayParamWasSet = false; // disable csharp compiler warning #0414: field assigned unused value #pragma warning disable 0414 internal bool myRequiredBoolParamWasSet = false; internal bool myRequiredBoolArrayParamWasSet = false; internal bool myRequiredIntParamWasSet = false; internal bool myRequiredIntArrayParamWasSet = false; internal bool myRequiredStringParamWasSet = false; internal bool myRequiredStringArrayParamWasSet = false; internal bool myRequiredITaskItemParamWasSet = false; internal bool myRequiredITaskItemArrayParamWasSet = false; #pragma warning restore 0414 /// <summary> /// Single bool parameter. /// </summary> public bool MyBoolParam { get { return _myBoolParam; } set { _myBoolParam = value; this.myBoolParamWasSet = true; } } /// <summary> /// bool[] parameter. /// </summary> public bool[] MyBoolArrayParam { get { return _myBoolArrayParam; } set { _myBoolArrayParam = value; this.myBoolArrayParamWasSet = true; } } /// <summary> /// Single int parameter. /// </summary> public int MyIntParam { get { return _myIntParam; } set { _myIntParam = value; this.myIntParamWasSet = true; } } /// <summary> /// int[] parameter. /// </summary> public int[] MyIntArrayParam { get { return _myIntArrayParam; } set { _myIntArrayParam = value; this.myIntArrayParamWasSet = true; } } /// <summary> /// Single string parameter /// </summary> public string MyStringParam { get { return _myStringParam; } set { _myStringParam = value; this.myStringParamWasSet = true; } } /// <summary> /// A string array parameter. /// </summary> public string[] MyStringArrayParam { get { return _myStringArrayParam; } set { _myStringArrayParam = value; this.myStringArrayParamWasSet = true; } } /// <summary> /// Single ITaskItem parameter. /// </summary> public ITaskItem MyITaskItemParam { get { return _myITaskItemParam; } set { _myITaskItemParam = value; this.myITaskItemParamWasSet = true; } } /// <summary> /// ITaskItem[] parameter. /// </summary> public ITaskItem[] MyITaskItemArrayParam { get { return _myITaskItemArrayParam; } set { _myITaskItemArrayParam = value; this.myITaskItemArrayParamWasSet = true; } } /// <summary> /// Single bool parameter. /// </summary> [Required] public bool MyRequiredBoolParam { get { return _myRequiredBoolParam; } set { _myRequiredBoolParam = value; this.myRequiredBoolParamWasSet = true; } } /// <summary> /// bool[] parameter. /// </summary> [Required] public bool[] MyRequiredBoolArrayParam { get { return _myRequiredBoolArrayParam; } set { _myRequiredBoolArrayParam = value; this.myRequiredBoolArrayParamWasSet = true; } } /// <summary> /// Single int parameter. /// </summary> [Required] public int MyRequiredIntParam { get { return _myRequiredIntParam; } set { _myRequiredIntParam = value; this.myRequiredIntParamWasSet = true; } } /// <summary> /// int[] parameter. /// </summary> [Required] public int[] MyRequiredIntArrayParam { get { return _myRequiredIntArrayParam; } set { _myRequiredIntArrayParam = value; this.myRequiredIntArrayParamWasSet = true; } } /// <summary> /// Single string parameter /// </summary> [Required] public string MyRequiredStringParam { get { return _myRequiredStringParam; } set { _myRequiredStringParam = value; this.myRequiredStringParamWasSet = true; } } /// <summary> /// A string array parameter. /// </summary> [Required] public string[] MyRequiredStringArrayParam { get { return _myRequiredStringArrayParam; } set { _myRequiredStringArrayParam = value; this.myRequiredStringArrayParamWasSet = true; } } /// <summary> /// Single ITaskItem parameter. /// </summary> [Required] public ITaskItem MyRequiredITaskItemParam { get { return _myRequiredITaskItemParam; } set { _myRequiredITaskItemParam = value; this.myRequiredITaskItemParamWasSet = true; } } /// <summary> /// ITaskItem[] parameter. /// </summary> [Required] public ITaskItem[] MyRequiredITaskItemArrayParam { get { return _myRequiredITaskItemArrayParam; } set { _myRequiredITaskItemArrayParam = value; this.myRequiredITaskItemArrayParamWasSet = true; } } /// <summary> /// ArrayList output parameter. (This is not supported by MSBuild.) /// </summary> [Output] public ArrayList MyArrayListOutputParam { get { return null; } } /// <summary> /// Null ITaskItem[] output parameter. /// </summary> [Output] public ITaskItem[] NullITaskItemArrayOutputParameter { get { ITaskItem[] myNullITaskItemArrayOutputParameter = null; return myNullITaskItemArrayOutputParameter; } } /// <summary> /// Empty string output parameter. /// </summary> [Output] public string EmptyStringOutputParameter { get { return String.Empty; } } /// <summary> /// Empty string output parameter. /// </summary> [Output] public string[] EmptyStringInStringArrayOutputParameter { get { string[] myArray = new string[] { "" }; return myArray; } } /// <summary> /// ITaskItem output parameter. /// </summary> [Output] public ITaskItem ITaskItemOutputParameter { get { ITaskItem myITaskItem = null; return myITaskItem; } } /// <summary> /// string output parameter. /// </summary> [Output] public string StringOutputParameter { get { return "foo"; } } /// <summary> /// string array output parameter. /// </summary> [Output] public string[] StringArrayOutputParameter { get { return new string[] { "foo", "bar" }; } } /// <summary> /// int output parameter. /// </summary> [Output] public int IntOutputParameter { get { return 1; } } /// <summary> /// int array output parameter. /// </summary> [Output] public int[] IntArrayOutputParameter { get { return new int[] { 1, 2 }; } } /// <summary> /// object array output parameter. /// </summary> [Output] public object[] ObjectArrayOutputParameter { get { return new object[] { new Object() }; } } /// <summary> /// itaskitem implementation output parameter /// </summary> [Output] public MyTaskItem MyTaskItemOutputParameter { get { return new MyTaskItem(); } } /// <summary> /// itaskitem implementation array output parameter /// </summary> [Output] public MyTaskItem[] MyTaskItemArrayOutputParameter { get { return new MyTaskItem[] { new MyTaskItem() }; } } /// <summary> /// taskitem output parameter /// </summary> [Output] public TaskItem TaskItemOutputParameter { get { return new TaskItem("foo", String.Empty); } } /// <summary> /// taskitem array output parameter /// </summary> [Output] public TaskItem[] TaskItemArrayOutputParameter { get { return new TaskItem[] { new TaskItem("foo", String.Empty) }; } } } /// <summary> /// A simple mock task for use with Unit Testing. /// </summary> sealed internal class MockTask : MockTaskBase, ITask { private IBuildEngine _e = null; /// <summary> /// Task constructor. /// </summary> /// <param name="e"></param> public MockTask(IBuildEngine e) { _e = e; } /// <summary> /// Access the engine. /// </summary> public IBuildEngine BuildEngine { get { return _e; } set { _e = value; } } /// <summary> /// Access the host object. /// </summary> public ITaskHost HostObject { get { return null; } set { } } /// <summary> /// Main Execute method of the task does nothing. /// </summary> /// <returns>true if successful</returns> public bool Execute() { return true; } } /// <summary> /// Custom implementation of ITaskItem for unit testing /// Just TaskItem would work fine, but why not test a custom type as well /// </summary> internal class MyTaskItem : ITaskItem { #region ITaskItem Members public string ItemSpec { get { return "foo"; } set { // do nothing } } public ICollection MetadataNames { get { return new ArrayList(); } } public int MetadataCount { get { return 1; } } public string GetMetadata(string attributeName) { return "foo"; } public void SetMetadata(string attributeName, string attributeValue) { // do nothing } public void RemoveMetadata(string attributeName) { // do nothing } public void CopyMetadataTo(ITaskItem destinationItem) { // do nothing } public IDictionary CloneCustomMetadata() { return new Hashtable(); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.ComponentModel.Composition.Hosting; using System.ComponentModel.Composition.Primitives; using System.Globalization; using System.Reflection; using System.Threading; using Microsoft.Internal; using Microsoft.Internal.Collections; namespace System.ComponentModel.Composition.ReflectionModel { internal class GenericSpecializationPartCreationInfo : IReflectionPartCreationInfo { private readonly IReflectionPartCreationInfo _originalPartCreationInfo; private readonly ReflectionComposablePartDefinition _originalPart; private readonly Type[] _specialization; private readonly string[] _specializationIdentities; private IEnumerable<ExportDefinition> _exports; private IEnumerable<ImportDefinition> _imports; private readonly Lazy<Type> _lazyPartType; private List<LazyMemberInfo> _members; private List<Lazy<ParameterInfo>> _parameters; private Dictionary<LazyMemberInfo, MemberInfo[]> _membersTable; private Dictionary<Lazy<ParameterInfo>, ParameterInfo> _parametersTable; private ConstructorInfo _constructor; private readonly object _lock = new object(); public GenericSpecializationPartCreationInfo(IReflectionPartCreationInfo originalPartCreationInfo, ReflectionComposablePartDefinition originalPart, Type[] specialization) { if (originalPartCreationInfo == null) { throw new ArgumentNullException(nameof(originalPartCreationInfo)); } if (originalPart == null) { throw new ArgumentNullException(nameof(originalPart)); } if (specialization == null) { throw new ArgumentNullException(nameof(specialization)); } _originalPartCreationInfo = originalPartCreationInfo; _originalPart = originalPart; _specialization = specialization; _specializationIdentities = new string[_specialization.Length]; for (int i = 0; i < _specialization.Length; i++) { _specializationIdentities[i] = AttributedModelServices.GetTypeIdentity(_specialization[i]); } _lazyPartType = new Lazy<Type>( () => _originalPartCreationInfo.GetPartType().MakeGenericType(specialization), LazyThreadSafetyMode.PublicationOnly); } public ReflectionComposablePartDefinition OriginalPart { get { return _originalPart; } } public Type GetPartType() { return _lazyPartType.Value; } public Lazy<Type> GetLazyPartType() { return _lazyPartType; } public ConstructorInfo GetConstructor() { if (_constructor == null) { ConstructorInfo genericConstuctor = _originalPartCreationInfo.GetConstructor(); ConstructorInfo result = null; if (genericConstuctor != null) { foreach (ConstructorInfo constructor in GetPartType().GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) { if (constructor.MetadataToken == genericConstuctor.MetadataToken) { result = constructor; break; } } } Thread.MemoryBarrier(); lock (_lock) { if (_constructor == null) { _constructor = result; } } } return _constructor; } public IDictionary<string, object> GetMetadata() { var originalMetadata = new Dictionary<string, object>(_originalPartCreationInfo.GetMetadata(), StringComparers.MetadataKeyNames); originalMetadata.Remove(CompositionConstants.IsGenericPartMetadataName); originalMetadata.Remove(CompositionConstants.GenericPartArityMetadataName); originalMetadata.Remove(CompositionConstants.GenericParameterConstraintsMetadataName); originalMetadata.Remove(CompositionConstants.GenericParameterAttributesMetadataName); return originalMetadata; } private MemberInfo[] GetAccessors(LazyMemberInfo originalLazyMember) { BuildTables(); if (_membersTable == null) { throw new ArgumentNullException(nameof(_membersTable)); } return _membersTable[originalLazyMember]; } private ParameterInfo GetParameter(Lazy<ParameterInfo> originalParameter) { BuildTables(); if (_parametersTable == null) { throw new ArgumentNullException(nameof(_parametersTable)); } return _parametersTable[originalParameter]; } private void BuildTables() { if (_membersTable != null) { return; } PopulateImportsAndExports(); List<LazyMemberInfo> members = null; List<Lazy<ParameterInfo>> parameters = null; lock (_lock) { if (_membersTable == null) { members = _members; parameters = _parameters; if (members == null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } } } // // Get all members that can be of interest and extract their MetadataTokens // Dictionary<LazyMemberInfo, MemberInfo[]> membersTable = BuildMembersTable(members); Dictionary<Lazy<ParameterInfo>, ParameterInfo> parametersTable = BuildParametersTable(parameters); lock (_lock) { if (_membersTable == null) { _membersTable = membersTable; _parametersTable = parametersTable; Thread.MemoryBarrier(); _parameters = null; _members = null; } } } private Dictionary<LazyMemberInfo, MemberInfo[]> BuildMembersTable(List<LazyMemberInfo> members) { if (members == null) { throw new ArgumentNullException(nameof(members)); } Dictionary<LazyMemberInfo, MemberInfo[]> membersTable = new Dictionary<LazyMemberInfo, MemberInfo[]>(); Dictionary<int, MemberInfo> specializedPartMembers = new Dictionary<int, MemberInfo>(); Type closedGenericPartType = GetPartType(); specializedPartMembers[closedGenericPartType.MetadataToken] = closedGenericPartType; foreach (MethodInfo method in closedGenericPartType.GetAllMethods()) { specializedPartMembers[method.MetadataToken] = method; } foreach (FieldInfo field in closedGenericPartType.GetAllFields()) { specializedPartMembers[field.MetadataToken] = field; } foreach (var iface in closedGenericPartType.GetInterfaces()) { specializedPartMembers[iface.MetadataToken] = iface; } foreach (var type in closedGenericPartType.GetNestedTypes()) { specializedPartMembers[type.MetadataToken] = type; } //Walk the base class list var baseType = closedGenericPartType.BaseType; while (baseType != null && baseType != typeof(object)) { specializedPartMembers[baseType.MetadataToken] = baseType; baseType = baseType.BaseType; } // // Now go through the members table and resolve them into the new closed type based on the tokens // foreach (LazyMemberInfo lazyMemberInfo in members) { MemberInfo[] genericAccessors = lazyMemberInfo.GetAccessors(); MemberInfo[] accessors = new MemberInfo[genericAccessors.Length]; for (int i = 0; i < genericAccessors.Length; i++) { if (genericAccessors[i] != null) { specializedPartMembers.TryGetValue(genericAccessors[i].MetadataToken, out accessors[i]); if (accessors[i] == null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } } } membersTable[lazyMemberInfo] = accessors; } return membersTable; } private Dictionary<Lazy<ParameterInfo>, ParameterInfo> BuildParametersTable(List<Lazy<ParameterInfo>> parameters) { if (parameters != null) { Dictionary<Lazy<ParameterInfo>, ParameterInfo> parametersTable = new Dictionary<Lazy<ParameterInfo>, ParameterInfo>(); // GENTODO - error case ParameterInfo[] constructorParameters = GetConstructor().GetParameters(); foreach (var lazyParameter in parameters) { parametersTable[lazyParameter] = constructorParameters[lazyParameter.Value.Position]; } return parametersTable; } else { return null; } } private List<ImportDefinition> PopulateImports(List<LazyMemberInfo> members, List<Lazy<ParameterInfo>> parameters) { List<ImportDefinition> imports = new List<ImportDefinition>(); foreach (ImportDefinition originalImport in _originalPartCreationInfo.GetImports()) { ReflectionImportDefinition reflectionImport = originalImport as ReflectionImportDefinition; if (reflectionImport == null) { // we always ignore these continue; } imports.Add(TranslateImport(reflectionImport, members, parameters)); } return imports; } private ImportDefinition TranslateImport(ReflectionImportDefinition reflectionImport, List<LazyMemberInfo> members, List<Lazy<ParameterInfo>> parameters) { bool isExportFactory = false; ContractBasedImportDefinition productImport = reflectionImport; IPartCreatorImportDefinition exportFactoryImportDefinition = reflectionImport as IPartCreatorImportDefinition; if (exportFactoryImportDefinition != null) { productImport = exportFactoryImportDefinition.ProductImportDefinition; isExportFactory = true; } string contractName = Translate(productImport.ContractName); string requiredTypeIdentity = Translate(productImport.RequiredTypeIdentity); IDictionary<string, object> metadata = TranslateImportMetadata(productImport); ReflectionMemberImportDefinition memberImport = reflectionImport as ReflectionMemberImportDefinition; ImportDefinition import = null; if (memberImport != null) { LazyMemberInfo lazyMember = memberImport.ImportingLazyMember; LazyMemberInfo importingMember = new LazyMemberInfo(lazyMember.MemberType, () => GetAccessors(lazyMember)); if (isExportFactory) { import = new PartCreatorMemberImportDefinition( importingMember, ((ICompositionElement)memberImport).Origin, new ContractBasedImportDefinition( contractName, requiredTypeIdentity, productImport.RequiredMetadata, productImport.Cardinality, productImport.IsRecomposable, false, CreationPolicy.NonShared, metadata)); } else { import = new ReflectionMemberImportDefinition( importingMember, contractName, requiredTypeIdentity, productImport.RequiredMetadata, productImport.Cardinality, productImport.IsRecomposable, false, productImport.RequiredCreationPolicy, metadata, ((ICompositionElement)memberImport).Origin); } members.Add(lazyMember); } else { ReflectionParameterImportDefinition parameterImport = reflectionImport as ReflectionParameterImportDefinition; if (parameterImport == null) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } Lazy<ParameterInfo> lazyParameter = parameterImport.ImportingLazyParameter; Lazy<ParameterInfo> parameter = new Lazy<ParameterInfo>(() => GetParameter(lazyParameter)); if (isExportFactory) { import = new PartCreatorParameterImportDefinition( parameter, ((ICompositionElement)parameterImport).Origin, new ContractBasedImportDefinition( contractName, requiredTypeIdentity, productImport.RequiredMetadata, productImport.Cardinality, false, true, CreationPolicy.NonShared, metadata)); } else { import = new ReflectionParameterImportDefinition( parameter, contractName, requiredTypeIdentity, productImport.RequiredMetadata, productImport.Cardinality, productImport.RequiredCreationPolicy, metadata, ((ICompositionElement)parameterImport).Origin); } parameters.Add(lazyParameter); } return import; } private List<ExportDefinition> PopulateExports(List<LazyMemberInfo> members) { List<ExportDefinition> exports = new List<ExportDefinition>(); foreach (ExportDefinition originalExport in _originalPartCreationInfo.GetExports()) { ReflectionMemberExportDefinition reflectionExport = originalExport as ReflectionMemberExportDefinition; if (reflectionExport == null) { // we always ignore these continue; } exports.Add(TranslateExpot(reflectionExport, members)); } return exports; } public ExportDefinition TranslateExpot(ReflectionMemberExportDefinition reflectionExport, List<LazyMemberInfo> members) { ExportDefinition export = null; LazyMemberInfo lazyMember = reflectionExport.ExportingLazyMember; var capturedLazyMember = lazyMember; var capturedReflectionExport = reflectionExport; string contractName = Translate(reflectionExport.ContractName, reflectionExport.Metadata.GetValue<int[]>(CompositionConstants.GenericExportParametersOrderMetadataName)); LazyMemberInfo exportingMember = new LazyMemberInfo(capturedLazyMember.MemberType, () => GetAccessors(capturedLazyMember)); Lazy<IDictionary<string, object>> lazyMetadata = new Lazy<IDictionary<string, object>>(() => TranslateExportMetadata(capturedReflectionExport)); export = new ReflectionMemberExportDefinition( exportingMember, new LazyExportDefinition(contractName, lazyMetadata), ((ICompositionElement)reflectionExport).Origin); members.Add(capturedLazyMember); return export; } private string Translate(string originalValue, int[] genericParametersOrder) { if (genericParametersOrder != null) { string[] specializationIdentities = GenericServices.Reorder(_specializationIdentities, genericParametersOrder); return string.Format(CultureInfo.InvariantCulture, originalValue, specializationIdentities); } else { return Translate(originalValue); } } private string Translate(string originalValue) { return string.Format(CultureInfo.InvariantCulture, originalValue, _specializationIdentities); } private IDictionary<string, object> TranslateImportMetadata(ContractBasedImportDefinition originalImport) { int[] importParametersOrder = originalImport.Metadata.GetValue<int[]>(CompositionConstants.GenericImportParametersOrderMetadataName); if (importParametersOrder != null) { Dictionary<string, object> metadata = new Dictionary<string, object>(originalImport.Metadata, StringComparers.MetadataKeyNames); // Get the newly re-qualified name of the generic contract and the subset of applicable types from the specialization metadata[CompositionConstants.GenericContractMetadataName] = GenericServices.GetGenericName(originalImport.ContractName, importParametersOrder, _specialization.Length); metadata[CompositionConstants.GenericParametersMetadataName] = GenericServices.Reorder(_specialization, importParametersOrder); metadata.Remove(CompositionConstants.GenericImportParametersOrderMetadataName); return metadata.AsReadOnly(); } else { return originalImport.Metadata; } } private IDictionary<string, object> TranslateExportMetadata(ReflectionMemberExportDefinition originalExport) { Dictionary<string, object> metadata = new Dictionary<string, object>(originalExport.Metadata, StringComparers.MetadataKeyNames); string exportTypeIdentity = originalExport.Metadata.GetValue<string>(CompositionConstants.ExportTypeIdentityMetadataName); if (!string.IsNullOrEmpty(exportTypeIdentity)) { metadata[CompositionConstants.ExportTypeIdentityMetadataName] = Translate(exportTypeIdentity, originalExport.Metadata.GetValue<int[]>(CompositionConstants.GenericExportParametersOrderMetadataName)); } metadata.Remove(CompositionConstants.GenericExportParametersOrderMetadataName); return metadata; } private void PopulateImportsAndExports() { if ((_exports == null) || (_imports == null)) { List<LazyMemberInfo> members = new List<LazyMemberInfo>(); List<Lazy<ParameterInfo>> parameters = new List<Lazy<ParameterInfo>>(); // we are very careful to not call any 3rd party code in either of these var exports = PopulateExports(members); var imports = PopulateImports(members, parameters); Thread.MemoryBarrier(); lock (_lock) { if ((_exports == null) || (_imports == null)) { _members = members; if (parameters.Count > 0) { _parameters = parameters; } _exports = exports; _imports = imports; } } } } public IEnumerable<ExportDefinition> GetExports() { PopulateImportsAndExports(); return _exports; } public IEnumerable<ImportDefinition> GetImports() { PopulateImportsAndExports(); return _imports; } public bool IsDisposalRequired { get { return _originalPartCreationInfo.IsDisposalRequired; } } public bool IsIdentityComparison { get { return false; } } public string DisplayName { get { return Translate(_originalPartCreationInfo.DisplayName); } } public ICompositionElement Origin { get { return _originalPartCreationInfo.Origin; } } public override bool Equals(object obj) { GenericSpecializationPartCreationInfo that = obj as GenericSpecializationPartCreationInfo; if (that == null) { return false; } return (_originalPartCreationInfo.Equals(that._originalPartCreationInfo)) && (_specialization.IsArrayEqual(that._specialization)); } public override int GetHashCode() { return _originalPartCreationInfo.GetHashCode(); } public static bool CanSpecialize(IDictionary<string, object> partMetadata, Type[] specialization) { int partArity = partMetadata.GetValue<int>(CompositionConstants.GenericPartArityMetadataName); if (partArity != specialization.Length) { return false; } object[] genericParameterConstraints = partMetadata.GetValue<object[]>(CompositionConstants.GenericParameterConstraintsMetadataName); GenericParameterAttributes[] genericParameterAttributes = partMetadata.GetValue<GenericParameterAttributes[]>(CompositionConstants.GenericParameterAttributesMetadataName); // if no constraints and attributes been specifed, anything can be created if ((genericParameterConstraints == null) && (genericParameterAttributes == null)) { return true; } if ((genericParameterConstraints != null) && (genericParameterConstraints.Length != partArity)) { return false; } if ((genericParameterAttributes != null) && (genericParameterAttributes.Length != partArity)) { return false; } for (int i = 0; i < partArity; i++) { if (!GenericServices.CanSpecialize( specialization[i], (genericParameterConstraints[i] as Type[]).CreateTypeSpecializations(specialization), genericParameterAttributes[i])) { return false; } } return true; } } }
using System; using NBitcoin.BouncyCastle.Crypto.Parameters; using NBitcoin.BouncyCastle.Crypto.Utilities; using NBitcoin.BouncyCastle.Utilities; namespace NBitcoin.BouncyCastle.Crypto.Engines { /** * an implementation of the AES (Rijndael), from FIPS-197. * <p> * For further details see: <a href="http://csrc.nist.gov/encryption/aes/">http://csrc.nist.gov/encryption/aes/</a>. * * This implementation is based on optimizations from Dr. Brian Gladman's paper and C code at * <a href="http://fp.gladman.plus.com/cryptography_technology/rijndael/">http://fp.gladman.plus.com/cryptography_technology/rijndael/</a> * * There are three levels of tradeoff of speed vs memory * Because java has no preprocessor, they are written as three separate classes from which to choose * * The fastest uses 8Kbytes of static tables to precompute round calculations, 4 256 word tables for encryption * and 4 for decryption. * * The middle performance version uses only one 256 word table for each, for a total of 2Kbytes, * adding 12 rotate operations per round to compute the values contained in the other tables from * the contents of the first. * * The slowest version uses no static tables at all and computes the values in each round. * </p> * <p> * This file contains the middle performance version with 2Kbytes of static tables for round precomputation. * </p> */ internal class AesEngine : IBlockCipher { // The S box private static readonly byte[] S = { 99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22, }; // The inverse S-box private static readonly byte[] Si = { 82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251, 124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203, 84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78, 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37, 114, 248, 246, 100, 134, 104, 152, 22, 212, 164, 92, 204, 93, 101, 182, 146, 108, 112, 72, 80, 253, 237, 185, 218, 94, 21, 70, 87, 167, 141, 157, 132, 144, 216, 171, 0, 140, 188, 211, 10, 247, 228, 88, 5, 184, 179, 69, 6, 208, 44, 30, 143, 202, 63, 15, 2, 193, 175, 189, 3, 1, 19, 138, 107, 58, 145, 17, 65, 79, 103, 220, 234, 151, 242, 207, 206, 240, 180, 230, 115, 150, 172, 116, 34, 231, 173, 53, 133, 226, 249, 55, 232, 28, 117, 223, 110, 71, 241, 26, 113, 29, 41, 197, 137, 111, 183, 98, 14, 170, 24, 190, 27, 252, 86, 62, 75, 198, 210, 121, 32, 154, 219, 192, 254, 120, 205, 90, 244, 31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95, 96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239, 160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97, 23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125, }; // vector used in calculating key schedule (powers of x in GF(256)) private static readonly byte[] rcon = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91 }; // precomputation tables of calculations for rounds private static readonly uint[] T0 = { 0xa56363c6, 0x847c7cf8, 0x997777ee, 0x8d7b7bf6, 0x0df2f2ff, 0xbd6b6bd6, 0xb16f6fde, 0x54c5c591, 0x50303060, 0x03010102, 0xa96767ce, 0x7d2b2b56, 0x19fefee7, 0x62d7d7b5, 0xe6abab4d, 0x9a7676ec, 0x45caca8f, 0x9d82821f, 0x40c9c989, 0x877d7dfa, 0x15fafaef, 0xeb5959b2, 0xc947478e, 0x0bf0f0fb, 0xecadad41, 0x67d4d4b3, 0xfda2a25f, 0xeaafaf45, 0xbf9c9c23, 0xf7a4a453, 0x967272e4, 0x5bc0c09b, 0xc2b7b775, 0x1cfdfde1, 0xae93933d, 0x6a26264c, 0x5a36366c, 0x413f3f7e, 0x02f7f7f5, 0x4fcccc83, 0x5c343468, 0xf4a5a551, 0x34e5e5d1, 0x08f1f1f9, 0x937171e2, 0x73d8d8ab, 0x53313162, 0x3f15152a, 0x0c040408, 0x52c7c795, 0x65232346, 0x5ec3c39d, 0x28181830, 0xa1969637, 0x0f05050a, 0xb59a9a2f, 0x0907070e, 0x36121224, 0x9b80801b, 0x3de2e2df, 0x26ebebcd, 0x6927274e, 0xcdb2b27f, 0x9f7575ea, 0x1b090912, 0x9e83831d, 0x742c2c58, 0x2e1a1a34, 0x2d1b1b36, 0xb26e6edc, 0xee5a5ab4, 0xfba0a05b, 0xf65252a4, 0x4d3b3b76, 0x61d6d6b7, 0xceb3b37d, 0x7b292952, 0x3ee3e3dd, 0x712f2f5e, 0x97848413, 0xf55353a6, 0x68d1d1b9, 0x00000000, 0x2cededc1, 0x60202040, 0x1ffcfce3, 0xc8b1b179, 0xed5b5bb6, 0xbe6a6ad4, 0x46cbcb8d, 0xd9bebe67, 0x4b393972, 0xde4a4a94, 0xd44c4c98, 0xe85858b0, 0x4acfcf85, 0x6bd0d0bb, 0x2aefefc5, 0xe5aaaa4f, 0x16fbfbed, 0xc5434386, 0xd74d4d9a, 0x55333366, 0x94858511, 0xcf45458a, 0x10f9f9e9, 0x06020204, 0x817f7ffe, 0xf05050a0, 0x443c3c78, 0xba9f9f25, 0xe3a8a84b, 0xf35151a2, 0xfea3a35d, 0xc0404080, 0x8a8f8f05, 0xad92923f, 0xbc9d9d21, 0x48383870, 0x04f5f5f1, 0xdfbcbc63, 0xc1b6b677, 0x75dadaaf, 0x63212142, 0x30101020, 0x1affffe5, 0x0ef3f3fd, 0x6dd2d2bf, 0x4ccdcd81, 0x140c0c18, 0x35131326, 0x2fececc3, 0xe15f5fbe, 0xa2979735, 0xcc444488, 0x3917172e, 0x57c4c493, 0xf2a7a755, 0x827e7efc, 0x473d3d7a, 0xac6464c8, 0xe75d5dba, 0x2b191932, 0x957373e6, 0xa06060c0, 0x98818119, 0xd14f4f9e, 0x7fdcdca3, 0x66222244, 0x7e2a2a54, 0xab90903b, 0x8388880b, 0xca46468c, 0x29eeeec7, 0xd3b8b86b, 0x3c141428, 0x79dedea7, 0xe25e5ebc, 0x1d0b0b16, 0x76dbdbad, 0x3be0e0db, 0x56323264, 0x4e3a3a74, 0x1e0a0a14, 0xdb494992, 0x0a06060c, 0x6c242448, 0xe45c5cb8, 0x5dc2c29f, 0x6ed3d3bd, 0xefacac43, 0xa66262c4, 0xa8919139, 0xa4959531, 0x37e4e4d3, 0x8b7979f2, 0x32e7e7d5, 0x43c8c88b, 0x5937376e, 0xb76d6dda, 0x8c8d8d01, 0x64d5d5b1, 0xd24e4e9c, 0xe0a9a949, 0xb46c6cd8, 0xfa5656ac, 0x07f4f4f3, 0x25eaeacf, 0xaf6565ca, 0x8e7a7af4, 0xe9aeae47, 0x18080810, 0xd5baba6f, 0x887878f0, 0x6f25254a, 0x722e2e5c, 0x241c1c38, 0xf1a6a657, 0xc7b4b473, 0x51c6c697, 0x23e8e8cb, 0x7cdddda1, 0x9c7474e8, 0x211f1f3e, 0xdd4b4b96, 0xdcbdbd61, 0x868b8b0d, 0x858a8a0f, 0x907070e0, 0x423e3e7c, 0xc4b5b571, 0xaa6666cc, 0xd8484890, 0x05030306, 0x01f6f6f7, 0x120e0e1c, 0xa36161c2, 0x5f35356a, 0xf95757ae, 0xd0b9b969, 0x91868617, 0x58c1c199, 0x271d1d3a, 0xb99e9e27, 0x38e1e1d9, 0x13f8f8eb, 0xb398982b, 0x33111122, 0xbb6969d2, 0x70d9d9a9, 0x898e8e07, 0xa7949433, 0xb69b9b2d, 0x221e1e3c, 0x92878715, 0x20e9e9c9, 0x49cece87, 0xff5555aa, 0x78282850, 0x7adfdfa5, 0x8f8c8c03, 0xf8a1a159, 0x80898909, 0x170d0d1a, 0xdabfbf65, 0x31e6e6d7, 0xc6424284, 0xb86868d0, 0xc3414182, 0xb0999929, 0x772d2d5a, 0x110f0f1e, 0xcbb0b07b, 0xfc5454a8, 0xd6bbbb6d, 0x3a16162c }; private static readonly uint[] Tinv0 = { 0x50a7f451, 0x5365417e, 0xc3a4171a, 0x965e273a, 0xcb6bab3b, 0xf1459d1f, 0xab58faac, 0x9303e34b, 0x55fa3020, 0xf66d76ad, 0x9176cc88, 0x254c02f5, 0xfcd7e54f, 0xd7cb2ac5, 0x80443526, 0x8fa362b5, 0x495ab1de, 0x671bba25, 0x980eea45, 0xe1c0fe5d, 0x02752fc3, 0x12f04c81, 0xa397468d, 0xc6f9d36b, 0xe75f8f03, 0x959c9215, 0xeb7a6dbf, 0xda595295, 0x2d83bed4, 0xd3217458, 0x2969e049, 0x44c8c98e, 0x6a89c275, 0x78798ef4, 0x6b3e5899, 0xdd71b927, 0xb64fe1be, 0x17ad88f0, 0x66ac20c9, 0xb43ace7d, 0x184adf63, 0x82311ae5, 0x60335197, 0x457f5362, 0xe07764b1, 0x84ae6bbb, 0x1ca081fe, 0x942b08f9, 0x58684870, 0x19fd458f, 0x876cde94, 0xb7f87b52, 0x23d373ab, 0xe2024b72, 0x578f1fe3, 0x2aab5566, 0x0728ebb2, 0x03c2b52f, 0x9a7bc586, 0xa50837d3, 0xf2872830, 0xb2a5bf23, 0xba6a0302, 0x5c8216ed, 0x2b1ccf8a, 0x92b479a7, 0xf0f207f3, 0xa1e2694e, 0xcdf4da65, 0xd5be0506, 0x1f6234d1, 0x8afea6c4, 0x9d532e34, 0xa055f3a2, 0x32e18a05, 0x75ebf6a4, 0x39ec830b, 0xaaef6040, 0x069f715e, 0x51106ebd, 0xf98a213e, 0x3d06dd96, 0xae053edd, 0x46bde64d, 0xb58d5491, 0x055dc471, 0x6fd40604, 0xff155060, 0x24fb9819, 0x97e9bdd6, 0xcc434089, 0x779ed967, 0xbd42e8b0, 0x888b8907, 0x385b19e7, 0xdbeec879, 0x470a7ca1, 0xe90f427c, 0xc91e84f8, 0x00000000, 0x83868009, 0x48ed2b32, 0xac70111e, 0x4e725a6c, 0xfbff0efd, 0x5638850f, 0x1ed5ae3d, 0x27392d36, 0x64d90f0a, 0x21a65c68, 0xd1545b9b, 0x3a2e3624, 0xb1670a0c, 0x0fe75793, 0xd296eeb4, 0x9e919b1b, 0x4fc5c080, 0xa220dc61, 0x694b775a, 0x161a121c, 0x0aba93e2, 0xe52aa0c0, 0x43e0223c, 0x1d171b12, 0x0b0d090e, 0xadc78bf2, 0xb9a8b62d, 0xc8a91e14, 0x8519f157, 0x4c0775af, 0xbbdd99ee, 0xfd607fa3, 0x9f2601f7, 0xbcf5725c, 0xc53b6644, 0x347efb5b, 0x7629438b, 0xdcc623cb, 0x68fcedb6, 0x63f1e4b8, 0xcadc31d7, 0x10856342, 0x40229713, 0x2011c684, 0x7d244a85, 0xf83dbbd2, 0x1132f9ae, 0x6da129c7, 0x4b2f9e1d, 0xf330b2dc, 0xec52860d, 0xd0e3c177, 0x6c16b32b, 0x99b970a9, 0xfa489411, 0x2264e947, 0xc48cfca8, 0x1a3ff0a0, 0xd82c7d56, 0xef903322, 0xc74e4987, 0xc1d138d9, 0xfea2ca8c, 0x360bd498, 0xcf81f5a6, 0x28de7aa5, 0x268eb7da, 0xa4bfad3f, 0xe49d3a2c, 0x0d927850, 0x9bcc5f6a, 0x62467e54, 0xc2138df6, 0xe8b8d890, 0x5ef7392e, 0xf5afc382, 0xbe805d9f, 0x7c93d069, 0xa92dd56f, 0xb31225cf, 0x3b99acc8, 0xa77d1810, 0x6e639ce8, 0x7bbb3bdb, 0x097826cd, 0xf418596e, 0x01b79aec, 0xa89a4f83, 0x656e95e6, 0x7ee6ffaa, 0x08cfbc21, 0xe6e815ef, 0xd99be7ba, 0xce366f4a, 0xd4099fea, 0xd67cb029, 0xafb2a431, 0x31233f2a, 0x3094a5c6, 0xc066a235, 0x37bc4e74, 0xa6ca82fc, 0xb0d090e0, 0x15d8a733, 0x4a9804f1, 0xf7daec41, 0x0e50cd7f, 0x2ff69117, 0x8dd64d76, 0x4db0ef43, 0x544daacc, 0xdf0496e4, 0xe3b5d19e, 0x1b886a4c, 0xb81f2cc1, 0x7f516546, 0x04ea5e9d, 0x5d358c01, 0x737487fa, 0x2e410bfb, 0x5a1d67b3, 0x52d2db92, 0x335610e9, 0x1347d66d, 0x8c61d79a, 0x7a0ca137, 0x8e14f859, 0x893c13eb, 0xee27a9ce, 0x35c961b7, 0xede51ce1, 0x3cb1477a, 0x59dfd29c, 0x3f73f255, 0x79ce1418, 0xbf37c773, 0xeacdf753, 0x5baafd5f, 0x146f3ddf, 0x86db4478, 0x81f3afca, 0x3ec468b9, 0x2c342438, 0x5f40a3c2, 0x72c31d16, 0x0c25e2bc, 0x8b493c28, 0x41950dff, 0x7101a839, 0xdeb30c08, 0x9ce4b4d8, 0x90c15664, 0x6184cb7b, 0x70b632d5, 0x745c6c48, 0x4257b8d0 }; private static uint Shift(uint r, int shift) { return (r >> shift) | (r << (32 - shift)); } /* multiply four bytes in GF(2^8) by 'x' {02} in parallel */ private const uint m1 = 0x80808080; private const uint m2 = 0x7f7f7f7f; private const uint m3 = 0x0000001b; private const uint m4 = 0xC0C0C0C0; private const uint m5 = 0x3f3f3f3f; private static uint FFmulX(uint x) { return ((x & m2) << 1) ^ (((x & m1) >> 7) * m3); } private static uint FFmulX2(uint x) { uint t0 = (x & m5) << 2; uint t1 = (x & m4); t1 ^= (t1 >> 1); return t0 ^ (t1 >> 2) ^ (t1 >> 5); } /* The following defines provide alternative definitions of FFmulX that might give improved performance if a fast 32-bit multiply is not available. private int FFmulX(int x) { int u = x & m1; u |= (u >> 1); return ((x & m2) << 1) ^ ((u >>> 3) | (u >>> 6)); } private static final int m4 = 0x1b1b1b1b; private int FFmulX(int x) { int u = x & m1; return ((x & m2) << 1) ^ ((u - (u >>> 7)) & m4); } */ private static uint Inv_Mcol(uint x) { uint t0, t1; t0 = x; t1 = t0 ^ Shift(t0, 8); t0 ^= FFmulX(t1); t1 ^= FFmulX2(t0); t0 ^= t1 ^ Shift(t1, 16); return t0; } private static uint SubWord(uint x) { return (uint)S[x & 255] | (((uint)S[(x >> 8) & 255]) << 8) | (((uint)S[(x >> 16) & 255]) << 16) | (((uint)S[(x >> 24) & 255]) << 24); } /** * Calculate the necessary round keys * The number of calculations depends on key size and block size * AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits * This code is written assuming those are the only possible values */ private uint[][] GenerateWorkingKey(byte[] key, bool forEncryption) { int keyLen = key.Length; if(keyLen < 16 || keyLen > 32 || (keyLen & 7) != 0) throw new ArgumentException("Key length not 128/192/256 bits."); int KC = keyLen >> 2; this.ROUNDS = KC + 6; // This is not always true for the generalized Rijndael that allows larger block sizes var W = new uint[this.ROUNDS + 1][]; // 4 words in a block for(int i = 0; i <= this.ROUNDS; ++i) { W[i] = new uint[4]; } switch(KC) { case 4: { uint t0 = Pack.LE_To_UInt32(key, 0); W[0][0] = t0; uint t1 = Pack.LE_To_UInt32(key, 4); W[0][1] = t1; uint t2 = Pack.LE_To_UInt32(key, 8); W[0][2] = t2; uint t3 = Pack.LE_To_UInt32(key, 12); W[0][3] = t3; for(int i = 1; i <= 10; ++i) { uint u = SubWord(Shift(t3, 8)) ^ rcon[i - 1]; t0 ^= u; W[i][0] = t0; t1 ^= t0; W[i][1] = t1; t2 ^= t1; W[i][2] = t2; t3 ^= t2; W[i][3] = t3; } break; } case 6: { uint t0 = Pack.LE_To_UInt32(key, 0); W[0][0] = t0; uint t1 = Pack.LE_To_UInt32(key, 4); W[0][1] = t1; uint t2 = Pack.LE_To_UInt32(key, 8); W[0][2] = t2; uint t3 = Pack.LE_To_UInt32(key, 12); W[0][3] = t3; uint t4 = Pack.LE_To_UInt32(key, 16); W[1][0] = t4; uint t5 = Pack.LE_To_UInt32(key, 20); W[1][1] = t5; uint rcon = 1; uint u = SubWord(Shift(t5, 8)) ^ rcon; rcon <<= 1; t0 ^= u; W[1][2] = t0; t1 ^= t0; W[1][3] = t1; t2 ^= t1; W[2][0] = t2; t3 ^= t2; W[2][1] = t3; t4 ^= t3; W[2][2] = t4; t5 ^= t4; W[2][3] = t5; for(int i = 3; i < 12; i += 3) { u = SubWord(Shift(t5, 8)) ^ rcon; rcon <<= 1; t0 ^= u; W[i][0] = t0; t1 ^= t0; W[i][1] = t1; t2 ^= t1; W[i][2] = t2; t3 ^= t2; W[i][3] = t3; t4 ^= t3; W[i + 1][0] = t4; t5 ^= t4; W[i + 1][1] = t5; u = SubWord(Shift(t5, 8)) ^ rcon; rcon <<= 1; t0 ^= u; W[i + 1][2] = t0; t1 ^= t0; W[i + 1][3] = t1; t2 ^= t1; W[i + 2][0] = t2; t3 ^= t2; W[i + 2][1] = t3; t4 ^= t3; W[i + 2][2] = t4; t5 ^= t4; W[i + 2][3] = t5; } u = SubWord(Shift(t5, 8)) ^ rcon; t0 ^= u; W[12][0] = t0; t1 ^= t0; W[12][1] = t1; t2 ^= t1; W[12][2] = t2; t3 ^= t2; W[12][3] = t3; break; } case 8: { uint t0 = Pack.LE_To_UInt32(key, 0); W[0][0] = t0; uint t1 = Pack.LE_To_UInt32(key, 4); W[0][1] = t1; uint t2 = Pack.LE_To_UInt32(key, 8); W[0][2] = t2; uint t3 = Pack.LE_To_UInt32(key, 12); W[0][3] = t3; uint t4 = Pack.LE_To_UInt32(key, 16); W[1][0] = t4; uint t5 = Pack.LE_To_UInt32(key, 20); W[1][1] = t5; uint t6 = Pack.LE_To_UInt32(key, 24); W[1][2] = t6; uint t7 = Pack.LE_To_UInt32(key, 28); W[1][3] = t7; uint u, rcon = 1; for(int i = 2; i < 14; i += 2) { u = SubWord(Shift(t7, 8)) ^ rcon; rcon <<= 1; t0 ^= u; W[i][0] = t0; t1 ^= t0; W[i][1] = t1; t2 ^= t1; W[i][2] = t2; t3 ^= t2; W[i][3] = t3; u = SubWord(t3); t4 ^= u; W[i + 1][0] = t4; t5 ^= t4; W[i + 1][1] = t5; t6 ^= t5; W[i + 1][2] = t6; t7 ^= t6; W[i + 1][3] = t7; } u = SubWord(Shift(t7, 8)) ^ rcon; t0 ^= u; W[14][0] = t0; t1 ^= t0; W[14][1] = t1; t2 ^= t1; W[14][2] = t2; t3 ^= t2; W[14][3] = t3; break; } default: { throw new InvalidOperationException("Should never get here"); } } if(!forEncryption) { for(int j = 1; j < this.ROUNDS; j++) { uint[] w = W[j]; for(int i = 0; i < 4; i++) { w[i] = Inv_Mcol(w[i]); } } } return W; } private int ROUNDS; private uint[][] WorkingKey; private uint C0, C1, C2, C3; private bool forEncryption; private const int BLOCK_SIZE = 16; /** * default constructor - 128 bit block size. */ public AesEngine() { } /** * initialise an AES cipher. * * @param forEncryption whether or not we are for encryption. * @param parameters the parameters required to set up the cipher. * @exception ArgumentException if the parameters argument is * inappropriate. */ public virtual void Init( bool forEncryption, ICipherParameters parameters) { var keyParameter = parameters as KeyParameter; if(keyParameter == null) { throw new ArgumentException("invalid parameter passed to AES init - " + Platform.GetTypeName(parameters)); } this.WorkingKey = GenerateWorkingKey(keyParameter.GetKey(), forEncryption); this.forEncryption = forEncryption; } public virtual string AlgorithmName { get { return "AES"; } } public virtual bool IsPartialBlockOkay { get { return false; } } public virtual int GetBlockSize() { return BLOCK_SIZE; } public virtual int ProcessBlock( byte[] input, int inOff, byte[] output, int outOff) { if(this.WorkingKey == null) throw new InvalidOperationException("AES engine not initialised"); Check.DataLength(input, inOff, 16, "input buffer too short"); Check.OutputLength(output, outOff, 16, "output buffer too short"); UnPackBlock(input, inOff); if(this.forEncryption) { EncryptBlock(this.WorkingKey); } else { DecryptBlock(this.WorkingKey); } PackBlock(output, outOff); return BLOCK_SIZE; } public virtual void Reset() { } private void UnPackBlock( byte[] bytes, int off) { this.C0 = Pack.LE_To_UInt32(bytes, off); this.C1 = Pack.LE_To_UInt32(bytes, off + 4); this.C2 = Pack.LE_To_UInt32(bytes, off + 8); this.C3 = Pack.LE_To_UInt32(bytes, off + 12); } private void PackBlock( byte[] bytes, int off) { Pack.UInt32_To_LE(this.C0, bytes, off); Pack.UInt32_To_LE(this.C1, bytes, off + 4); Pack.UInt32_To_LE(this.C2, bytes, off + 8); Pack.UInt32_To_LE(this.C3, bytes, off + 12); } private void EncryptBlock(uint[][] KW) { uint[] kw = KW[0]; uint t0 = this.C0 ^ kw[0]; uint t1 = this.C1 ^ kw[1]; uint t2 = this.C2 ^ kw[2]; uint r0, r1, r2, r3 = this.C3 ^ kw[3]; int r = 1; while(r < this.ROUNDS - 1) { kw = KW[r++]; r0 = T0[t0 & 255] ^ Shift(T0[(t1 >> 8) & 255], 24) ^ Shift(T0[(t2 >> 16) & 255], 16) ^ Shift(T0[(r3 >> 24) & 255], 8) ^ kw[0]; r1 = T0[t1 & 255] ^ Shift(T0[(t2 >> 8) & 255], 24) ^ Shift(T0[(r3 >> 16) & 255], 16) ^ Shift(T0[(t0 >> 24) & 255], 8) ^ kw[1]; r2 = T0[t2 & 255] ^ Shift(T0[(r3 >> 8) & 255], 24) ^ Shift(T0[(t0 >> 16) & 255], 16) ^ Shift(T0[(t1 >> 24) & 255], 8) ^ kw[2]; r3 = T0[r3 & 255] ^ Shift(T0[(t0 >> 8) & 255], 24) ^ Shift(T0[(t1 >> 16) & 255], 16) ^ Shift(T0[(t2 >> 24) & 255], 8) ^ kw[3]; kw = KW[r++]; t0 = T0[r0 & 255] ^ Shift(T0[(r1 >> 8) & 255], 24) ^ Shift(T0[(r2 >> 16) & 255], 16) ^ Shift(T0[(r3 >> 24) & 255], 8) ^ kw[0]; t1 = T0[r1 & 255] ^ Shift(T0[(r2 >> 8) & 255], 24) ^ Shift(T0[(r3 >> 16) & 255], 16) ^ Shift(T0[(r0 >> 24) & 255], 8) ^ kw[1]; t2 = T0[r2 & 255] ^ Shift(T0[(r3 >> 8) & 255], 24) ^ Shift(T0[(r0 >> 16) & 255], 16) ^ Shift(T0[(r1 >> 24) & 255], 8) ^ kw[2]; r3 = T0[r3 & 255] ^ Shift(T0[(r0 >> 8) & 255], 24) ^ Shift(T0[(r1 >> 16) & 255], 16) ^ Shift(T0[(r2 >> 24) & 255], 8) ^ kw[3]; } kw = KW[r++]; r0 = T0[t0 & 255] ^ Shift(T0[(t1 >> 8) & 255], 24) ^ Shift(T0[(t2 >> 16) & 255], 16) ^ Shift(T0[(r3 >> 24) & 255], 8) ^ kw[0]; r1 = T0[t1 & 255] ^ Shift(T0[(t2 >> 8) & 255], 24) ^ Shift(T0[(r3 >> 16) & 255], 16) ^ Shift(T0[(t0 >> 24) & 255], 8) ^ kw[1]; r2 = T0[t2 & 255] ^ Shift(T0[(r3 >> 8) & 255], 24) ^ Shift(T0[(t0 >> 16) & 255], 16) ^ Shift(T0[(t1 >> 24) & 255], 8) ^ kw[2]; r3 = T0[r3 & 255] ^ Shift(T0[(t0 >> 8) & 255], 24) ^ Shift(T0[(t1 >> 16) & 255], 16) ^ Shift(T0[(t2 >> 24) & 255], 8) ^ kw[3]; // the final round's table is a simple function of S so we don't use a whole other four tables for it kw = KW[r]; this.C0 = (uint)S[r0 & 255] ^ (((uint)S[(r1 >> 8) & 255]) << 8) ^ (((uint)S[(r2 >> 16) & 255]) << 16) ^ (((uint)S[(r3 >> 24) & 255]) << 24) ^ kw[0]; this.C1 = (uint)S[r1 & 255] ^ (((uint)S[(r2 >> 8) & 255]) << 8) ^ (((uint)S[(r3 >> 16) & 255]) << 16) ^ (((uint)S[(r0 >> 24) & 255]) << 24) ^ kw[1]; this.C2 = (uint)S[r2 & 255] ^ (((uint)S[(r3 >> 8) & 255]) << 8) ^ (((uint)S[(r0 >> 16) & 255]) << 16) ^ (((uint)S[(r1 >> 24) & 255]) << 24) ^ kw[2]; this.C3 = (uint)S[r3 & 255] ^ (((uint)S[(r0 >> 8) & 255]) << 8) ^ (((uint)S[(r1 >> 16) & 255]) << 16) ^ (((uint)S[(r2 >> 24) & 255]) << 24) ^ kw[3]; } private void DecryptBlock(uint[][] KW) { uint[] kw = KW[this.ROUNDS]; uint t0 = this.C0 ^ kw[0]; uint t1 = this.C1 ^ kw[1]; uint t2 = this.C2 ^ kw[2]; uint r0, r1, r2, r3 = this.C3 ^ kw[3]; int r = this.ROUNDS - 1; while(r > 1) { kw = KW[r--]; r0 = Tinv0[t0 & 255] ^ Shift(Tinv0[(r3 >> 8) & 255], 24) ^ Shift(Tinv0[(t2 >> 16) & 255], 16) ^ Shift(Tinv0[(t1 >> 24) & 255], 8) ^ kw[0]; r1 = Tinv0[t1 & 255] ^ Shift(Tinv0[(t0 >> 8) & 255], 24) ^ Shift(Tinv0[(r3 >> 16) & 255], 16) ^ Shift(Tinv0[(t2 >> 24) & 255], 8) ^ kw[1]; r2 = Tinv0[t2 & 255] ^ Shift(Tinv0[(t1 >> 8) & 255], 24) ^ Shift(Tinv0[(t0 >> 16) & 255], 16) ^ Shift(Tinv0[(r3 >> 24) & 255], 8) ^ kw[2]; r3 = Tinv0[r3 & 255] ^ Shift(Tinv0[(t2 >> 8) & 255], 24) ^ Shift(Tinv0[(t1 >> 16) & 255], 16) ^ Shift(Tinv0[(t0 >> 24) & 255], 8) ^ kw[3]; kw = KW[r--]; t0 = Tinv0[r0 & 255] ^ Shift(Tinv0[(r3 >> 8) & 255], 24) ^ Shift(Tinv0[(r2 >> 16) & 255], 16) ^ Shift(Tinv0[(r1 >> 24) & 255], 8) ^ kw[0]; t1 = Tinv0[r1 & 255] ^ Shift(Tinv0[(r0 >> 8) & 255], 24) ^ Shift(Tinv0[(r3 >> 16) & 255], 16) ^ Shift(Tinv0[(r2 >> 24) & 255], 8) ^ kw[1]; t2 = Tinv0[r2 & 255] ^ Shift(Tinv0[(r1 >> 8) & 255], 24) ^ Shift(Tinv0[(r0 >> 16) & 255], 16) ^ Shift(Tinv0[(r3 >> 24) & 255], 8) ^ kw[2]; r3 = Tinv0[r3 & 255] ^ Shift(Tinv0[(r2 >> 8) & 255], 24) ^ Shift(Tinv0[(r1 >> 16) & 255], 16) ^ Shift(Tinv0[(r0 >> 24) & 255], 8) ^ kw[3]; } kw = KW[1]; r0 = Tinv0[t0 & 255] ^ Shift(Tinv0[(r3 >> 8) & 255], 24) ^ Shift(Tinv0[(t2 >> 16) & 255], 16) ^ Shift(Tinv0[(t1 >> 24) & 255], 8) ^ kw[0]; r1 = Tinv0[t1 & 255] ^ Shift(Tinv0[(t0 >> 8) & 255], 24) ^ Shift(Tinv0[(r3 >> 16) & 255], 16) ^ Shift(Tinv0[(t2 >> 24) & 255], 8) ^ kw[1]; r2 = Tinv0[t2 & 255] ^ Shift(Tinv0[(t1 >> 8) & 255], 24) ^ Shift(Tinv0[(t0 >> 16) & 255], 16) ^ Shift(Tinv0[(r3 >> 24) & 255], 8) ^ kw[2]; r3 = Tinv0[r3 & 255] ^ Shift(Tinv0[(t2 >> 8) & 255], 24) ^ Shift(Tinv0[(t1 >> 16) & 255], 16) ^ Shift(Tinv0[(t0 >> 24) & 255], 8) ^ kw[3]; // the final round's table is a simple function of Si so we don't use a whole other four tables for it kw = KW[0]; this.C0 = (uint)Si[r0 & 255] ^ (((uint)Si[(r3 >> 8) & 255]) << 8) ^ (((uint)Si[(r2 >> 16) & 255]) << 16) ^ (((uint)Si[(r1 >> 24) & 255]) << 24) ^ kw[0]; this.C1 = (uint)Si[r1 & 255] ^ (((uint)Si[(r0 >> 8) & 255]) << 8) ^ (((uint)Si[(r3 >> 16) & 255]) << 16) ^ (((uint)Si[(r2 >> 24) & 255]) << 24) ^ kw[1]; this.C2 = (uint)Si[r2 & 255] ^ (((uint)Si[(r1 >> 8) & 255]) << 8) ^ (((uint)Si[(r0 >> 16) & 255]) << 16) ^ (((uint)Si[(r3 >> 24) & 255]) << 24) ^ kw[2]; this.C3 = (uint)Si[r3 & 255] ^ (((uint)Si[(r2 >> 8) & 255]) << 8) ^ (((uint)Si[(r1 >> 16) & 255]) << 16) ^ (((uint)Si[(r0 >> 24) & 255]) << 24) ^ kw[3]; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Diagnostics; using System.IO; using System.Threading; namespace Microsoft.NodejsTools.Npm.SPI { internal class NpmController : AbstractNpmLogSource, INpmController { private string cachePath; private bool showMissingDevOptionalSubPackages; private INpmPathProvider npmPathProvider; private IRootPackage rootPackage; private readonly object packageLock = new object(); private readonly FileSystemWatcher localWatcher; private Timer fileSystemWatcherTimer; private int refreshRetryCount; private readonly object fileBitsLock = new object(); private bool isDisposed; private bool isReloadingModules = false; public NpmController( string fullPathToRootPackageDirectory, string cachePath, bool isProject, bool showMissingDevOptionalSubPackages = false, INpmPathProvider npmPathProvider = null) { this.IsProject = isProject; this.FullPathToRootPackageDirectory = fullPathToRootPackageDirectory; this.cachePath = cachePath; this.showMissingDevOptionalSubPackages = showMissingDevOptionalSubPackages; this.npmPathProvider = npmPathProvider; this.localWatcher = CreateModuleDirectoryWatcherIfDirectoryExists(this.FullPathToRootPackageDirectory); try { ReloadModules(); } catch (NpmNotFoundException) { } } public bool IsProject { get; } internal string FullPathToRootPackageDirectory { get; } internal string PathToNpm { get { try { return this.npmPathProvider?.PathToNpm; } catch (NpmNotFoundException) { return null; } } } public event EventHandler StartingRefresh; private void RaiseEvents(EventHandler handlers) { if (null != handlers) { handlers(this, EventArgs.Empty); } } private void OnStartingRefresh() { RaiseEvents(StartingRefresh); } public event EventHandler FinishedRefresh; private void OnFinishedRefresh() { RaiseEvents(FinishedRefresh); } public void Refresh() { try { RefreshImplementation(); } catch (Exception ex) { if (ex != null) { OnOutputLogged(ex.ToString()); #if DEBUG Debug.Fail(ex.ToString()); #endif } } } private void RefreshImplementation() { OnStartingRefresh(); try { lock (this.fileBitsLock) { if (this.isReloadingModules) { RestartFileSystemWatcherTimer(); return; } else { this.isReloadingModules = true; } } this.RootPackage = RootPackageFactory.Create( this.FullPathToRootPackageDirectory, this.showMissingDevOptionalSubPackages); return; } catch (IOException) { // Can sometimes happen when packages are still installing because the file may still be used by another process } finally { lock (this.fileBitsLock) { this.isReloadingModules = false; } if (this.RootPackage == null) { OnOutputLogged("Error - Cannot load local packages."); } OnFinishedRefresh(); } } public IRootPackage RootPackage { get { lock (this.packageLock) { return this.rootPackage; } } private set { lock (this.packageLock) { this.rootPackage = value; } } } public INpmCommander CreateNpmCommander() { return new NpmCommander(this); } public void LogCommandStarted(object sender, EventArgs args) { OnCommandStarted(); } public void LogOutput(object sender, NpmLogEventArgs e) { OnOutputLogged(e.LogText); } public void LogError(object sender, NpmLogEventArgs e) { OnErrorLogged(e.LogText); } public void LogException(object sender, NpmExceptionEventArgs e) { OnExceptionLogged(e.Exception); } public void LogCommandCompleted(object sender, NpmCommandCompletedEventArgs e) { OnCommandCompleted(e.Arguments, e.WithErrors, e.Cancelled); } private FileSystemWatcher CreateModuleDirectoryWatcherIfDirectoryExists(string directory) { if (!Directory.Exists(directory)) { return null; } FileSystemWatcher watcher = null; try { watcher = new FileSystemWatcher(directory) { NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.CreationTime, IncludeSubdirectories = true }; watcher.Changed += this.WatcherModified; watcher.Created += this.WatcherModified; watcher.Deleted += this.WatcherModified; watcher.EnableRaisingEvents = true; } catch (Exception ex) { if (watcher != null) { watcher.Dispose(); } if (ex is IOException || ex is ArgumentException) { Debug.WriteLine("Error starting FileSystemWatcher:\r\n{0}", ex); } else { throw; } } return watcher; } private void WatcherModified(object sender, FileSystemEventArgs e) { string path = e.FullPath; // Check that the file is either a package.json file, or exists in the node_modules directory // This allows us to properly detect both installed and uninstalled/linked packages (where we don't receive an event for package.json) if (path.EndsWith("package.json", StringComparison.OrdinalIgnoreCase) || path.IndexOf(NodejsConstants.NodeModulesFolder, StringComparison.OrdinalIgnoreCase) != -1) { RestartFileSystemWatcherTimer(); } return; } private void RestartFileSystemWatcherTimer() { lock (this.fileBitsLock) { if (null != this.fileSystemWatcherTimer) { this.fileSystemWatcherTimer.Dispose(); } // Be sure to update the FileWatcher in NodejsProjectNode if the dueTime value changes. this.fileSystemWatcherTimer = new Timer(o => UpdateModulesFromTimer(), null, 1000, Timeout.Infinite); } } private void UpdateModulesFromTimer() { lock (this.fileBitsLock) { if (null != this.fileSystemWatcherTimer) { this.fileSystemWatcherTimer.Dispose(); this.fileSystemWatcherTimer = null; } } ReloadModules(); } private void ReloadModules() { var retry = false; Exception ex = null; try { this.Refresh(); } catch (PackageJsonException pje) { retry = true; ex = pje; } catch (AggregateException ae) { retry = true; ex = ae; } catch (FileLoadException fle) { // Fixes bug reported in work item 447 - just wait a bit and retry! retry = true; ex = fle; } if (retry) { if (this.refreshRetryCount < 5) { ++this.refreshRetryCount; RestartFileSystemWatcherTimer(); } else { OnExceptionLogged(ex); } } } public void Dispose() { if (!this.isDisposed) { lock (this.fileBitsLock) { if (this.localWatcher != null) { this.localWatcher.Changed -= this.WatcherModified; this.localWatcher.Created -= this.WatcherModified; this.localWatcher.Deleted -= this.WatcherModified; this.localWatcher.Dispose(); } } lock (this.fileBitsLock) { if (null != this.fileSystemWatcherTimer) { this.fileSystemWatcherTimer.Dispose(); this.fileSystemWatcherTimer = null; } } this.isDisposed = true; } } } }
// 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. //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // RuntimeHelpers // This class defines a set of static methods that provide support for compilers. // using Internal.Reflection.Augments; using Internal.Reflection.Core.NonPortable; using Internal.Runtime.Augments; using System.Runtime; using System.Runtime.Serialization; using System.Threading; namespace System.Runtime.CompilerServices { public static class RuntimeHelpers { [Intrinsic] public static void InitializeArray(Array array, RuntimeFieldHandle fldHandle) { // We only support this intrinsic when it occurs within a well-defined IL sequence. // If a call to this method occurs within the recognized sequence, codegen must expand the IL sequence completely. // For any other purpose, the API is currently unsupported. // https://github.com/dotnet/corert/issues/364 throw new PlatformNotSupportedException(); } public static void RunClassConstructor(RuntimeTypeHandle type) { if (type.IsNull) throw new ArgumentException(SR.InvalidOperation_HandleIsNotInitialized); IntPtr pStaticClassConstructionContext = RuntimeAugments.Callbacks.TryGetStaticClassConstructionContext(type); if (pStaticClassConstructionContext == IntPtr.Zero) return; unsafe { ClassConstructorRunner.EnsureClassConstructorRun((StaticClassConstructionContext*)pStaticClassConstructionContext); } } public static void RunModuleConstructor(ModuleHandle module) { if (module.AssociatedModule == null) throw new ArgumentException(SR.InvalidOperation_HandleIsNotInitialized); ReflectionAugments.ReflectionCoreCallbacks.RunModuleConstructor(module.AssociatedModule); } public static Object GetObjectValue(Object obj) { if (obj == null) return null; EETypePtr eeType = obj.EETypePtr; if ((!eeType.IsValueType) || eeType.IsPrimitive) return obj; return RuntimeImports.RhMemberwiseClone(obj); } public new static bool Equals(Object obj1, Object obj2) { if (obj1 == obj2) return true; if ((obj1 == null) || (obj2 == null)) return false; // If it's not a value class, don't compare by value if (!obj1.EETypePtr.IsValueType) return false; // Make sure they are the same type. if (obj1.EETypePtr != obj2.EETypePtr) return false; return RuntimeImports.RhCompareObjectContentsAndPadding(obj1, obj2); } #if !FEATURE_SYNCTABLE private const int HASHCODE_BITS = 26; private const int MASK_HASHCODE = (1 << HASHCODE_BITS) - 1; #endif [ThreadStatic] private static int t_hashSeed; internal static int GetNewHashCode() { int multiplier = Environment.CurrentManagedThreadId * 4 + 5; // Every thread has its own generator for hash codes so that we won't get into a situation // where two threads consistently give out the same hash codes. // Choice of multiplier guarantees period of 2**32 - see Knuth Vol 2 p16 (3.2.1.2 Theorem A). t_hashSeed = t_hashSeed * multiplier + 1; return t_hashSeed; } public static unsafe int GetHashCode(Object o) { #if FEATURE_SYNCTABLE return ObjectHeader.GetHashCode(o); #else if (o == null) return 0; fixed (IntPtr* pEEType = &o.m_pEEType) { int* pSyncBlockIndex = (int*)((byte*)pEEType - 4); // skipping exactly 4 bytes for the SyncTableEntry (exactly 4 bytes not a pointer size). int hash = *pSyncBlockIndex & MASK_HASHCODE; if (hash == 0) return MakeHashCode(o, pSyncBlockIndex); else return hash; } #endif } #if !FEATURE_SYNCTABLE private static unsafe int MakeHashCode(Object o, int* pSyncBlockIndex) { int hash = GetNewHashCode() & MASK_HASHCODE; if (hash == 0) hash = 1; while (true) { int oldIndex = Volatile.Read(ref *pSyncBlockIndex); int currentHash = oldIndex & MASK_HASHCODE; if (currentHash != 0) { // Someone else set the hash code. hash = currentHash; break; } int newIndex = oldIndex | hash; if (Interlocked.CompareExchange(ref *pSyncBlockIndex, newIndex, oldIndex) == oldIndex) break; // If we get here someone else modified the header. They may have set the hash code, or maybe some // other bits. Let's try again. } return hash; } #endif public static int OffsetToStringData { get { // Number of bytes from the address pointed to by a reference to // a String to the first 16-bit character in the String. // This property allows C#'s fixed statement to work on Strings. return String.FIRST_CHAR_OFFSET; } } [ThreadStatic] private static unsafe byte* t_sufficientStackLimit; public static unsafe void EnsureSufficientExecutionStack() { byte* limit = t_sufficientStackLimit; if (limit == null) limit = GetSufficientStackLimit(); byte* currentStackPtr = (byte*)(&limit); if (currentStackPtr < limit) throw new InsufficientExecutionStackException(); } public static unsafe bool TryEnsureSufficientExecutionStack() { byte* limit = t_sufficientStackLimit; if (limit == null) limit = GetSufficientStackLimit(); byte* currentStackPtr = (byte*)(&limit); return (currentStackPtr >= limit); } [MethodImpl(MethodImplOptions.NoInlining)] // Only called once per thread, no point in inlining. private static unsafe byte* GetSufficientStackLimit() { IntPtr lower, upper; RuntimeImports.RhGetCurrentThreadStackBounds(out lower, out upper); // Compute the limit used by EnsureSufficientExecutionStack and cache it on the thread. This minimum // stack size should be sufficient to allow a typical non-recursive call chain to execute, including // potential exception handling and garbage collection. #if BIT64 const int MinExecutionStackSize = 128 * 1024; #else const int MinExecutionStackSize = 64 * 1024; #endif byte* limit = (((byte*)upper - (byte*)lower > MinExecutionStackSize)) ? ((byte*)lower + MinExecutionStackSize) : ((byte*)upper); return (t_sufficientStackLimit = limit); } [Intrinsic] public static bool IsReferenceOrContainsReferences<T>() { var pEEType = EETypePtr.EETypePtrOf<T>(); return !pEEType.IsValueType || pEEType.HasPointers; } [Intrinsic] public static bool IsReference<T>() { var pEEType = EETypePtr.EETypePtrOf<T>(); return !pEEType.IsValueType; } // Constrained Execution Regions APIs are NOP's because we do not support CERs in .NET Core at all. public static void ProbeForSufficientStack() { } public static void PrepareConstrainedRegions() { } public static void PrepareConstrainedRegionsNoOP() { } public static void PrepareMethod(RuntimeMethodHandle method) { } public static void PrepareMethod(RuntimeMethodHandle method, RuntimeTypeHandle[] instantiation) { } public static void PrepareContractedDelegate(Delegate d) { } public static void PrepareDelegate(Delegate d) { if (d == null) throw new ArgumentNullException(nameof(d)); } public static void ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) { if (code == null) throw new ArgumentNullException(nameof(code)); if (backoutCode == null) throw new ArgumentNullException(nameof(backoutCode)); bool exceptionThrown = false; try { code(userData); } catch { exceptionThrown = true; throw; } finally { backoutCode(userData, exceptionThrown); } } public delegate void TryCode(Object userData); public delegate void CleanupCode(Object userData, bool exceptionThrown); public static object GetUninitializedObject(Type type) { if (type == null) { throw new ArgumentNullException(nameof(type), SR.ArgumentNull_Type); } if(!type.IsRuntimeImplemented()) { throw new SerializationException(SR.Format(SR.Serialization_InvalidType, type.ToString())); } if (type.HasElementType || type.IsGenericParameter) { throw new ArgumentException(SR.Argument_InvalidValue); } if (type.ContainsGenericParameters) { throw new MemberAccessException(SR.Acc_CreateGeneric); } if (type.IsCOMObject) { throw new NotSupportedException(SR.NotSupported_ManagedActivation); } EETypePtr eeTypePtr = type.TypeHandle.ToEETypePtr(); if (eeTypePtr == EETypePtr.EETypePtrOf<string>()) { throw new ArgumentException(SR.Argument_NoUninitializedStrings); } if (eeTypePtr.IsAbstract) { throw new MemberAccessException(SR.Acc_CreateAbst); } if (eeTypePtr.IsByRefLike) { throw new NotSupportedException(SR.NotSupported_ByRefLike); } if (eeTypePtr.IsNullable) { return GetUninitializedObject(ReflectionCoreNonPortable.GetRuntimeTypeForEEType(eeTypePtr.NullableType)); } // Triggering the .cctor here is slightly different than desktop/CoreCLR, which // decide based on BeforeFieldInit, but we don't want to include BeforeFieldInit // in EEType just for this API to behave slightly differently. RunClassConstructor(type.TypeHandle); return RuntimeImports.RhNewObject(eeTypePtr); } } }
// 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.IO; using System.IO.Pipelines; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Net.Http.Headers; using Moq; using Xunit; namespace Microsoft.AspNetCore.Internal { public abstract class VirtualFileResultTestBase { protected abstract Task ExecuteAsync( HttpContext httpContext, string path, string contentType, DateTimeOffset? lastModified = null, EntityTagHeaderValue entityTag = null, bool enableRangeProcessing = false); [Theory] [InlineData(0, 3, 4)] [InlineData(8, 13, 6)] [InlineData(null, 4, 4)] [InlineData(8, null, 25)] public async Task WriteFileAsync_WritesRangeRequested( long? start, long? end, long contentLength) { // Arrange var path = Path.GetFullPath("helllo.txt"); var contentType = "text/plain; charset=us-ascii; p1=p1-value"; var appEnvironment = new Mock<IWebHostEnvironment>(); appEnvironment.Setup(app => app.WebRootFileProvider) .Returns(GetFileProvider(path)); var sendFileFeature = new TestSendFileFeature(); var httpContext = GetHttpContext(GetFileProvider(path)); httpContext.Features.Set<IHttpResponseBodyFeature>(sendFileFeature); var requestHeaders = httpContext.Request.GetTypedHeaders(); requestHeaders.Range = new RangeHeaderValue(start, end); requestHeaders.IfUnmodifiedSince = DateTimeOffset.MinValue.AddDays(1); httpContext.Request.Method = HttpMethods.Get; // Act await ExecuteAsync(httpContext, path, contentType, enableRangeProcessing: true); // Assert var startResult = start ?? 33 - end; var endResult = startResult + contentLength - 1; var httpResponse = httpContext.Response; var contentRange = new ContentRangeHeaderValue(startResult.Value, endResult.Value, 33); Assert.Equal(StatusCodes.Status206PartialContent, httpResponse.StatusCode); Assert.Equal("bytes", httpResponse.Headers.AcceptRanges); Assert.Equal(contentRange.ToString(), httpResponse.Headers.ContentRange); Assert.NotEmpty(httpResponse.Headers.LastModified); Assert.Equal(contentLength, httpResponse.ContentLength); Assert.Equal(path, sendFileFeature.Name); Assert.Equal(startResult, sendFileFeature.Offset); Assert.Equal((long?)contentLength, sendFileFeature.Length); } [Fact] public async Task WriteFileAsync_IfRangeHeaderValid_WritesRequestedRange() { // Arrange var path = Path.GetFullPath("helllo.txt"); var contentType = "text/plain; charset=us-ascii; p1=p1-value"; var appEnvironment = new Mock<IWebHostEnvironment>(); appEnvironment.Setup(app => app.WebRootFileProvider) .Returns(GetFileProvider(path)); var sendFileFeature = new TestSendFileFeature(); var httpContext = GetHttpContext(GetFileProvider(path)); httpContext.Features.Set<IHttpResponseBodyFeature>(sendFileFeature); var entityTag = new EntityTagHeaderValue("\"Etag\""); var requestHeaders = httpContext.Request.GetTypedHeaders(); requestHeaders.IfModifiedSince = DateTimeOffset.MinValue; requestHeaders.Range = new RangeHeaderValue(0, 3); requestHeaders.IfRange = new RangeConditionHeaderValue(new EntityTagHeaderValue("\"Etag\"")); httpContext.Request.Method = HttpMethods.Get; // Act await ExecuteAsync(httpContext, path, contentType, entityTag: entityTag, enableRangeProcessing: true); // Assert var httpResponse = httpContext.Response; Assert.Equal(StatusCodes.Status206PartialContent, httpResponse.StatusCode); Assert.Equal("bytes", httpResponse.Headers.AcceptRanges); var contentRange = new ContentRangeHeaderValue(0, 3, 33); Assert.Equal(contentRange.ToString(), httpResponse.Headers.ContentRange); Assert.Equal(entityTag.ToString(), httpResponse.Headers.ETag); Assert.Equal(4, httpResponse.ContentLength); Assert.Equal(path, sendFileFeature.Name); Assert.Equal(0, sendFileFeature.Offset); Assert.Equal(4, sendFileFeature.Length); } [Fact] public async Task WriteFileAsync_RangeProcessingNotEnabled_RangeRequestedIgnored() { // Arrange var path = Path.GetFullPath("helllo.txt"); var contentType = "text/plain; charset=us-ascii; p1=p1-value"; var appEnvironment = new Mock<IWebHostEnvironment>(); appEnvironment.Setup(app => app.WebRootFileProvider) .Returns(GetFileProvider(path)); var sendFileFeature = new TestSendFileFeature(); var httpContext = GetHttpContext(GetFileProvider(path)); httpContext.Features.Set<IHttpResponseBodyFeature>(sendFileFeature); var entityTag = new EntityTagHeaderValue("\"Etag\""); var requestHeaders = httpContext.Request.GetTypedHeaders(); requestHeaders.IfModifiedSince = DateTimeOffset.MinValue; requestHeaders.Range = new RangeHeaderValue(0, 3); requestHeaders.IfRange = new RangeConditionHeaderValue(new EntityTagHeaderValue("\"Etag\"")); httpContext.Request.Method = HttpMethods.Get; // Act await ExecuteAsync(httpContext, path, contentType, entityTag: entityTag); // Assert var httpResponse = httpContext.Response; Assert.Equal(StatusCodes.Status200OK, httpResponse.StatusCode); Assert.Equal(entityTag.ToString(), httpResponse.Headers.ETag); Assert.Equal(path, sendFileFeature.Name); Assert.Equal(0, sendFileFeature.Offset); Assert.Null(sendFileFeature.Length); } [Fact] public async Task WriteFileAsync_IfRangeHeaderInvalid_RangeRequestedIgnored() { // Arrange var path = Path.GetFullPath("helllo.txt"); var contentType = "text/plain; charset=us-ascii; p1=p1-value"; var appEnvironment = new Mock<IWebHostEnvironment>(); appEnvironment.Setup(app => app.WebRootFileProvider) .Returns(GetFileProvider(path)); var sendFileFeature = new TestSendFileFeature(); var httpContext = GetHttpContext(GetFileProvider(path)); httpContext.Features.Set<IHttpResponseBodyFeature>(sendFileFeature); var entityTag = new EntityTagHeaderValue("\"Etag\""); var requestHeaders = httpContext.Request.GetTypedHeaders(); requestHeaders.IfModifiedSince = DateTimeOffset.MinValue; requestHeaders.Range = new RangeHeaderValue(0, 3); requestHeaders.IfRange = new RangeConditionHeaderValue(new EntityTagHeaderValue("\"NotEtag\"")); httpContext.Request.Method = HttpMethods.Get; // Act await ExecuteAsync(httpContext, path, contentType, entityTag: entityTag, enableRangeProcessing: true); // Assert var httpResponse = httpContext.Response; Assert.Equal(StatusCodes.Status200OK, httpResponse.StatusCode); Assert.Equal(entityTag.ToString(), httpResponse.Headers.ETag); Assert.Equal(path, sendFileFeature.Name); Assert.Equal(0, sendFileFeature.Offset); Assert.Null(sendFileFeature.Length); } [Theory] [InlineData("0-5")] [InlineData("bytes = ")] [InlineData("bytes = 1-4, 5-11")] public async Task WriteFileAsync_RangeHeaderMalformed_RangeRequestIgnored(string rangeString) { // Arrange var path = Path.GetFullPath("helllo.txt"); var contentType = "text/plain; charset=us-ascii; p1=p1-value"; var appEnvironment = new Mock<IWebHostEnvironment>(); appEnvironment.Setup(app => app.WebRootFileProvider) .Returns(GetFileProvider(path)); var sendFileFeature = new TestSendFileFeature(); var httpContext = GetHttpContext(GetFileProvider(path)); httpContext.Features.Set<IHttpResponseBodyFeature>(sendFileFeature); var requestHeaders = httpContext.Request.GetTypedHeaders(); httpContext.Request.Headers.Range = rangeString; requestHeaders.IfUnmodifiedSince = DateTimeOffset.MinValue.AddDays(1); httpContext.Request.Method = HttpMethods.Get; // Act await ExecuteAsync(httpContext, path, contentType, enableRangeProcessing: true); // Assert var httpResponse = httpContext.Response; Assert.Equal(StatusCodes.Status200OK, httpResponse.StatusCode); Assert.Empty(httpResponse.Headers.ContentRange); Assert.NotEmpty(httpResponse.Headers.LastModified); Assert.Equal(path, sendFileFeature.Name); Assert.Equal(0, sendFileFeature.Offset); Assert.Null(sendFileFeature.Length); } [Theory] [InlineData("bytes = 35-36")] [InlineData("bytes = -0")] public async Task WriteFileAsync_RangeRequestedNotSatisfiable(string rangeString) { // Arrange var path = Path.GetFullPath("helllo.txt"); var contentType = "text/plain; charset=us-ascii; p1=p1-value"; var appEnvironment = new Mock<IWebHostEnvironment>(); appEnvironment.Setup(app => app.WebRootFileProvider) .Returns(GetFileProvider(path)); var httpContext = GetHttpContext(GetFileProvider(path)); httpContext.Response.Body = new MemoryStream(); var requestHeaders = httpContext.Request.GetTypedHeaders(); httpContext.Request.Headers.Range = rangeString; requestHeaders.IfUnmodifiedSince = DateTimeOffset.MinValue.AddDays(1); httpContext.Request.Method = HttpMethods.Get; httpContext.Response.Body = new MemoryStream(); // Act await ExecuteAsync(httpContext, path, contentType, enableRangeProcessing: true); // Assert var httpResponse = httpContext.Response; httpResponse.Body.Seek(0, SeekOrigin.Begin); var streamReader = new StreamReader(httpResponse.Body); var body = streamReader.ReadToEndAsync().Result; var contentRange = new ContentRangeHeaderValue(33); Assert.Equal(StatusCodes.Status416RangeNotSatisfiable, httpResponse.StatusCode); Assert.Equal("bytes", httpResponse.Headers.AcceptRanges); Assert.Equal(contentRange.ToString(), httpResponse.Headers.ContentRange); Assert.NotEmpty(httpResponse.Headers.LastModified); Assert.Equal(0, httpResponse.ContentLength); Assert.Empty(body); } [Fact] public async Task WriteFileAsync_RangeRequested_PreconditionFailed() { // Arrange var path = Path.GetFullPath("helllo.txt"); var contentType = "text/plain; charset=us-ascii; p1=p1-value"; var appEnvironment = new Mock<IWebHostEnvironment>(); appEnvironment.Setup(app => app.WebRootFileProvider) .Returns(GetFileProvider(path)); var sendFileFeature = new TestSendFileFeature(); var httpContext = GetHttpContext(GetFileProvider(path)); httpContext.Features.Set<IHttpResponseBodyFeature>(sendFileFeature); var requestHeaders = httpContext.Request.GetTypedHeaders(); requestHeaders.IfUnmodifiedSince = DateTimeOffset.MinValue; httpContext.Request.Headers.Range = "bytes = 0-6"; httpContext.Request.Method = HttpMethods.Get; // Act await ExecuteAsync(httpContext, path, contentType, enableRangeProcessing: true); // Assert var httpResponse = httpContext.Response; Assert.Equal(StatusCodes.Status412PreconditionFailed, httpResponse.StatusCode); Assert.Null(httpResponse.ContentLength); Assert.Empty(httpResponse.Headers.ContentRange); Assert.NotEmpty(httpResponse.Headers.LastModified); Assert.Null(sendFileFeature.Name); // Not called } [Fact] public async Task WriteFileAsync_RangeRequested_NotModified() { // Arrange var path = Path.GetFullPath("helllo.txt"); var contentType = "text/plain; charset=us-ascii; p1=p1-value"; var appEnvironment = new Mock<IWebHostEnvironment>(); appEnvironment.Setup(app => app.WebRootFileProvider) .Returns(GetFileProvider(path)); var sendFileFeature = new TestSendFileFeature(); var httpContext = GetHttpContext(GetFileProvider(path)); httpContext.Features.Set<IHttpResponseBodyFeature>(sendFileFeature); var requestHeaders = httpContext.Request.GetTypedHeaders(); requestHeaders.IfModifiedSince = DateTimeOffset.MinValue.AddDays(1); httpContext.Request.Headers.Range = "bytes = 0-6"; httpContext.Request.Method = HttpMethods.Get; // Act await ExecuteAsync(httpContext, path, contentType, enableRangeProcessing: true); // Assert var httpResponse = httpContext.Response; Assert.Equal(StatusCodes.Status304NotModified, httpResponse.StatusCode); Assert.Null(httpResponse.ContentLength); Assert.Empty(httpResponse.Headers.ContentRange); Assert.NotEmpty(httpResponse.Headers.LastModified); Assert.False(httpResponse.Headers.ContainsKey(HeaderNames.ContentType)); Assert.Null(sendFileFeature.Name); // Not called } [Theory] [InlineData(0, 3, 4)] [InlineData(8, 13, 6)] [InlineData(null, 3, 3)] [InlineData(8, null, 25)] public async Task ExecuteResultAsync_CallsSendFileAsyncWithRequestedRange_IfIHttpSendFilePresent(long? start, long? end, long contentLength) { // Arrange var path = Path.Combine("TestFiles", "FilePathResultTestFile.txt"); var sendFile = new TestSendFileFeature(); var httpContext = GetHttpContext(GetFileProvider(path)); httpContext.Features.Set<IHttpResponseBodyFeature>(sendFile); var appEnvironment = new Mock<IWebHostEnvironment>(); appEnvironment.Setup(app => app.WebRootFileProvider) .Returns(GetFileProvider(path)); var requestHeaders = httpContext.Request.GetTypedHeaders(); requestHeaders.Range = new RangeHeaderValue(start, end); requestHeaders.IfUnmodifiedSince = DateTimeOffset.MinValue.AddDays(1); httpContext.Request.Method = HttpMethods.Get; // Act await ExecuteAsync(httpContext, path, "text/plain", enableRangeProcessing: true); // Assert start = start ?? 33 - end; end = start + contentLength - 1; var httpResponse = httpContext.Response; Assert.Equal(Path.Combine("TestFiles", "FilePathResultTestFile.txt"), sendFile.Name); Assert.Equal(start, sendFile.Offset); Assert.Equal(contentLength, sendFile.Length); Assert.Equal(CancellationToken.None, sendFile.Token); var contentRange = new ContentRangeHeaderValue(start.Value, end.Value, 33); Assert.Equal(StatusCodes.Status206PartialContent, httpResponse.StatusCode); Assert.Equal("bytes", httpResponse.Headers.AcceptRanges); Assert.Equal(contentRange.ToString(), httpResponse.Headers.ContentRange); Assert.NotEmpty(httpResponse.Headers.LastModified); Assert.Equal(contentLength, httpResponse.ContentLength); } [Fact] public async Task ExecuteResultAsync_SetsSuppliedContentTypeAndEncoding() { // Arrange var expectedContentType = "text/foo; charset=us-ascii"; var sendFileFeature = new TestSendFileFeature(); var httpContext = GetHttpContext(GetFileProvider("FilePathResultTestFile_ASCII.txt")); httpContext.Features.Set<IHttpResponseBodyFeature>(sendFileFeature); // Act await ExecuteAsync(httpContext, "FilePathResultTestFile_ASCII.txt", expectedContentType); // Assert Assert.Equal(expectedContentType, httpContext.Response.ContentType); Assert.Equal("FilePathResultTestFile_ASCII.txt", sendFileFeature.Name); } [Fact] public async Task ExecuteResultAsync_ReturnsFileContentsForRelativePaths() { // Arrange var path = Path.Combine("TestFiles", "FilePathResultTestFile.txt"); var sendFileFeature = new TestSendFileFeature(); var httpContext = GetHttpContext(GetFileProvider(path)); httpContext.Features.Set<IHttpResponseBodyFeature>(sendFileFeature); // Act await ExecuteAsync(httpContext, path, "text/plain"); // Assert Assert.Equal(path, sendFileFeature.Name); } [Theory] [InlineData("FilePathResultTestFile.txt")] [InlineData("TestFiles/FilePathResultTestFile.txt")] [InlineData("TestFiles/../FilePathResultTestFile.txt")] [InlineData("TestFiles\\FilePathResultTestFile.txt")] [InlineData("TestFiles\\..\\FilePathResultTestFile.txt")] [InlineData(@"\\..//?><|""&@#\c:\..\? /..txt")] public async Task ExecuteResultAsync_ReturnsFiles_ForDifferentPaths(string path) { // Arrange var sendFileFeature = new TestSendFileFeature(); var webRootFileProvider = GetFileProvider(path); var httpContext = GetHttpContext(webRootFileProvider); httpContext.Features.Set<IHttpResponseBodyFeature>(sendFileFeature); // Act await ExecuteAsync(httpContext, path, "text/plain"); // Assert Mock.Get(webRootFileProvider).Verify(); Assert.Equal(path, sendFileFeature.Name); } [Theory] [InlineData("~/FilePathResultTestFile.txt")] [InlineData("~/TestFiles/FilePathResultTestFile.txt")] [InlineData("~/TestFiles/../FilePathResultTestFile.txt")] [InlineData("~/TestFiles\\..\\FilePathResultTestFile.txt")] [InlineData(@"~~~~\\..//?>~<|""&@#\c:\..\? /..txt~~~")] public async Task ExecuteResultAsync_TrimsTilde_BeforeInvokingFileProvider(string path) { // Arrange var expectedPath = path.Substring(1); var sendFileFeature = new TestSendFileFeature(); var webRootFileProvider = GetFileProvider(expectedPath); var httpContext = GetHttpContext(webRootFileProvider); httpContext.Features.Set<IHttpResponseBodyFeature>(sendFileFeature); // Act await ExecuteAsync(httpContext, path, "text/plain"); // Assert Mock.Get(webRootFileProvider).Verify(); Assert.Equal(expectedPath, sendFileFeature.Name); } [Fact] public async Task ExecuteResultAsync_WorksWithNonDiskBasedFiles() { // Arrange var expectedData = "This is an embedded resource"; var sourceStream = new MemoryStream(Encoding.UTF8.GetBytes(expectedData)); var nonDiskFileInfo = new Mock<IFileInfo>(); nonDiskFileInfo.SetupGet(fi => fi.Exists).Returns(true); nonDiskFileInfo.SetupGet(fi => fi.PhysicalPath).Returns(() => null); // set null to indicate non-disk file nonDiskFileInfo.Setup(fi => fi.CreateReadStream()).Returns(sourceStream); var nonDiskFileProvider = new Mock<IFileProvider>(); nonDiskFileProvider.Setup(fp => fp.GetFileInfo(It.IsAny<string>())).Returns(nonDiskFileInfo.Object); var httpContext = GetHttpContext(nonDiskFileProvider.Object); httpContext.Response.Body = new MemoryStream(); // Act await ExecuteAsync(httpContext, "/SampleEmbeddedFile.txt", "text/plain"); // Assert httpContext.Response.Body.Position = 0; var contents = await new StreamReader(httpContext.Response.Body).ReadToEndAsync(); Assert.Equal(expectedData, contents); } [Fact] public async Task ExecuteResultAsync_ThrowsFileNotFound_IfFileProviderCanNotFindTheFile() { // Arrange var path = "TestPath.txt"; var fileInfo = new Mock<IFileInfo>(); fileInfo.SetupGet(f => f.Exists).Returns(false); var fileProvider = new Mock<IFileProvider>(); fileProvider.Setup(f => f.GetFileInfo(path)).Returns(fileInfo.Object); var expectedMessage = $"Could not find file: {path}."; var httpContext = GetHttpContext(fileProvider.Object); // Act var ex = await Assert.ThrowsAsync<FileNotFoundException>(() => ExecuteAsync(httpContext, path, "text/plain")); // Assert Assert.Equal(expectedMessage, ex.Message); Assert.Equal(path, ex.FileName); } private static IServiceCollection CreateServices(IFileProvider webRootFileProvider) { var services = new ServiceCollection(); var hostingEnvironment = Mock.Of<IWebHostEnvironment>(e => e.WebRootFileProvider == webRootFileProvider); services.AddSingleton<IWebHostEnvironment>(hostingEnvironment); services.AddSingleton<ILoggerFactory>(NullLoggerFactory.Instance); services.AddSingleton(typeof(ILogger<>), typeof(NullLogger<>)); return services; } private static HttpContext GetHttpContext(IFileProvider webRootFileProvider) { var services = CreateServices(webRootFileProvider); var httpContext = new DefaultHttpContext(); httpContext.RequestServices = services.BuildServiceProvider(); return httpContext; } protected static IFileProvider GetFileProvider(string path) { var fileInfo = new Mock<IFileInfo>(); fileInfo.SetupGet(fi => fi.Length).Returns(33); fileInfo.SetupGet(fi => fi.Exists).Returns(true); var lastModified = DateTimeOffset.MinValue.AddDays(1); lastModified = new DateTimeOffset(lastModified.Year, lastModified.Month, lastModified.Day, lastModified.Hour, lastModified.Minute, lastModified.Second, TimeSpan.FromSeconds(0)); fileInfo.SetupGet(fi => fi.LastModified).Returns(lastModified); fileInfo.SetupGet(fi => fi.PhysicalPath).Returns(path); var fileProvider = new Mock<IFileProvider>(); fileProvider.Setup(fp => fp.GetFileInfo(path)) .Returns(fileInfo.Object) .Verifiable(); return fileProvider.Object; } private class TestSendFileFeature : IHttpResponseBodyFeature { public string Name { get; set; } public long Offset { get; set; } public long? Length { get; set; } public CancellationToken Token { get; set; } public Stream Stream => throw new NotImplementedException(); public PipeWriter Writer => throw new NotImplementedException(); public Task CompleteAsync() { throw new NotImplementedException(); } public void DisableBuffering() { throw new NotImplementedException(); } public Task SendFileAsync(string path, long offset, long? length, CancellationToken cancellation) { Name = path; Offset = offset; Length = length; Token = cancellation; return Task.FromResult(0); } public Task StartAsync(CancellationToken cancellation = default) { throw new NotImplementedException(); } } } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using JSONObject = System.Collections.Generic.Dictionary<string, JSON>; using JSONArray = System.Collections.Generic.List<JSON>; public enum JSONType { NULL, OBJECT, ARRAY, STRING, INTEGER, FLOAT, BOOLEAN }; public class JSON : IEnumerable { #region Data Containers private JSONObject object_data; private JSONArray array_data; private string string_data; private int integer_data; private float float_data; private bool boolean_data; public object Value { get { switch (Type) { case JSONType.OBJECT: return array_data; case JSONType.STRING: return string_data; case JSONType.INTEGER: return integer_data; case JSONType.FLOAT: return float_data; case JSONType.BOOLEAN: return boolean_data; } return null; } } #endregion #region Type JSONType _type; public JSONType Type { get { return this._type; } set { switch (value) { case JSONType.OBJECT: this.object_data = new JSONObject(); break; case JSONType.ARRAY: this.array_data = new JSONArray(); break; default: break; } this._type = value; } } #endregion #region Parser Variables JSON parent; #endregion #region Constructors And Parser public JSON() { Type = JSONType.NULL; } public JSON(JSON p) { parent = p; } public JSON (string json) { JSON current = this; for (int pos = 0; pos < json.Length; pos++) { switch (json[pos]) { // Object start case '{': current.Type = JSONType.OBJECT; break; // Object end case '}': if (System.Object.ReferenceEquals(current, this)) return; UpOneLevel (ref current); break; // Array start case '[': if (System.Object.ReferenceEquals(current, this)) return; if (current.Type == JSONType.NULL) current.Type = JSONType.ARRAY; NewArrayElement(ref current); break; // Array end case ']': UpOneLevel (ref current, false); current.array_data.RemoveAt(current.array_data.Count - 1); UpOneLevel (ref current); break; // String start case '"': switch (current.Type) { // String value case JSONType.NULL: current.Type = JSONType.STRING; current.string_data = ParseString(json, ref pos); UpOneLevel (ref current); break; // String key case JSONType.OBJECT: string key = ParseString(json, ref pos); current.object_data[key] = new JSON(current); current = current.object_data[key]; break; default: throw new FormatException("JSON error: unexpected string"); } break; // NULL case 'n': if (json.Substring(pos, 4) == "null") { UpOneLevel (ref current); pos += 3; } else { throw new FormatException("JSON error: invalid syntax (did you expect 'null'?)"); } break; // True case 't': if (json.Substring(pos, 4) == "true") { current.SetValue(true); UpOneLevel (ref current); pos += 3; } else { throw new FormatException("JSON error: invalid syntax (did you expect 'true'?)"); } break; // False case 'f': if (json.Substring(pos, 5) == "false") { current.SetValue(false); UpOneLevel (ref current); pos += 4; } else { throw new FormatException("JSON error: invalid syntax (did you expect 'false'?)"); } break; // Numbers case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (current.Type != JSONType.NULL) throw new InvalidOperationException("JSON error: numbers can be only values"); int start, end; string num_symbols = "01234567890.eE+-"; start = end = pos; while (num_symbols.Contains(json[end].ToString())) { end++; } string number_str = json.Substring(start, end - start); try { int i = System.Convert.ToInt32(number_str); current.SetValue(i); UpOneLevel (ref current); } catch (Exception) { try { float f = System.Convert.ToSingle(number_str); current.SetValue(f); UpOneLevel (ref current); } catch (FormatException) { throw new FormatException("JSON error: invalid number format"); } } pos = end - 1; break; // Whitespaces case ' ': case '\t': case '\n': case '\r': case '\b': break; case ':': break; case ',': break; default: throw new FormatException("JSON error: unexpected symbol"); } } } public JSON(object obj) { Type = JSONType.NULL; } #endregion #region Conversions static public implicit operator JSON(string s) { JSON json = new JSON(); json.SetValue(s); return json; } static public implicit operator JSON(int i) { JSON json = new JSON(); json.SetValue(i); return json; } static public implicit operator JSON(float f) { JSON json = new JSON(); json.SetValue(f); return json; } static public implicit operator JSON(bool b) { JSON json = new JSON(); json.SetValue(b); return json; } static public implicit operator string (JSON json) { if(json.Type != JSONType.STRING) throw new InvalidOperationException("JSON error: the instance is not a string"); return json.string_data; } static public implicit operator int (JSON json) { if(json.Type != JSONType.INTEGER && json.Type != JSONType.FLOAT) throw new InvalidOperationException("JSON error: the instance is not a number"); if(json.Type == JSONType.INTEGER) { return json.integer_data; } else { return (int)json.float_data; } } static public implicit operator float (JSON json) { if(json.Type != JSONType.FLOAT && json.Type != JSONType.INTEGER) throw new InvalidOperationException("JSON error: the instance is not a number"); if(json.Type == JSONType.INTEGER) { return json.integer_data; } else { return json.float_data; } } static public implicit operator bool (JSON json) { if(json.Type != JSONType.BOOLEAN) throw new InvalidOperationException("JSON error: the instance is not a boolean"); return json.boolean_data; } #endregion #region Accessors public JSON this[string key] { get { if (Type != JSONType.OBJECT) throw new InvalidOperationException("Instance must be an object"); return object_data[key]; } set { if (Type == JSONType.NULL) Type = JSONType.OBJECT; if (Type != JSONType.OBJECT) throw new InvalidOperationException("Instance must be an object"); object_data[key] = new JSON(value); } } public JSON this[int index] { get { if (Type != JSONType.ARRAY) throw new InvalidOperationException("Instance must be an array"); return array_data[index]; } } public void Add(JSON element) { if (Type == JSONType.NULL) Type = JSONType.ARRAY; if (Type != JSONType.ARRAY) throw new InvalidOperationException("Instance must be an array"); array_data.Add(element); } public void Add(string key, JSON val) { if (Type == JSONType.NULL) Type = JSONType.OBJECT; if (Type != JSONType.OBJECT) throw new InvalidOperationException("Instance must be an object"); object_data.Add(key, val); } public int Count { get { return array_data.Count; } } #endregion #region Setters (internal use only) void SetValue (string s) { Type = JSONType.STRING; string_data = s; } void SetValue (int i) { Type = JSONType.INTEGER; integer_data = i; } void SetValue (float f) { Type = JSONType.FLOAT; float_data = f; } void SetValue (bool b) { Type = JSONType.BOOLEAN; boolean_data = b; } #endregion #region Utils static string ParseString (string json, ref int pos) { int start, end; start = pos + 1; for (end = start; json[end].ToString() != "\"" || json[end-1].ToString() == "\\"; end++); pos = end; return json.Substring(start, end - start); } static void UpOneLevel(ref JSON current, bool add_new = true) { current = current.parent; if ((current.Type == JSONType.ARRAY) && add_new) { NewArrayElement(ref current); } } static void NewArrayElement(ref JSON current) { JSON elm = new JSON(current); current.array_data.Add(elm); current = elm; } #endregion #region Enumerator public IEnumerator GetEnumerator() { return array_data.GetEnumerator(); } #endregion #region Serializer public override string ToString() { string json = ""; switch(Type) { case JSONType.OBJECT: foreach (KeyValuePair<string,JSON> item in object_data) { json += "\"" + item.Key + "\":" + item.Value.ToString() + ","; } if (json.Length > 0) json = json.Remove(json.Length - 1); json = "{" + json + "}"; break; case JSONType.ARRAY: foreach (JSON item in array_data) { json += item.ToString() + ","; } if (json.Length > 0) json = json.Remove(json.Length - 1); json = "[" + json + "]"; break; case JSONType.STRING: json = "\"" + string_data + "\""; break; case JSONType.INTEGER: case JSONType.FLOAT: case JSONType.BOOLEAN: json = System.Convert.ToString(Value).ToLower(); break; case JSONType.NULL: json = "null"; break; } return json; } #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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // Central spin logic used across the entire code-base. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Diagnostics; namespace System.Threading { // SpinWait is just a little value type that encapsulates some common spinning // logic. It ensures we always yield on single-proc machines (instead of using busy // waits), and that we work well on HT. It encapsulates a good mixture of spinning // and real yielding. It's a value type so that various areas of the engine can use // one by allocating it on the stack w/out unnecessary GC allocation overhead, e.g.: // // void f() { // SpinWait wait = new SpinWait(); // while (!p) { wait.SpinOnce(); } // ... // } // // Internally it just maintains a counter that is used to decide when to yield, etc. // // A common usage is to spin before blocking. In those cases, the NextSpinWillYield // property allows a user to decide to fall back to waiting once it returns true: // // void f() { // SpinWait wait = new SpinWait(); // while (!p) { // if (wait.NextSpinWillYield) { /* block! */ } // else { wait.SpinOnce(); } // } // ... // } /// <summary> /// Provides support for spin-based waiting. /// </summary> /// <remarks> /// <para> /// <see cref="SpinWait"/> encapsulates common spinning logic. On single-processor machines, yields are /// always used instead of busy waits, and on computers with Intel(R) processors employing Hyper-Threading /// technology, it helps to prevent hardware thread starvation. SpinWait encapsulates a good mixture of /// spinning and true yielding. /// </para> /// <para> /// <see cref="SpinWait"/> is a value type, which means that low-level code can utilize SpinWait without /// fear of unnecessary allocation overheads. SpinWait is not generally useful for ordinary applications. /// In most cases, you should use the synchronization classes provided by the .NET Framework, such as /// <see cref="System.Threading.Monitor"/>. For most purposes where spin waiting is required, however, /// the <see cref="SpinWait"/> type should be preferred over the <see /// cref="System.Threading.Thread.SpinWait"/> method. /// </para> /// <para> /// While SpinWait is designed to be used in concurrent applications, it is not designed to be /// used from multiple threads concurrently. SpinWait's members are not thread-safe. If multiple /// threads must spin, each should use its own instance of SpinWait. /// </para> /// </remarks> public struct SpinWait { // These constants determine the frequency of yields versus spinning. The // numbers may seem fairly arbitrary, but were derived with at least some // thought in the design document. I fully expect they will need to change // over time as we gain more experience with performance. internal const int YieldThreshold = 10; // When to switch over to a true yield. private const int Sleep0EveryHowManyYields = 5; // After how many yields should we Sleep(0)? internal const int DefaultSleep1Threshold = 20; // After how many yields should we Sleep(1) frequently? /// <summary> /// A suggested number of spin iterations before doing a proper wait, such as waiting on an event that becomes signaled /// when the resource becomes available. /// </summary> /// <remarks> /// These numbers were arrived at by experimenting with different numbers in various cases that currently use it. It's /// only a suggested value and typically works well when the proper wait is something like an event. /// /// Spinning less can lead to early waiting and more context switching, spinning more can decrease latency but may use /// up some CPU time unnecessarily. Depends on the situation too, for instance SemaphoreSlim uses more iterations /// because the waiting there is currently a lot more expensive (involves more spinning, taking a lock, etc.). It also /// depends on the likelihood of the spin being successful and how long the wait would be but those are not accounted /// for here. /// </remarks> internal static readonly int SpinCountforSpinBeforeWait = PlatformHelper.IsSingleProcessor ? 1 : 35; // The number of times we've spun already. private int _count; /// <summary> /// Gets the number of times <see cref="SpinOnce()"/> has been called on this instance. /// </summary> public int Count { get => _count; internal set { Debug.Assert(value >= 0); _count = value; } } /// <summary> /// Gets whether the next call to <see cref="SpinOnce()"/> will yield the processor, triggering a /// forced context switch. /// </summary> /// <value>Whether the next call to <see cref="SpinOnce()"/> will yield the processor, triggering a /// forced context switch.</value> /// <remarks> /// On a single-CPU machine, <see cref="SpinOnce()"/> always yields the processor. On machines with /// multiple CPUs, <see cref="SpinOnce()"/> may yield after an unspecified number of calls. /// </remarks> public bool NextSpinWillYield => _count >= YieldThreshold || PlatformHelper.IsSingleProcessor; /// <summary> /// Performs a single spin. /// </summary> /// <remarks> /// This is typically called in a loop, and may change in behavior based on the number of times a /// <see cref="SpinOnce()"/> has been called thus far on this instance. /// </remarks> public void SpinOnce() { SpinOnceCore(DefaultSleep1Threshold); } /// <summary> /// Performs a single spin. /// </summary> /// <param name="sleep1Threshold"> /// A minimum spin count after which <code>Thread.Sleep(1)</code> may be used. A value of <code>-1</code> may be used to /// disable the use of <code>Thread.Sleep(1)</code>. /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="sleep1Threshold"/> is less than <code>-1</code>. /// </exception> /// <remarks> /// This is typically called in a loop, and may change in behavior based on the number of times a /// <see cref="SpinOnce()"/> has been called thus far on this instance. /// </remarks> public void SpinOnce(int sleep1Threshold) { if (sleep1Threshold < -1) { throw new ArgumentOutOfRangeException(nameof(sleep1Threshold), sleep1Threshold, SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } if (sleep1Threshold >= 0 && sleep1Threshold < YieldThreshold) { sleep1Threshold = YieldThreshold; } SpinOnceCore(sleep1Threshold); } private void SpinOnceCore(int sleep1Threshold) { Debug.Assert(sleep1Threshold >= -1); Debug.Assert(sleep1Threshold < 0 || sleep1Threshold >= YieldThreshold); // (_count - YieldThreshold) % 2 == 0: The purpose of this check is to interleave Thread.Yield/Sleep(0) with // Thread.SpinWait. Otherwise, the following issues occur: // - When there are no threads to switch to, Yield and Sleep(0) become no-op and it turns the spin loop into a // busy-spin that may quickly reach the max spin count and cause the thread to enter a wait state, or may // just busy-spin for longer than desired before a Sleep(1). Completing the spin loop too early can cause // excessive context switcing if a wait follows, and entering the Sleep(1) stage too early can cause // excessive delays. // - If there are multiple threads doing Yield and Sleep(0) (typically from the same spin loop due to // contention), they may switch between one another, delaying work that can make progress. if (( _count >= YieldThreshold && ((_count >= sleep1Threshold && sleep1Threshold >= 0) || (_count - YieldThreshold) % 2 == 0) ) || PlatformHelper.IsSingleProcessor) { // // We must yield. // // We prefer to call Thread.Yield first, triggering a SwitchToThread. This // unfortunately doesn't consider all runnable threads on all OS SKUs. In // some cases, it may only consult the runnable threads whose ideal processor // is the one currently executing code. Thus we occasionally issue a call to // Sleep(0), which considers all runnable threads at equal priority. Even this // is insufficient since we may be spin waiting for lower priority threads to // execute; we therefore must call Sleep(1) once in a while too, which considers // all runnable threads, regardless of ideal processor and priority, but may // remove the thread from the scheduler's queue for 10+ms, if the system is // configured to use the (default) coarse-grained system timer. // if (_count >= sleep1Threshold && sleep1Threshold >= 0) { Thread.Sleep(1); } else { int yieldsSoFar = _count >= YieldThreshold ? (_count - YieldThreshold) / 2 : _count; if ((yieldsSoFar % Sleep0EveryHowManyYields) == (Sleep0EveryHowManyYields - 1)) { Thread.Sleep(0); } else { Thread.Yield(); } } } else { // // Otherwise, we will spin. // // We do this using the CLR's SpinWait API, which is just a busy loop that // issues YIELD/PAUSE instructions to ensure multi-threaded CPUs can react // intelligently to avoid starving. (These are NOOPs on other CPUs.) We // choose a number for the loop iteration count such that each successive // call spins for longer, to reduce cache contention. We cap the total // number of spins we are willing to tolerate to reduce delay to the caller, // since we expect most callers will eventually block anyway. // // Also, cap the maximum spin count to a value such that many thousands of CPU cycles would not be wasted doing // the equivalent of YieldProcessor(), as at that point SwitchToThread/Sleep(0) are more likely to be able to // allow other useful work to run. Long YieldProcessor() loops can help to reduce contention, but Sleep(1) is // usually better for that. // // Thread.OptimalMaxSpinWaitsPerSpinIteration: // - See Thread::InitializeYieldProcessorNormalized(), which describes and calculates this value. // int n = Thread.OptimalMaxSpinWaitsPerSpinIteration; if (_count <= 30 && (1 << _count) < n) { n = 1 << _count; } Thread.SpinWait(n); } // Finally, increment our spin counter. _count = (_count == int.MaxValue ? YieldThreshold : _count + 1); } /// <summary> /// Resets the spin counter. /// </summary> /// <remarks> /// This makes <see cref="SpinOnce()"/> and <see cref="NextSpinWillYield"/> behave as though no calls /// to <see cref="SpinOnce()"/> had been issued on this instance. If a <see cref="SpinWait"/> instance /// is reused many times, it may be useful to reset it to avoid yielding too soon. /// </remarks> public void Reset() { _count = 0; } #region Static Methods /// <summary> /// Spins until the specified condition is satisfied. /// </summary> /// <param name="condition">A delegate to be executed over and over until it returns true.</param> /// <exception cref="ArgumentNullException">The <paramref name="condition"/> argument is null.</exception> public static void SpinUntil(Func<bool> condition) { #if DEBUG bool result = #endif SpinUntil(condition, Timeout.Infinite); #if DEBUG Debug.Assert(result); #endif } /// <summary> /// Spins until the specified condition is satisfied or until the specified timeout is expired. /// </summary> /// <param name="condition">A delegate to be executed over and over until it returns true.</param> /// <param name="timeout"> /// A <see cref="TimeSpan"/> that represents the number of milliseconds to wait, /// or a TimeSpan that represents -1 milliseconds to wait indefinitely.</param> /// <returns>True if the condition is satisfied within the timeout; otherwise, false</returns> /// <exception cref="ArgumentNullException">The <paramref name="condition"/> argument is null.</exception> /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative number /// other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater than /// <see cref="int.MaxValue"/>.</exception> public static bool SpinUntil(Func<bool> condition, TimeSpan timeout) { // Validate the timeout long totalMilliseconds = (long)timeout.TotalMilliseconds; if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new System.ArgumentOutOfRangeException( nameof(timeout), timeout, SR.SpinWait_SpinUntil_TimeoutWrong); } // Call wait with the timeout milliseconds return SpinUntil(condition, (int)totalMilliseconds); } /// <summary> /// Spins until the specified condition is satisfied or until the specified timeout is expired. /// </summary> /// <param name="condition">A delegate to be executed over and over until it returns true.</param> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see /// cref="System.Threading.Timeout.Infinite"/> (-1) to wait indefinitely.</param> /// <returns>True if the condition is satisfied within the timeout; otherwise, false</returns> /// <exception cref="ArgumentNullException">The <paramref name="condition"/> argument is null.</exception> /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a /// negative number other than -1, which represents an infinite time-out.</exception> public static bool SpinUntil(Func<bool> condition, int millisecondsTimeout) { if (millisecondsTimeout < Timeout.Infinite) { throw new ArgumentOutOfRangeException( nameof(millisecondsTimeout), millisecondsTimeout, SR.SpinWait_SpinUntil_TimeoutWrong); } if (condition == null) { throw new ArgumentNullException(nameof(condition), SR.SpinWait_SpinUntil_ArgumentNull); } uint startTime = 0; if (millisecondsTimeout != 0 && millisecondsTimeout != Timeout.Infinite) { startTime = TimeoutHelper.GetTime(); } SpinWait spinner = new SpinWait(); while (!condition()) { if (millisecondsTimeout == 0) { return false; } spinner.SpinOnce(); if (millisecondsTimeout != Timeout.Infinite && spinner.NextSpinWillYield) { if (millisecondsTimeout <= (TimeoutHelper.GetTime() - startTime)) { return false; } } } return true; } #endregion } /// <summary> /// A helper class to get the number of processors, it updates the numbers of processors every sampling interval. /// </summary> internal static class PlatformHelper { private const int PROCESSOR_COUNT_REFRESH_INTERVAL_MS = 30000; // How often to refresh the count, in milliseconds. private static volatile int s_processorCount; // The last count seen. private static volatile int s_lastProcessorCountRefreshTicks; // The last time we refreshed. /// <summary> /// Gets the number of available processors /// </summary> internal static int ProcessorCount { get { int now = Environment.TickCount; int procCount = s_processorCount; if (procCount == 0 || (now - s_lastProcessorCountRefreshTicks) >= PROCESSOR_COUNT_REFRESH_INTERVAL_MS) { s_processorCount = procCount = Environment.ProcessorCount; s_lastProcessorCountRefreshTicks = now; } Debug.Assert(procCount > 0, "Processor count should be greater than 0."); return procCount; } } /// <summary> /// Gets whether the current machine has only a single processor. /// </summary> /// <remarks>This typically does not change on a machine, so it's checked only once.</remarks> internal static readonly bool IsSingleProcessor = ProcessorCount == 1; } }
using System; using System.Drawing; namespace LandscapeGenCore { public class TerranValues { public float waterLevel = 0.5F; // Water upto % public float beachLevel = 0.52F; // Beaches upto % public float grassLevel = 0.75F; // Grass upto % public float moutainLevel = 0.95F; // Moutains upto % public float snowLevel = 1.0F; // Snow upto %, this should always be 1 (100%) public Color waterColor = Color.Blue; // Water public Color beachColor = Color.Yellow; // Beaches public Color grassColor = Color.Green; // Grass public Color moutainColor = Color.Brown; // Moutains public Color snowColor = Color.White; // Snow } public class Render2D: IRender { private TerranValues _settings; private float _boundsMin = float.MinValue; private float _boundsMax = float.MaxValue; public float BoundsMax { get {return _boundsMax; } set { _boundsMax = value; } } public float BoundsMin { get {return _boundsMin; } set { _boundsMin = value; } } public Render2D() { _settings = new TerranValues(); } public void Free() { } private Color ScaleGreyscale(float val) { int grey; float newVal; float range = _boundsMax - _boundsMin; newVal = val; newVal = 255/range*newVal; grey = (int)Math.Round(newVal); return Color.FromArgb(grey, grey, grey); } // TODO: This isn't correct :( It's not taking _boundsMin into account and it can't cope with negitive values private Color ScaleTerran(float val, TerranValues vals) { float range = _boundsMax - _boundsMin; if (val <= _boundsMax * vals.waterLevel) { return vals.waterColor; } else if (val <= _boundsMax * vals.beachLevel) { return vals.beachColor; } else if (val <= _boundsMax * vals.grassLevel) { return vals.grassColor; } else if (val <= _boundsMax * vals.moutainLevel) { return vals.moutainColor; } else if (val <= _boundsMax * vals.snowLevel) { return vals.snowColor; } else { return Color.Red; } } private Color ScaleThreeColor(float val, Color color1, Color color2, Color color3) { int red; int green; int blue; float bias; float range = _boundsMax - _boundsMin; float midPoint = range / 2F; /* _boundsMin: 100% color1 * Inbetween: color1 -> color2 * float midPoint: 100% color2 * Inbetween: color2 -> color3 * _boundsMax: = 100% color3 * */ if (val == _boundsMin) { // 100% Color 1 red = color1.R; green = color1.G; blue = color1.B; } else if (val == midPoint) { // 100% Color 2 red = color2.R; green = color2.G; blue = color2.B; } else if (val == _boundsMax) { // 100% Color 3 red = color3.R; green = color3.G; blue = color3.B; } else if (val < midPoint) { // Blend of Color 1 and 2 bias = val / midPoint; // Blend between the two colours red = (int)Math.Round(Common.Linear_Interpolate(color1.R, color2.R, bias)); green = (int)Math.Round(Common.Linear_Interpolate(color1.G, color2.G, bias)); blue = (int)Math.Round(Common.Linear_Interpolate(color1.B, color2.B, bias)); } else if (val < _boundsMax) { // Blend of Color 2 and 3 bias = (val - midPoint) / (_boundsMax - midPoint); // Blend between the two colours red = (int)Math.Round(Common.Linear_Interpolate(color2.R, color3.R, bias)); green = (int)Math.Round(Common.Linear_Interpolate(color2.G, color3.G, bias)); blue = (int)Math.Round(Common.Linear_Interpolate(color2.B, color3.B, bias)); } else { throw new Exception("Out of range :("); } return Color.FromArgb(red, green, blue); } private Color ScaleTwoColor(float val, Color color1, Color color2) { float bios; bios = (float)val / (_boundsMax - _boundsMin); int red; int green; int blue; // Blend between the two colours red = (int)Math.Round(Common.Linear_Interpolate(color1.R, color2.R, bios)); green = (int)Math.Round(Common.Linear_Interpolate(color1.G, color2.G, bios)); blue = (int)Math.Round(Common.Linear_Interpolate(color1.B, color2.B, bios)); return Color.FromArgb(red, green, blue); } public Bitmap RenderRainbow(float[,] ResultGrid) { Bitmap img = new Bitmap(ResultGrid.GetLength(0), ResultGrid.GetLength(1)); for (int y=0; y<ResultGrid.GetLength(1); y++) { for (int x=0; x<ResultGrid.GetLength(0); x++) { img.SetPixel(x,y, ScaleThreeColor(ResultGrid[x,y], Color.Red, Color.Lime, Color.Blue)); } } return img; } public Bitmap RenderGreyscale(float[,] ResultGrid) { Bitmap img = new Bitmap(ResultGrid.GetLength(0), ResultGrid.GetLength(1)); for (int x=0; x<ResultGrid.GetLength(0); x++) { for (int y=0; y<ResultGrid.GetLength(1); y++) { img.SetPixel(x,y, ScaleGreyscale(ResultGrid[x,y])); } } return img; } public Bitmap RenderClouds(float[,] ResultGrid) { Bitmap img = new Bitmap(ResultGrid.GetLength(0), ResultGrid.GetLength(1)); for (int y=0; y<ResultGrid.GetLength(1); y++) { for (int x=0; x<ResultGrid.GetLength(0); x++) { img.SetPixel(x,y, ScaleTwoColor(ResultGrid[x,y], Color.Blue, Color.White)); } } return img; } public Bitmap RenderFire(float[,] ResultGrid) { Bitmap img = new Bitmap(ResultGrid.GetLength(0), ResultGrid.GetLength(1)); for (int y=0; y<ResultGrid.GetLength(1); y++) { for (int x=0; x<ResultGrid.GetLength(0); x++) { img.SetPixel(x,y, ScaleThreeColor(ResultGrid[x,y], Color.Orange, Color.Red, Color.Black)); } } return img; } public Bitmap RenderFire2(float[,] ResultGrid) { Bitmap img = new Bitmap(ResultGrid.GetLength(0), ResultGrid.GetLength(1)); for (int y=0; y<ResultGrid.GetLength(1); y++) { for (int x=0; x<ResultGrid.GetLength(0); x++) { img.SetPixel(x,y, ScaleThreeColor(ResultGrid[x,y], Color.Red, Color.Orange, Color.Black)); } } return img; } public Bitmap RenderTerran(float[,] ResultGrid) { Bitmap img = new Bitmap(ResultGrid.GetLength(0), ResultGrid.GetLength(1)); for (int x=0; x<ResultGrid.GetLength(0); x++) { for (int y=0; y<ResultGrid.GetLength(1); y++) { img.SetPixel(x,y, ScaleTerran(ResultGrid[x,y], _settings)); } } return img; } public Bitmap Render(float[,] ResultGrid) { return RenderGreyscale(ResultGrid); } } }
// 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 Xunit; namespace System.Linq.Tests { public class OrderedSubsetting : EnumerableTests { [Fact] public void FirstMultipleTruePredicateResult() { Assert.Equal(10, Enumerable.Range(1, 99).OrderBy(i => i).First(x => x % 10 == 0)); Assert.Equal(100, Enumerable.Range(1, 999).Concat(Enumerable.Range(1001, 3)).OrderByDescending(i => i.ToString().Length).ThenBy(i => i).First(x => x % 10 == 0)); } [Fact] public void FirstOrDefaultMultipleTruePredicateResult() { Assert.Equal(10, Enumerable.Range(1, 99).OrderBy(i => i).FirstOrDefault(x => x % 10 == 0)); Assert.Equal(100, Enumerable.Range(1, 999).Concat(Enumerable.Range(1001, 3)).OrderByDescending(i => i.ToString().Length).ThenBy(i => i).FirstOrDefault(x => x % 10 == 0)); } [Fact] public void FirstNoTruePredicateResult() { Assert.Throws<InvalidOperationException>(() => Enumerable.Range(1, 99).OrderBy(i => i).First(x => x > 1000)); } [Fact] public void FirstEmptyOrderedEnumerable() { Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<int>().OrderBy(i => i).First()); Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<int>().OrderBy(i => i).First(x => true)); } [Fact] public void FirstOrDefaultNoTruePredicateResult() { Assert.Equal(0, Enumerable.Range(1, 99).OrderBy(i => i).FirstOrDefault(x => x > 1000)); } [Fact] public void FirstOrDefaultEmptyOrderedEnumerable() { Assert.Equal(0, Enumerable.Empty<int>().OrderBy(i => i).FirstOrDefault()); Assert.Equal(0, Enumerable.Empty<int>().OrderBy(i => i).FirstOrDefault(x => true)); } [Fact] public void Last() { Assert.Equal(10, Enumerable.Range(1, 99).Reverse().OrderByDescending(i => i).Last(x => x % 10 == 0)); Assert.Equal(100, Enumerable.Range(1, 999).Concat(Enumerable.Range(1001, 3)).Reverse().OrderBy(i => i.ToString().Length).ThenByDescending(i => i).Last(x => x % 10 == 0)); Assert.Equal(10, Enumerable.Range(1, 10).OrderBy(i => 1).Last()); } [Fact] public void LastMultipleTruePredicateResult() { Assert.Equal(90, Enumerable.Range(1, 99).OrderBy(i => i).Last(x => x % 10 == 0)); Assert.Equal(90, Enumerable.Range(1, 999).Concat(Enumerable.Range(1001, 3)).OrderByDescending(i => i.ToString().Length).ThenBy(i => i).Last(x => x % 10 == 0)); } [Fact] public void LastOrDefaultMultipleTruePredicateResult() { Assert.Equal(90, Enumerable.Range(1, 99).OrderBy(i => i).LastOrDefault(x => x % 10 == 0)); Assert.Equal(90, Enumerable.Range(1, 999).Concat(Enumerable.Range(1001, 3)).OrderByDescending(i => i.ToString().Length).ThenBy(i => i).LastOrDefault(x => x % 10 == 0)); } [Fact] public void LastNoTruePredicateResult() { Assert.Throws<InvalidOperationException>(() => Enumerable.Range(1, 99).OrderBy(i => i).Last(x => x > 1000)); } [Fact] public void LastEmptyOrderedEnumerable() { Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<int>().OrderBy(i => i).Last()); Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<int>().OrderBy(i => i).Last(x => true)); } [Fact] public void LastOrDefaultNoTruePredicateResult() { Assert.Equal(0, Enumerable.Range(1, 99).OrderBy(i => i).LastOrDefault(x => x > 1000)); } [Fact] public void LastOrDefaultEmptyOrderedEnumerable() { Assert.Equal(0, Enumerable.Empty<int>().OrderBy(i => i).LastOrDefault()); Assert.Equal(0, Enumerable.Empty<int>().OrderBy(i => i).LastOrDefault(x => true)); } [Fact] public void Take() { var source = Enumerable.Range(0, 100).Shuffle().ToArray(); var ordered = source.OrderBy(i => i); Assert.Equal(Enumerable.Range(0, 20), ordered.Take(20)); Assert.Equal(Enumerable.Range(0, 30), ordered.Take(50).Take(30)); Assert.Empty(ordered.Take(0)); Assert.Empty(ordered.Take(-1)); Assert.Empty(ordered.Take(int.MinValue)); Assert.Equal(new int[] { 0 }, ordered.Take(1)); Assert.Equal(Enumerable.Range(0, 100), ordered.Take(101)); Assert.Equal(Enumerable.Range(0, 100), ordered.Take(int.MaxValue)); Assert.Equal(Enumerable.Range(0, 100), ordered.Take(100)); Assert.Equal(Enumerable.Range(0, 99), ordered.Take(99)); Assert.Equal(Enumerable.Range(0, 100), ordered); } [Fact] public void TakeThenFirst() { var source = Enumerable.Range(0, 100).Shuffle().ToArray(); var ordered = source.OrderBy(i => i); Assert.Equal(0, ordered.Take(20).First()); Assert.Equal(0, ordered.Take(20).FirstOrDefault()); } [Fact] public void TakeThenLast() { var source = Enumerable.Range(0, 100).Shuffle().ToArray(); var ordered = source.OrderBy(i => i); Assert.Equal(19, ordered.Take(20).Last()); Assert.Equal(19, ordered.Take(20).LastOrDefault()); } [Fact] public void Skip() { var source = Enumerable.Range(0, 100).Shuffle().ToArray(); var ordered = source.OrderBy(i => i); Assert.Equal(Enumerable.Range(20, 80), ordered.Skip(20)); Assert.Equal(Enumerable.Range(80, 20), ordered.Skip(50).Skip(30)); Assert.Equal(20, ordered.Skip(20).First()); Assert.Equal(20, ordered.Skip(20).FirstOrDefault()); Assert.Equal(Enumerable.Range(0, 100), ordered.Skip(0)); Assert.Equal(Enumerable.Range(0, 100), ordered.Skip(-1)); Assert.Equal(Enumerable.Range(0, 100), ordered.Skip(int.MinValue)); Assert.Equal(new int[] { 99 }, ordered.Skip(99)); Assert.Empty(ordered.Skip(101)); Assert.Empty(ordered.Skip(int.MaxValue)); Assert.Empty(ordered.Skip(100)); Assert.Equal(Enumerable.Range(1, 99), ordered.Skip(1)); Assert.Equal(Enumerable.Range(0, 100), ordered); } [Fact] public void SkipThenFirst() { var source = Enumerable.Range(0, 100).Shuffle().ToArray(); var ordered = source.OrderBy(i => i); Assert.Equal(20, ordered.Skip(20).First()); Assert.Equal(20, ordered.Skip(20).FirstOrDefault()); } [Fact] public void SkipExcessiveThenFirstThrows() { Assert.Throws<InvalidOperationException>(() => Enumerable.Range(2, 10).Shuffle().OrderBy(i => i).Skip(20).First()); } [Fact] public void SkipExcessiveThenFirstOrDefault() { Assert.Equal(0, Enumerable.Range(2, 10).Shuffle().OrderBy(i => i).Skip(20).FirstOrDefault()); } [Fact] public void SkipExcessiveEmpty() { Assert.Empty(Enumerable.Range(0, 10).Shuffle().OrderBy(i => i).Skip(42)); } [Fact] public void SkipThenLast() { var source = Enumerable.Range(0, 100).Shuffle().ToArray(); var ordered = source.OrderBy(i => i); Assert.Equal(99, ordered.Skip(20).Last()); Assert.Equal(99, ordered.Skip(20).LastOrDefault()); } [Fact] public void SkipExcessiveThenLastThrows() { Assert.Throws<InvalidOperationException>(() => Enumerable.Range(2, 10).Shuffle().OrderBy(i => i).Skip(20).Last()); } [Fact] public void SkipExcessiveThenLastOrDefault() { Assert.Equal(0, Enumerable.Range(2, 10).Shuffle().OrderBy(i => i).Skip(20).LastOrDefault()); } [Fact] public void SkipAndTake() { var source = Enumerable.Range(0, 100).Shuffle().ToArray(); var ordered = source.OrderBy(i => i); Assert.Equal(Enumerable.Range(20, 60), ordered.Skip(20).Take(60)); Assert.Equal(Enumerable.Range(30, 20), ordered.Skip(20).Skip(10).Take(50).Take(20)); Assert.Equal(Enumerable.Range(30, 20), ordered.Skip(20).Skip(10).Take(20).Take(int.MaxValue)); Assert.Empty(ordered.Skip(10).Take(9).Take(0)); Assert.Empty(ordered.Skip(200).Take(10)); Assert.Empty(ordered.Skip(3).Take(0)); } [Fact] public void TakeThenTakeExcessive() { var source = Enumerable.Range(0, 100).Shuffle().ToArray(); var ordered = source.OrderBy(i => i); Assert.Equal(ordered.Take(20), ordered.Take(20).Take(100)); } [Fact] public void TakeThenSkipAll() { var source = Enumerable.Range(0, 100).Shuffle().ToArray(); var ordered = source.OrderBy(i => i); Assert.Empty(ordered.Take(20).Skip(30)); } [Fact] public void SkipAndTakeThenFirst() { var source = Enumerable.Range(0, 100).Shuffle().ToArray(); var ordered = source.OrderBy(i => i); Assert.Equal(20, ordered.Skip(20).Take(60).First()); Assert.Equal(20, ordered.Skip(20).Take(60).FirstOrDefault()); } [Fact] public void SkipAndTakeThenLast() { var source = Enumerable.Range(0, 100).Shuffle().ToArray(); var ordered = source.OrderBy(i => i); Assert.Equal(79, ordered.Skip(20).Take(60).Last()); Assert.Equal(79, ordered.Skip(20).Take(60).LastOrDefault()); } [Fact] public void ElementAt() { var source = Enumerable.Range(0, 100).Shuffle().ToArray(); var ordered = source.OrderBy(i => i); Assert.Equal(42, ordered.ElementAt(42)); Assert.Equal(93, ordered.ElementAt(93)); Assert.Equal(99, ordered.ElementAt(99)); Assert.Equal(42, ordered.ElementAtOrDefault(42)); Assert.Equal(93, ordered.ElementAtOrDefault(93)); Assert.Equal(99, ordered.ElementAtOrDefault(99)); Assert.Throws<ArgumentOutOfRangeException>(() => ordered.ElementAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => ordered.ElementAt(100)); Assert.Throws<ArgumentOutOfRangeException>(() => ordered.ElementAt(1000)); Assert.Throws<ArgumentOutOfRangeException>(() => ordered.ElementAt(int.MinValue)); Assert.Throws<ArgumentOutOfRangeException>(() => ordered.ElementAt(int.MaxValue)); Assert.Equal(0, ordered.ElementAtOrDefault(-1)); Assert.Equal(0, ordered.ElementAtOrDefault(100)); Assert.Equal(0, ordered.ElementAtOrDefault(1000)); Assert.Equal(0, ordered.ElementAtOrDefault(int.MinValue)); Assert.Equal(0, ordered.ElementAtOrDefault(int.MaxValue)); var skipped = ordered.Skip(10).Take(80); Assert.Equal(52, skipped.ElementAt(42)); Assert.Equal(83, skipped.ElementAt(73)); Assert.Equal(89, skipped.ElementAt(79)); Assert.Equal(52, skipped.ElementAtOrDefault(42)); Assert.Equal(83, skipped.ElementAtOrDefault(73)); Assert.Equal(89, skipped.ElementAtOrDefault(79)); Assert.Throws<ArgumentOutOfRangeException>(() => skipped.ElementAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => skipped.ElementAt(80)); Assert.Throws<ArgumentOutOfRangeException>(() => skipped.ElementAt(1000)); Assert.Throws<ArgumentOutOfRangeException>(() => skipped.ElementAt(int.MinValue)); Assert.Throws<ArgumentOutOfRangeException>(() => skipped.ElementAt(int.MaxValue)); Assert.Equal(0, skipped.ElementAtOrDefault(-1)); Assert.Equal(0, skipped.ElementAtOrDefault(80)); Assert.Equal(0, skipped.ElementAtOrDefault(1000)); Assert.Equal(0, skipped.ElementAtOrDefault(int.MinValue)); Assert.Equal(0, skipped.ElementAtOrDefault(int.MaxValue)); skipped = ordered.Skip(1000).Take(20); Assert.Throws<ArgumentOutOfRangeException>(() => skipped.ElementAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => skipped.ElementAt(0)); Assert.Throws<InvalidOperationException>(() => skipped.First()); Assert.Throws<InvalidOperationException>(() => skipped.Last()); Assert.Equal(0, skipped.ElementAtOrDefault(-1)); Assert.Equal(0, skipped.ElementAtOrDefault(0)); Assert.Equal(0, skipped.FirstOrDefault()); Assert.Equal(0, skipped.LastOrDefault()); } [Fact] public void ToArray() { Assert.Equal(Enumerable.Range(10, 20), Enumerable.Range(0, 100).Shuffle().OrderBy(i => i).Skip(10).Take(20).ToArray()); } [Fact] public void ToList() { Assert.Equal(Enumerable.Range(10, 20), Enumerable.Range(0, 100).Shuffle().OrderBy(i => i).Skip(10).Take(20).ToList()); } [Fact] public void Count() { Assert.Equal(20, Enumerable.Range(0, 100).Shuffle().OrderBy(i => i).Skip(10).Take(20).Count()); } [Fact] public void EmptyToArray() { Assert.Empty(Enumerable.Range(0, 100).Shuffle().OrderBy(i => i).Skip(100).ToArray()); } [Fact] public void EmptyToList() { Assert.Empty(Enumerable.Range(0, 100).Shuffle().OrderBy(i => i).Skip(100).ToList()); } [Fact] public void EmptyCount() { Assert.Equal(0, Enumerable.Range(0, 100).Shuffle().OrderBy(i => i).Skip(100).Count()); Assert.Equal(0, Enumerable.Range(0, 100).Shuffle().OrderBy(i => i).Take(0).Count()); } [Fact] public void AttemptedMoreArray() { Assert.Equal(Enumerable.Range(0, 20), Enumerable.Range(0, 20).Shuffle().OrderBy(i => i).Take(30).ToArray()); } [Fact] public void AttemptedMoreList() { Assert.Equal(Enumerable.Range(0, 20), Enumerable.Range(0, 20).Shuffle().OrderBy(i => i).Take(30).ToList()); } [Fact] public void AttemptedMoreCount() { Assert.Equal(20, Enumerable.Range(0, 20).Shuffle().OrderBy(i => i).Take(30).Count()); } [Fact] public void SingleElementToArray() { Assert.Equal(Enumerable.Repeat(10, 1), Enumerable.Range(0, 20).Shuffle().OrderBy(i => i).Skip(10).Take(1).ToArray()); } [Fact] public void SingleElementToList() { Assert.Equal(Enumerable.Repeat(10, 1), Enumerable.Range(0, 20).Shuffle().OrderBy(i => i).Skip(10).Take(1).ToList()); } [Fact] public void SingleElementCount() { Assert.Equal(1, Enumerable.Range(0, 20).Shuffle().OrderBy(i => i).Skip(10).Take(1).Count()); } [Fact] public void EnumeratorDoesntContinue() { var enumerator = NumberRangeGuaranteedNotCollectionType(0, 3).Shuffle().OrderBy(i => i).Skip(1).GetEnumerator(); while (enumerator.MoveNext()) { } Assert.False(enumerator.MoveNext()); } [Fact] public void Select() { Assert.Equal(new[] { 0, 2, 4, 6, 8 }, Enumerable.Range(-1, 8).Shuffle().OrderBy(i => i).Skip(1).Take(5).Select(i => i * 2)); } [Fact] public void SelectForcedToEnumeratorDoesntEnumerate() { var iterator = Enumerable.Range(-1, 8).Shuffle().OrderBy(i => i).Skip(1).Take(5).Select(i => i * 2); // Don't insist on this behaviour, but check its correct if it happens var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void SelectElementAt() { var source = Enumerable.Range(0, 9).Shuffle().OrderBy(i => i).Skip(1).Take(5).Select(i => i * 2); Assert.Equal(6, source.ElementAt(2)); Assert.Equal(8, source.ElementAtOrDefault(3)); Assert.Equal(0, source.ElementAtOrDefault(8)); Assert.Throws<ArgumentOutOfRangeException>("index", () => source.ElementAt(-2)); } [Fact] public void SelectFirst() { var source = Enumerable.Range(0, 9).Shuffle().OrderBy(i => i).Skip(1).Take(5).Select(i => i * 2); Assert.Equal(2, source.First()); Assert.Equal(2, source.FirstOrDefault()); source = source.Skip(20); Assert.Equal(0, source.FirstOrDefault()); Assert.Throws<InvalidOperationException>(() => source.First()); } [Fact] public void SelectLast() { var source = Enumerable.Range(0, 9).Shuffle().OrderBy(i => i).Skip(1).Take(5).Select(i => i * 2); Assert.Equal(10, source.Last()); Assert.Equal(10, source.LastOrDefault()); source = source.Skip(20); Assert.Equal(0, source.LastOrDefault()); Assert.Throws<InvalidOperationException>(() => source.Last()); } [Fact] public void SelectArray() { var source = Enumerable.Range(0, 9).Shuffle().OrderBy(i => i).Skip(1).Take(5).Select(i => i * 2); Assert.Equal(new[] { 2, 4, 6, 8, 10 }, source.ToArray()); } [Fact] public void SelectList() { var source = Enumerable.Range(0, 9).Shuffle().OrderBy(i => i).Skip(1).Take(5).Select(i => i * 2); Assert.Equal(new[] { 2, 4, 6, 8, 10 }, source.ToList()); } [Fact] public void SelectCount() { var source = Enumerable.Range(0, 9).Shuffle().OrderBy(i => i).Skip(1).Take(5).Select(i => i * 2); Assert.Equal(5, source.Count()); source = Enumerable.Range(0, 9).Shuffle().OrderBy(i => i).Skip(1).Take(1000).Select(i => i * 2); Assert.Equal(8, source.Count()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.IO; using System.Net.Mail; using System.Text; namespace System.Net.Http.Headers { internal static class HeaderUtilities { private const string qualityName = "q"; internal const string ConnectionClose = "close"; internal static readonly TransferCodingHeaderValue TransferEncodingChunked = new TransferCodingHeaderValue("chunked"); internal static readonly NameValueWithParametersHeaderValue ExpectContinue = new NameValueWithParametersHeaderValue("100-continue"); internal const string BytesUnit = "bytes"; // Validator internal static readonly Action<HttpHeaderValueCollection<string>, string> TokenValidator = ValidateToken; private static readonly char[] s_hexUpperChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; internal static void SetQuality(ObjectCollection<NameValueHeaderValue> parameters, double? value) { Debug.Assert(parameters != null); NameValueHeaderValue qualityParameter = NameValueHeaderValue.Find(parameters, qualityName); if (value.HasValue) { // Note that even if we check the value here, we can't prevent a user from adding an invalid quality // value using Parameters.Add(). Even if we would prevent the user from adding an invalid value // using Parameters.Add() he could always add invalid values using HttpHeaders.AddWithoutValidation(). // So this check is really for convenience to show users that they're trying to add an invalid // value. if ((value < 0) || (value > 1)) { throw new ArgumentOutOfRangeException(nameof(value)); } string qualityString = ((double)value).ToString("0.0##", NumberFormatInfo.InvariantInfo); if (qualityParameter != null) { qualityParameter.Value = qualityString; } else { parameters.Add(new NameValueHeaderValue(qualityName, qualityString)); } } else { // Remove quality parameter if (qualityParameter != null) { parameters.Remove(qualityParameter); } } } // Encode a string using RFC 5987 encoding. // encoding'lang'PercentEncodedSpecials internal static string Encode5987(string input) { string output; IsInputEncoded5987(input, out output); return output; } internal static bool IsInputEncoded5987(string input, out string output) { // Encode a string using RFC 5987 encoding. // encoding'lang'PercentEncodedSpecials bool wasEncoded = false; StringBuilder builder = StringBuilderCache.Acquire(); builder.Append("utf-8\'\'"); foreach (char c in input) { // attr-char = ALPHA / DIGIT / "!" / "#" / "$" / "&" / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" // ; token except ( "*" / "'" / "%" ) if (c > 0x7F) // Encodes as multiple utf-8 bytes { byte[] bytes = Encoding.UTF8.GetBytes(c.ToString()); foreach (byte b in bytes) { AddHexEscaped((char)b, builder); wasEncoded = true; } } else if (!HttpRuleParser.IsTokenChar(c) || c == '*' || c == '\'' || c == '%') { // ASCII - Only one encoded byte. AddHexEscaped(c, builder); wasEncoded = true; } else { builder.Append(c); } } output = StringBuilderCache.GetStringAndRelease(builder); return wasEncoded; } /// <summary>Transforms an ASCII character into its hexadecimal representation, adding the characters to a StringBuilder.</summary> private static void AddHexEscaped(char c, StringBuilder destination) { Debug.Assert(destination != null); Debug.Assert(c <= 0xFF); destination.Append('%'); destination.Append(s_hexUpperChars[(c & 0xf0) >> 4]); destination.Append(s_hexUpperChars[c & 0xf]); } internal static double? GetQuality(ObjectCollection<NameValueHeaderValue> parameters) { Debug.Assert(parameters != null); NameValueHeaderValue qualityParameter = NameValueHeaderValue.Find(parameters, qualityName); if (qualityParameter != null) { // Note that the RFC requires decimal '.' regardless of the culture. I.e. using ',' as decimal // separator is considered invalid (even if the current culture would allow it). double qualityValue = 0; if (double.TryParse(qualityParameter.Value, NumberStyles.AllowDecimalPoint, NumberFormatInfo.InvariantInfo, out qualityValue)) { return qualityValue; } // If the stored value is an invalid quality value, just return null and log a warning. if (NetEventSource.IsEnabled) NetEventSource.Error(null, SR.Format(SR.net_http_log_headers_invalid_quality, qualityParameter.Value)); } return null; } internal static void CheckValidToken(string value, string parameterName) { if (string.IsNullOrEmpty(value)) { throw new ArgumentException(SR.net_http_argument_empty_string, parameterName); } if (HttpRuleParser.GetTokenLength(value, 0) != value.Length) { throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value)); } } internal static void CheckValidComment(string value, string parameterName) { if (string.IsNullOrEmpty(value)) { throw new ArgumentException(SR.net_http_argument_empty_string, parameterName); } int length = 0; if ((HttpRuleParser.GetCommentLength(value, 0, out length) != HttpParseResult.Parsed) || (length != value.Length)) // no trailing spaces allowed { throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value)); } } internal static void CheckValidQuotedString(string value, string parameterName) { if (string.IsNullOrEmpty(value)) { throw new ArgumentException(SR.net_http_argument_empty_string, parameterName); } int length = 0; if ((HttpRuleParser.GetQuotedStringLength(value, 0, out length) != HttpParseResult.Parsed) || (length != value.Length)) // no trailing spaces allowed { throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value)); } } internal static bool AreEqualCollections<T>(ObjectCollection<T> x, ObjectCollection<T> y) where T : class { return AreEqualCollections(x, y, null); } internal static bool AreEqualCollections<T>(ObjectCollection<T> x, ObjectCollection<T> y, IEqualityComparer<T> comparer) where T : class { if (x == null) { return (y == null) || (y.Count == 0); } if (y == null) { return (x.Count == 0); } if (x.Count != y.Count) { return false; } if (x.Count == 0) { return true; } // We have two unordered lists. So comparison is an O(n*m) operation which is expensive. Usually // headers have 1-2 parameters (if any), so this comparison shouldn't be too expensive. bool[] alreadyFound = new bool[x.Count]; int i = 0; foreach (var xItem in x) { Debug.Assert(xItem != null); i = 0; bool found = false; foreach (var yItem in y) { if (!alreadyFound[i]) { if (((comparer == null) && xItem.Equals(yItem)) || ((comparer != null) && comparer.Equals(xItem, yItem))) { alreadyFound[i] = true; found = true; break; } } i++; } if (!found) { return false; } } // Since we never re-use a "found" value in 'y', we expect 'alreadyFound' to have all fields set to 'true'. // Otherwise the two collections can't be equal and we should not get here. Debug.Assert(Contract.ForAll(alreadyFound, value => { return value; }), "Expected all values in 'alreadyFound' to be true since collections are considered equal."); return true; } internal static int GetNextNonEmptyOrWhitespaceIndex(string input, int startIndex, bool skipEmptyValues, out bool separatorFound) { Debug.Assert(input != null); Debug.Assert(startIndex <= input.Length); // it's OK if index == value.Length. separatorFound = false; int current = startIndex + HttpRuleParser.GetWhitespaceLength(input, startIndex); if ((current == input.Length) || (input[current] != ',')) { return current; } // If we have a separator, skip the separator and all following whitespace. If we support // empty values, continue until the current character is neither a separator nor a whitespace. separatorFound = true; current++; // skip delimiter. current = current + HttpRuleParser.GetWhitespaceLength(input, current); if (skipEmptyValues) { while ((current < input.Length) && (input[current] == ',')) { current++; // skip delimiter. current = current + HttpRuleParser.GetWhitespaceLength(input, current); } } return current; } internal static DateTimeOffset? GetDateTimeOffsetValue(HeaderDescriptor descriptor, HttpHeaders store) { Debug.Assert(store != null); object storedValue = store.GetParsedValues(descriptor); if (storedValue != null) { return (DateTimeOffset)storedValue; } return null; } internal static TimeSpan? GetTimeSpanValue(HeaderDescriptor descriptor, HttpHeaders store) { Debug.Assert(store != null); object storedValue = store.GetParsedValues(descriptor); if (storedValue != null) { return (TimeSpan)storedValue; } return null; } internal static bool TryParseInt32(string value, out int result) => TryParseInt32(value, 0, value.Length, out result); internal static bool TryParseInt32(string value, int offset, int length, out int result) // TODO #21281: Replace with int.TryParse(Span<char>) once it's available { if (offset < 0 || length < 0 || offset > value.Length - length) { result = 0; return false; } int tmpResult = 0; int pos = offset, endPos = offset + length; while (pos < endPos) { char c = value[pos++]; int digit = c - '0'; if ((uint)digit > 9 || // invalid digit tmpResult > int.MaxValue / 10 || // will overflow when shifting digits (tmpResult == int.MaxValue / 10 && digit > 7)) // will overflow when adding in digit { goto ReturnFalse; // Remove goto once https://github.com/dotnet/coreclr/issues/9692 is addressed } tmpResult = (tmpResult * 10) + digit; } result = tmpResult; return true; ReturnFalse: result = 0; return false; } internal static bool TryParseInt64(string value, int offset, int length, out long result) // TODO #21281: Replace with int.TryParse(Span<char>) once it's available { if (offset < 0 || length < 0 || offset > value.Length - length) { result = 0; return false; } long tmpResult = 0; int pos = offset, endPos = offset + length; while (pos < endPos) { char c = value[pos++]; int digit = c - '0'; if ((uint)digit > 9 || // invalid digit tmpResult > long.MaxValue / 10 || // will overflow when shifting digits (tmpResult == long.MaxValue / 10 && digit > 7)) // will overflow when adding in digit { goto ReturnFalse; // Remove goto once https://github.com/dotnet/coreclr/issues/9692 is addressed } tmpResult = (tmpResult * 10) + digit; } result = tmpResult; return true; ReturnFalse: result = 0; return false; } internal static string DumpHeaders(params HttpHeaders[] headers) { // Return all headers as string similar to: // { // HeaderName1: Value1 // HeaderName1: Value2 // HeaderName2: Value1 // ... // } StringBuilder sb = new StringBuilder(); sb.Append("{\r\n"); for (int i = 0; i < headers.Length; i++) { if (headers[i] != null) { foreach (var header in headers[i]) { foreach (var headerValue in header.Value) { sb.Append(" "); sb.Append(header.Key); sb.Append(": "); sb.Append(headerValue); sb.Append("\r\n"); } } } } sb.Append('}'); return sb.ToString(); } internal static bool IsValidEmailAddress(string value) { try { #if uap new MailAddress(value); #else MailAddressParser.ParseAddress(value); #endif return true; } catch (FormatException e) { if (NetEventSource.IsEnabled) NetEventSource.Error(null, SR.Format(SR.net_http_log_headers_wrong_email_format, value, e.Message)); } return false; } private static void ValidateToken(HttpHeaderValueCollection<string> collection, string value) { CheckValidToken(value, "item"); } } }
namespace System.Data.Entity.Core.Objects.ELinq { using System.Collections.Generic; using System.Data.Entity.Core.Common.CommandTrees; using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder; using System.Data.Entity.Core.Metadata.Edm; using System.Data.Entity.Resources; using System.Data.Entity.Utilities; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Linq.Expressions; using CqtExpression = System.Data.Entity.Core.Common.CommandTrees.DbExpression; using LinqExpression = System.Linq.Expressions.Expression; internal sealed partial class ExpressionConverter { internal static class StringTranslatorUtil { [SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Justification = "the same linqExpression value is never cast to ConstantExpression twice")] internal static DbExpression ConvertToString(ExpressionConverter parent, LinqExpression linqExpression) { if (linqExpression.Type == typeof(object)) { var constantExpression = linqExpression as ConstantExpression; linqExpression = constantExpression != null ? Expression.Constant(constantExpression.Value) : linqExpression.RemoveConvert(); } var expression = parent.TranslateExpression(linqExpression); var clrType = TypeSystem.GetNonNullableType(linqExpression.Type); if (clrType.IsEnum) { //Flag enums are not supported. if (Attribute.IsDefined(clrType, typeof(FlagsAttribute))) { throw new NotSupportedException(Strings.Elinq_ToStringNotSupportedForEnumsWithFlags); } if (linqExpression.IsNullConstant()) { return DbExpressionBuilder.Constant(string.Empty); } //Constant expression, optimize to constant name if (linqExpression.NodeType == ExpressionType.Constant) { var value = ((ConstantExpression)linqExpression).Value; var name = Enum.GetName(clrType, value) ?? value.ToString(); return DbExpressionBuilder.Constant(name); } var integralType = clrType.GetEnumUnderlyingType(); var type = parent.GetValueLayerType(integralType); var values = clrType.GetEnumValues() .Cast<object>() .Select(v => System.Convert.ChangeType(v, integralType, CultureInfo.InvariantCulture)) //cast to integral type so that unmapped enum types works too .Select(v => DbExpressionBuilder.Constant(v)) .Select(c => (DbExpression)expression.CastTo(type).Equal(c)) //cast expression to integral type before comparing to constant .Concat(new[] { expression.CastTo(type).IsNull() }); // default case var names = clrType.GetEnumNames() .Select(s => DbExpressionBuilder.Constant(s)) .Concat(new[] { DbExpressionBuilder.Constant(string.Empty) }); // default case //translate unnamed enum values for the else clause, raw linq -> as integral value -> translate to cqt -> to string //e.g. ((DayOfWeek)99) -> "99" var asIntegralLinq = LinqExpression.Convert(linqExpression, integralType); var asStringCqt = parent .TranslateExpression(asIntegralLinq) .CastTo(parent.GetValueLayerType(typeof(string))); return DbExpressionBuilder.Case(values, names, asStringCqt); } else if (TypeSemantics.IsPrimitiveType(expression.ResultType, PrimitiveTypeKind.String)) { return StripNull(linqExpression, expression, expression, useDatabaseNullSemantics); } else if (TypeSemantics.IsPrimitiveType(expression.ResultType, PrimitiveTypeKind.Guid)) { return StripNull(linqExpression, expression, expression.CastTo(parent.GetValueLayerType(typeof(string))).ToLower(), useDatabaseNullSemantics); } else if (TypeSemantics.IsPrimitiveType(expression.ResultType, PrimitiveTypeKind.Boolean)) { if (linqExpression.IsNullConstant()) { return DbExpressionBuilder.Constant(string.Empty); } if (linqExpression.NodeType == ExpressionType.Constant) { var name = ((ConstantExpression)linqExpression).Value.ToString(); return DbExpressionBuilder.Constant(name); } var whenTrue = expression.Equal(DbExpressionBuilder.True); var whenFalse = expression.Equal(DbExpressionBuilder.False); var thenTrue = DbExpressionBuilder.Constant(true.ToString()); var thenFalse = DbExpressionBuilder.Constant(false.ToString()); return DbExpressionBuilder.Case( new[] { whenTrue, whenFalse }, new[] { thenTrue, thenFalse }, DbExpressionBuilder.Constant(string.Empty)); } else { if (!SupportsCastToString(expression.ResultType)) { throw new NotSupportedException( Strings.Elinq_ToStringNotSupportedForType(expression.ResultType.EdmType.Name)); } //treat all other types as a simple cast return StripNull(linqExpression, expression, expression.CastTo(parent.GetValueLayerType(typeof(string)))); } } internal static IEnumerable<Expression> GetConcatArgs(Expression linq) { if (linq.IsStringAddExpression()) { foreach (var arg in GetConcatArgs((BinaryExpression)linq)) { yield return arg; } } else { yield return linq; //leaf node } } internal static IEnumerable<Expression> GetConcatArgs(BinaryExpression linq) { // one could also flatten calls to String.Concat here, to avoid multi concat // in "a + b + String.Concat(d, e)", just flatten it to a, b, c, d, e //rec traverse left node foreach (var arg in GetConcatArgs(linq.Left)) { yield return arg; } //rec traverse right node foreach (var arg in GetConcatArgs(linq.Right)) { yield return arg; } } internal static CqtExpression ConcatArgs(ExpressionConverter parent, BinaryExpression linq) { return ConcatArgs(parent, linq, GetConcatArgs(linq).ToArray()); } internal static CqtExpression ConcatArgs(ExpressionConverter parent, Expression linq, Expression[] linqArgs) { var args = linqArgs .Where(arg => !arg.IsNullConstant()) // remove null constants .Select(arg => ConvertToString(parent, arg)) // Apply ToString semantics .ToArray(); //if all args was null constants, optimize the entire expression to constant "" // e.g null + null + null == "" if (args.Length == 0) { return DbExpressionBuilder.Constant(string.Empty); } var current = args.First(); foreach (var next in args.Skip(1)) //concat all args { current = parent.CreateCanonicalFunction(Concat, linq, current, next); } return current; } internal static CqtExpression StripNull(LinqExpression sourceExpression, DbExpression inputExpression, DbExpression outputExpression) { if (sourceExpression.IsNullConstant()) { return DbExpressionBuilder.Constant(string.Empty); } if (sourceExpression.NodeType == ExpressionType.Constant) { return outputExpression; } // converts evaluated null values to empty string, nullable primitive properties etc. var castNullToEmptyString = DbExpressionBuilder.Case( new[] { inputExpression.IsNull() }, new[] { DbExpressionBuilder.Constant(string.Empty) }, outputExpression); return castNullToEmptyString; } internal static bool SupportsCastToString(TypeUsage typeUsage) { return (TypeSemantics.IsPrimitiveType(typeUsage, PrimitiveTypeKind.String) || TypeSemantics.IsNumericType(typeUsage) || TypeSemantics.IsBooleanType(typeUsage) || TypeSemantics.IsPrimitiveType(typeUsage, PrimitiveTypeKind.DateTime) || TypeSemantics.IsPrimitiveType(typeUsage, PrimitiveTypeKind.DateTimeOffset) || TypeSemantics.IsPrimitiveType(typeUsage, PrimitiveTypeKind.Time) || TypeSemantics.IsPrimitiveType(typeUsage, PrimitiveTypeKind.Guid)); } } } }
/* * Copyright 2002-2015 Drew Noakes * * Modified by Yakov Danilov <yakodani@gmail.com> for Imazen LLC (Ported from Java to C#) * 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. * * More information about this project is available at: * * https://drewnoakes.com/code/exif/ * https://github.com/drewnoakes/metadata-extractor */ using System.Collections.Generic; using JetBrains.Annotations; using Sharpen; namespace Com.Drew.Metadata.Exif.Makernotes { /// <summary>Describes tags specific to Nikon (type 2) cameras.</summary> /// <remarks> /// Describes tags specific to Nikon (type 2) cameras. Type-2 applies to the E990 and D-series cameras such as the E990, D1, /// D70 and D100. /// <p> /// Thanks to Fabrizio Giudici for publishing his reverse-engineering of the D100 makernote data. /// http://www.timelesswanderings.net/equipment/D100/NEF.html /// <p> /// Note that the camera implements image protection (locking images) via the file's 'readonly' attribute. Similarly /// image hiding uses the 'hidden' attribute (observed on the D70). Consequently, these values are not available here. /// <p> /// Additional sample images have been observed, and their tag values recorded in javadoc comments for each tag's field. /// New tags have subsequently been added since Fabrizio's observations. /// <p> /// In earlier models (such as the E990 and D1), this directory begins at the first byte of the makernote IFD. In /// later models, the IFD was given the standard prefix to indicate the camera models (most other manufacturers also /// provide this prefix to aid in software decoding). /// </remarks> /// <author>Drew Noakes https://drewnoakes.com</author> public class NikonType2MakernoteDirectory : Com.Drew.Metadata.Directory { /// <summary> /// Values observed /// - 0200 (D70) /// - 0200 (D1X) /// </summary> public const int TagFirmwareVersion = unchecked((int)(0x0001)); /// <summary> /// Values observed /// - 0 250 /// - 0 400 /// </summary> public const int TagIso1 = unchecked((int)(0x0002)); /// <summary>The camera's color mode, as an uppercase string.</summary> /// <remarks> /// The camera's color mode, as an uppercase string. Examples include: /// <ul> /// <li><code>B &amp; W</code></li> /// <li><code>COLOR</code></li> /// <li><code>COOL</code></li> /// <li><code>SEPIA</code></li> /// <li><code>VIVID</code></li> /// </ul> /// </remarks> public const int TagColorMode = unchecked((int)(0x0003)); /// <summary>The camera's quality setting, as an uppercase string.</summary> /// <remarks> /// The camera's quality setting, as an uppercase string. Examples include: /// <ul> /// <li><code>BASIC</code></li> /// <li><code>FINE</code></li> /// <li><code>NORMAL</code></li> /// <li><code>RAW</code></li> /// <li><code>RAW2.7M</code></li> /// </ul> /// </remarks> public const int TagQualityAndFileFormat = unchecked((int)(0x0004)); /// <summary>The camera's white balance setting, as an uppercase string.</summary> /// <remarks> /// The camera's white balance setting, as an uppercase string. Examples include: /// <ul> /// <li><code>AUTO</code></li> /// <li><code>CLOUDY</code></li> /// <li><code>FLASH</code></li> /// <li><code>FLUORESCENT</code></li> /// <li><code>INCANDESCENT</code></li> /// <li><code>PRESET</code></li> /// <li><code>PRESET0</code></li> /// <li><code>PRESET1</code></li> /// <li><code>PRESET3</code></li> /// <li><code>SUNNY</code></li> /// <li><code>WHITE PRESET</code></li> /// <li><code>4350K</code></li> /// <li><code>5000K</code></li> /// <li><code>DAY WHITE FL</code></li> /// <li><code>SHADE</code></li> /// </ul> /// </remarks> public const int TagCameraWhiteBalance = unchecked((int)(0x0005)); /// <summary>The camera's sharpening setting, as an uppercase string.</summary> /// <remarks> /// The camera's sharpening setting, as an uppercase string. Examples include: /// <ul> /// <li><code>AUTO</code></li> /// <li><code>HIGH</code></li> /// <li><code>LOW</code></li> /// <li><code>NONE</code></li> /// <li><code>NORMAL</code></li> /// <li><code>MED.H</code></li> /// <li><code>MED.L</code></li> /// </ul> /// </remarks> public const int TagCameraSharpening = unchecked((int)(0x0006)); /// <summary>The camera's auto-focus mode, as an uppercase string.</summary> /// <remarks> /// The camera's auto-focus mode, as an uppercase string. Examples include: /// <ul> /// <li><code>AF-C</code></li> /// <li><code>AF-S</code></li> /// <li><code>MANUAL</code></li> /// <li><code>AF-A</code></li> /// </ul> /// </remarks> public const int TagAfType = unchecked((int)(0x0007)); /// <summary>The camera's flash setting, as an uppercase string.</summary> /// <remarks> /// The camera's flash setting, as an uppercase string. Examples include: /// <ul> /// <li><code></code></li> /// <li><code>NORMAL</code></li> /// <li><code>RED-EYE</code></li> /// <li><code>SLOW</code></li> /// <li><code>NEW_TTL</code></li> /// <li><code>REAR</code></li> /// <li><code>REAR SLOW</code></li> /// </ul> /// Note: when TAG_AUTO_FLASH_MODE is blank (whitespace), Nikon Browser displays "Flash Sync Mode: Not Attached" /// </remarks> public const int TagFlashSyncMode = unchecked((int)(0x0008)); /// <summary>The type of flash used in the photograph, as a string.</summary> /// <remarks> /// The type of flash used in the photograph, as a string. Examples include: /// <ul> /// <li><code></code></li> /// <li><code>Built-in,TTL</code></li> /// <li><code>NEW_TTL</code> Nikon Browser interprets as "D-TTL"</li> /// <li><code>Built-in,M</code></li> /// <li><code>Optional,TTL</code> with speedlight SB800, flash sync mode as "NORMAL"</li> /// </ul> /// </remarks> public const int TagAutoFlashMode = unchecked((int)(0x0009)); /// <summary>An unknown tag, as a rational.</summary> /// <remarks> /// An unknown tag, as a rational. Several values given here: /// http://gvsoft.homedns.org/exif/makernote-nikon-type2.html#0x000b /// </remarks> public const int TagUnknown34 = unchecked((int)(0x000A)); /// <summary>The camera's white balance bias setting, as an uint16 array having either one or two elements.</summary> /// <remarks> /// The camera's white balance bias setting, as an uint16 array having either one or two elements. /// <ul> /// <li><code>0</code></li> /// <li><code>1</code></li> /// <li><code>-3</code></li> /// <li><code>-2</code></li> /// <li><code>-1</code></li> /// <li><code>0,0</code></li> /// <li><code>1,0</code></li> /// <li><code>5,-5</code></li> /// </ul> /// </remarks> public const int TagCameraWhiteBalanceFine = unchecked((int)(0x000B)); /// <summary> /// The first two numbers are coefficients to multiply red and blue channels according to white balance as set in the /// camera. /// </summary> /// <remarks> /// The first two numbers are coefficients to multiply red and blue channels according to white balance as set in the /// camera. The meaning of the third and the fourth numbers is unknown. /// Values observed /// - 2.25882352 1.76078431 0.0 0.0 /// - 10242/1 34305/1 0/1 0/1 /// - 234765625/100000000 1140625/1000000 1/1 1/1 /// </remarks> public const int TagCameraWhiteBalanceRbCoeff = unchecked((int)(0x000C)); /// <summary>The camera's program shift setting, as an array of four integers.</summary> /// <remarks> /// The camera's program shift setting, as an array of four integers. /// The value, in EV, is calculated as <code>a*b/c</code>. /// <ul> /// <li><code>0,1,3,0</code> = 0 EV</li> /// <li><code>1,1,3,0</code> = 0.33 EV</li> /// <li><code>-3,1,3,0</code> = -1 EV</li> /// <li><code>1,1,2,0</code> = 0.5 EV</li> /// <li><code>2,1,6,0</code> = 0.33 EV</li> /// </ul> /// </remarks> public const int TagProgramShift = unchecked((int)(0x000D)); /// <summary>The exposure difference, as an array of four integers.</summary> /// <remarks> /// The exposure difference, as an array of four integers. /// The value, in EV, is calculated as <code>a*b/c</code>. /// <ul> /// <li><code>-105,1,12,0</code> = -8.75 EV</li> /// <li><code>-72,1,12,0</code> = -6.00 EV</li> /// <li><code>-11,1,12,0</code> = -0.92 EV</li> /// </ul> /// </remarks> public const int TagExposureDifference = unchecked((int)(0x000E)); /// <summary>The camera's ISO mode, as an uppercase string.</summary> /// <remarks> /// The camera's ISO mode, as an uppercase string. /// <ul> /// <li><code>AUTO</code></li> /// <li><code>MANUAL</code></li> /// </ul> /// </remarks> public const int TagIsoMode = unchecked((int)(0x000F)); /// <summary>Added during merge of Type2 &amp; Type3.</summary> /// <remarks>Added during merge of Type2 &amp; Type3. May apply to earlier models, such as E990 and D1.</remarks> public const int TagDataDump = unchecked((int)(0x0010)); /// <summary> /// Preview to another IFD (?) /// <p> /// Details here: http://gvsoft.homedns.org/exif/makernote-nikon-2-tag0x0011.html /// // TODO if this is another IFD, decode it /// </summary> public const int TagPreviewIfd = unchecked((int)(0x0011)); /// <summary>The flash compensation, as an array of four integers.</summary> /// <remarks> /// The flash compensation, as an array of four integers. /// The value, in EV, is calculated as <code>a*b/c</code>. /// <ul> /// <li><code>-18,1,6,0</code> = -3 EV</li> /// <li><code>4,1,6,0</code> = 0.67 EV</li> /// <li><code>6,1,6,0</code> = 1 EV</li> /// </ul> /// </remarks> public const int TagAutoFlashCompensation = unchecked((int)(0x0012)); /// <summary>The requested ISO value, as an array of two integers.</summary> /// <remarks> /// The requested ISO value, as an array of two integers. /// <ul> /// <li><code>0,0</code></li> /// <li><code>0,125</code></li> /// <li><code>1,2500</code></li> /// </ul> /// </remarks> public const int TagIsoRequested = unchecked((int)(0x0013)); /// <summary>Defines the photo corner coordinates, in 8 bytes.</summary> /// <remarks> /// Defines the photo corner coordinates, in 8 bytes. Treated as four 16-bit integers, they /// decode as: top-left (x,y); bot-right (x,y) /// - 0 0 49163 53255 /// - 0 0 3008 2000 (the image dimensions were 3008x2000) (D70) /// <ul> /// <li><code>0,0,4288,2848</code> The max resolution of the D300 camera</li> /// <li><code>0,0,3008,2000</code> The max resolution of the D70 camera</li> /// <li><code>0,0,4256,2832</code> The max resolution of the D3 camera</li> /// </ul> /// </remarks> public const int TagImageBoundary = unchecked((int)(0x0016)); /// <summary>The flash exposure compensation, as an array of four integers.</summary> /// <remarks> /// The flash exposure compensation, as an array of four integers. /// The value, in EV, is calculated as <code>a*b/c</code>. /// <ul> /// <li><code>0,0,0,0</code> = 0 EV</li> /// <li><code>0,1,6,0</code> = 0 EV</li> /// <li><code>4,1,6,0</code> = 0.67 EV</li> /// </ul> /// </remarks> public const int TagFlashExposureCompensation = unchecked((int)(0x0017)); /// <summary>The flash bracket compensation, as an array of four integers.</summary> /// <remarks> /// The flash bracket compensation, as an array of four integers. /// The value, in EV, is calculated as <code>a*b/c</code>. /// <ul> /// <li><code>0,0,0,0</code> = 0 EV</li> /// <li><code>0,1,6,0</code> = 0 EV</li> /// <li><code>4,1,6,0</code> = 0.67 EV</li> /// </ul> /// </remarks> public const int TagFlashBracketCompensation = unchecked((int)(0x0018)); /// <summary>The AE bracket compensation, as a rational number.</summary> /// <remarks> /// The AE bracket compensation, as a rational number. /// <ul> /// <li><code>0/0</code></li> /// <li><code>0/1</code></li> /// <li><code>0/6</code></li> /// <li><code>4/6</code></li> /// <li><code>6/6</code></li> /// </ul> /// </remarks> public const int TagAeBracketCompensation = unchecked((int)(0x0019)); /// <summary>Flash mode, as a string.</summary> /// <remarks> /// Flash mode, as a string. /// <ul> /// <li><code></code></li> /// <li><code>Red Eye Reduction</code></li> /// <li><code>D-Lighting</code></li> /// <li><code>Distortion control</code></li> /// </ul> /// </remarks> public const int TagFlashMode = unchecked((int)(0x001a)); public const int TagCropHighSpeed = unchecked((int)(0x001b)); public const int TagExposureTuning = unchecked((int)(0x001c)); /// <summary>The camera's serial number, as a string.</summary> /// <remarks> /// The camera's serial number, as a string. /// Note that D200 is always blank, and D50 is always <code>"D50"</code>. /// </remarks> public const int TagCameraSerialNumber = unchecked((int)(0x001d)); /// <summary>The camera's color space setting.</summary> /// <remarks> /// The camera's color space setting. /// <ul> /// <li><code>1</code> sRGB</li> /// <li><code>2</code> Adobe RGB</li> /// </ul> /// </remarks> public const int TagColorSpace = unchecked((int)(0x001e)); public const int TagVrInfo = unchecked((int)(0x001f)); public const int TagImageAuthentication = unchecked((int)(0x0020)); public const int TagUnknown35 = unchecked((int)(0x0021)); /// <summary>The active D-Lighting setting.</summary> /// <remarks> /// The active D-Lighting setting. /// <ul> /// <li><code>0</code> Off</li> /// <li><code>1</code> Low</li> /// <li><code>3</code> Normal</li> /// <li><code>5</code> High</li> /// <li><code>7</code> Extra High</li> /// <li><code>65535</code> Auto</li> /// </ul> /// </remarks> public const int TagActiveDLighting = unchecked((int)(0x0022)); public const int TagPictureControl = unchecked((int)(0x0023)); public const int TagWorldTime = unchecked((int)(0x0024)); public const int TagIsoInfo = unchecked((int)(0x0025)); public const int TagUnknown36 = unchecked((int)(0x0026)); public const int TagUnknown37 = unchecked((int)(0x0027)); public const int TagUnknown38 = unchecked((int)(0x0028)); public const int TagUnknown39 = unchecked((int)(0x0029)); /// <summary>The camera's vignette control setting.</summary> /// <remarks> /// The camera's vignette control setting. /// <ul> /// <li><code>0</code> Off</li> /// <li><code>1</code> Low</li> /// <li><code>3</code> Normal</li> /// <li><code>5</code> High</li> /// </ul> /// </remarks> public const int TagVignetteControl = unchecked((int)(0x002a)); public const int TagUnknown40 = unchecked((int)(0x002b)); public const int TagUnknown41 = unchecked((int)(0x002c)); public const int TagUnknown42 = unchecked((int)(0x002d)); public const int TagUnknown43 = unchecked((int)(0x002e)); public const int TagUnknown44 = unchecked((int)(0x002f)); public const int TagUnknown45 = unchecked((int)(0x0030)); public const int TagUnknown46 = unchecked((int)(0x0031)); /// <summary>The camera's image adjustment setting, as a string.</summary> /// <remarks> /// The camera's image adjustment setting, as a string. /// <ul> /// <li><code>AUTO</code></li> /// <li><code>CONTRAST(+)</code></li> /// <li><code>CONTRAST(-)</code></li> /// <li><code>NORMAL</code></li> /// <li><code>B &amp; W</code></li> /// <li><code>BRIGHTNESS(+)</code></li> /// <li><code>BRIGHTNESS(-)</code></li> /// <li><code>SEPIA</code></li> /// </ul> /// </remarks> public const int TagImageAdjustment = unchecked((int)(0x0080)); /// <summary>The camera's tone compensation setting, as a string.</summary> /// <remarks> /// The camera's tone compensation setting, as a string. /// <ul> /// <li><code>NORMAL</code></li> /// <li><code>LOW</code></li> /// <li><code>MED.L</code></li> /// <li><code>MED.H</code></li> /// <li><code>HIGH</code></li> /// <li><code>AUTO</code></li> /// </ul> /// </remarks> public const int TagCameraToneCompensation = unchecked((int)(0x0081)); /// <summary>A description of any auxiliary lens, as a string.</summary> /// <remarks> /// A description of any auxiliary lens, as a string. /// <ul> /// <li><code>OFF</code></li> /// <li><code>FISHEYE 1</code></li> /// <li><code>FISHEYE 2</code></li> /// <li><code>TELEPHOTO 2</code></li> /// <li><code>WIDE ADAPTER</code></li> /// </ul> /// </remarks> public const int TagAdapter = unchecked((int)(0x0082)); /// <summary>The type of lens used, as a byte.</summary> /// <remarks> /// The type of lens used, as a byte. /// <ul> /// <li><code>0x00</code> AF</li> /// <li><code>0x01</code> MF</li> /// <li><code>0x02</code> D</li> /// <li><code>0x06</code> G, D</li> /// <li><code>0x08</code> VR</li> /// <li><code>0x0a</code> VR, D</li> /// <li><code>0x0e</code> VR, G, D</li> /// </ul> /// </remarks> public const int TagLensType = unchecked((int)(0x0083)); /// <summary>A pair of focal/max-fstop values that describe the lens used.</summary> /// <remarks> /// A pair of focal/max-fstop values that describe the lens used. /// Values observed /// - 180.0,180.0,2.8,2.8 (D100) /// - 240/10 850/10 35/10 45/10 /// - 18-70mm f/3.5-4.5 (D70) /// - 17-35mm f/2.8-2.8 (D1X) /// - 70-200mm f/2.8-2.8 (D70) /// Nikon Browser identifies the lens as "18-70mm F/3.5-4.5 G" which /// is identical to metadata extractor, except for the "G". This must /// be coming from another tag... /// </remarks> public const int TagLens = unchecked((int)(0x0084)); /// <summary>Added during merge of Type2 &amp; Type3.</summary> /// <remarks>Added during merge of Type2 &amp; Type3. May apply to earlier models, such as E990 and D1.</remarks> public const int TagManualFocusDistance = unchecked((int)(0x0085)); /// <summary>The amount of digital zoom used.</summary> public const int TagDigitalZoom = unchecked((int)(0x0086)); /// <summary>Whether the flash was used in this image.</summary> /// <remarks> /// Whether the flash was used in this image. /// <ul> /// <li><code>0</code> Flash Not Used</li> /// <li><code>1</code> Manual Flash</li> /// <li><code>3</code> Flash Not Ready</li> /// <li><code>7</code> External Flash</li> /// <li><code>8</code> Fired, Commander Mode</li> /// <li><code>9</code> Fired, TTL Mode</li> /// </ul> /// </remarks> public const int TagFlashUsed = unchecked((int)(0x0087)); /// <summary>The position of the autofocus target.</summary> public const int TagAfFocusPosition = unchecked((int)(0x0088)); /// <summary>The camera's shooting mode.</summary> /// <remarks> /// The camera's shooting mode. /// <p> /// A bit-array with: /// <ul> /// <li><code>0</code> Single Frame</li> /// <li><code>1</code> Continuous</li> /// <li><code>2</code> Delay</li> /// <li><code>8</code> PC Control</li> /// <li><code>16</code> Exposure Bracketing</li> /// <li><code>32</code> Auto ISO</li> /// <li><code>64</code> White-Balance Bracketing</li> /// <li><code>128</code> IR Control</li> /// </ul> /// </remarks> public const int TagShootingMode = unchecked((int)(0x0089)); public const int TagUnknown20 = unchecked((int)(0x008A)); /// <summary>Lens stops, as an array of four integers.</summary> /// <remarks> /// Lens stops, as an array of four integers. /// The value, in EV, is calculated as <code>a*b/c</code>. /// <ul> /// <li><code>64,1,12,0</code> = 5.33 EV</li> /// <li><code>72,1,12,0</code> = 6 EV</li> /// </ul> /// </remarks> public const int TagLensStops = unchecked((int)(0x008B)); public const int TagContrastCurve = unchecked((int)(0x008C)); /// <summary>The color space as set in the camera, as a string.</summary> /// <remarks> /// The color space as set in the camera, as a string. /// <ul> /// <li><code>MODE1</code> = Mode 1 (sRGB)</li> /// <li><code>MODE1a</code> = Mode 1 (sRGB)</li> /// <li><code>MODE2</code> = Mode 2 (Adobe RGB)</li> /// <li><code>MODE3</code> = Mode 2 (sRGB): Higher Saturation</li> /// <li><code>MODE3a</code> = Mode 2 (sRGB): Higher Saturation</li> /// <li><code>B &amp; W</code> = B &amp; W</li> /// </ul> /// </remarks> public const int TagCameraColorMode = unchecked((int)(0x008D)); public const int TagUnknown47 = unchecked((int)(0x008E)); /// <summary>The camera's scene mode, as a string.</summary> /// <remarks> /// The camera's scene mode, as a string. Examples include: /// <ul> /// <li><code>BEACH/SNOW</code></li> /// <li><code>CLOSE UP</code></li> /// <li><code>NIGHT PORTRAIT</code></li> /// <li><code>PORTRAIT</code></li> /// <li><code>ANTI-SHAKE</code></li> /// <li><code>BACK LIGHT</code></li> /// <li><code>BEST FACE</code></li> /// <li><code>BEST</code></li> /// <li><code>COPY</code></li> /// <li><code>DAWN/DUSK</code></li> /// <li><code>FACE-PRIORITY</code></li> /// <li><code>FIREWORKS</code></li> /// <li><code>FOOD</code></li> /// <li><code>HIGH SENS.</code></li> /// <li><code>LAND SCAPE</code></li> /// <li><code>MUSEUM</code></li> /// <li><code>PANORAMA ASSIST</code></li> /// <li><code>PARTY/INDOOR</code></li> /// <li><code>SCENE AUTO</code></li> /// <li><code>SMILE</code></li> /// <li><code>SPORT</code></li> /// <li><code>SPORT CONT.</code></li> /// <li><code>SUNSET</code></li> /// </ul> /// </remarks> public const int TagSceneMode = unchecked((int)(0x008F)); /// <summary>The lighting type, as a string.</summary> /// <remarks> /// The lighting type, as a string. Examples include: /// <ul> /// <li><code></code></li> /// <li><code>NATURAL</code></li> /// <li><code>SPEEDLIGHT</code></li> /// <li><code>COLORED</code></li> /// <li><code>MIXED</code></li> /// <li><code>NORMAL</code></li> /// </ul> /// </remarks> public const int TagLightSource = unchecked((int)(0x0090)); /// <summary>Advertised as ASCII, but actually isn't.</summary> /// <remarks> /// Advertised as ASCII, but actually isn't. A variable number of bytes (eg. 18 to 533). Actual number of bytes /// appears fixed for a given camera model. /// </remarks> public const int TagShotInfo = unchecked((int)(0x0091)); /// <summary>The hue adjustment as set in the camera.</summary> /// <remarks>The hue adjustment as set in the camera. Values observed are either 0 or 3.</remarks> public const int TagCameraHueAdjustment = unchecked((int)(0x0092)); /// <summary>The NEF (RAW) compression.</summary> /// <remarks> /// The NEF (RAW) compression. Examples include: /// <ul> /// <li><code>1</code> Lossy (Type 1)</li> /// <li><code>2</code> Uncompressed</li> /// <li><code>3</code> Lossless</li> /// <li><code>4</code> Lossy (Type 2)</li> /// </ul> /// </remarks> public const int TagNefCompression = unchecked((int)(0x0093)); /// <summary>The saturation level, as a signed integer.</summary> /// <remarks> /// The saturation level, as a signed integer. Examples include: /// <ul> /// <li><code>+3</code></li> /// <li><code>+2</code></li> /// <li><code>+1</code></li> /// <li><code>0</code> Normal</li> /// <li><code>-1</code></li> /// <li><code>-2</code></li> /// <li><code>-3</code> (B&amp;W)</li> /// </ul> /// </remarks> public const int TagSaturation = unchecked((int)(0x0094)); /// <summary>The type of noise reduction, as a string.</summary> /// <remarks> /// The type of noise reduction, as a string. Examples include: /// <ul> /// <li><code>OFF</code></li> /// <li><code>FPNR</code></li> /// </ul> /// </remarks> public const int TagNoiseReduction = unchecked((int)(0x0095)); public const int TagLinearizationTable = unchecked((int)(0x0096)); public const int TagColorBalance = unchecked((int)(0x0097)); public const int TagLensData = unchecked((int)(0x0098)); /// <summary>The NEF (RAW) thumbnail size, as an integer array with two items representing [width,height].</summary> public const int TagNefThumbnailSize = unchecked((int)(0x0099)); /// <summary>The sensor pixel size, as a pair of rational numbers.</summary> public const int TagSensorPixelSize = unchecked((int)(0x009A)); public const int TagUnknown10 = unchecked((int)(0x009B)); public const int TagSceneAssist = unchecked((int)(0x009C)); public const int TagUnknown11 = unchecked((int)(0x009D)); public const int TagRetouchHistory = unchecked((int)(0x009E)); public const int TagUnknown12 = unchecked((int)(0x009F)); /// <summary>The camera serial number, as a string.</summary> /// <remarks> /// The camera serial number, as a string. /// <ul> /// <li><code>NO= 00002539</code></li> /// <li><code>NO= -1000d71</code></li> /// <li><code>PKG597230621263</code></li> /// <li><code>PKG5995671330625116</code></li> /// <li><code>PKG49981281631130677</code></li> /// <li><code>BU672230725063</code></li> /// <li><code>NO= 200332c7</code></li> /// <li><code>NO= 30045efe</code></li> /// </ul> /// </remarks> public const int TagCameraSerialNumber2 = unchecked((int)(0x00A0)); public const int TagImageDataSize = unchecked((int)(0x00A2)); public const int TagUnknown27 = unchecked((int)(0x00A3)); public const int TagUnknown28 = unchecked((int)(0x00A4)); public const int TagImageCount = unchecked((int)(0x00A5)); public const int TagDeletedImageCount = unchecked((int)(0x00A6)); /// <summary>The number of total shutter releases.</summary> /// <remarks>The number of total shutter releases. This value increments for each exposure (observed on D70).</remarks> public const int TagExposureSequenceNumber = unchecked((int)(0x00A7)); public const int TagFlashInfo = unchecked((int)(0x00A8)); /// <summary>The camera's image optimisation, as a string.</summary> /// <remarks> /// The camera's image optimisation, as a string. /// <ul> /// <li><code></code></li> /// <li><code>NORMAL</code></li> /// <li><code>CUSTOM</code></li> /// <li><code>BLACK AND WHITE</code></li> /// <li><code>LAND SCAPE</code></li> /// <li><code>MORE VIVID</code></li> /// <li><code>PORTRAIT</code></li> /// <li><code>SOFT</code></li> /// <li><code>VIVID</code></li> /// </ul> /// </remarks> public const int TagImageOptimisation = unchecked((int)(0x00A9)); /// <summary>The camera's saturation level, as a string.</summary> /// <remarks> /// The camera's saturation level, as a string. /// <ul> /// <li><code></code></li> /// <li><code>NORMAL</code></li> /// <li><code>AUTO</code></li> /// <li><code>ENHANCED</code></li> /// <li><code>MODERATE</code></li> /// </ul> /// </remarks> public const int TagSaturation2 = unchecked((int)(0x00AA)); /// <summary>The camera's digital vari-program setting, as a string.</summary> /// <remarks> /// The camera's digital vari-program setting, as a string. /// <ul> /// <li><code></code></li> /// <li><code>AUTO</code></li> /// <li><code>AUTO(FLASH OFF)</code></li> /// <li><code>CLOSE UP</code></li> /// <li><code>LANDSCAPE</code></li> /// <li><code>NIGHT PORTRAIT</code></li> /// <li><code>PORTRAIT</code></li> /// <li><code>SPORT</code></li> /// </ul> /// </remarks> public const int TagDigitalVariProgram = unchecked((int)(0x00AB)); /// <summary>The camera's digital vari-program setting, as a string.</summary> /// <remarks> /// The camera's digital vari-program setting, as a string. /// <ul> /// <li><code></code></li> /// <li><code>VR-ON</code></li> /// <li><code>VR-OFF</code></li> /// <li><code>VR-HYBRID</code></li> /// <li><code>VR-ACTIVE</code></li> /// </ul> /// </remarks> public const int TagImageStabilisation = unchecked((int)(0x00AC)); /// <summary>The camera's digital vari-program setting, as a string.</summary> /// <remarks> /// The camera's digital vari-program setting, as a string. /// <ul> /// <li><code></code></li> /// <li><code>HYBRID</code></li> /// <li><code>STANDARD</code></li> /// </ul> /// </remarks> public const int TagAfResponse = unchecked((int)(0x00AD)); public const int TagUnknown29 = unchecked((int)(0x00AE)); public const int TagUnknown30 = unchecked((int)(0x00AF)); public const int TagMultiExposure = unchecked((int)(0x00B0)); /// <summary>The camera's high ISO noise reduction setting, as an integer.</summary> /// <remarks> /// The camera's high ISO noise reduction setting, as an integer. /// <ul> /// <li><code>0</code> Off</li> /// <li><code>1</code> Minimal</li> /// <li><code>2</code> Low</li> /// <li><code>4</code> Normal</li> /// <li><code>6</code> High</li> /// </ul> /// </remarks> public const int TagHighIsoNoiseReduction = unchecked((int)(0x00B1)); public const int TagUnknown31 = unchecked((int)(0x00B2)); public const int TagUnknown32 = unchecked((int)(0x00B3)); public const int TagUnknown33 = unchecked((int)(0x00B4)); public const int TagUnknown48 = unchecked((int)(0x00B5)); public const int TagPowerUpTime = unchecked((int)(0x00B6)); public const int TagAfInfo2 = unchecked((int)(0x00B7)); public const int TagFileInfo = unchecked((int)(0x00B8)); public const int TagAfTune = unchecked((int)(0x00B9)); public const int TagUnknown49 = unchecked((int)(0x00BB)); public const int TagUnknown50 = unchecked((int)(0x00BD)); public const int TagUnknown51 = unchecked((int)(0x0103)); public const int TagPrintIm = unchecked((int)(0x0E00)); /// <summary>Data about changes set by Nikon Capture Editor.</summary> /// <remarks> /// Data about changes set by Nikon Capture Editor. /// Values observed /// </remarks> public const int TagNikonCaptureData = unchecked((int)(0x0E01)); public const int TagUnknown52 = unchecked((int)(0x0E05)); public const int TagUnknown53 = unchecked((int)(0x0E08)); public const int TagNikonCaptureVersion = unchecked((int)(0x0E09)); public const int TagNikonCaptureOffsets = unchecked((int)(0x0E0E)); public const int TagNikonScan = unchecked((int)(0x0E10)); public const int TagUnknown54 = unchecked((int)(0x0E19)); public const int TagNefBitDepth = unchecked((int)(0x0E22)); public const int TagUnknown55 = unchecked((int)(0x0E23)); [NotNull] protected internal static readonly Dictionary<int?, string> _tagNameMap = new Dictionary<int?, string>(); static NikonType2MakernoteDirectory() { _tagNameMap.Put(TagFirmwareVersion, "Firmware Version"); _tagNameMap.Put(TagIso1, "ISO"); _tagNameMap.Put(TagQualityAndFileFormat, "Quality & File Format"); _tagNameMap.Put(TagCameraWhiteBalance, "White Balance"); _tagNameMap.Put(TagCameraSharpening, "Sharpening"); _tagNameMap.Put(TagAfType, "AF Type"); _tagNameMap.Put(TagCameraWhiteBalanceFine, "White Balance Fine"); _tagNameMap.Put(TagCameraWhiteBalanceRbCoeff, "White Balance RB Coefficients"); _tagNameMap.Put(TagIsoRequested, "ISO"); _tagNameMap.Put(TagIsoMode, "ISO Mode"); _tagNameMap.Put(TagDataDump, "Data Dump"); _tagNameMap.Put(TagProgramShift, "Program Shift"); _tagNameMap.Put(TagExposureDifference, "Exposure Difference"); _tagNameMap.Put(TagPreviewIfd, "Preview IFD"); _tagNameMap.Put(TagLensType, "Lens Type"); _tagNameMap.Put(TagFlashUsed, "Flash Used"); _tagNameMap.Put(TagAfFocusPosition, "AF Focus Position"); _tagNameMap.Put(TagShootingMode, "Shooting Mode"); _tagNameMap.Put(TagLensStops, "Lens Stops"); _tagNameMap.Put(TagContrastCurve, "Contrast Curve"); _tagNameMap.Put(TagLightSource, "Light source"); _tagNameMap.Put(TagShotInfo, "Shot Info"); _tagNameMap.Put(TagColorBalance, "Color Balance"); _tagNameMap.Put(TagLensData, "Lens Data"); _tagNameMap.Put(TagNefThumbnailSize, "NEF Thumbnail Size"); _tagNameMap.Put(TagSensorPixelSize, "Sensor Pixel Size"); _tagNameMap.Put(TagUnknown10, "Unknown 10"); _tagNameMap.Put(TagSceneAssist, "Scene Assist"); _tagNameMap.Put(TagUnknown11, "Unknown 11"); _tagNameMap.Put(TagRetouchHistory, "Retouch History"); _tagNameMap.Put(TagUnknown12, "Unknown 12"); _tagNameMap.Put(TagFlashSyncMode, "Flash Sync Mode"); _tagNameMap.Put(TagAutoFlashMode, "Auto Flash Mode"); _tagNameMap.Put(TagAutoFlashCompensation, "Auto Flash Compensation"); _tagNameMap.Put(TagExposureSequenceNumber, "Exposure Sequence Number"); _tagNameMap.Put(TagColorMode, "Color Mode"); _tagNameMap.Put(TagUnknown20, "Unknown 20"); _tagNameMap.Put(TagImageBoundary, "Image Boundary"); _tagNameMap.Put(TagFlashExposureCompensation, "Flash Exposure Compensation"); _tagNameMap.Put(TagFlashBracketCompensation, "Flash Bracket Compensation"); _tagNameMap.Put(TagAeBracketCompensation, "AE Bracket Compensation"); _tagNameMap.Put(TagFlashMode, "Flash Mode"); _tagNameMap.Put(TagCropHighSpeed, "Crop High Speed"); _tagNameMap.Put(TagExposureTuning, "Exposure Tuning"); _tagNameMap.Put(TagCameraSerialNumber, "Camera Serial Number"); _tagNameMap.Put(TagColorSpace, "Color Space"); _tagNameMap.Put(TagVrInfo, "VR Info"); _tagNameMap.Put(TagImageAuthentication, "Image Authentication"); _tagNameMap.Put(TagUnknown35, "Unknown 35"); _tagNameMap.Put(TagActiveDLighting, "Active D-Lighting"); _tagNameMap.Put(TagPictureControl, "Picture Control"); _tagNameMap.Put(TagWorldTime, "World Time"); _tagNameMap.Put(TagIsoInfo, "ISO Info"); _tagNameMap.Put(TagUnknown36, "Unknown 36"); _tagNameMap.Put(TagUnknown37, "Unknown 37"); _tagNameMap.Put(TagUnknown38, "Unknown 38"); _tagNameMap.Put(TagUnknown39, "Unknown 39"); _tagNameMap.Put(TagVignetteControl, "Vignette Control"); _tagNameMap.Put(TagUnknown40, "Unknown 40"); _tagNameMap.Put(TagUnknown41, "Unknown 41"); _tagNameMap.Put(TagUnknown42, "Unknown 42"); _tagNameMap.Put(TagUnknown43, "Unknown 43"); _tagNameMap.Put(TagUnknown44, "Unknown 44"); _tagNameMap.Put(TagUnknown45, "Unknown 45"); _tagNameMap.Put(TagUnknown46, "Unknown 46"); _tagNameMap.Put(TagUnknown47, "Unknown 47"); _tagNameMap.Put(TagSceneMode, "Scene Mode"); _tagNameMap.Put(TagCameraSerialNumber2, "Camera Serial Number"); _tagNameMap.Put(TagImageDataSize, "Image Data Size"); _tagNameMap.Put(TagUnknown27, "Unknown 27"); _tagNameMap.Put(TagUnknown28, "Unknown 28"); _tagNameMap.Put(TagImageCount, "Image Count"); _tagNameMap.Put(TagDeletedImageCount, "Deleted Image Count"); _tagNameMap.Put(TagSaturation2, "Saturation"); _tagNameMap.Put(TagDigitalVariProgram, "Digital Vari Program"); _tagNameMap.Put(TagImageStabilisation, "Image Stabilisation"); _tagNameMap.Put(TagAfResponse, "AF Response"); _tagNameMap.Put(TagUnknown29, "Unknown 29"); _tagNameMap.Put(TagUnknown30, "Unknown 30"); _tagNameMap.Put(TagMultiExposure, "Multi Exposure"); _tagNameMap.Put(TagHighIsoNoiseReduction, "High ISO Noise Reduction"); _tagNameMap.Put(TagUnknown31, "Unknown 31"); _tagNameMap.Put(TagUnknown32, "Unknown 32"); _tagNameMap.Put(TagUnknown33, "Unknown 33"); _tagNameMap.Put(TagUnknown48, "Unknown 48"); _tagNameMap.Put(TagPowerUpTime, "Power Up Time"); _tagNameMap.Put(TagAfInfo2, "AF Info 2"); _tagNameMap.Put(TagFileInfo, "File Info"); _tagNameMap.Put(TagAfTune, "AF Tune"); _tagNameMap.Put(TagFlashInfo, "Flash Info"); _tagNameMap.Put(TagImageOptimisation, "Image Optimisation"); _tagNameMap.Put(TagImageAdjustment, "Image Adjustment"); _tagNameMap.Put(TagCameraToneCompensation, "Tone Compensation"); _tagNameMap.Put(TagAdapter, "Adapter"); _tagNameMap.Put(TagLens, "Lens"); _tagNameMap.Put(TagManualFocusDistance, "Manual Focus Distance"); _tagNameMap.Put(TagDigitalZoom, "Digital Zoom"); _tagNameMap.Put(TagCameraColorMode, "Colour Mode"); _tagNameMap.Put(TagCameraHueAdjustment, "Camera Hue Adjustment"); _tagNameMap.Put(TagNefCompression, "NEF Compression"); _tagNameMap.Put(TagSaturation, "Saturation"); _tagNameMap.Put(TagNoiseReduction, "Noise Reduction"); _tagNameMap.Put(TagLinearizationTable, "Linearization Table"); _tagNameMap.Put(TagNikonCaptureData, "Nikon Capture Data"); _tagNameMap.Put(TagUnknown49, "Unknown 49"); _tagNameMap.Put(TagUnknown50, "Unknown 50"); _tagNameMap.Put(TagUnknown51, "Unknown 51"); _tagNameMap.Put(TagPrintIm, "Print IM"); _tagNameMap.Put(TagUnknown52, "Unknown 52"); _tagNameMap.Put(TagUnknown53, "Unknown 53"); _tagNameMap.Put(TagNikonCaptureVersion, "Nikon Capture Version"); _tagNameMap.Put(TagNikonCaptureOffsets, "Nikon Capture Offsets"); _tagNameMap.Put(TagNikonScan, "Nikon Scan"); _tagNameMap.Put(TagUnknown54, "Unknown 54"); _tagNameMap.Put(TagNefBitDepth, "NEF Bit Depth"); _tagNameMap.Put(TagUnknown55, "Unknown 55"); } public NikonType2MakernoteDirectory() { this.SetDescriptor(new NikonType2MakernoteDescriptor(this)); } [NotNull] public override string GetName() { return "Nikon Makernote"; } [NotNull] protected internal override Dictionary<int?, string> GetTagNameMap() { return _tagNameMap; } } }
using System; namespace XSharpx { public struct Tree<A> { private readonly A root; private readonly List<Tree<A>> children; internal Tree(A root, List<Tree<A>> children) { this.root = root; this.children = children; } public Store<A, Tree<A>> Root { get { var t = this; return root.StoreSet(r => new Tree<A>(r, t.children)); } } public Store<List<Tree<A>>, Tree<A>> Children { get { var t = this; return children.StoreSet(c => new Tree<A>(t.root, c)); } } public Tree<Tree<A>> Duplicate { get { return this.UnfoldTree(t => t.And(t.children)); } } public Tree<B> Extend<B>(Func<Tree<A>, B> f) { return this.UnfoldTree(t => f(t).And(t.children)); } public Tree<C> ZipWith<B, C>(Tree<B> o, Func<A, Func<B, C>> f) { return this.SelectMany(a => o.Select(b => f(a)(b))); } public Tree<Pair<A, B>> Zip<B>(Tree<B> o) { return ZipWith<B, Pair<A, B>>(o, Pair<A, B>.pairF()); } public Tree<B> ScanRight<B>(Func<A, List<Tree<B>>, B> f) { var c = children.Select(t => t.ScanRight(f)); return f(root, c).TreeNode(c); } private List<A> Squish(List<A> x) { return root + children.FoldRight((a, b) => a.Squish(b), x); } public List<A> PreOrder { get { return Squish(List<A>.Empty); } } public List<List<A>> BreadthFirst { get { return this.ListValue().UnfoldList<List<Tree<A>>, List<A>>(a => a.IsEmpty ? Option.Empty : a.Select(q => q.Root.Get).And(a.SumMapRight(t => t.Children.Get, Monoid<Tree<A>>.List)).Some()); } } public B FoldRight<B>(Func<A, B, B> f, B b) { return PreOrder.FoldRight(f, b); } public B FoldLeft<B>(Func<B, A, B> f, B b) { return PreOrder.FoldLeft(f, b); } public List<Tree<B>> TraverseList<B>(Func<A, List<B>> f) { return f(root).ProductWith<List<Tree<B>>, Tree<B>>( children.TraverseList(w => w.TraverseList(f)) , b => bs => b.TreeNode(bs) ); } public Option<Tree<B>> TraverseOption<B>(Func<A, Option<B>> f) { return f(root).ZipWith<List<Tree<B>>, Tree<B>>( children.TraverseOption(w => w.TraverseOption(f)) , b => bs => b.TreeNode(bs) ); } public Terminal<Tree<B>> TraverseTerminal<B>(Func<A, Terminal<B>> f) { return f(root).ZipWith<List<Tree<B>>, Tree<B>>( children.TraverseTerminal(w => w.TraverseTerminal(f)) , b => bs => b.TreeNode(bs) ); } public Input<Tree<B>> TraverseInput<B>(Func<A, Input<B>> f) { return f(root).ZipWith<List<Tree<B>>, Tree<B>>( children.TraverseInput(w => w.TraverseInput(f)) , b => bs => b.TreeNode(bs) ); } public Either<X, Tree<B>> TraverseEither<X, B>(Func<A, Either<X, B>> f) { return f(root).ZipWith<List<Tree<B>>, Tree<B>>( children.TraverseEither(w => w.TraverseEither(f)) , b => bs => b.TreeNode(bs) ); } public NonEmptyList<Tree<B>> TraverseNonEmptyList<B>(Func<A, NonEmptyList<B>> f) { return f(root).ZipWith<List<Tree<B>>, Tree<B>>( children.TraverseNonEmptyList(w => w.TraverseNonEmptyList(f)) , b => bs => b.TreeNode(bs) ); } public Pair<X, Tree<B>> TraversePair<X, B>(Func<A, Pair<X, B>> f, Monoid<X> m) { return f(root).Constrain(m).ZipWith<List<Tree<B>>, Tree<B>>( children.TraversePair(w => w.TraversePair(f, m), m).Constrain(m) , b => bs => b.TreeNode(bs) ).Pair; } public Func<X, Tree<B>> TraverseFunc<X, B>(Func<A, Func<X, B>> f) { return f(root).ZipWith<B, List<Tree<B>>, Tree<B>, X>( children.TraverseFunc<X, Tree<B>>(w => w.TraverseFunc(f)) , b => bs => b.TreeNode(bs) ); } public Tree<Tree<B>> TraverseTree<B>(Func<A, Tree<B>> f) { return f(root).ZipWith<List<Tree<B>>, Tree<B>>( children.TraverseTree(w => w.TraverseTree(f)) , b => bs => b.TreeNode(bs) ); } } public static class TreeExtension { public static Tree<A> TreeValue<A>(this A a) { return new Tree<A>(a, List<Tree<A>>.Empty); } public static Tree<A> TreeNode<A>(this A a, List<Tree<A>> c) { return new Tree<A>(a, c); } public static Tree<B> Select<A, B>(this Tree<A> k, Func<A, B> f) { return f(k.Root.Get).TreeNode(k.Children.Get.Select(q => q.Select(f))); } public static Tree<B> SelectMany<A, B>(this Tree<A> k, Func<A, Tree<B>> f) { var r = f(k.Root.Get); return r.Root.Get.TreeNode(r.Children.Get * k.Children.Get.Select(q => q.SelectMany(f))); } public static Tree<C> SelectMany<A, B, C>(this Tree<A> k, Func<A, Tree<B>> p, Func<A, B, C> f) { return SelectMany(k, a => Select(p(a), b => f(a, b))); } public static Tree<B> Apply<A, B>(this Tree<Func<A, B>> f, Tree<A> o) { return f.SelectMany(g => o.Select(p => g(p))); } public static Tree<A> Flatten<A>(this Tree<Tree<A>> o) { return o.SelectMany(z => z); } public static Pair<Tree<A>, Tree<B>> Unzip<A, B>(this Tree<Pair<A, B>> p) { var c = p.Children.Get.Select(l => l.Unzip()); var r1 = c.Select(q => q._1.Get); var r2 = c.Select(q => q._2.Get); return p.Root.Get._1.Get.TreeNode(r1).And(p.Root.Get._2.Get.TreeNode(r2)); } public static List<Tree<B>> UnfoldChildren<A, B>(this List<A> a, Func<A, Pair<B, List<A>>> f) { return a.Select(z => z.UnfoldTree(f)); } public static Tree<B> UnfoldTree<A, B>(this A a, Func<A, Pair<B, List<A>>> f) { var p = f(a); return p._1.Get.TreeNode(p._2.Get.UnfoldChildren(f)); } } public struct TreeForest<A> { private readonly List<Tree<A>> forest; internal TreeForest(List<Tree<A>> forest) { this.forest = forest; } public Store<List<Tree<A>>, TreeForest<A>> Forest { get { return forest.StoreSet(f => new TreeForest<A>(f)); } } } public static class TreeForestExtension { public static TreeForest<B> Select<A, B>(this TreeForest<A> k, Func<A, B> f) { return k.Forest.Get.Select(q => q.Select(f)).Forest(); } public static TreeForest<B> SelectMany<A, B>(this TreeForest<A> k, Func<A, TreeForest<B>> f) { return k.Forest.Get.SelectMany(t => TreeT(a => f(a).Forest.Get, t)).Forest(); } private static List<Tree<B>> TreeT<A, B>(Func<A, List<Tree<B>>> f, Tree<A> t) { return from r in f(t.Root.Get) from s in t.Children.Get.TraverseList(a => TreeT(f, a)) select r.Root.Get.TreeNode(s.Append(r.Children.Get)); } public static TreeForest<C> SelectMany<A, B, C>(this TreeForest<A> k, Func<A, TreeForest<B>> p, Func<A, B, C> f) { return SelectMany(k, a => Select(p(a), b => f(a, b))); } public static TreeForest<B> Apply<A, B>(this TreeForest<Func<A, B>> f, TreeForest<A> o) { return f.SelectMany(g => o.Select(p => g(p))); } public static TreeForest<A> Flatten<A>(this TreeForest<TreeForest<A>> o) { return o.SelectMany(z => z); } public static Pair<TreeForest<A>, TreeForest<B>> Unzip<A, B>(this TreeForest<Pair<A, B>> p) { return Pair<TreeForest<A>, TreeForest<B>>.pair(p.Select(a => a._1.Get), p.Select(a => a._2.Get)); } public static TreeForest<A> Forest<A>(this List<Tree<A>> f) { return new TreeForest<A>(f); } } }
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Globalization; using System.IO; using System.Linq; using Xunit; using NLog.Common; using System.Text; using NLog.Time; #if !SILVERLIGHT using Xunit.Extensions; #endif namespace NLog.UnitTests.Common { public class InternalLoggerTests : NLogTestBase, IDisposable { /// <summary> /// Test the return values of all Is[Level]Enabled() methods. /// </summary> [Fact] public void IsEnabledTests() { // Setup LogLevel to minimum named level. InternalLogger.LogLevel = LogLevel.Trace; Assert.True(InternalLogger.IsTraceEnabled); Assert.True(InternalLogger.IsDebugEnabled); Assert.True(InternalLogger.IsInfoEnabled); Assert.True(InternalLogger.IsWarnEnabled); Assert.True(InternalLogger.IsErrorEnabled); Assert.True(InternalLogger.IsFatalEnabled); // Setup LogLevel to maximum named level. InternalLogger.LogLevel = LogLevel.Fatal; Assert.False(InternalLogger.IsTraceEnabled); Assert.False(InternalLogger.IsDebugEnabled); Assert.False(InternalLogger.IsInfoEnabled); Assert.False(InternalLogger.IsWarnEnabled); Assert.False(InternalLogger.IsErrorEnabled); Assert.True(InternalLogger.IsFatalEnabled); // Switch off the internal logging. InternalLogger.LogLevel = LogLevel.Off; Assert.False(InternalLogger.IsTraceEnabled); Assert.False(InternalLogger.IsDebugEnabled); Assert.False(InternalLogger.IsInfoEnabled); Assert.False(InternalLogger.IsWarnEnabled); Assert.False(InternalLogger.IsErrorEnabled); Assert.False(InternalLogger.IsFatalEnabled); } [Fact] public void WriteToStringWriterTests() { // Expected result is the same for both types of method invocation. const string expected = "Warn WWW\nError EEE\nFatal FFF\nTrace TTT\nDebug DDD\nInfo III\n"; InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; { StringWriter writer1 = new StringWriter() { NewLine = "\n" }; InternalLogger.LogWriter = writer1; // Named (based on LogLevel) public methods. InternalLogger.Warn("WWW"); InternalLogger.Error("EEE"); InternalLogger.Fatal("FFF"); InternalLogger.Trace("TTT"); InternalLogger.Debug("DDD"); InternalLogger.Info("III"); TestWriter(expected, writer1); } { // // Reconfigure the LogWriter. StringWriter writer2 = new StringWriter() { NewLine = "\n" }; InternalLogger.LogWriter = writer2; // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, "WWW"); InternalLogger.Log(LogLevel.Error, "EEE"); InternalLogger.Log(LogLevel.Fatal, "FFF"); InternalLogger.Log(LogLevel.Trace, "TTT"); InternalLogger.Log(LogLevel.Debug, "DDD"); InternalLogger.Log(LogLevel.Info, "III"); TestWriter(expected, writer2); } } [Fact] public void WriteToStringWriterWithArgsTests() { // Expected result is the same for both types of method invocation. const string expected = "Warn WWW 0\nError EEE 0, 1\nFatal FFF 0, 1, 2\nTrace TTT 0, 1, 2\nDebug DDD 0, 1\nInfo III 0\n"; InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; { StringWriter writer1 = new StringWriter() { NewLine = "\n" }; InternalLogger.LogWriter = writer1; // Named (based on LogLevel) public methods. InternalLogger.Warn("WWW {0}", 0); InternalLogger.Error("EEE {0}, {1}", 0, 1); InternalLogger.Fatal("FFF {0}, {1}, {2}", 0, 1, 2); InternalLogger.Trace("TTT {0}, {1}, {2}", 0, 1, 2); InternalLogger.Debug("DDD {0}, {1}", 0, 1); InternalLogger.Info("III {0}", 0); TestWriter(expected, writer1); } { // // Reconfigure the LogWriter. StringWriter writer2 = new StringWriter() { NewLine = "\n" }; InternalLogger.LogWriter = writer2; // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, "WWW {0}", 0); InternalLogger.Log(LogLevel.Error, "EEE {0}, {1}", 0, 1); InternalLogger.Log(LogLevel.Fatal, "FFF {0}, {1}, {2}", 0, 1, 2); InternalLogger.Log(LogLevel.Trace, "TTT {0}, {1}, {2}", 0, 1, 2); InternalLogger.Log(LogLevel.Debug, "DDD {0}, {1}", 0, 1); InternalLogger.Log(LogLevel.Info, "III {0}", 0); TestWriter(expected, writer2); } } /// <summary> /// Test output van een textwriter /// </summary> /// <param name="expected"></param> /// <param name="writer"></param> private static void TestWriter(string expected, StringWriter writer) { writer.Flush(); var writerOutput = writer.ToString(); Assert.Equal(expected, writerOutput); } #if !SILVERLIGHT [Fact] public void WriteToConsoleOutTests() { // Expected result is the same for both types of method invocation. const string expected = "Warn WWW\nError EEE\nFatal FFF\nTrace TTT\nDebug DDD\nInfo III\n"; InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; InternalLogger.LogToConsole = true; { StringWriter consoleOutWriter1 = new StringWriter() { NewLine = "\n" }; // Redirect the console output to a StringWriter. Console.SetOut(consoleOutWriter1); // Named (based on LogLevel) public methods. InternalLogger.Warn("WWW"); InternalLogger.Error("EEE"); InternalLogger.Fatal("FFF"); InternalLogger.Trace("TTT"); InternalLogger.Debug("DDD"); InternalLogger.Info("III"); TestWriter(expected, consoleOutWriter1); } // // Redirect the console output to another StringWriter. { StringWriter consoleOutWriter2 = new StringWriter() { NewLine = "\n" }; Console.SetOut(consoleOutWriter2); // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, "WWW"); InternalLogger.Log(LogLevel.Error, "EEE"); InternalLogger.Log(LogLevel.Fatal, "FFF"); InternalLogger.Log(LogLevel.Trace, "TTT"); InternalLogger.Log(LogLevel.Debug, "DDD"); InternalLogger.Log(LogLevel.Info, "III"); TestWriter(expected, consoleOutWriter2); } } [Fact] public void WriteToConsoleErrorTests() { // Expected result is the same for both types of method invocation. const string expected = "Warn WWW\nError EEE\nFatal FFF\nTrace TTT\nDebug DDD\nInfo III\n"; InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; InternalLogger.LogToConsoleError = true; { StringWriter consoleWriter1 = new StringWriter() { NewLine = "\n" }; // Redirect the console output to a StringWriter. Console.SetError(consoleWriter1); // Named (based on LogLevel) public methods. InternalLogger.Warn("WWW"); InternalLogger.Error("EEE"); InternalLogger.Fatal("FFF"); InternalLogger.Trace("TTT"); InternalLogger.Debug("DDD"); InternalLogger.Info("III"); TestWriter(expected, consoleWriter1); } { // // Redirect the console output to another StringWriter. StringWriter consoleWriter2 = new StringWriter() { NewLine = "\n" }; Console.SetError(consoleWriter2); // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, "WWW"); InternalLogger.Log(LogLevel.Error, "EEE"); InternalLogger.Log(LogLevel.Fatal, "FFF"); InternalLogger.Log(LogLevel.Trace, "TTT"); InternalLogger.Log(LogLevel.Debug, "DDD"); InternalLogger.Log(LogLevel.Info, "III"); TestWriter(expected, consoleWriter2); } } [Fact] public void WriteToFileTests() { string expected = "Warn WWW" + Environment.NewLine + "Error EEE" + Environment.NewLine + "Fatal FFF" + Environment.NewLine + "Trace TTT" + Environment.NewLine + "Debug DDD" + Environment.NewLine + "Info III" + Environment.NewLine; var tempFile = Path.GetTempFileName(); InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; InternalLogger.LogFile = tempFile; try { // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, "WWW"); InternalLogger.Log(LogLevel.Error, "EEE"); InternalLogger.Log(LogLevel.Fatal, "FFF"); InternalLogger.Log(LogLevel.Trace, "TTT"); InternalLogger.Log(LogLevel.Debug, "DDD"); InternalLogger.Log(LogLevel.Info, "III"); AssertFileContents(tempFile, expected, Encoding.UTF8); } finally { if (File.Exists(tempFile)) { File.Delete(tempFile); } } } /// <summary> /// <see cref="TimeSource"/> that returns always the same time, /// passed into object constructor. /// </summary> private class FixedTimeSource : TimeSource { private readonly DateTime _time; public FixedTimeSource(DateTime time) { _time = time; } public override DateTime Time { get { return _time; } } public override DateTime FromSystemTime(DateTime systemTime) { return _time; } } [Fact] public void TimestampTests() { InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = true; InternalLogger.LogToConsole = true; StringWriter consoleOutWriter = new StringWriter() { NewLine = "\n" }; // Redirect the console output to a StringWriter. Console.SetOut(consoleOutWriter); // Set fixed time source to test time output TimeSource.Current = new FixedTimeSource(DateTime.Now); // Named (based on LogLevel) public methods. InternalLogger.Warn("WWW"); InternalLogger.Error("EEE"); InternalLogger.Fatal("FFF"); InternalLogger.Trace("TTT"); InternalLogger.Debug("DDD"); InternalLogger.Info("III"); string expectedDateTime = TimeSource.Current.Time.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture); var strings = consoleOutWriter.ToString().Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); foreach (var str in strings) { Assert.Contains(expectedDateTime + ".", str); } } /// <summary> /// Test exception overloads /// </summary> [Fact] public void ExceptionTests() { using (new InternalLoggerScope()) { InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.LogToConsole = true; InternalLogger.IncludeTimestamp = false; var ex1 = new Exception("e1"); var ex2 = new Exception("e2", new Exception("inner")); var ex3 = new NLogConfigurationException("config error"); var ex4 = new NLogConfigurationException("config error", ex2); var ex5 = new PathTooLongException(); ex5.Data["key1"] = "value1"; Exception ex6 = null; const string prefix = " Exception: "; string expected = "Warn WWW" + prefix + ex1 + Environment.NewLine + "Error EEE" + prefix + ex2 + Environment.NewLine + "Fatal FFF" + prefix + ex3 + Environment.NewLine + "Trace TTT" + prefix + ex4 + Environment.NewLine + "Debug DDD" + prefix + ex5 + Environment.NewLine + "Info III" + Environment.NewLine; StringWriter consoleOutWriter = new StringWriter() { NewLine = Environment.NewLine }; // Redirect the console output to a StringWriter. Console.SetOut(consoleOutWriter); // Named (based on LogLevel) public methods. InternalLogger.Warn(ex1, "WWW"); InternalLogger.Error(ex2, "EEE"); InternalLogger.Fatal(ex3, "FFF"); InternalLogger.Trace(ex4, "TTT"); InternalLogger.Debug(ex5, "DDD"); InternalLogger.Info(ex6, "III"); consoleOutWriter.Flush(); var strings = consoleOutWriter.ToString(); Assert.Equal(expected, strings); } } [Theory] [InlineData("trace", true)] [InlineData("debug", true)] [InlineData("info", true)] [InlineData("warn", true)] [InlineData("error", true)] [InlineData("fatal", true)] [InlineData("off", false)] public void CreateDirectoriesIfNeededTests(string rawLogLevel, bool shouldCreateDirectory) { var tempPath = Path.GetTempPath(); var tempFileName = Path.GetRandomFileName(); var randomSubDirectory = Path.Combine(tempPath, Path.GetRandomFileName()); string tempFile = Path.Combine(randomSubDirectory, tempFileName); InternalLogger.LogLevel = LogLevel.FromString(rawLogLevel); InternalLogger.IncludeTimestamp = false; if (Directory.Exists(randomSubDirectory)) { Directory.Delete(randomSubDirectory); } Assert.False(Directory.Exists(randomSubDirectory)); // Set the log file, which will only create the needed directories InternalLogger.LogFile = tempFile; Assert.Equal(Directory.Exists(randomSubDirectory), shouldCreateDirectory); try { Assert.False(File.Exists(tempFile)); InternalLogger.Log(LogLevel.FromString(rawLogLevel), "File and Directory created."); Assert.Equal(File.Exists(tempFile), shouldCreateDirectory); } finally { if (File.Exists(tempFile)) { File.Delete(tempFile); } if (Directory.Exists(randomSubDirectory)) { Directory.Delete(randomSubDirectory); } } } [Fact] public void CreateFileInCurrentDirectoryTests() { string expected = "Warn WWW" + Environment.NewLine + "Error EEE" + Environment.NewLine + "Fatal FFF" + Environment.NewLine + "Trace TTT" + Environment.NewLine + "Debug DDD" + Environment.NewLine + "Info III" + Environment.NewLine; // Store off the previous log file string previousLogFile = InternalLogger.LogFile; var tempFileName = Path.GetRandomFileName(); InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; Assert.False(File.Exists(tempFileName)); // Set the log file, which only has a filename InternalLogger.LogFile = tempFileName; try { Assert.False(File.Exists(tempFileName)); // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, "WWW"); InternalLogger.Log(LogLevel.Error, "EEE"); InternalLogger.Log(LogLevel.Fatal, "FFF"); InternalLogger.Log(LogLevel.Trace, "TTT"); InternalLogger.Log(LogLevel.Debug, "DDD"); InternalLogger.Log(LogLevel.Info, "III"); AssertFileContents(tempFileName, expected, Encoding.UTF8); Assert.True(File.Exists(tempFileName)); } finally { if (File.Exists(tempFileName)) { File.Delete(tempFileName); } } } #endif public void Dispose() { TimeSource.Current = new FastLocalTimeSource(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Test.ModuleCore; using System; using System.Xml; namespace CoreXml.Test.XLinq { public partial class XNodeReaderFunctionalTests : TestModule { public partial class XNodeReaderTests : XLinqTestCase { public enum EINTEGRITY { //DataReader BEFORE_READ, AFTER_READ_FALSE, AFTER_RESETSTATE, //DataWriter BEFORE_WRITE, AFTER_WRITE_FALSE, AFTER_CLEAR, AFTER_FLUSH, // Both DataWriter and DataReader AFTER_CLOSE, CLOSE_IN_THE_MIDDLE, } //[TestCase(Name = "XMLIntegrityBase", Desc = "XMLIntegrityBase")] public partial class TCXMLIntegrityBase : BridgeHelpers { private EINTEGRITY _eEIntegrity; public EINTEGRITY IntegrityVer { get { return _eEIntegrity; } set { _eEIntegrity = value; } } public static string pATTR = "Attr1"; public static string pNS = "Foo"; public static string pNAME = "PLAY0"; public XmlReader ReloadSource() { string strFile = GetTestFileName(); XmlReader DataReader = GetReader(strFile); InitReaderPointer(DataReader); return DataReader; } public void InitReaderPointer(XmlReader DataReader) { if (this.Desc == "BeforeRead") { IntegrityVer = EINTEGRITY.BEFORE_READ; TestLog.Compare(DataReader.ReadState, ReadState.Initial, "ReadState=Initial"); TestLog.Compare(DataReader.EOF, false, "EOF==false"); } else if (this.Desc == "AfterReadIsFalse") { IntegrityVer = EINTEGRITY.AFTER_READ_FALSE; while (DataReader.Read()) ; TestLog.Compare(DataReader.ReadState, ReadState.EndOfFile, "ReadState=EOF"); TestLog.Compare(DataReader.EOF, true, "EOF==true"); } else if (this.Desc == "AfterClose") { IntegrityVer = EINTEGRITY.AFTER_CLOSE; while (DataReader.Read()) ; DataReader.Dispose(); TestLog.Compare(DataReader.ReadState, ReadState.Closed, "ReadState=Closed"); TestLog.Compare(DataReader.EOF, false, "EOF==true"); } else if (this.Desc == "AfterCloseInTheMiddle") { IntegrityVer = EINTEGRITY.CLOSE_IN_THE_MIDDLE; for (int i = 0; i < 1; i++) { if (false == DataReader.Read()) throw new TestFailedException(""); TestLog.Compare(DataReader.ReadState, ReadState.Interactive, "ReadState=Interactive"); } DataReader.Dispose(); TestLog.Compare(DataReader.ReadState, ReadState.Closed, "ReadState=Closed"); TestLog.Compare(DataReader.EOF, false, "EOF==true"); } else if (this.Desc == "AfterResetState") { IntegrityVer = EINTEGRITY.AFTER_RESETSTATE; // position the reader somewhere in the middle of the file PositionOnElement(DataReader, "elem1"); TestLog.Compare(DataReader.ReadState, ReadState.Initial, "ReadState=Initial"); } } //[Variation("NodeType")] public void GetXmlReaderNodeType() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.NodeType, XmlNodeType.None, Variation.Desc); TestLog.Compare(DataReader.NodeType, XmlNodeType.None, Variation.Desc); } //[Variation("Name")] public void GetXmlReaderName() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.Name, string.Empty, Variation.Desc); TestLog.Compare(DataReader.Name, string.Empty, Variation.Desc); } //[Variation("LocalName")] public void GetXmlReaderLocalName() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.LocalName, string.Empty, Variation.Desc); TestLog.Compare(DataReader.LocalName, string.Empty, Variation.Desc); } //[Variation("NamespaceURI")] public void Namespace() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.NamespaceURI, string.Empty, Variation.Desc); TestLog.Compare(DataReader.NamespaceURI, string.Empty, Variation.Desc); } //[Variation("Prefix")] public void Prefix() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.Prefix, string.Empty, Variation.Desc); TestLog.Compare(DataReader.Prefix, string.Empty, Variation.Desc); } //[Variation("HasValue")] public void HasValue() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.HasValue, false, Variation.Desc); TestLog.Compare(DataReader.HasValue, false, Variation.Desc); } //[Variation("Value")] public void GetXmlReaderValue() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.Value, string.Empty, Variation.Desc); TestLog.Compare(DataReader.Value, string.Empty, Variation.Desc); } //[Variation("Depth")] public void GetDepth() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.Depth, 0, Variation.Desc); TestLog.Compare(DataReader.Depth, 0, Variation.Desc); } //[Variation("BaseURI")] public void GetBaseURI() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.BaseURI, string.Empty, Variation.Desc); TestLog.Compare(DataReader.BaseURI, string.Empty, Variation.Desc); } //[Variation("IsEmptyElement")] public void IsEmptyElement() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.IsEmptyElement, false, Variation.Desc); TestLog.Compare(DataReader.IsEmptyElement, false, Variation.Desc); } //[Variation("IsDefault")] public void IsDefault() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.IsDefault, false, Variation.Desc); TestLog.Compare(DataReader.IsDefault, false, Variation.Desc); } //[Variation("XmlSpace")] public void GetXmlSpace() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.XmlSpace, XmlSpace.None, Variation.Desc); TestLog.Compare(DataReader.XmlSpace, XmlSpace.None, Variation.Desc); } //[Variation("XmlLang")] public void GetXmlLang() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.XmlLang, string.Empty, Variation.Desc); TestLog.Compare(DataReader.XmlLang, string.Empty, Variation.Desc); } //[Variation("AttributeCount")] public void AttributeCount() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.AttributeCount, 0, Variation.Desc); TestLog.Compare(DataReader.AttributeCount, 0, Variation.Desc); } //[Variation("HasAttributes")] public void HasAttribute() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.HasAttributes, false, Variation.Desc); TestLog.Compare(DataReader.HasAttributes, false, Variation.Desc); } //[Variation("GetAttributes(name)")] public void GetAttributeName() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.GetAttribute(pATTR), null, "Compare the GetAttribute"); } //[Variation("GetAttribute(String.Empty)")] public void GetAttributeEmptyName() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.GetAttribute(string.Empty), null, "Compare the GetAttribute"); } //[Variation("GetAttribute(name,ns)")] public void GetAttributeNameNamespace() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.GetAttribute(pATTR, pNS), null, "Compare the GetAttribute"); } //[Variation("GetAttribute(String.Empty, String.Empty)")] public void GetAttributeEmptyNameNamespace() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.GetAttribute(string.Empty, string.Empty), null, "Compare the GetAttribute"); } //[Variation("GetAttribute(i)")] public void GetAttributeOrdinal() { XmlReader DataReader = ReloadSource(); DataReader.GetAttribute(0); } //[Variation("this[i]")] public void HelperThisOrdinal() { XmlReader DataReader = ReloadSource(); string str = DataReader[0]; } //[Variation("this[name]")] public void HelperThisName() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader[pATTR], null, "Compare the GetAttribute"); } //[Variation("this[name,namespace]")] public void HelperThisNameNamespace() { XmlReader DataReader = ReloadSource(); string str = DataReader[pATTR, pNS]; TestLog.Compare(DataReader[pATTR, pNS], null, "Compare the GetAttribute"); } //[Variation("MoveToAttribute(name)")] public void MoveToAttributeName() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.MoveToAttribute(pATTR), false, Variation.Desc); TestLog.Compare(DataReader.MoveToAttribute(pATTR), false, Variation.Desc); } //[Variation("MoveToAttributeNameNamespace(name,ns)")] public void MoveToAttributeNameNamespace() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.MoveToAttribute(pATTR, pNS), false, Variation.Desc); TestLog.Compare(DataReader.MoveToAttribute(pATTR, pNS), false, Variation.Desc); } //[Variation("MoveToAttribute(i)")] public void MoveToAttributeOrdinal() { XmlReader DataReader = ReloadSource(); DataReader.MoveToAttribute(0); } //[Variation("MoveToFirstAttribute()")] public void MoveToFirstAttribute() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.MoveToFirstAttribute(), false, Variation.Desc); TestLog.Compare(DataReader.MoveToFirstAttribute(), false, Variation.Desc); } //[Variation("MoveToNextAttribute()")] public void MoveToNextAttribute() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.MoveToNextAttribute(), false, Variation.Desc); TestLog.Compare(DataReader.MoveToNextAttribute(), false, Variation.Desc); } //[Variation("MoveToElement()")] public void MoveToElement() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.MoveToElement(), false, Variation.Desc); TestLog.Compare(DataReader.MoveToElement(), false, Variation.Desc); } //[Variation("Read")] public void ReadTestAfterClose() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.Read(), true, Variation.Desc); TestLog.Compare(DataReader.Read(), true, Variation.Desc); } //[Variation("GetEOF")] public void GetEOF() { XmlReader DataReader = ReloadSource(); if ((IntegrityVer == EINTEGRITY.AFTER_READ_FALSE)) { TestLog.Compare(DataReader.EOF, true, Variation.Desc); TestLog.Compare(DataReader.EOF, true, Variation.Desc); } else { TestLog.Compare(DataReader.EOF, false, Variation.Desc); TestLog.Compare(DataReader.EOF, false, Variation.Desc); } } //[Variation("GetReadState")] public void GetReadState() { XmlReader DataReader = ReloadSource(); ReadState iState = ReadState.Initial; // EndOfFile State if ((IntegrityVer == EINTEGRITY.AFTER_READ_FALSE)) { iState = ReadState.EndOfFile; } // Closed State if ((IntegrityVer == EINTEGRITY.AFTER_CLOSE) || (IntegrityVer == EINTEGRITY.CLOSE_IN_THE_MIDDLE)) { iState = ReadState.Closed; } TestLog.Compare(DataReader.ReadState, iState, Variation.Desc); TestLog.Compare(DataReader.ReadState, iState, Variation.Desc); } //[Variation("Skip")] public void XMLSkip() { XmlReader DataReader = ReloadSource(); DataReader.Skip(); DataReader.Skip(); } //[Variation("NameTable")] public void TestNameTable() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.NameTable != null, "nt"); } //[Variation("ReadInnerXml")] public void ReadInnerXmlTestAfterClose() { XmlReader DataReader = ReloadSource(); XmlNodeType nt = DataReader.NodeType; string name = DataReader.Name; string value = DataReader.Value; TestLog.Compare(DataReader.ReadInnerXml(), string.Empty, Variation.Desc); TestLog.Compare(VerifyNode(DataReader, nt, name, value), "vn"); } //[Variation("ReadOuterXml")] public void TestReadOuterXml() { XmlReader DataReader = ReloadSource(); XmlNodeType nt = DataReader.NodeType; string name = DataReader.Name; string value = DataReader.Value; TestLog.Compare(DataReader.ReadOuterXml(), string.Empty, Variation.Desc); TestLog.Compare(VerifyNode(DataReader, nt, name, value), "vn"); } //[Variation("MoveToContent")] public void TestMoveToContent() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.Element, Variation.Desc); } //[Variation("IsStartElement")] public void TestIsStartElement() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.IsStartElement(), true, Variation.Desc); } //[Variation("IsStartElement(name)")] public void TestIsStartElementName() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.IsStartElement(pNAME), false, Variation.Desc); } //[Variation("IsStartElement(String.Empty)")] public void TestIsStartElementName2() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.IsStartElement(string.Empty), false, Variation.Desc); } //[Variation("IsStartElement(name, ns)")] public void TestIsStartElementNameNs() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.IsStartElement(pNAME, pNS), false, Variation.Desc); } //[Variation("IsStartElement(String.Empty,String.Empty)")] public void TestIsStartElementNameNs2() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.IsStartElement(string.Empty, string.Empty), false, Variation.Desc); } //[Variation("ReadStartElement")] public void TestReadStartElement() { XmlReader DataReader = ReloadSource(); DataReader.ReadStartElement(); } //[Variation("ReadStartElement(name)")] public void TestReadStartElementName() { XmlReader DataReader = ReloadSource(); try { DataReader.ReadStartElement(pNAME); } catch (XmlException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("ReadStartElement(String.Empty)")] public void TestReadStartElementName2() { XmlReader DataReader = ReloadSource(); try { DataReader.ReadStartElement(string.Empty); } catch (XmlException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("ReadStartElement(name, ns)")] public void TestReadStartElementNameNs() { XmlReader DataReader = ReloadSource(); try { DataReader.ReadStartElement(pNAME, pNS); } catch (XmlException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("ReadStartElement(String.Empty,String.Empty)")] public void TestReadStartElementNameNs2() { XmlReader DataReader = ReloadSource(); try { DataReader.ReadStartElement(string.Empty, string.Empty); } catch (XmlException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("ReadEndElement")] public void TestReadEndElement() { XmlReader DataReader = ReloadSource(); try { DataReader.ReadEndElement(); } catch (XmlException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("LookupNamespace")] public void LookupNamespace() { XmlReader DataReader = ReloadSource(); string[] astr = { "a", "Foo", string.Empty, "Foo1", "Foo_S" }; for (int i = 0; i < astr.Length; i++) { if (DataReader.LookupNamespace(astr[i]) != null) { } TestLog.Compare(DataReader.LookupNamespace(astr[i]), null, Variation.Desc); } } //[Variation("ReadAttributeValue")] public void ReadAttributeValue() { XmlReader DataReader = ReloadSource(); TestLog.Compare(DataReader.ReadAttributeValue(), false, Variation.Desc); TestLog.Compare(DataReader.ReadAttributeValue(), false, Variation.Desc); } //[Variation("Close")] public void CloseTest() { XmlReader DataReader = ReloadSource(); DataReader.Dispose(); DataReader.Dispose(); DataReader.Dispose(); } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using System.IO; using UnityEngine.UI; public class LoadPVM { //fields private int currentBit = 0; private byte currentByte; private const string DDS_ID = "DDS v3d\n"; private const string DDS_ID2 = "DDS v3e\n"; private const uint DDS_BLOCKSIZE = 1 << 20; private const uint DDS_INTERLEAVE = 1 << 24; private const uint DDS_RL = 7; // properties // methods // We need 2^n dimensions uint countNewDim(uint Dim) { uint newDim = 1; while (newDim < Dim) { newDim *= 2; } return newDim; } byte[] compress16to8(byte[] inputData) { int newLength = inputData.Length / 2; byte[] retArray = new byte[newLength]; for (int i = 0; i < newLength; ++i) { retArray[i] = inputData[i * 2 + 1]; } return retArray; } public Color32[] LoadPVMFile(string volumeName, ref uint width, ref uint height, ref uint depth, ref uint components) { currentBit = 0; byte[] raw = ReadPVMVolume(volumeName, ref width, ref height, ref depth, ref components); uint nwidth, nheight, ndepth; nwidth = countNewDim(width); nheight = countNewDim(height); ndepth = countNewDim(depth); uint nsize = nwidth * nheight * ndepth; Color32[] retArr = new Color32[nsize]; for (uint i = 0; i < nsize; ++i) { retArr[i] = new Color32(0, 0, 0, 255); } if (components == 1) { for (uint z = 0; z < depth; ++z) { for (uint y = 0; y < height; ++y) { for (uint x = 0; x < width; ++x) { uint nIndex = x + y * nwidth + z * nwidth * nheight; uint oIndex = x + y * width + z * width * height; retArr[nIndex].r = raw[oIndex]; retArr[nIndex].g = raw[oIndex]; retArr[nIndex].b = raw[oIndex]; } } } } else if (components == 3) { for (uint z = 0; z < depth; ++z) { for (uint y = 0; y < height; ++y) { for (uint x = 0; x < width; ++x) { uint nIndex = x + y * nwidth + z * nwidth * nheight; uint oIndex = (x + y * width + z * width * height) * 3; retArr[nIndex].r = raw[oIndex]; retArr[nIndex].g = raw[oIndex + 1]; retArr[nIndex].b = raw[oIndex + 2]; } } } } else if (components == 2) { byte[] nRaw = compress16to8(raw); for (uint z = 0; z < depth; ++z) { for (uint y = 0; y < height; ++y) { for (uint x = 0; x < width; ++x) { uint nIndex = x + y * nwidth + z * nwidth * nheight; uint oIndex = x + y * width + z * width * height; retArr[nIndex].r = nRaw[oIndex]; retArr[nIndex].g = nRaw[oIndex]; retArr[nIndex].b = nRaw[oIndex]; } } } } else { GameObject.Find("UICanvas").transform.FindChild("PanelLog"). transform.FindChild("TextLog").GetComponent<Text>().text += "Component Error\n"; Debug.Log("Component Error"); } width = nwidth; height = nheight; depth = ndepth; return retArr; } private bool? ReadBit(ref BinaryReader binReader) { if (currentBit == 0 || currentBit == 8) { if (binReader.BaseStream.Length == binReader.BaseStream.Position) { return null; } currentByte = binReader.ReadByte(); currentBit = 0; } bool outputBit; outputBit = (currentByte & (1 << (7 - currentBit))) > 0; ++currentBit; return outputBit; } private uint ReadNBits(ref BinaryReader binReader, int bits) { uint outputNBits = 0; for (int i = 0; i < bits; ++i) { outputNBits = outputNBits << 1; bool? curBit = ReadBit(ref binReader); if (curBit == null) { return 0; } outputNBits = outputNBits | Convert.ToUInt16(curBit); } return outputNBits; } private int CodeDDS(int bits) { return (bits > 1 ? bits - 1 : bits); } private int DecodeDDS(int bits) { return (bits >= 1 ? bits + 1 : bits); } private void CopyBytes(ref byte[] data, byte[] data2, uint shift, uint length) { for (uint i = 0; i < length; ++i) { data[i + shift] = data2[i]; } } // deinterleave a byte stream private void DeinterleaveByteStream(ref byte[] dataArray, uint bytes, uint skip, uint block = 0, bool restore = false) { uint i, j, k; uint ind = 0; byte []tempByteArray; if (skip <= 1) { return; } if (block == 0) { tempByteArray = new byte[bytes]; if (!restore) { ind = 0; for (i = 0; i < skip; ++i) { for (j = i; j < bytes; j += skip) { tempByteArray[ind++] = dataArray[j]; } } } else { ind = 0; for (i = 0; i < skip; ++i) { for (j = i; j < bytes; j += skip) { tempByteArray[j] = dataArray[ind++]; } } } CopyBytes(ref dataArray, tempByteArray, 0, bytes); } else { tempByteArray = new byte[(bytes < skip * block) ? bytes : skip * block]; if (!restore) { for (k = 0; k<bytes / skip / block; ++k) { ind = 0; for (i = 0; i < skip; ++i) { for (j = i; j < skip * block; j += skip) { tempByteArray[ind++] = dataArray[k * skip * block + j]; } } CopyBytes(ref dataArray, tempByteArray, k * skip * block, skip * block); } ind = 0; for (i = 0; i < skip; ++i) { for (j = i; j < bytes - k * skip * block; j += skip) { tempByteArray[ind++] = dataArray[k * skip * block + j]; } } CopyBytes(ref dataArray, tempByteArray, k * skip * block, bytes - k * skip * block); } else { for (k = 0; k<bytes / skip / block; ++k) { ind = k * skip * block; for (i = 0; i < skip; ++i) { for (j = i; j < skip * block; j += skip) { tempByteArray[j] = dataArray[ind++]; } } CopyBytes(ref dataArray, tempByteArray, k * skip * block, skip * block); } ind = k * skip * block; for (i = 0; i < skip; ++i) { for (j = i; j < bytes - k * skip * block; j += skip) { tempByteArray[j] = dataArray[ind++]; } } CopyBytes(ref dataArray, tempByteArray, k * skip * block, bytes - k * skip * block); } } } // interleave a byte stream private void InterleaveByteStream(ref byte[] dataArray, uint bytes, uint skip, uint block = 0) { DeinterleaveByteStream(ref dataArray, bytes, skip, block, true); } // decode a Differential Data Stream private byte[] DecodeDataStream(ref BinaryReader binReader, ref uint bytes, uint block) { uint skip, strip; byte[] dataArray = new byte[0]; uint cnt, cnt1, cnt2; int bits, act; skip = ReadNBits(ref binReader, 2) + 1; strip = ReadNBits(ref binReader, 16) + 1; cnt = 0; act = 0; while ((cnt1 = ReadNBits(ref binReader, (int)DDS_RL)) != 0) { bits = DecodeDDS((int)ReadNBits(ref binReader, 3)); for (cnt2 = 0; cnt2 < cnt1; ++cnt2) { if (strip == 1 || cnt <= strip) { act += (int)ReadNBits(ref binReader, bits) - (1 << bits) / 2; } else { act += dataArray[cnt - strip] - dataArray[cnt - strip - 1] + (int)ReadNBits(ref binReader, bits) - (1 << bits) / 2; } while (act < 0) { act += 256; } while (act > 255) { act -= 256; } if (cnt % DDS_BLOCKSIZE == 0) { byte[] data2 = new byte[dataArray.Length + DDS_BLOCKSIZE]; dataArray.CopyTo(data2, 0); dataArray = data2; } dataArray[cnt] = (byte)act; ++cnt; } } InterleaveByteStream(ref dataArray, cnt, skip, block); bytes = cnt; return dataArray; } // read a RAW file private byte[] ReadRAWFile(string volumeName, ref uint bytes) { BinaryReader binReader = new BinaryReader(File.Open("Assets/Resources/" + volumeName, FileMode.Open)); byte[] dataArray = binReader.ReadBytes((int)binReader.BaseStream.Length); bytes = (uint)binReader.BaseStream.Length; return dataArray; } // read a Differential Data Stream private byte[] ReadDDSFile(string volumeName, ref uint bytes, ref bool hasDDSHead) { int version = 1; Stream inputStream = File.Open("Assets/Resources/" + volumeName, FileMode.Open); BinaryReader binReader = new BinaryReader(inputStream); byte[] headLine = binReader.ReadBytes(8); hasDDSHead = true; byte[] dataArray; for (int i = 0; i < DDS_ID.Length; ++i) { if (DDS_ID[i] != headLine[i]) { version = 0; } } if (version == 0) { for (int i = 0; i < DDS_ID2.Length; ++i) { if (DDS_ID2[i] != headLine[i]) { hasDDSHead = false; version = 0; return null; } version = 2; } } dataArray = DecodeDataStream(ref binReader, ref bytes, version == 1 ? 0 : DDS_INTERLEAVE); return dataArray; } bool CompareStrChunk(byte[] dataArray, string str, uint start, uint length) { if (start + length > dataArray.Length || str.Length < length) { return false; } for (int i = 0; i < length; ++i) { if (str[i] != dataArray[start + i]) { return false; } } return true; } // read a compressed PVM volume private byte[] ReadPVMVolume(string volumeName, ref uint width, ref uint height, ref uint depth, ref uint components) { byte[] data; uint bytes = 0, numc; byte[] volume = null; bool hadDDSHead = false; data = ReadDDSFile(volumeName, ref bytes, ref hadDDSHead); if (hadDDSHead == false) { data = ReadRAWFile(volumeName, ref bytes); } if (bytes < 5) { return null; } if (CompareStrChunk(data, "PVM\n", 0, 4) == false) { if (CompareStrChunk(data, "PVM2\n", 0, 5) == true) { //version = 2; } else if (CompareStrChunk(data, "PVM3\n", 0, 5) == true) { //version = 3; } else { return null; } string result = System.Text.Encoding.ASCII.GetString(data); string[] lines = result.Split('\n'); string[] dimInfo = lines[1].Split(' '); width = uint.Parse(dimInfo[0]); height = uint.Parse(dimInfo[1]); depth = uint.Parse(dimInfo[2]); string[] compon = lines[3].Split(' '); numc = uint.Parse(compon[0]); components = numc; int line4Length = lines[0].Length + lines[1].Length + lines[2].Length + lines[3].Length + 4; uint allbytes = width * height * depth * numc; volume = new byte[allbytes]; for (uint i = 0; i < allbytes; ++i) { volume[i] = data[i + line4Length]; } } else { int ind = 4; while (data[ind] == '#') { while (data[ind++] != '\n') ; } string result = System.Text.Encoding.ASCII.GetString(data, ind, data.Length - ind); string[] lines = result.Replace("\r\n", "\n").Split('\n'); string[] dimInfo = lines[0].Split(' '); width = uint.Parse(dimInfo[0]); height = uint.Parse(dimInfo[1]); depth = uint.Parse(dimInfo[2]); string[] compon = lines[1].Split(' '); numc = uint.Parse(compon[0]); components = numc; } return volume; } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; using TextSpan = Microsoft.CodeAnalysis.Text.TextSpan; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation { internal sealed class VisualStudioDocumentNavigationService : ForegroundThreadAffinitizedObject, IDocumentNavigationService { private readonly IServiceProvider _serviceProvider; private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService; public VisualStudioDocumentNavigationService( SVsServiceProvider serviceProvider, IVsEditorAdaptersFactoryService editorAdaptersFactoryService) { _serviceProvider = serviceProvider; _editorAdaptersFactoryService = editorAdaptersFactoryService; } public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan) { // Navigation should not change the context of linked files and Shared Projects. documentId = workspace.GetDocumentIdInCurrentContext(documentId); if (!IsSecondaryBuffer(workspace, documentId)) { return true; } var document = workspace.CurrentSolution.GetDocument(documentId); var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); var vsTextSpan = text.GetVsTextSpanForSpan(textSpan); return CanMapFromSecondaryBufferToPrimaryBuffer(workspace, documentId, vsTextSpan); } public bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset) { // Navigation should not change the context of linked files and Shared Projects. documentId = workspace.GetDocumentIdInCurrentContext(documentId); if (!IsSecondaryBuffer(workspace, documentId)) { return true; } var document = workspace.CurrentSolution.GetDocument(documentId); var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); var vsTextSpan = text.GetVsTextSpanForLineOffset(lineNumber, offset); return CanMapFromSecondaryBufferToPrimaryBuffer(workspace, documentId, vsTextSpan); } public bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace = 0) { // Navigation should not change the context of linked files and Shared Projects. documentId = workspace.GetDocumentIdInCurrentContext(documentId); if (!IsSecondaryBuffer(workspace, documentId)) { return true; } var document = workspace.CurrentSolution.GetDocument(documentId); var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); var vsTextSpan = text.GetVsTextSpanForPosition(position, virtualSpace); return CanMapFromSecondaryBufferToPrimaryBuffer(workspace, documentId, vsTextSpan); } public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options) { // Navigation should not change the context of linked files and Shared Projects. documentId = workspace.GetDocumentIdInCurrentContext(documentId); if (!IsForeground()) { throw new InvalidOperationException(ServicesVSResources.NavigationMustBePerformedOnTheForegroundThread); } var document = OpenDocument(workspace, documentId, options); if (document == null) { return false; } var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); var textBuffer = text.Container.GetTextBuffer(); var vsTextSpan = text.GetVsTextSpanForSpan(textSpan); if (IsSecondaryBuffer(workspace, documentId) && !vsTextSpan.TryMapSpanFromSecondaryBufferToPrimaryBuffer(workspace, documentId, out vsTextSpan)) { return false; } return NavigateTo(textBuffer, vsTextSpan); } public bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options) { // Navigation should not change the context of linked files and Shared Projects. documentId = workspace.GetDocumentIdInCurrentContext(documentId); if (!IsForeground()) { throw new InvalidOperationException(ServicesVSResources.NavigationMustBePerformedOnTheForegroundThread); } var document = OpenDocument(workspace, documentId, options); if (document == null) { return false; } var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); var textBuffer = text.Container.GetTextBuffer(); var vsTextSpan = text.GetVsTextSpanForLineOffset(lineNumber, offset); if (IsSecondaryBuffer(workspace, documentId) && !vsTextSpan.TryMapSpanFromSecondaryBufferToPrimaryBuffer(workspace, documentId, out vsTextSpan)) { return false; } return NavigateTo(textBuffer, vsTextSpan); } public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options) { // Navigation should not change the context of linked files and Shared Projects. documentId = workspace.GetDocumentIdInCurrentContext(documentId); if (!IsForeground()) { throw new InvalidOperationException(ServicesVSResources.NavigationMustBePerformedOnTheForegroundThread); } var document = OpenDocument(workspace, documentId, options); if (document == null) { return false; } var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); var textBuffer = text.Container.GetTextBuffer(); var vsTextSpan = text.GetVsTextSpanForPosition(position, virtualSpace); if (IsSecondaryBuffer(workspace, documentId) && !vsTextSpan.TryMapSpanFromSecondaryBufferToPrimaryBuffer(workspace, documentId, out vsTextSpan)) { return false; } return NavigateTo(textBuffer, vsTextSpan); } private static Document OpenDocument(Workspace workspace, DocumentId documentId, OptionSet options) { options = options ?? workspace.Options; // Always open the document again, even if the document is already open in the // workspace. If a document is already open in a preview tab and it is opened again // in a permanent tab, this allows the document to transition to the new state. if (workspace.CanOpenDocuments) { if (options.GetOption(NavigationOptions.PreferProvisionalTab)) { using (NewDocumentStateScope ndss = new NewDocumentStateScope(__VSNEWDOCUMENTSTATE.NDS_Provisional, VSConstants.NewDocumentStateReason.Navigation)) { workspace.OpenDocument(documentId); } } else { workspace.OpenDocument(documentId); } } if (!workspace.IsDocumentOpen(documentId)) { return null; } return workspace.CurrentSolution.GetDocument(documentId); } private bool NavigateTo(ITextBuffer textBuffer, VsTextSpan vsTextSpan) { using (Logger.LogBlock(FunctionId.NavigationService_VSDocumentNavigationService_NavigateTo, CancellationToken.None)) { var vsTextBuffer = _editorAdaptersFactoryService.GetBufferAdapter(textBuffer); if (vsTextBuffer == null) { Debug.Fail("Could not get IVsTextBuffer for document!"); return false; } var textManager = (IVsTextManager2)_serviceProvider.GetService(typeof(SVsTextManager)); if (textManager == null) { Debug.Fail("Could not get IVsTextManager service!"); return false; } return ErrorHandler.Succeeded( textManager.NavigateToLineAndColumn2( vsTextBuffer, VSConstants.LOGVIEWID.TextView_guid, vsTextSpan.iStartLine, vsTextSpan.iStartIndex, vsTextSpan.iEndLine, vsTextSpan.iEndIndex, (uint)_VIEWFRAMETYPE.vftCodeWindow)); } } private bool IsSecondaryBuffer(Workspace workspace, DocumentId documentId) { var visualStudioWorkspace = workspace as VisualStudioWorkspaceImpl; if (visualStudioWorkspace == null) { return false; } var containedDocument = visualStudioWorkspace.GetHostDocument(documentId) as ContainedDocument; if (containedDocument == null) { return false; } return true; } private bool CanMapFromSecondaryBufferToPrimaryBuffer(Workspace workspace, DocumentId documentId, VsTextSpan spanInSecondaryBuffer) { VsTextSpan spanInPrimaryBuffer; return spanInSecondaryBuffer.TryMapSpanFromSecondaryBufferToPrimaryBuffer(workspace, documentId, out spanInPrimaryBuffer); } } }
// // Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s). // All rights reserved. // using System; using System.Collections; using OpenADK.Library; using OpenADK.Library.Infra; using OpenADK.Library.Tools.Cfg; using OpenADK.Util; using OpenADK.Library.au; namespace Library.Examples.Chameleon { /// <summary> /// Chameleon is a universal subscribing and logging agent. /// </summary> public class Chameleon : Agent, IQueryResults { private AgentConfig fCfg; private static AdkConsoleWait sWaitMutex; private ObjectLogger fLogger; private string fRequestState = Guid.NewGuid().ToString(); public Chameleon() : base( "Chameleon" ) { } /// <summary> /// The main entry point for the application. /// </summary> [STAThread] private static void Main( string[] args ) { try { Adk.Debug = AdkDebugFlags.Moderate; Adk.Initialize(SifVersion.LATEST, SIFVariant.SIF_AU, (int)SdoLibraryType.All); Chameleon agent; agent = new Chameleon(); // Start agent... agent.StartAgent( args ); Console.WriteLine( "Agent is running (Press Ctrl-C to stop)" ); sWaitMutex = new AdkConsoleWait(); sWaitMutex.WaitForExit(); // Always shutdown the agent on exit agent.Shutdown( ProvisioningFlags.None ); } catch ( Exception e ) { Console.WriteLine( e ); } } /// <summary> Initialize and start the agent /// </summary> /// <param name="args">Command-line arguments (run with no arguments to display help) /// </param> public virtual void StartAgent( string[] args ) { Console.WriteLine( "Initializing agent..." ); // Read the configuration file fCfg = new AgentConfig(); Console.Out.WriteLine( "Reading configuration file..." ); fCfg.Read( "agent.cfg", false ); // Override the SourceId passed to the constructor with the SourceId // specified in the configuration file Id = fCfg.SourceId; // Inform the ADK of the version of SIF specified in the sifVersion= // attribute of the <agent> element SifVersion version = fCfg.Version; Adk.SifVersion = version; // Now call the superclass initialize once the configuration file has been read base.Initialize(); // Ask the AgentConfig instance to "apply" all configuration settings // to this Agent; for example, all <property> elements that are children // of the root <agent> node are parsed and applied to this Agent's // AgentProperties object; all <zone> elements are parsed and registered // with the Agent's ZoneFactory, and so on. // fCfg.Apply( this, true ); // Create the logging object fLogger = new ObjectLogger( this ); Query zoneQuery = new Query( InfraDTD.SIF_ZONESTATUS ); zoneQuery.AddFieldRestriction( InfraDTD.SIF_ZONESTATUS_SIF_PROVIDERS ); //zoneQuery.AddFieldRestriction( SifDtd.SIF_ZONESTATUS_SIF_SIFNODES ); zoneQuery.UserData = fRequestState; ITopic zoneTopic = TopicFactory.GetInstance( InfraDTD.SIF_ZONESTATUS ); zoneTopic.SetQueryResults( this ); // Now, connect to all zones and just get the zone status foreach ( IZone zone in ZoneFactory.GetAllZones() ) { if ( getChameleonProperty( zone, "logRaw", false ) ) { zone.Properties.KeepMessageContent = true; zone.AddMessagingListener( fLogger ); } zone.Connect( ProvisioningFlags.Register ); zoneTopic.Join( zone ); } Console.WriteLine(); Console.WriteLine( "Requesting SIF_ZoneStatus from all zones..." ); zoneTopic.Query( zoneQuery ); } public override ISubscriber GetSubscriber( SifContext context, IElementDef objectType ) { return fLogger; } public override IQueryResults GetQueryResults( SifContext context, IElementDef objectType ) { return fLogger; } public void OnQueryPending( IMessageInfo info, IZone zone ) { Adk.Log.Info ( string.Format ( "Requested {0} from {1}", ((SifMessageInfo) info).SIFRequestObjectType.Name, zone.ZoneId ) ); } public bool getChameleonProperty( IZone zone, string propertyName, bool defaultValue ) { bool retValue = true; try { retValue = zone.Properties.GetProperty( "chameleon." + propertyName, defaultValue ); } catch ( Exception ex ) { Log.Warn( ex.Message, ex ); } return retValue; } public void OnQueryResults( IDataObjectInputStream data, SIF_Error error, IZone zone, IMessageInfo info ) { SifMessageInfo smi = (SifMessageInfo) info; if ( !(fRequestState.Equals( smi.SIFRequestInfo.UserData )) ) { // This is a SIF_ZoneStatus response from a previous invocation of the agent return; } if ( data.Available ) { SIF_ZoneStatus zoneStatus = data.ReadDataObject() as SIF_ZoneStatus; AsyncUtils.QueueTaskToThreadPool( new zsDelegate( _processSIF_ZoneStatus ), zoneStatus, zone ); } } private delegate void zsDelegate( SIF_ZoneStatus zoneStatus, IZone zone ); private void _processSIF_ZoneStatus( SIF_ZoneStatus zoneStatus, IZone zone ) { if ( zoneStatus == null ) { return; } bool sync = getChameleonProperty( zone, "sync", false ); bool events = getChameleonProperty( zone, "logEvents", true ); bool logEntry = getChameleonProperty( zone, "sifLogEntrySupport", false ); ArrayList objectDefs = new ArrayList(); SIF_Providers providers = zoneStatus.SIF_Providers; if ( providers != null ) { foreach ( SIF_Provider p in providers ) { foreach ( SIF_Object obj in p.SIF_ObjectList ) { // Lookup the topic for each provided object in the zone IElementDef def = Adk.Dtd.LookupElementDef( obj.ObjectName ); if ( def != null ) { objectDefs.Add( def ); ITopic topic = TopicFactory.GetInstance( def ); if ( topic.GetSubscriber() == null ) { if ( events ) { topic.SetSubscriber( fLogger, new SubscriptionOptions() ); } if ( sync ) { topic.SetQueryResults( fLogger ); } } } } } } if ( logEntry ) { ITopic sifLogEntryTopic = TopicFactory.GetInstance( InfraDTD.SIF_LOGENTRY ); sifLogEntryTopic.SetSubscriber( fLogger, new SubscriptionOptions() ); } foreach ( ITopic topic in TopicFactory.GetAllTopics( SifContext.DEFAULT ) ) { try { // Join the topic to each zone ( causes the agent to subscribe to the joined objects ) // TODO: Add an "isJoinedTo()" API to topic so that it doesn't throw an exception if ( topic.ObjectType != InfraDTD.SIF_ZONESTATUS.Name ) { topic.Join( zone ); } } catch ( Exception ex ) { zone.Log.Error( ex.Message, ex ); } } if ( sync ) { if ( objectDefs.Count == 0 ) { zone.ServerLog.Log ( LogLevel.WARNING, "No objects are being provided in this zone", null, "1001" ); } string syncObjects = zone.Properties.GetProperty( "chameleon.syncObjects" ); foreach ( IElementDef def in objectDefs ) { if ( def.IsSupported( Adk.SifVersion ) ) { if ( syncObjects == null || (syncObjects.Length > 0 && syncObjects.IndexOf( def.Name ) > -1) ) { Query q = new Query( def ); // Query by specific parameters string condition = zone.Properties.GetProperty ( "chameleon.syncConditions." + def.Name ); if ( condition != null && condition.Length > 0 ) { // The condition should be in the format "path=value" e.g "@RefId=123412341...1234|@Name=asdfasdf" String[] queryConditions = condition.Split( '|' ); foreach ( String cond in queryConditions ) { string[] conds = cond.Split( '=' ); if ( conds.Length == 2 ) { q.AddCondition( conds[0], "EQ", conds[1] ); } } } if ( logEntry ) { zone.ServerLog.Log ( LogLevel.INFO, "Requesting " + q.ObjectType.Name + " from the zone", q.ToXml( Adk.SifVersion ), "1002" ); } zone.Query( q ); } } else { String debug = "Will not request " + def.Name + " because it is not supported in " + Adk.SifVersion.ToString(); Console.WriteLine( debug ); zone.ServerLog.Log( LogLevel.WARNING, debug, null, "1001" ); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: Debugging Macros for use in the Base Class Libraries ** ** ============================================================*/ namespace System { using System.IO; using System.Text; using System.Diagnostics; using Microsoft.Win32; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Diagnostics.Contracts; [Serializable] internal enum LogLevel { Trace = 0, Status = 20, Warning = 40, Error = 50, Panic = 100, } internal struct SwitchStructure { internal String name; internal int value; internal SwitchStructure(String n, int v) { name = n; value = v; } } // Only statics, does not need to be marked with the serializable attribute internal static class BCLDebug { internal static volatile bool m_registryChecked = false; internal static volatile bool m_loggingNotEnabled = false; internal static bool m_perfWarnings; internal static bool m_correctnessWarnings; internal static bool m_safeHandleStackTraces; #if _DEBUG internal static volatile bool m_domainUnloadAdded; #endif private static readonly SwitchStructure[] switches = { new SwitchStructure("NLS", 0x00000001), new SwitchStructure("SER", 0x00000002), new SwitchStructure("DYNIL",0x00000004), new SwitchStructure("REMOTE",0x00000008), new SwitchStructure("BINARY",0x00000010), //Binary Formatter new SwitchStructure("SOAP",0x00000020), // Soap Formatter new SwitchStructure("REMOTINGCHANNELS",0x00000040), new SwitchStructure("CACHE",0x00000080), new SwitchStructure("RESMGRFILEFORMAT", 0x00000100), // .resources files new SwitchStructure("PERF", 0x00000200), new SwitchStructure("CORRECTNESS", 0x00000400), new SwitchStructure("MEMORYFAILPOINT", 0x00000800), new SwitchStructure("DATETIME", 0x00001000), // System.DateTime managed tracing new SwitchStructure("INTEROP", 0x00002000), // Interop tracing }; private static readonly LogLevel[] levelConversions = { LogLevel.Panic, LogLevel.Error, LogLevel.Error, LogLevel.Warning, LogLevel.Warning, LogLevel.Status, LogLevel.Status, LogLevel.Trace, LogLevel.Trace, LogLevel.Trace, LogLevel.Trace }; #if _DEBUG internal static void WaitForFinalizers(Object sender, EventArgs e) { if (!m_registryChecked) { CheckRegistry(); } if (m_correctnessWarnings) { GC.GetTotalMemory(true); GC.WaitForPendingFinalizers(); } } #endif [Conditional("_DEBUG")] static public void Assert(bool condition) { #if _DEBUG Assert(condition, "Assert failed."); #endif } [Conditional("_DEBUG")] static public void Assert(bool condition, String message) { #if _DEBUG // Speed up debug builds marginally by avoiding the garbage from // concatinating "BCL Assert: " and the message. if (!condition) System.Diagnostics.Assert.Check(condition, "BCL Assert", message); #endif } [Pure] [Conditional("_LOGGING")] static public void Log(String message) { if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) return; if (!m_registryChecked) { CheckRegistry(); } System.Diagnostics.Log.Trace(message); System.Diagnostics.Log.Trace(Environment.NewLine); } [Pure] [Conditional("_LOGGING")] static public void Log(String switchName, String message) { if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) return; if (!m_registryChecked) { CheckRegistry(); } try { LogSwitch ls; ls = LogSwitch.GetSwitch(switchName); if (ls != null) { System.Diagnostics.Log.Trace(ls, message); System.Diagnostics.Log.Trace(ls, Environment.NewLine); } } catch { System.Diagnostics.Log.Trace("Exception thrown in logging." + Environment.NewLine); System.Diagnostics.Log.Trace("Switch was: " + ((switchName == null) ? "<null>" : switchName) + Environment.NewLine); System.Diagnostics.Log.Trace("Message was: " + ((message == null) ? "<null>" : message) + Environment.NewLine); } } // // This code gets called during security startup, so we can't go through Marshal to get the values. This is // just a small helper in native code instead of that. // [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern static int GetRegistryLoggingValues(out bool loggingEnabled, out bool logToConsole, out int logLevel, out bool perfWarnings, out bool correctnessWarnings, out bool safeHandleStackTraces); private static void CheckRegistry() { if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) return; if (m_registryChecked) { return; } m_registryChecked = true; bool loggingEnabled; bool logToConsole; int logLevel; int facilityValue; facilityValue = GetRegistryLoggingValues(out loggingEnabled, out logToConsole, out logLevel, out m_perfWarnings, out m_correctnessWarnings, out m_safeHandleStackTraces); // Note we can get into some recursive situations where we call // ourseves recursively through the .cctor. That's why we have the // check for levelConversions == null. if (!loggingEnabled) { m_loggingNotEnabled = true; } if (loggingEnabled && levelConversions != null) { try { //The values returned for the logging levels in the registry don't map nicely onto the //values which we support internally (which are an approximation of the ones that //the System.Diagnostics namespace uses) so we have a quick map. Assert(logLevel >= 0 && logLevel <= 10, "logLevel>=0 && logLevel<=10"); logLevel = (int)levelConversions[logLevel]; if (facilityValue > 0) { for (int i = 0; i < switches.Length; i++) { if ((switches[i].value & facilityValue) != 0) { LogSwitch L = new LogSwitch(switches[i].name, switches[i].name, System.Diagnostics.Log.GlobalSwitch); L.MinimumLevel = (LoggingLevels)logLevel; } } System.Diagnostics.Log.GlobalSwitch.MinimumLevel = (LoggingLevels)logLevel; System.Diagnostics.Log.IsConsoleEnabled = logToConsole; } } catch { //Silently eat any exceptions. } } } internal static bool CheckEnabled(String switchName) { if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) return false; if (!m_registryChecked) CheckRegistry(); LogSwitch logSwitch = LogSwitch.GetSwitch(switchName); if (logSwitch == null) { return false; } return ((int)logSwitch.MinimumLevel <= (int)LogLevel.Trace); } private static bool CheckEnabled(String switchName, LogLevel level, out LogSwitch logSwitch) { if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) { logSwitch = null; return false; } logSwitch = LogSwitch.GetSwitch(switchName); if (logSwitch == null) { return false; } return ((int)logSwitch.MinimumLevel <= (int)level); } [Pure] [Conditional("_LOGGING")] public static void Log(String switchName, LogLevel level, params Object[] messages) { if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) return; //Add code to check if logging is enabled in the registry. LogSwitch logSwitch; if (!m_registryChecked) { CheckRegistry(); } if (!CheckEnabled(switchName, level, out logSwitch)) { return; } StringBuilder sb = StringBuilderCache.Acquire(); for (int i = 0; i < messages.Length; i++) { String s; try { if (messages[i] == null) { s = "<null>"; } else { s = messages[i].ToString(); } } catch { s = "<unable to convert>"; } sb.Append(s); } System.Diagnostics.Log.LogMessage((LoggingLevels)((int)level), logSwitch, StringBuilderCache.GetStringAndRelease(sb)); } [Pure] [Conditional("_LOGGING")] public static void Trace(String switchName, String format, params Object[] messages) { if (m_loggingNotEnabled) { return; } LogSwitch logSwitch; if (!CheckEnabled(switchName, LogLevel.Trace, out logSwitch)) { return; } StringBuilder sb = StringBuilderCache.Acquire(); sb.AppendFormat(format, messages); sb.Append(Environment.NewLine); System.Diagnostics.Log.LogMessage(LoggingLevels.TraceLevel0, logSwitch, StringBuilderCache.GetStringAndRelease(sb)); } // For perf-related asserts. On a debug build, set the registry key // BCLPerfWarnings to non-zero. [Conditional("_DEBUG")] internal static void Perf(bool expr, String msg) { if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) return; if (!m_registryChecked) CheckRegistry(); if (!m_perfWarnings) return; if (!expr) { Log("PERF", "BCL Perf Warning: " + msg); } System.Diagnostics.Assert.Check(expr, "BCL Perf Warning: Your perf may be less than perfect because...", msg); } // For correctness-related asserts. On a debug build, set the registry key // BCLCorrectnessWarnings to non-zero. [Conditional("_DEBUG")] #if _DEBUG #endif internal static void Correctness(bool expr, String msg) { #if _DEBUG if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) return; if (!m_registryChecked) CheckRegistry(); if (!m_correctnessWarnings) return; if (!m_domainUnloadAdded) { m_domainUnloadAdded = true; AppDomain.CurrentDomain.DomainUnload += new EventHandler(WaitForFinalizers); } if (!expr) { Log("CORRECTNESS", "BCL Correctness Warning: " + msg); } System.Diagnostics.Assert.Check(expr, "BCL Correctness Warning: Your program may not work because...", msg); #endif } // Whether SafeHandles include a stack trace showing where they // were allocated. Only useful in checked & debug builds. internal static bool SafeHandleStackTracesEnabled { get { #if _DEBUG if (!m_registryChecked) CheckRegistry(); return m_safeHandleStackTraces; #else return false; #endif } } } }
using CppSharp.AST; using CppSharp.Generators; using CppSharp.Parser; using CppSharp.Passes; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using CppAbi = CppSharp.Parser.AST.CppAbi; namespace CppSharp { class Generator : ILibrary { private Options options = null; private string triple = ""; private CppAbi abi = CppAbi.Microsoft; public Generator(Options options) { if (options == null) throw new ArgumentNullException(nameof(options)); this.options = options; } static TargetPlatform GetCurrentPlatform() { if (Platform.IsWindows) return TargetPlatform.Windows; if (Platform.IsMacOS) return TargetPlatform.MacOS; if (Platform.IsLinux) return TargetPlatform.Linux; throw new System.NotImplementedException("Unknown host platform"); } void SetupTargetTriple() { var tripleBuilder = new StringBuilder(); if (options.Architecture == TargetArchitecture.x64) tripleBuilder.Append("x86_64-"); else if(options.Architecture == TargetArchitecture.x86) tripleBuilder.Append("i686-"); if (options.Platform == TargetPlatform.Windows) { tripleBuilder.Append("pc-win32-msvc"); abi = CppAbi.Microsoft; } else if (options.Platform == TargetPlatform.MacOS) { tripleBuilder.Append("apple-darwin12.4.0"); abi = CppAbi.Itanium; } else if (options.Platform == TargetPlatform.Linux) { tripleBuilder.Append("linux-gnu"); abi = CppAbi.Itanium; if(options.Cpp11ABI) tripleBuilder.Append("-cxx11abi"); } triple = tripleBuilder.ToString(); } public bool ValidateOptions(List<string> messages) { if (!options.Platform.HasValue) options.Platform = GetCurrentPlatform(); if (Platform.IsWindows && options.Platform != TargetPlatform.Windows) { messages.Add("Cannot create bindings for a platform other that Windows from a Windows host."); return false; } else if (Platform.IsMacOS && options.Platform != TargetPlatform.MacOS) { messages.Add("Cannot create bindings for a platform other that macOS from a macOS host."); return false; } else if (Platform.IsLinux && options.Platform != TargetPlatform.Linux) { messages.Add("Cannot create bindings for a platform other that Linux from a Linux host."); return false; } if (options.Platform != TargetPlatform.Windows && options.Kind != GeneratorKind.CSharp) { messages.Add("Cannot create bindings for languages other than C# from a non-Windows host."); return false; } if (options.Platform == TargetPlatform.Linux && options.Architecture != TargetArchitecture.x64) { messages.Add("Cannot create bindings for architectures other than x64 for Linux targets."); return false; } if (options.HeaderFiles.Count == 0) { messages.Add("No source header file has been given to generate bindings from."); return false; } if (string.IsNullOrEmpty(options.OutputNamespace)) { messages.Add("Output namespace not specified (see --outputnamespace option)."); return false; } if (string.IsNullOrEmpty(options.OutputFileName)) { messages.Add("Output directory not specified (see --output option)."); return false; } if (string.IsNullOrEmpty(options.InputLibraryName) && !options.CheckSymbols) { messages.Add("Input library name not specified and check symbols option not enabled.\nEither set the input library name (see or the check symbols flag."); return false; } if (string.IsNullOrEmpty(options.InputLibraryName) && options.CheckSymbols && options.Libraries.Count == 0) { messages.Add("Input library name not specified and check symbols is enabled but no libraries were given.\nEither set the input library name or add at least one library."); return false; } SetupTargetTriple(); return true; } public void Setup(Driver driver) { var parserOptions = driver.ParserOptions; parserOptions.TargetTriple = triple; parserOptions.Abi = abi; parserOptions.Verbose = options.Verbose; var driverOptions = driver.Options; driverOptions.GeneratorKind = options.Kind; var module = driverOptions.AddModule(options.OutputFileName); if(!string.IsNullOrEmpty(options.InputLibraryName)) module.SharedLibraryName = options.InputLibraryName; module.Headers.AddRange(options.HeaderFiles); module.Libraries.AddRange(options.Libraries); module.OutputNamespace = options.OutputNamespace; if (abi == CppAbi.Microsoft) parserOptions.MicrosoftMode = true; if (triple.Contains("apple")) SetupMacOptions(parserOptions); if (triple.Contains("linux")) SetupLinuxOptions(parserOptions); foreach (string s in options.Arguments) parserOptions.AddArguments(s); foreach (string s in options.IncludeDirs) parserOptions.AddIncludeDirs(s); foreach (string s in options.LibraryDirs) parserOptions.AddLibraryDirs(s); foreach (KeyValuePair<string, string> d in options.Defines) { if(string.IsNullOrEmpty(d.Value)) parserOptions.AddDefines(d.Key); else parserOptions.AddDefines(d.Key + "=" + d.Value); } driverOptions.GenerateDebugOutput = options.Debug; driverOptions.CompileCode = options.Compile; driverOptions.OutputDir = options.OutputDir; driverOptions.CheckSymbols = options.CheckSymbols; driverOptions.UnityBuild = options.UnityBuild; driverOptions.Verbose = options.Verbose; } private void SetupLinuxOptions(ParserOptions parserOptions) { parserOptions.MicrosoftMode = false; parserOptions.NoBuiltinIncludes = true; var headersPath = string.Empty; // Search for the available GCC versions on the provided headers. var versions = Directory.EnumerateDirectories(Path.Combine(headersPath, "usr/include/c++")); if (versions.Count() == 0) throw new Exception("No valid GCC version found on system include paths"); string gccVersionPath = versions.First(); string gccVersion = gccVersionPath.Substring(gccVersionPath.LastIndexOf(Path.DirectorySeparatorChar) + 1); string[] systemIncludeDirs = { Path.Combine("usr", "include", "c++", gccVersion), Path.Combine("usr", "include", "x86_64-linux-gnu", "c++", gccVersion), Path.Combine("usr", "include", "c++", gccVersion, "backward"), Path.Combine("usr", "lib", "gcc", "x86_64-linux-gnu", gccVersion, "include"), Path.Combine("usr", "include", "x86_64-linux-gnu"), Path.Combine("usr", "include") }; foreach (var dir in systemIncludeDirs) parserOptions.AddSystemIncludeDirs(Path.Combine(headersPath, dir)); parserOptions.AddDefines("_GLIBCXX_USE_CXX11_ABI=" + (options.Cpp11ABI ? "1" : "0")); } private static void SetupMacOptions(ParserOptions options) { options.MicrosoftMode = false; options.NoBuiltinIncludes = true; if (Platform.IsMacOS) { var headersPaths = new List<string> { "/usr/include" }; foreach (var header in headersPaths) options.AddSystemIncludeDirs(header); } options.AddArguments("-stdlib=libc++"); } public void SetupPasses(Driver driver) { driver.Context.TranslationUnitPasses.AddPass(new FunctionToInstanceMethodPass()); driver.Context.TranslationUnitPasses.AddPass(new MarshalPrimitivePointersAsRefTypePass()); } public void Preprocess(Driver driver, ASTContext ctx) { } public void Postprocess(Driver driver, ASTContext ctx) { } public void Run() { StringBuilder messageBuilder = new StringBuilder(); messageBuilder.Append("Generating "); switch(options.Kind) { case GeneratorKind.CLI: messageBuilder.Append("C++/CLI"); break; case GeneratorKind.CSharp: messageBuilder.Append("C#"); break; } messageBuilder.Append(" bindings for "); switch (options.Platform) { case TargetPlatform.Linux: messageBuilder.Append("Linux"); break; case TargetPlatform.MacOS: messageBuilder.Append("OSX"); break; case TargetPlatform.Windows: messageBuilder.Append("Windows"); break; } messageBuilder.Append(" "); switch (options.Architecture) { case TargetArchitecture.x86: messageBuilder.Append("x86"); break; case TargetArchitecture.x64: messageBuilder.Append("x64"); break; } if(options.Cpp11ABI) messageBuilder.Append(" (GCC C++11 ABI)"); messageBuilder.Append("..."); Console.WriteLine(messageBuilder.ToString()); ConsoleDriver.Run(this); Console.WriteLine(); } } }
using LambdicSql.ConverterServices; using LambdicSql.ConverterServices.SymbolConverters; namespace LambdicSql.SqlServer { public static partial class Symbol { /// <summary> /// CONCAT function. /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/concat-transact-sql /// </summary> /// <param name="targets">A string value to concatenate to the other values.</param> /// <returns>concatenated result.</returns> [FuncStyleConverter] public static string Concat(params string[] targets) { throw new InvalitContextException(nameof(Concat)); } /// <summary> /// CONCAT_WS function. /// support start with SQL Server 2017 /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/concat-ws-transact-sql /// </summary> /// <param name="targets">A string value to concatenate to the other values.</param> /// <returns>concatenat-ws-ed result.</returns> [FuncStyleConverter] public static string Concat_WS(params string[] targets) { throw new InvalitContextException(nameof(Concat_WS)); } /// <summary> /// LEN function. /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/len-transact-sql /// </summary> /// <param name="target">target.</param> /// <returns>String length.</returns> [FuncStyleConverter] public static int Len(string target) { throw new InvalitContextException(nameof(Len)); } /// <summary> /// LOWER function. /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/lower-transact-sql /// </summary> /// <param name="target">target.</param> /// <returns>Changed string.</returns> [FuncStyleConverter] public static string Lower(string target) { throw new InvalitContextException(nameof(Lower)); } /// <summary> /// REPLACE function. /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/replace-transact-sql /// </summary> /// <param name="target">target.</param> /// <param name="src">source.</param> /// <param name="dst">destination.</param> /// <returns>Changed string.</returns> [FuncStyleConverter] public static string Replace(string target, string src, string dst) { throw new InvalitContextException(nameof(Replace)); } /// <summary> /// SUBSTRING function. /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/substring-transact-sql /// </summary> /// <param name="target">target.</param> /// <param name="startIndex">Specify the starting position of the character string to be acquired.</param> /// <param name="length">Specify the length of the string to be retrieved.</param> /// <returns>Part of a text.</returns> [FuncStyleConverter] public static string Substring(string target, int startIndex, int length) { throw new InvalitContextException(nameof(Substring)); } /// <summary> /// UPPER function. /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/upper-transact-sql /// </summary> /// <param name="target">target.</param> /// <returns>Changed string.</returns> [FuncStyleConverter] public static string Upper(string target) { throw new InvalitContextException(nameof(Upper)); } /// <summary> /// SPACE Function /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/space-transact-sql /// </summary> /// <param name="expression">number of spaces</param> /// <returns>same as SPACE(n) result</returns> [FuncStyleConverter] public static string Space(int expression) { throw new InvalitContextException(nameof(Space)); } /// <summary> /// STR Function /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/str-transact-sql /// </summary> /// <param name="expression">float expression</param> /// <param name="length">total length</param> /// <param name="decimalFormat">Decimal format</param> /// <returns>same as STR(value, int, int) result</returns> [FuncStyleConverter] public static string Str(double expression, int length, int decimalFormat) { throw new InvalitContextException(nameof(Str)); } /// <summary> /// ASCII Function /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/ascii-transact-sql /// </summary> /// <param name="value">ASCII charactor</param> /// <returns></returns> [FuncStyleConverter] public static int Ascii(char value) { throw new InvalitContextException(nameof(Ascii)); } /// <summary> /// CHAR Function /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/char-transact-sql /// </summary> /// <param name="value">CHAR charactor</param> /// <returns></returns> [FuncStyleConverter] public static char Char(int value) { throw new InvalitContextException(nameof(Char)); } /// <summary> /// CHARINDEX Function /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/charindex-transact-sql /// Lambda expression does not support default value. /// </summary> /// <param name="searchTarget">Search string</param> /// <param name="searchString">Search Source String</param> /// <param name="startLocation">search index position</param> /// <returns></returns> [FuncStyleConverter] public static int CharIndex(string searchTarget, string searchString, int startLocation) { throw new InvalitContextException(nameof(CharIndex)); } /// <summary> /// CHARINDEX Function /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/charindex-transact-sql /// </summary> /// <param name="searchTarget">Search string</param> /// <param name="searchString">Search Source String</param> /// <returns></returns> [FuncStyleConverter] public static int CharIndex(string searchTarget, string searchString) { throw new InvalitContextException(nameof(CharIndex)); } /// <summary> /// DIFFERENCE Function /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/difference-transact-sql /// </summary> /// <param name="target1">difference string</param> /// <param name="target2">difference string</param> /// <returns></returns> [FuncStyleConverter] public static int Difference(string target1, string target2) { throw new InvalitContextException(nameof(Difference)); } /// <summary> /// FORMAT Function /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/format-transact-sql /// </summary> /// <param name="value">1st is target value, 2nd is format string</param> /// <param name="formatStrings">1st is target value, 2nd is format string</param> /// <returns></returns> [FuncStyleConverter] public static string Format(object value, params string[] formatStrings) { throw new InvalitContextException(nameof(Symbol.Format)); } /// <summary> /// LEFT Function /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/left-transact-sql /// </summary> /// <param name="searchTarget">Search string</param> /// <param name="startLocation">start index</param> /// <returns></returns> [FuncStyleConverter] public static string Left(string searchTarget, int startLocation) { throw new InvalitContextException(nameof(Left)); } /// <summary> /// LTRIM Function /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/ltrim-transact-sql /// </summary> /// <param name="searchTarget">Trim position</param> /// <returns></returns> [FuncStyleConverter] public static string Ltrim(string searchTarget) { throw new InvalitContextException(nameof(Ltrim)); } /// <summary> /// NCHAR Function /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/nchar-transact-sql /// </summary> /// <param name="codepoint">unicode codepoint</param> /// <returns></returns> [FuncStyleConverter] public static char NChar(int codepoint) { throw new InvalitContextException(nameof(NChar)); } /// <summary> /// PATINDEX Function /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/patindex-transact-sql /// </summary> /// <param name="searchString">search pattern</param> /// <param name="targetString">search target</param> /// <returns></returns> [FuncStyleConverter] public static int PatIndex(string searchString, string targetString) { throw new InvalitContextException(nameof(PatIndex)); } /// <summary> /// QUOTENAME Function /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/quotename-transact-sql /// </summary> /// <param name="value">Quotering string</param> /// <returns></returns> [FuncStyleConverter] public static string QuoteName(string value) { throw new InvalitContextException(nameof(QuoteName)); } /// <summary> /// REPLICATE Function /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/replicate-transact-sql /// </summary> /// <param name="value">repeate value</param> /// <param name="replicateCounter">repete count</param> /// <returns></returns> [FuncStyleConverter] public static string Replicate(string value, int replicateCounter) { throw new InvalitContextException(nameof(Replicate)); } /// <summary> /// REPLICATE Function /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/reverse-transact-sql /// </summary> /// <param name="value">reverse string</param> /// <returns></returns> [FuncStyleConverter] public static string Reverse(string value) { throw new InvalitContextException(nameof(Reverse)); } /// <summary> /// RIGHT Function /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/right-transact-sql /// </summary> /// <param name="searchTarget">Search string</param> /// <param name="startLocation">start index</param> /// <returns></returns> [FuncStyleConverter] public static string Right(string searchTarget, int startLocation) { throw new InvalitContextException(nameof(Right)); } /// <summary> /// RTRIM Function /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/rtrim-transact-sql /// </summary> /// <param name="searchTarget">Trim position</param> /// <returns></returns> [FuncStyleConverter] public static string Rtrim(string searchTarget) { throw new InvalitContextException(nameof(Rtrim)); } /// <summary> /// SOUNDEX Function /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/soundex-transact-sql /// </summary> /// <param name="value">sound text</param> /// <returns></returns> [FuncStyleConverter] public static string SoundEx(string value) { throw new InvalitContextException(nameof(SoundEx)); } /// <summary> /// STRING_AGG Function /// Supports with start SQL Server 2017 /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/string-agg-transact-sql /// </summary> /// <param name="value">Aggrigate string</param> /// <param name="separator">separator charactor</param> /// <returns></returns> [FuncStyleConverter] public static string String_Agg(string value, string separator) { throw new InvalitContextException(nameof(String_Agg)); } /// <summary> /// STRING_AGG Function /// Supports with start SQL Server 2017 /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/string-agg-transact-sql /// </summary> /// <param name="value">Aggrigate string</param> /// <param name="separator">separator charactor</param> /// <returns></returns> [FuncStyleConverter] public static string String_Agg(string value, char separator) { throw new InvalitContextException(nameof(String_Agg)); } /// <summary> /// STRING_ESCAPE Function /// Supports with start SQL Server 2016 /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/string-escape-transact-sql /// </summary> /// <param name="value">escape string</param> /// <param name="escapeType"> supports only 'JSON'</param> /// <returns></returns> [FuncStyleConverter] public static string String_Escape(string value, string escapeType) { throw new InvalitContextException(nameof(String_Escape)); } /// <summary> /// STRING_SPLIT Function /// Supports with start SQL Server 2016 /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/string-split-transact-sql /// </summary> /// <param name="value">Aggrigate string</param> /// <param name="separator">separator charactor</param> /// <returns></returns> [FuncStyleConverter] public static string String_Split(string value, string separator) { throw new InvalitContextException(nameof(String_Split)); } /// <summary> /// STRING_SPLIT Function /// Supports with start SQL Server 2016 /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/string-agg-transact-sql /// </summary> /// <param name="value">Aggrigate string</param> /// <param name="separator">separator charactor</param> /// <returns></returns> [FuncStyleConverter] public static string String_Split(string value, char separator) { throw new InvalitContextException(nameof(String_Split)); } /// <summary> /// STUFF Function /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/stuff-transact-sql /// </summary> /// <param name="value">stuff text</param> /// <param name="start">stuff start position</param> /// <param name="length">stuff length</param> /// <param name="replaceString">replacement string</param> /// <returns></returns> [FuncStyleConverter] public static string Stuff(string value, long start, long length, string replaceString) { throw new InvalitContextException(nameof(Stuff)); } /// <summary> /// TRANSLATE Function /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/translate-transact-sql /// </summary> /// <param name="value">translate text</param> /// <param name="targetString">replace target</param> /// <param name="replaceString">replace string</param> /// <returns></returns> [FuncStyleConverter] public static string Translate(string value, string targetString, string replaceString) { throw new InvalitContextException(nameof(Translate)); } /// <summary> /// TRIM Function /// TRIM supports start with SQL Server 2017 /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/trim-transact-sql /// </summary> /// <param name="trimString">Trim String</param> /// <returns></returns> [FuncStyleConverter] public static string Trim(string trimString) { throw new InvalitContextException(nameof(Rtrim)); } /// <summary> /// UNICODE Function /// https://docs.microsoft.com/ja-jp/sql/t-sql/functions/unicode-transact-sql /// </summary> /// <param name="UnicodeString">Unicode String</param> /// <returns></returns> [FuncStyleConverter] public static int Unicode(string UnicodeString) { throw new InvalitContextException(nameof(Unicode)); } } }
// // WebKit# - WebKit bindings for Mono // // Author: // Everaldo Canuto <ecanuto@novell.com> // // Copyright (c) 2008 Novell, Inc. All rights reserved. // // 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 Gtk; using GtkSharp; using WebKit; namespace FunnyBrowser { public class MainClass { public static void Main (string[] args) { string url = (args.Length > 0) ? args[0] : ""; Application.Init (); MainWindow window = new MainWindow (url); window.Show (); Application.Run (); } } public class MainWindow: Gtk.Window { const string APP_NAME = "FunnyBrowser"; private string url = "http://www.google.com/"; private Gtk.VBox vbox = null; private Gtk.Toolbar toolbar = null; private Gtk.Toolbar findbar = null; private Gtk.Entry uri_entry = null; private Gtk.Entry find_entry = null; private WebKit.WebView webview = null; private Gtk.Statusbar statusbar = null; private Gtk.Action action_back; private Gtk.Action action_forward; private Gtk.Action action_reload; private Gtk.Action action_stop; private Gtk.Action action_jump; public MainWindow (string url): base (Gtk.WindowType.Toplevel) { if (url != "") this.url = url; CreateWidgets (); webview.Open (this.url); } private void CreateWidgets () { this.Title = APP_NAME; this.SetDefaultSize (700, 500); this.DeleteEvent += new DeleteEventHandler (OnDeleteEvent); CreateActions (); CreateToolbar (); CreateWebView (); CreateFindbar (); CreateStatusBar (); Gtk.ScrolledWindow scroll = new Gtk.ScrolledWindow (); scroll.Add (webview); vbox = new Gtk.VBox (false, 1); vbox.PackStart (toolbar, false, false, 0); vbox.PackStart (scroll); //vbox.PackStart (findbar, false, false, 0); vbox.PackEnd (statusbar, false, true, 0); this.Add (vbox); this.ShowAll (); } private void CreateActions () { action_back = new Gtk.Action("go-back", "Go Back", null, "gtk-go-back"); action_forward = new Gtk.Action("go-forward", "Go Forward", null, "gtk-go-forward"); action_reload = new Gtk.Action("reload", "Reload", null, "gtk-refresh"); action_stop = new Gtk.Action("stop", "Stop", null, "gtk-stop"); action_jump = new Gtk.Action("jump", "Jump", null, "gtk-jump-to"); action_back.Activated += new EventHandler(on_back_activate); action_forward.Activated += new EventHandler(on_forward_activate); action_reload.Activated += new EventHandler(on_reload_activate); action_stop.Activated += new EventHandler(on_stop_activate); action_jump.Activated += new EventHandler(on_uri_activate); } private void CreateToolbar () { // UrlEntry uri_entry = new Gtk.Entry (); uri_entry.Activated += new EventHandler(on_uri_activate); Gtk.ToolItem uri_item = new Gtk.ToolItem (); uri_item.Expand = true; uri_item.Add (uri_entry); // Toolbar toolbar = new Toolbar (); toolbar.ToolbarStyle = ToolbarStyle.Icons; toolbar.Orientation = Orientation.Horizontal; toolbar.ShowArrow = true; // Toolbar Itens toolbar.Add (action_back.CreateToolItem()); toolbar.Add (action_forward.CreateToolItem()); toolbar.Add (action_reload.CreateToolItem()); toolbar.Add (action_stop.CreateToolItem()); toolbar.Add (uri_item); toolbar.Add (action_jump.CreateToolItem()); } private void CreateWebView () { webview = new WebView (); webview.Editable = false; webview.TitleChanged += new TitleChangedHandler (OnTitleChanged); webview.HoveringOverLink += new HoveringOverLinkHandler (OnHoveringOverLink); webview.LoadCommitted += new LoadCommittedHandler (OnLoadCommitted); webview.LoadFinished += new LoadFinishedHandler (OnLoadFinished); } private void CreateStatusBar () { statusbar = new Gtk.Statusbar (); } private void CreateFindbar () { // FindEntry find_entry = new Gtk.Entry (); //find_entry.Activated += new EventHandler(on_uri_activate); Gtk.ToolItem find_item = new Gtk.ToolItem (); //find_item.Expand = true; find_item.Add (find_entry); // Toolbar findbar = new Toolbar (); findbar.ToolbarStyle = ToolbarStyle.Icons; findbar.Orientation = Orientation.Horizontal; findbar.ShowArrow = true; // Toolbar Itens findbar.Add (action_stop.CreateToolItem()); findbar.Add (find_item); findbar.Add (action_back.CreateToolItem()); findbar.Add (action_forward.CreateToolItem()); } protected void OnDeleteEvent (object sender, DeleteEventArgs args) { Application.Quit (); args.RetVal = true; } private void OnTitleChanged (object o, TitleChangedArgs args) { if (args.Title == String.Empty) this.Title = APP_NAME; else this.Title = String.Format ("{0} - {1}", args.Title, APP_NAME); } private void OnHoveringOverLink (object o, HoveringOverLinkArgs args) { statusbar.Pop (1); if (args.Link != null) { statusbar.Push (1, args.Link); } } private void OnLoadCommitted (object o, LoadCommittedArgs args) { action_back.Sensitive = webview.CanGoBack (); action_forward.Sensitive = webview.CanGoForward (); uri_entry.Text = args.Frame.Uri; } private void OnLoadFinished (object o, LoadFinishedArgs args) { // } private void on_back_activate (object o, EventArgs args) { webview.GoBack (); } private void on_forward_activate (object o, EventArgs args) { webview.GoForward (); } private void on_reload_activate (object o, EventArgs args) { webview.Reload (); } private void on_stop_activate (object o, EventArgs args) { webview.StopLoading (); } private void on_uri_activate (object o, EventArgs args) { webview.Open (uri_entry.Text); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Globalization; using System.Threading.Tasks; using System.Collections.Generic; using Xunit; namespace System.Data.SqlClient.ManualTesting.Tests { public static class ExceptionTest { // data value and server consts private const string badServer = "NotAServer"; private const string sqlsvrBadConn = "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections."; private const string logonFailedErrorMessage = "Login failed for user '{0}'."; private const string execReaderFailedMessage = "ExecuteReader requires an open and available Connection. The connection's current state is closed."; private const string warningNoiseMessage = "The full-text search condition contained noise word(s)."; private const string warningInfoMessage = "Test of info messages"; private const string orderIdQuery = "select orderid from orders where orderid < 10250"; #if MANAGED_SNI [CheckConnStrSetupFact] public static void NonWindowsIntAuthFailureTest() { string connectionString = (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { IntegratedSecurity = true }).ConnectionString; Assert.Throws<NotSupportedException>(() => new SqlConnection(connectionString).Open()); // Should not receive any exception when using IntAuth=false connectionString = (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { IntegratedSecurity = false }).ConnectionString; new SqlConnection(connectionString).Open(); } #endif [CheckConnStrSetupFact] public static void WarningTest() { Action<object, SqlInfoMessageEventArgs> warningCallback = (object sender, SqlInfoMessageEventArgs imevent) => { for (int i = 0; i < imevent.Errors.Count; i++) { Assert.True(imevent.Errors[i].Message.Contains(warningInfoMessage), "FAILED: WarningTest Callback did not contain correct message."); } }; SqlInfoMessageEventHandler handler = new SqlInfoMessageEventHandler(warningCallback); using (SqlConnection sqlConnection = new SqlConnection((new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { Pooling = false }).ConnectionString)) { sqlConnection.InfoMessage += handler; sqlConnection.Open(); SqlCommand cmd = new SqlCommand(string.Format("PRINT N'{0}'", warningInfoMessage), sqlConnection); cmd.ExecuteNonQuery(); sqlConnection.InfoMessage -= handler; cmd.ExecuteNonQuery(); } } [CheckConnStrSetupFact] public static void WarningsBeforeRowsTest() { bool hitWarnings = false; int iteration = 0; Action<object, SqlInfoMessageEventArgs> warningCallback = (object sender, SqlInfoMessageEventArgs imevent) => { for (int i = 0; i < imevent.Errors.Count; i++) { Assert.True(imevent.Errors[i].Message.Contains(warningNoiseMessage), "FAILED: WarningsBeforeRowsTest Callback did not contain correct message. Failed in loop iteration: " + iteration); } hitWarnings = true; }; SqlInfoMessageEventHandler handler = new SqlInfoMessageEventHandler(warningCallback); SqlConnection sqlConnection = new SqlConnection(DataTestUtility.TcpConnStr); sqlConnection.InfoMessage += handler; sqlConnection.Open(); foreach (string orderClause in new string[] { "", " order by FirstName" }) { foreach (bool messagesOnErrors in new bool[] { true, false }) { iteration++; sqlConnection.FireInfoMessageEventOnUserErrors = messagesOnErrors; // These queries should return warnings because AND here is a noise word. SqlCommand cmd = new SqlCommand("select FirstName from Northwind.dbo.Employees where contains(FirstName, '\"Anne AND\"')" + orderClause, sqlConnection); using (SqlDataReader reader = cmd.ExecuteReader()) { Assert.True(reader.HasRows, "FAILED: SqlDataReader.HasRows is not correct (should be TRUE)"); bool receivedRows = false; while (reader.Read()) { receivedRows = true; } Assert.True(receivedRows, "FAILED: Should have received rows from this query."); Assert.True(hitWarnings, "FAILED: Should have received warnings from this query"); } hitWarnings = false; cmd.CommandText = "select FirstName from Northwind.dbo.Employees where contains(FirstName, '\"NotARealPerson AND\"')" + orderClause; using (SqlDataReader reader = cmd.ExecuteReader()) { Assert.False(reader.HasRows, "FAILED: SqlDataReader.HasRows is not correct (should be FALSE)"); bool receivedRows = false; while (reader.Read()) { receivedRows = true; } Assert.False(receivedRows, "FAILED: Should have NOT received rows from this query."); Assert.True(hitWarnings, "FAILED: Should have received warnings from this query"); } } } sqlConnection.Close(); } private static bool CheckThatExceptionsAreDistinctButHaveSameData(SqlException e1, SqlException e2) { Assert.True(e1 != e2, "FAILED: verification of exception cloning in subsequent connection attempts"); Assert.False((e1 == null) || (e2 == null), "FAILED: One of exceptions is null, another is not"); bool equal = (e1.Message == e2.Message) && (e1.HelpLink == e2.HelpLink) && (e1.InnerException == e2.InnerException) && (e1.Source == e2.Source) && (e1.Data.Count == e2.Data.Count) && (e1.Errors == e2.Errors); IDictionaryEnumerator enum1 = e1.Data.GetEnumerator(); IDictionaryEnumerator enum2 = e2.Data.GetEnumerator(); while (equal) { if (!enum1.MoveNext()) break; enum2.MoveNext(); equal = (enum1.Key == enum2.Key) && (enum2.Value == enum2.Value); } Assert.True(equal, string.Format("FAILED: exceptions do not contain the same data (besides call stack):\nFirst: {0}\nSecond: {1}\n", e1, e2)); return true; } [CheckConnStrSetupFact] public static void ExceptionTests() { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr); // tests improper server name thrown from constructor of tdsparser SqlConnectionStringBuilder badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { DataSource = badServer, ConnectTimeout = 1 }; VerifyConnectionFailure<SqlException>(() => GenerateConnectionException(badBuilder.ConnectionString), sqlsvrBadConn, VerifyException); // tests incorrect password - thrown from the adapter badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { Password = string.Empty }; string errorMessage = string.Format(CultureInfo.InvariantCulture, logonFailedErrorMessage, badBuilder.UserID); VerifyConnectionFailure<SqlException>(() => GenerateConnectionException(badBuilder.ConnectionString), errorMessage, (ex) => VerifyException(ex, 1, 18456, 1, 14)); // tests incorrect database name - exception thrown from adapter badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { InitialCatalog = "NotADatabase" }; errorMessage = string.Format(CultureInfo.InvariantCulture, "Cannot open database \"{0}\" requested by the login. The login failed.", badBuilder.InitialCatalog); SqlException firstAttemptException = VerifyConnectionFailure<SqlException>(() => GenerateConnectionException(badBuilder.ConnectionString), errorMessage, (ex) => VerifyException(ex, 2, 4060, 1, 11)); // Verify that the same error results in a different instance of an exception, but with the same data VerifyConnectionFailure<SqlException>(() => GenerateConnectionException(badBuilder.ConnectionString), errorMessage, (ex) => CheckThatExceptionsAreDistinctButHaveSameData(firstAttemptException, ex)); // tests incorrect user name - exception thrown from adapter badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { UserID = "NotAUser" }; errorMessage = string.Format(CultureInfo.InvariantCulture, logonFailedErrorMessage, badBuilder.UserID); VerifyConnectionFailure<SqlException>(() => GenerateConnectionException(badBuilder.ConnectionString), errorMessage, (ex) => VerifyException(ex, 1, 18456, 1, 14)); } [CheckConnStrSetupFact] public static void VariousExceptionTests() { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr); // Test 1 - A SqlConnectionStringBuilder badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { DataSource = badServer, ConnectTimeout = 1 }; using (var sqlConnection = new SqlConnection(badBuilder.ConnectionString)) { using (SqlCommand command = sqlConnection.CreateCommand()) { command.CommandText = orderIdQuery; VerifyConnectionFailure<InvalidOperationException>(() => command.ExecuteReader(), execReaderFailedMessage); } } // Test 1 - B badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { Password = string.Empty }; using (var sqlConnection = new SqlConnection(badBuilder.ConnectionString)) { string errorMessage = string.Format(CultureInfo.InvariantCulture, logonFailedErrorMessage, badBuilder.UserID); VerifyConnectionFailure<SqlException>(() => sqlConnection.Open(), errorMessage, (ex) => VerifyException(ex, 1, 18456, 1, 14)); } } [CheckConnStrSetupFact] public static void IndependentConnectionExceptionTest() { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr); SqlConnectionStringBuilder badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { DataSource = badServer, ConnectTimeout = 1 }; using (var sqlConnection = new SqlConnection(badBuilder.ConnectionString)) { // Test 1 VerifyConnectionFailure<SqlException>(() => sqlConnection.Open(), sqlsvrBadConn, VerifyException); // Test 2 using (SqlCommand command = new SqlCommand(orderIdQuery, sqlConnection)) { VerifyConnectionFailure<InvalidOperationException>(() => command.ExecuteReader(), execReaderFailedMessage); } } } [CheckConnStrSetupFact] public static async Task UnobservedTaskExceptionTest() { List<Exception> exceptionsSeen = new List<Exception>(); Action<object, UnobservedTaskExceptionEventArgs> unobservedTaskCallback = (object sender, UnobservedTaskExceptionEventArgs e) => { Assert.False(exceptionsSeen.Contains(e.Exception.InnerException), "FAILED: This exception was already observed by awaiting: " + e.Exception.InnerException); }; EventHandler<UnobservedTaskExceptionEventArgs> handler = new EventHandler<UnobservedTaskExceptionEventArgs>(unobservedTaskCallback); TaskScheduler.UnobservedTaskException += handler; using(var connection = new SqlConnection(DataTestUtility.TcpConnStr)) { await connection.OpenAsync(); using (var command = new SqlCommand("select null; select * from dbo.NonexistentTable;", connection)) { try { using (var reader = await command.ExecuteReaderAsync()) { do { while (await reader.ReadAsync()) { } } while (await reader.NextResultAsync()); } } catch (SqlException ex) { exceptionsSeen.Add(ex); } } } GC.Collect(); GC.WaitForPendingFinalizers(); TaskScheduler.UnobservedTaskException -= handler; } private static void GenerateConnectionException(string connectionString) { using (SqlConnection sqlConnection = new SqlConnection(connectionString)) { sqlConnection.Open(); using (SqlCommand command = sqlConnection.CreateCommand()) { command.CommandText = orderIdQuery; command.ExecuteReader(); } } } private static TException VerifyConnectionFailure<TException>(Action connectAction, string expectedExceptionMessage, Func<TException, bool> exVerifier) where TException : Exception { TException ex = Assert.Throws<TException>(connectAction); Assert.True(ex.Message.Contains(expectedExceptionMessage), string.Format("FAILED: SqlException did not contain expected error message. Actual message: {0}", ex.Message)); Assert.True(exVerifier(ex), "FAILED: Exception verifier failed on the exception."); return ex; } private static TException VerifyConnectionFailure<TException>(Action connectAction, string expectedExceptionMessage) where TException : Exception { return VerifyConnectionFailure<TException>(connectAction, expectedExceptionMessage, (ex) => true); } private static bool VerifyException(SqlException exception) { VerifyException(exception, 1); return true; } private static bool VerifyException(SqlException exception, int count, int? errorNumber = null, int? errorState = null, int? severity = null) { // Verify that there are the correct number of errors in the exception Assert.True(exception.Errors.Count == count, string.Format("FAILED: Incorrect number of errors. Expected: {0}. Actual: {1}.", count, exception.Errors.Count)); // Ensure that all errors have an error-level severity for (int i = 0; i < count; i++) { Assert.True(exception.Errors[i].Class >= 10, "FAILED: verification of Exception! Exception contains a warning!"); } // Check the properties of the exception populated by the server are correct if (errorNumber.HasValue) { Assert.True(errorNumber.Value == exception.Number, string.Format("FAILED: Error number of exception is incorrect. Expected: {0}. Actual: {1}.", errorNumber.Value, exception.Number)); } if (errorState.HasValue) { Assert.True(errorState.Value == exception.State, string.Format("FAILED: Error state of exception is incorrect. Expected: {0}. Actual: {1}.", errorState.Value, exception.State)); } if (severity.HasValue) { Assert.True(severity.Value == exception.Class, string.Format("FAILED: Severity of exception is incorrect. Expected: {0}. Actual: {1}.", severity.Value, exception.Class)); } if ((errorNumber.HasValue) && (errorState.HasValue) && (severity.HasValue)) { string detailsText = string.Format("Error Number:{0},State:{1},Class:{2}", errorNumber.Value, errorState.Value, severity.Value); Assert.True(exception.ToString().Contains(detailsText), string.Format("FAILED: SqlException.ToString does not contain the error number, state and severity information")); } // verify that the this[] function on the collection works, as well as the All function SqlError[] errors = new SqlError[exception.Errors.Count]; exception.Errors.CopyTo(errors, 0); Assert.True((errors[0].Message).Equals(exception.Errors[0].Message), string.Format("FAILED: verification of Exception! ErrorCollection indexer/CopyTo resulted in incorrect value.")); return true; } } }
using System; using System.Runtime.InteropServices; using System.Security; using BulletSharp.Math; namespace BulletSharp { public enum RotateOrder { XYZ, XZY, YXZ, YZX, ZXY, ZYX } public class RotationalLimitMotor2 : IDisposable { internal IntPtr _native; bool _preventDelete; internal RotationalLimitMotor2(IntPtr native, bool preventDelete) { _native = native; _preventDelete = preventDelete; } public RotationalLimitMotor2() { _native = btRotationalLimitMotor2_new(); } public RotationalLimitMotor2(RotationalLimitMotor2 limitMotor) { _native = btRotationalLimitMotor2_new2(limitMotor._native); } public void TestLimitValue(float testValue) { btRotationalLimitMotor2_testLimitValue(_native, testValue); } public float Bounce { get { return btRotationalLimitMotor2_getBounce(_native); } set { btRotationalLimitMotor2_setBounce(_native, value); } } public int CurrentLimit { get { return btRotationalLimitMotor2_getCurrentLimit(_native); } set { btRotationalLimitMotor2_setCurrentLimit(_native, value); } } public float CurrentLimitError { get { return btRotationalLimitMotor2_getCurrentLimitError(_native); } set { btRotationalLimitMotor2_setCurrentLimitError(_native, value); } } public float CurrentLimitErrorHi { get { return btRotationalLimitMotor2_getCurrentLimitErrorHi(_native); } set { btRotationalLimitMotor2_setCurrentLimitErrorHi(_native, value); } } public float CurrentPosition { get { return btRotationalLimitMotor2_getCurrentPosition(_native); } set { btRotationalLimitMotor2_setCurrentPosition(_native, value); } } public bool EnableMotor { get { return btRotationalLimitMotor2_getEnableMotor(_native); } set { btRotationalLimitMotor2_setEnableMotor(_native, value); } } public bool EnableSpring { get { return btRotationalLimitMotor2_getEnableSpring(_native); } set { btRotationalLimitMotor2_setEnableSpring(_native, value); } } public float EquilibriumPoint { get { return btRotationalLimitMotor2_getEquilibriumPoint(_native); } set { btRotationalLimitMotor2_setEquilibriumPoint(_native, value); } } public float HiLimit { get { return btRotationalLimitMotor2_getHiLimit(_native); } set { btRotationalLimitMotor2_setHiLimit(_native, value); } } public bool IsLimited { get { return btRotationalLimitMotor2_isLimited(_native); } } public float LoLimit { get { return btRotationalLimitMotor2_getLoLimit(_native); } set { btRotationalLimitMotor2_setLoLimit(_native, value); } } public float MaxMotorForce { get { return btRotationalLimitMotor2_getMaxMotorForce(_native); } set { btRotationalLimitMotor2_setMaxMotorForce(_native, value); } } public float MotorCFM { get { return btRotationalLimitMotor2_getMotorCFM(_native); } set { btRotationalLimitMotor2_setMotorCFM(_native, value); } } public float MotorERP { get { return btRotationalLimitMotor2_getMotorERP(_native); } set { btRotationalLimitMotor2_setMotorERP(_native, value); } } public bool ServoMotor { get { return btRotationalLimitMotor2_getServoMotor(_native); } set { btRotationalLimitMotor2_setServoMotor(_native, value); } } public float ServoTarget { get { return btRotationalLimitMotor2_getServoTarget(_native); } set { btRotationalLimitMotor2_setServoTarget(_native, value); } } public float SpringDamping { get { return btRotationalLimitMotor2_getSpringDamping(_native); } set { btRotationalLimitMotor2_setSpringDamping(_native, value); } } public bool SpringDampingLimited { get { return btRotationalLimitMotor2_getSpringDampingLimited(_native); } set { btRotationalLimitMotor2_setSpringDampingLimited(_native, value); } } public float SpringStiffness { get { return btRotationalLimitMotor2_getSpringStiffness(_native); } set { btRotationalLimitMotor2_setSpringStiffness(_native, value); } } public bool SpringStiffnessLimited { get { return btRotationalLimitMotor2_getSpringStiffnessLimited(_native); } set { btRotationalLimitMotor2_setSpringStiffnessLimited(_native, value); } } public float StopCFM { get { return btRotationalLimitMotor2_getStopCFM(_native); } set { btRotationalLimitMotor2_setStopCFM(_native, value); } } public float StopERP { get { return btRotationalLimitMotor2_getStopERP(_native); } set { btRotationalLimitMotor2_setStopERP(_native, value); } } public float TargetVelocity { get { return btRotationalLimitMotor2_getTargetVelocity(_native); } set { btRotationalLimitMotor2_setTargetVelocity(_native, value); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_native != IntPtr.Zero) { if (!_preventDelete) { btRotationalLimitMotor2_delete(_native); } _native = IntPtr.Zero; } } ~RotationalLimitMotor2() { Dispose(false); } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btRotationalLimitMotor2_new(); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btRotationalLimitMotor2_new2(IntPtr limot); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btRotationalLimitMotor2_getBounce(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btRotationalLimitMotor2_getCurrentLimit(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btRotationalLimitMotor2_getCurrentLimitError(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btRotationalLimitMotor2_getCurrentLimitErrorHi(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btRotationalLimitMotor2_getCurrentPosition(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btRotationalLimitMotor2_getEnableMotor(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btRotationalLimitMotor2_getEnableSpring(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btRotationalLimitMotor2_getEquilibriumPoint(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btRotationalLimitMotor2_getHiLimit(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btRotationalLimitMotor2_getLoLimit(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btRotationalLimitMotor2_getMaxMotorForce(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btRotationalLimitMotor2_getMotorCFM(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btRotationalLimitMotor2_getMotorERP(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btRotationalLimitMotor2_getServoMotor(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btRotationalLimitMotor2_getServoTarget(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btRotationalLimitMotor2_getSpringDamping(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btRotationalLimitMotor2_getSpringDampingLimited(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btRotationalLimitMotor2_getSpringStiffness(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btRotationalLimitMotor2_getSpringStiffnessLimited(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btRotationalLimitMotor2_getStopCFM(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btRotationalLimitMotor2_getStopERP(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btRotationalLimitMotor2_getTargetVelocity(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btRotationalLimitMotor2_isLimited(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btRotationalLimitMotor2_setBounce(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btRotationalLimitMotor2_setCurrentLimit(IntPtr obj, int value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btRotationalLimitMotor2_setCurrentLimitError(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btRotationalLimitMotor2_setCurrentLimitErrorHi(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btRotationalLimitMotor2_setCurrentPosition(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btRotationalLimitMotor2_setEnableMotor(IntPtr obj, bool value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btRotationalLimitMotor2_setEnableSpring(IntPtr obj, bool value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btRotationalLimitMotor2_setEquilibriumPoint(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btRotationalLimitMotor2_setHiLimit(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btRotationalLimitMotor2_setLoLimit(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btRotationalLimitMotor2_setMaxMotorForce(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btRotationalLimitMotor2_setMotorCFM(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btRotationalLimitMotor2_setMotorERP(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btRotationalLimitMotor2_setServoMotor(IntPtr obj, bool value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btRotationalLimitMotor2_setServoTarget(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btRotationalLimitMotor2_setSpringDamping(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btRotationalLimitMotor2_setSpringDampingLimited(IntPtr obj, bool value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btRotationalLimitMotor2_setSpringStiffness(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btRotationalLimitMotor2_setSpringStiffnessLimited(IntPtr obj, bool value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btRotationalLimitMotor2_setStopCFM(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btRotationalLimitMotor2_setStopERP(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btRotationalLimitMotor2_setTargetVelocity(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btRotationalLimitMotor2_testLimitValue(IntPtr obj, float test_value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btRotationalLimitMotor2_delete(IntPtr obj); } public class TranslationalLimitMotor2 : IDisposable { internal IntPtr _native; bool _preventDelete; internal TranslationalLimitMotor2(IntPtr native, bool preventDelete) { _native = native; _preventDelete = preventDelete; } public TranslationalLimitMotor2() { _native = btTranslationalLimitMotor2_new(); } public TranslationalLimitMotor2(TranslationalLimitMotor2 other) { _native = btTranslationalLimitMotor2_new2(other._native); } public bool IsLimited(int limitIndex) { return btTranslationalLimitMotor2_isLimited(_native, limitIndex); } public void TestLimitValue(int limitIndex, float testValue) { btTranslationalLimitMotor2_testLimitValue(_native, limitIndex, testValue); } public Vector3 Bounce { get { Vector3 value; btTranslationalLimitMotor2_getBounce(_native, out value); return value; } set { btTranslationalLimitMotor2_setBounce(_native, ref value); } } /* public IntArray CurrentLimit { get { return new IntArray(btTranslationalLimitMotor2_getCurrentLimit(_native), 3); } } */ public Vector3 CurrentLimitError { get { Vector3 value; btTranslationalLimitMotor2_getCurrentLimitError(_native, out value); return value; } set { btTranslationalLimitMotor2_setCurrentLimitError(_native, ref value); } } public Vector3 CurrentLimitErrorHi { get { Vector3 value; btTranslationalLimitMotor2_getCurrentLimitErrorHi(_native, out value); return value; } set { btTranslationalLimitMotor2_setCurrentLimitErrorHi(_native, ref value); } } public Vector3 CurrentLinearDiff { get { Vector3 value; btTranslationalLimitMotor2_getCurrentLinearDiff(_native, out value); return value; } set { btTranslationalLimitMotor2_setCurrentLinearDiff(_native, ref value); } } /* public BoolArray EnableMotor { get { return new BoolArray(btTranslationalLimitMotor2_getEnableMotor(_native), 3); } } public BoolArray EnableSpring { get { return new BoolArray(btTranslationalLimitMotor2_getEnableSpring(_native), 3); } } */ public Vector3 EquilibriumPoint { get { Vector3 value; btTranslationalLimitMotor2_getEquilibriumPoint(_native, out value); return value; } set { btTranslationalLimitMotor2_setEquilibriumPoint(_native, ref value); } } public Vector3 LowerLimit { get { Vector3 value; btTranslationalLimitMotor2_getLowerLimit(_native, out value); return value; } set { btTranslationalLimitMotor2_setLowerLimit(_native, ref value); } } public Vector3 MaxMotorForce { get { Vector3 value; btTranslationalLimitMotor2_getMaxMotorForce(_native, out value); return value; } set { btTranslationalLimitMotor2_setMaxMotorForce(_native, ref value); } } public Vector3 MotorCFM { get { Vector3 value; btTranslationalLimitMotor2_getMotorCFM(_native, out value); return value; } set { btTranslationalLimitMotor2_setMotorCFM(_native, ref value); } } public Vector3 MotorERP { get { Vector3 value; btTranslationalLimitMotor2_getMotorERP(_native, out value); return value; } set { btTranslationalLimitMotor2_setMotorERP(_native, ref value); } } /* public BoolArray ServoMotor { get { return new BoolArray(btTranslationalLimitMotor2_getServoMotor(_native)); } } */ public Vector3 ServoTarget { get { Vector3 value; btTranslationalLimitMotor2_getServoTarget(_native, out value); return value; } set { btTranslationalLimitMotor2_setServoTarget(_native, ref value); } } public Vector3 SpringDamping { get { Vector3 value; btTranslationalLimitMotor2_getSpringDamping(_native, out value); return value; } set { btTranslationalLimitMotor2_setSpringDamping(_native, ref value); } } /* public BoolArray SpringDampingLimited { get { return btTranslationalLimitMotor2_getSpringDampingLimited(_native); } } */ public Vector3 SpringStiffness { get { Vector3 value; btTranslationalLimitMotor2_getSpringStiffness(_native, out value); return value; } set { btTranslationalLimitMotor2_setSpringStiffness(_native, ref value); } } /* public BoolArray SpringStiffnessLimited { get { return btTranslationalLimitMotor2_getSpringStiffnessLimited(_native); } } */ public Vector3 StopCFM { get { Vector3 value; btTranslationalLimitMotor2_getStopCFM(_native, out value); return value; } set { btTranslationalLimitMotor2_setStopCFM(_native, ref value); } } public Vector3 StopERP { get { Vector3 value; btTranslationalLimitMotor2_getStopERP(_native, out value); return value; } set { btTranslationalLimitMotor2_setStopERP(_native, ref value); } } public Vector3 TargetVelocity { get { Vector3 value; btTranslationalLimitMotor2_getTargetVelocity(_native, out value); return value; } set { btTranslationalLimitMotor2_setTargetVelocity(_native, ref value); } } public Vector3 UpperLimit { get { Vector3 value; btTranslationalLimitMotor2_getUpperLimit(_native, out value); return value; } set { btTranslationalLimitMotor2_setUpperLimit(_native, ref value); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_native != IntPtr.Zero) { if (!_preventDelete) { btTranslationalLimitMotor2_delete(_native); } _native = IntPtr.Zero; } } ~TranslationalLimitMotor2() { Dispose(false); } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btTranslationalLimitMotor2_new(); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btTranslationalLimitMotor2_new2(IntPtr other); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_getBounce(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btTranslationalLimitMotor2_getCurrentLimit(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_getCurrentLimitError(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_getCurrentLimitErrorHi(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_getCurrentLinearDiff(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern IntPtr btTranslationalLimitMotor2_getEnableMotor(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern IntPtr btTranslationalLimitMotor2_getEnableSpring(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_getEquilibriumPoint(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_getLowerLimit(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_getMaxMotorForce(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_getMotorCFM(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_getMotorERP(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern IntPtr btTranslationalLimitMotor2_getServoMotor(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_getServoTarget(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_getSpringDamping(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern IntPtr btTranslationalLimitMotor2_getSpringDampingLimited(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_getSpringStiffness(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern IntPtr btTranslationalLimitMotor2_getSpringStiffnessLimited(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_getStopCFM(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_getStopERP(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_getTargetVelocity(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_getUpperLimit(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btTranslationalLimitMotor2_isLimited(IntPtr obj, int limitIndex); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_setBounce(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_setCurrentLimitError(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_setCurrentLimitErrorHi(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_setCurrentLinearDiff(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_setEquilibriumPoint(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_setLowerLimit(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_setMaxMotorForce(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_setMotorCFM(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_setMotorERP(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_setServoTarget(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_setSpringDamping(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_setSpringStiffness(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_setStopCFM(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_setStopERP(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_setTargetVelocity(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_setUpperLimit(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_testLimitValue(IntPtr obj, int limitIndex, float test_value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btTranslationalLimitMotor2_delete(IntPtr obj); } public class Generic6DofSpring2Constraint : TypedConstraint { RotationalLimitMotor2[] _angularLimits = new RotationalLimitMotor2[3]; TranslationalLimitMotor2 _linearLimits; internal Generic6DofSpring2Constraint(IntPtr native) : base(native) { } public Generic6DofSpring2Constraint(RigidBody rigidBodyA, RigidBody rigidBodyB, Matrix frameInA, Matrix frameInB) : base(btGeneric6DofSpring2Constraint_new(rigidBodyA._native, rigidBodyB._native, ref frameInA, ref frameInB)) { _rigidBodyA = rigidBodyA; _rigidBodyB = rigidBodyB; } public Generic6DofSpring2Constraint(RigidBody rigidBodyA, RigidBody rigidBodyB, Matrix frameInA, Matrix frameInB, RotateOrder rotOrder) : base(btGeneric6DofSpring2Constraint_new2(rigidBodyA._native, rigidBodyB._native, ref frameInA, ref frameInB, rotOrder)) { _rigidBodyA = rigidBodyA; _rigidBodyB = rigidBodyB; } public Generic6DofSpring2Constraint(RigidBody rigidBodyB, Matrix frameInB) : base(btGeneric6DofSpring2Constraint_new3(rigidBodyB._native, ref frameInB)) { _rigidBodyA = GetFixedBody(); _rigidBodyB = rigidBodyB; } public Generic6DofSpring2Constraint(RigidBody rigidBodyB, Matrix frameInB, RotateOrder rotOrder) : base(btGeneric6DofSpring2Constraint_new4(rigidBodyB._native, ref frameInB, rotOrder)) { _rigidBodyA = GetFixedBody(); _rigidBodyB = rigidBodyB; } public void CalculateTransforms(Matrix transA, Matrix transB) { btGeneric6DofSpring2Constraint_calculateTransforms(_native, ref transA, ref transB); } public void CalculateTransforms() { btGeneric6DofSpring2Constraint_calculateTransforms2(_native); } public void EnableMotor(int index, bool onOff) { btGeneric6DofSpring2Constraint_enableMotor(_native, index, onOff); } public void EnableSpring(int index, bool onOff) { btGeneric6DofSpring2Constraint_enableSpring(_native, index, onOff); } public float GetAngle(int axisIndex) { return btGeneric6DofSpring2Constraint_getAngle(_native, axisIndex); } public Vector3 GetAxis(int axisIndex) { Vector3 value; btGeneric6DofSpring2Constraint_getAxis(_native, axisIndex, out value); return value; } public float GetRelativePivotPosition(int axisIndex) { return btGeneric6DofSpring2Constraint_getRelativePivotPosition(_native, axisIndex); } public RotationalLimitMotor2 GetRotationalLimitMotor(int index) { if (_angularLimits[index] == null) { _angularLimits[index] = new RotationalLimitMotor2(btGeneric6DofSpring2Constraint_getRotationalLimitMotor(_native, index), true); } return _angularLimits[index]; } public bool IsLimited(int limitIndex) { return btGeneric6DofSpring2Constraint_isLimited(_native, limitIndex); } public void SetAxis(Vector3 axis1, Vector3 axis2) { btGeneric6DofSpring2Constraint_setAxis(_native, ref axis1, ref axis2); } public void SetBounce(int index, float bounce) { btGeneric6DofSpring2Constraint_setBounce(_native, index, bounce); } public void SetDamping(int index, float damping) { btGeneric6DofSpring2Constraint_setDamping(_native, index, damping); } public void SetDamping(int index, float damping, bool limitIfNeeded) { btGeneric6DofSpring2Constraint_setDamping2(_native, index, damping, limitIfNeeded); } public void SetEquilibriumPoint() { btGeneric6DofSpring2Constraint_setEquilibriumPoint(_native); } public void SetEquilibriumPoint(int index, float val) { btGeneric6DofSpring2Constraint_setEquilibriumPoint2(_native, index, val); } public void SetEquilibriumPoint(int index) { btGeneric6DofSpring2Constraint_setEquilibriumPoint3(_native, index); } public void SetFrames(Matrix frameA, Matrix frameB) { btGeneric6DofSpring2Constraint_setFrames(_native, ref frameA, ref frameB); } public void SetLimit(int axis, float lo, float hi) { btGeneric6DofSpring2Constraint_setLimit(_native, axis, lo, hi); } public void SetLimitReversed(int axis, float lo, float hi) { btGeneric6DofSpring2Constraint_setLimitReversed(_native, axis, lo, hi); } public void SetMaxMotorForce(int index, float force) { btGeneric6DofSpring2Constraint_setMaxMotorForce(_native, index, force); } public void SetServo(int index, bool onOff) { btGeneric6DofSpring2Constraint_setServo(_native, index, onOff); } public void SetServoTarget(int index, float target) { btGeneric6DofSpring2Constraint_setServoTarget(_native, index, target); } public void SetStiffness(int index, float stiffness) { btGeneric6DofSpring2Constraint_setStiffness(_native, index, stiffness); } public void SetStiffness(int index, float stiffness, bool limitIfNeeded) { btGeneric6DofSpring2Constraint_setStiffness2(_native, index, stiffness, limitIfNeeded); } public void SetTargetVelocity(int index, float velocity) { btGeneric6DofSpring2Constraint_setTargetVelocity(_native, index, velocity); } public Vector3 AngularLowerLimit { get { Vector3 value; btGeneric6DofSpring2Constraint_getAngularLowerLimit(_native, out value); return value; } set { btGeneric6DofSpring2Constraint_setAngularLowerLimit(_native, ref value); } } public Vector3 AngularLowerLimitReversed { get { Vector3 value; btGeneric6DofSpring2Constraint_getAngularLowerLimitReversed(_native, out value); return value; } set { btGeneric6DofSpring2Constraint_setAngularLowerLimitReversed(_native, ref value); } } public Vector3 AngularUpperLimit { get { Vector3 value; btGeneric6DofSpring2Constraint_getAngularUpperLimit(_native, out value); return value; } set { btGeneric6DofSpring2Constraint_setAngularUpperLimit(_native, ref value); } } public Vector3 AngularUpperLimitReversed { get { Vector3 value; btGeneric6DofSpring2Constraint_getAngularUpperLimitReversed(_native, out value); return value; } set { btGeneric6DofSpring2Constraint_setAngularUpperLimitReversed(_native, ref value); } } public Matrix CalculatedTransformA { get { Matrix value; btGeneric6DofSpring2Constraint_getCalculatedTransformA(_native, out value); return value; } } public Matrix CalculatedTransformB { get { Matrix value; btGeneric6DofSpring2Constraint_getCalculatedTransformB(_native, out value); return value; } } public Matrix FrameOffsetA { get { Matrix value; btGeneric6DofSpring2Constraint_getFrameOffsetA(_native, out value); return value; } } public Matrix FrameOffsetB { get { Matrix value; btGeneric6DofSpring2Constraint_getFrameOffsetB(_native, out value); return value; } } public Vector3 LinearLowerLimit { get { Vector3 value; btGeneric6DofSpring2Constraint_getLinearLowerLimit(_native, out value); return value; } set { btGeneric6DofSpring2Constraint_setLinearLowerLimit(_native, ref value); } } public Vector3 LinearUpperLimit { get { Vector3 value; btGeneric6DofSpring2Constraint_getLinearUpperLimit(_native, out value); return value; } set { btGeneric6DofSpring2Constraint_setLinearUpperLimit(_native, ref value); } } public RotateOrder RotationOrder { get { return btGeneric6DofSpring2Constraint_getRotationOrder(_native); } set { btGeneric6DofSpring2Constraint_setRotationOrder(_native, value); } } public TranslationalLimitMotor2 TranslationalLimitMotor { get { if (_linearLimits == null) { _linearLimits = new TranslationalLimitMotor2(btGeneric6DofSpring2Constraint_getTranslationalLimitMotor(_native), true); } return _linearLimits; } } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btGeneric6DofSpring2Constraint_new(IntPtr rbA, IntPtr rbB, [In] ref Matrix frameInA, [In] ref Matrix frameInB); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btGeneric6DofSpring2Constraint_new2(IntPtr rbA, IntPtr rbB, [In] ref Matrix frameInA, [In] ref Matrix frameInB, RotateOrder rotOrder); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btGeneric6DofSpring2Constraint_new3(IntPtr rbB, [In] ref Matrix frameInB); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btGeneric6DofSpring2Constraint_new4(IntPtr rbB, [In] ref Matrix frameInB, RotateOrder rotOrder); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_calculateTransforms(IntPtr obj, [In] ref Matrix transA, [In] ref Matrix transB); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_calculateTransforms2(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_enableMotor(IntPtr obj, int index, bool onOff); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_enableSpring(IntPtr obj, int index, bool onOff); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btGeneric6DofSpring2Constraint_getAngle(IntPtr obj, int axis_index); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_getAngularLowerLimit(IntPtr obj, [Out] out Vector3 angularLower); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_getAngularLowerLimitReversed(IntPtr obj, [Out] out Vector3 angularLower); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_getAngularUpperLimit(IntPtr obj, [Out] out Vector3 angularUpper); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_getAngularUpperLimitReversed(IntPtr obj, [Out] out Vector3 angularUpper); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_getAxis(IntPtr obj, int axis_index, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_getCalculatedTransformA(IntPtr obj, [Out] out Matrix value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_getCalculatedTransformB(IntPtr obj, [Out] out Matrix value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_getFrameOffsetA(IntPtr obj, [Out] out Matrix value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_getFrameOffsetB(IntPtr obj, [Out] out Matrix value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_getLinearLowerLimit(IntPtr obj, [Out] out Vector3 linearLower); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_getLinearUpperLimit(IntPtr obj, [Out] out Vector3 linearUpper); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btGeneric6DofSpring2Constraint_getRelativePivotPosition(IntPtr obj, int axis_index); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btGeneric6DofSpring2Constraint_getRotationalLimitMotor(IntPtr obj, int index); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern RotateOrder btGeneric6DofSpring2Constraint_getRotationOrder(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btGeneric6DofSpring2Constraint_getTranslationalLimitMotor(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btGeneric6DofSpring2Constraint_isLimited(IntPtr obj, int limitIndex); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_setAngularLowerLimit(IntPtr obj, [In] ref Vector3 angularLower); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_setAngularLowerLimitReversed(IntPtr obj, [In] ref Vector3 angularLower); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_setAngularUpperLimit(IntPtr obj, [In] ref Vector3 angularUpper); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_setAngularUpperLimitReversed(IntPtr obj, [In] ref Vector3 angularUpper); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_setAxis(IntPtr obj, [In] ref Vector3 axis1, [In] ref Vector3 axis2); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_setBounce(IntPtr obj, int index, float bounce); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_setDamping(IntPtr obj, int index, float damping); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_setDamping2(IntPtr obj, int index, float damping, bool limitIfNeeded); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_setEquilibriumPoint(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_setEquilibriumPoint2(IntPtr obj, int index, float val); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_setEquilibriumPoint3(IntPtr obj, int index); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_setFrames(IntPtr obj, [In] ref Matrix frameA, [In] ref Matrix frameB); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_setLimit(IntPtr obj, int axis, float lo, float hi); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_setLimitReversed(IntPtr obj, int axis, float lo, float hi); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_setLinearLowerLimit(IntPtr obj, [In] ref Vector3 linearLower); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_setLinearUpperLimit(IntPtr obj, [In] ref Vector3 linearUpper); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_setMaxMotorForce(IntPtr obj, int index, float force); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_setRotationOrder(IntPtr obj, RotateOrder order); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_setServo(IntPtr obj, int index, bool onOff); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_setServoTarget(IntPtr obj, int index, float target); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_setStiffness(IntPtr obj, int index, float stiffness); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_setStiffness2(IntPtr obj, int index, float stiffness, bool limitIfNeeded); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btGeneric6DofSpring2Constraint_setTargetVelocity(IntPtr obj, int index, float velocity); } [StructLayout(LayoutKind.Sequential)] internal unsafe struct Generic6DofSpring2ConstraintFloatData { public TypedConstraintFloatData TypeConstraintData; public TransformFloatData RigidBodyAFrame; public TransformFloatData RigidBodyBFrame; public Vector3FloatData LinearUpperLimit; public Vector3FloatData LinearLowerLimit; public Vector3FloatData LinearBounce; public Vector3FloatData LinearStopErp; public Vector3FloatData LinearStopCfm; public Vector3FloatData LinearMotorErp; public Vector3FloatData LinearMotorCfm; public Vector3FloatData LinearTargetVelocity; public Vector3FloatData LinearMaxMotorForce; public Vector3FloatData LinearServoTarget; public Vector3FloatData LinearSpringStiffness; public Vector3FloatData LinearSpringDamping; public Vector3FloatData LinearEquilibriumPoint; public fixed byte LinearEnableMotor[4]; public fixed byte LinearServoMotor[4]; public fixed byte LinearEnableSpring[4]; public fixed byte LinearSpringStiffnessLimited[4]; public fixed byte LinearSpringDampingLimited[4]; public int Padding; public Vector3FloatData AngularUpperLimit; public Vector3FloatData AngularLowerLimit; public Vector3FloatData AngularBounce; public Vector3FloatData AngularStopErp; public Vector3FloatData AngularStopCfm; public Vector3FloatData AngularMotorErp; public Vector3FloatData AngularMotorCfm; public Vector3FloatData AngularTargetVelocity; public Vector3FloatData AngularMaxMotorForce; public Vector3FloatData AngularServoTarget; public Vector3FloatData AngularSpringStiffness; public Vector3FloatData AngularSpringDamping; public Vector3FloatData AngularEquilibriumPoint; public fixed byte AngularEnableMotor[4]; public fixed byte AngularServoMotor[4]; public fixed byte AngularEnableSpring[4]; public fixed byte AngularSpringStiffnessLimited[4]; public fixed byte AngularSpringDampingLimited[4]; public int RotateOrder; public static int Offset(string fieldName) { return Marshal.OffsetOf(typeof(Generic6DofSpring2ConstraintFloatData), fieldName).ToInt32(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.Serialization; using System.Text; namespace IrcDotNet.Common.Collections { /// <summary> /// Represents a read-only collection of keys and values. /// </summary> /// <typeparam name="TKey">The type of the keys in the dictionary.</typeparam> /// <typeparam name="TValue">The type of the values in the dictionary.</typeparam> [Serializable()] [DebuggerDisplay("Count = {Count}")] public class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback { private IDictionary<TKey, TValue> dictionary; /// <summary> /// Initializes a new instance of the <see cref="ReadOnlyDictionary{TKey, TValue}"/> class. /// </summary> /// <param name="dictionary">The dictionary to wrap.</param> /// <exception cref="ArgumentNullException"><paramref name="dictionary"/> is <see langword="null"/>.</exception> public ReadOnlyDictionary(IDictionary<TKey, TValue> dictionary) { if (dictionary == null) throw new ArgumentNullException("dictionary"); this.dictionary = dictionary; } #region IDictionary<TKey, TValue> Members public ICollection<TKey> Keys { get { return this.dictionary.Keys; } } public ICollection<TValue> Values { get { return this.dictionary.Values; } } public TValue this[TKey key] { get { return this.dictionary[key]; } set { throw new NotSupportedException(); } } void IDictionary<TKey, TValue>.Add(TKey key, TValue value) { throw new NotSupportedException(); } bool IDictionary<TKey, TValue>.Remove(TKey key) { throw new NotSupportedException(); } public bool ContainsKey(TKey key) { return this.dictionary.ContainsKey(key); } public bool TryGetValue(TKey key, out TValue value) { return this.dictionary.TryGetValue(key, out value); } #endregion #region ICollection<KeyValuePair<TKey, TValue>> Members public int Count { get { return this.dictionary.Count; } } public bool IsReadOnly { get { return true; } } void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) { throw new NotSupportedException(); } bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) { throw new NotSupportedException(); } void ICollection<KeyValuePair<TKey, TValue>>.Clear() { throw new NotSupportedException(); } public bool Contains(KeyValuePair<TKey, TValue> item) { return this.dictionary.Contains(item); } public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { this.dictionary.CopyTo(array, arrayIndex); } #endregion #region IEnumerable<KeyValuePair<TKey, TValue>> Members public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return ((IEnumerable<KeyValuePair<TKey, TValue>>)this.dictionary).GetEnumerator(); } #endregion #region IDictionary Members ICollection IDictionary.Keys { get { return ((IDictionary)this.dictionary).Keys; } } ICollection IDictionary.Values { get { return ((IDictionary)this.dictionary).Values; } } bool IDictionary.IsFixedSize { get { return ((IDictionary)this.dictionary).IsFixedSize; } } bool IDictionary.IsReadOnly { get { return true; } } object IDictionary.this[object key] { get { return ((IDictionary)this.dictionary)[key]; } set { throw new NotSupportedException(); } } void IDictionary.Add(object key, object value) { throw new NotSupportedException(); } void IDictionary.Remove(object key) { throw new NotSupportedException(); } void IDictionary.Clear() { throw new NotSupportedException(); } bool IDictionary.Contains(object key) { return ((IDictionary)this.dictionary).Contains(key); } IDictionaryEnumerator IDictionary.GetEnumerator() { return ((IDictionary)this.dictionary).GetEnumerator(); } #endregion #region ICollection Members void ICollection.CopyTo(Array array, int index) { ((ICollection)this.dictionary).CopyTo(array, index); } int ICollection.Count { get { return ((ICollection)this.dictionary).Count; } } bool ICollection.IsSynchronized { get { return ((ICollection)this.dictionary).IsSynchronized; } } object ICollection.SyncRoot { get { return ((ICollection)this.dictionary).SyncRoot; } } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)this.dictionary).GetEnumerator(); } #endregion #region ISerializable Members void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { ((ISerializable)this.dictionary).GetObjectData(info, context); } #endregion #region IDeserializationCallback Members void IDeserializationCallback.OnDeserialization(object sender) { ((IDeserializationCallback)this.dictionary).OnDeserialization(sender); } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces { public class TestHostProject { private readonly HostLanguageServices _languageServices; private readonly ProjectId _id; private readonly string _name; private readonly IEnumerable<ProjectReference> _projectReferences; private readonly IEnumerable<MetadataReference> _metadataReferences; private readonly IEnumerable<AnalyzerReference> _analyzerReferences; private readonly CompilationOptions _compilationOptions; private readonly ParseOptions _parseOptions; private readonly bool _isSubmission; private readonly string _assemblyName; private readonly Type _hostObjectType; private readonly VersionStamp _version; private readonly string _filePath; private readonly string _outputFilePath; public IEnumerable<TestHostDocument> Documents; public IEnumerable<TestHostDocument> AdditionalDocuments; public string Name { get { return _name; } } public IEnumerable<ProjectReference> ProjectReferences { get { return _projectReferences; } } public IEnumerable<MetadataReference> MetadataReferences { get { return _metadataReferences; } } public IEnumerable<AnalyzerReference> AnalyzerReferences { get { return _analyzerReferences; } } public CompilationOptions CompilationOptions { get { return _compilationOptions; } } public ParseOptions ParseOptions { get { return _parseOptions; } } public ProjectId Id { get { return _id; } } public bool IsSubmission { get { return _isSubmission; } } public string AssemblyName { get { return _assemblyName; } } public Type HostObjectType { get { return _hostObjectType; } } public VersionStamp Version { get { return _version; } } public string FilePath { get { return _filePath; } } public string OutputFilePath { get { return _outputFilePath; } } internal TestHostProject( HostLanguageServices languageServices, CompilationOptions compilationOptions, ParseOptions parseOptions, params MetadataReference[] references) : this(languageServices, compilationOptions, parseOptions, "Test", references) { } internal TestHostProject( HostLanguageServices languageServices, CompilationOptions compilationOptions, ParseOptions parseOptions, string assemblyName, params MetadataReference[] references) : this(languageServices, compilationOptions, parseOptions, assemblyName: assemblyName, projectName: assemblyName, references: references, documents: SpecializedCollections.EmptyArray<TestHostDocument>()) { } internal TestHostProject( HostLanguageServices languageServices, CompilationOptions compilationOptions, ParseOptions parseOptions, string assemblyName, string projectName, IList<MetadataReference> references, IList<TestHostDocument> documents, IList<TestHostDocument> additionalDocuments = null, Type hostObjectType = null, bool isSubmission = false, string filePath = null, IList<AnalyzerReference> analyzerReferences = null) { _assemblyName = assemblyName; _name = projectName; _id = ProjectId.CreateNewId(debugName: this.AssemblyName); _languageServices = languageServices; _compilationOptions = compilationOptions; _parseOptions = parseOptions; _metadataReferences = references; _analyzerReferences = analyzerReferences ?? SpecializedCollections.EmptyEnumerable<AnalyzerReference>(); this.Documents = documents; this.AdditionalDocuments = additionalDocuments ?? SpecializedCollections.EmptyEnumerable<TestHostDocument>(); _projectReferences = SpecializedCollections.EmptyEnumerable<ProjectReference>(); _isSubmission = isSubmission; _hostObjectType = hostObjectType; _version = VersionStamp.Create(); _filePath = filePath; _outputFilePath = GetTestOutputFilePath(filePath); } public TestHostProject( TestWorkspace workspace, TestHostDocument document, string name = null, string language = null, CompilationOptions compilationOptions = null, ParseOptions parseOptions = null, IEnumerable<TestHostProject> projectReferences = null, IEnumerable<MetadataReference> metadataReferences = null, IEnumerable<AnalyzerReference> analyzerReferences = null, string assemblyName = null) : this(workspace, name, language, compilationOptions, parseOptions, SpecializedCollections.SingletonEnumerable(document), SpecializedCollections.EmptyEnumerable<TestHostDocument>(), projectReferences, metadataReferences, analyzerReferences, assemblyName) { } public TestHostProject( TestWorkspace workspace, string name = null, string language = null, CompilationOptions compilationOptions = null, ParseOptions parseOptions = null, IEnumerable<TestHostDocument> documents = null, IEnumerable<TestHostDocument> additionalDocuments = null, IEnumerable<TestHostProject> projectReferences = null, IEnumerable<MetadataReference> metadataReferences = null, IEnumerable<AnalyzerReference> analyzerReferences = null, string assemblyName = null) { _name = name ?? "TestProject"; _id = ProjectId.CreateNewId(debugName: this.Name); language = language ?? LanguageNames.CSharp; _languageServices = workspace.Services.GetLanguageServices(language); _compilationOptions = compilationOptions ?? this.LanguageServiceProvider.GetService<ICompilationFactoryService>().GetDefaultCompilationOptions(); _parseOptions = parseOptions ?? this.LanguageServiceProvider.GetService<ISyntaxTreeFactoryService>().GetDefaultParseOptions(); this.Documents = documents ?? SpecializedCollections.EmptyEnumerable<TestHostDocument>(); this.AdditionalDocuments = additionalDocuments ?? SpecializedCollections.EmptyEnumerable<TestHostDocument>(); _projectReferences = projectReferences != null ? projectReferences.Select(p => new ProjectReference(p.Id)) : SpecializedCollections.EmptyEnumerable<ProjectReference>(); _metadataReferences = metadataReferences ?? new MetadataReference[] { TestReferences.NetFx.v4_0_30319.mscorlib }; _analyzerReferences = analyzerReferences ?? SpecializedCollections.EmptyEnumerable<AnalyzerReference>(); _assemblyName = assemblyName ?? "TestProject"; _version = VersionStamp.Create(); _outputFilePath = GetTestOutputFilePath(_filePath); if (documents != null) { foreach (var doc in documents) { doc.SetProject(this); } } if (additionalDocuments != null) { foreach (var doc in additionalDocuments) { doc.SetProject(this); } } } internal void SetSolution(TestHostSolution solution) { // set up back pointer to this project. if (this.Documents != null) { foreach (var doc in this.Documents) { doc.SetProject(this); } foreach (var doc in this.AdditionalDocuments) { doc.SetProject(this); } } } internal void AddDocument(TestHostDocument document) { this.Documents = this.Documents.Concat(new TestHostDocument[] { document }); document.SetProject(this); } internal void RemoveDocument(TestHostDocument document) { this.Documents = this.Documents.Where(d => d != document); } internal void AddAdditionalDocument(TestHostDocument document) { this.AdditionalDocuments = this.AdditionalDocuments.Concat(new TestHostDocument[] { document }); document.SetProject(this); } internal void RemoveAdditionalDocument(TestHostDocument document) { this.AdditionalDocuments = this.AdditionalDocuments.Where(d => d != document); } public string Language { get { return _languageServices.Language; } } internal HostLanguageServices LanguageServiceProvider { get { return _languageServices; } } public ProjectInfo ToProjectInfo() { return ProjectInfo.Create( this.Id, this.Version, this.Name, this.AssemblyName, this.Language, this.FilePath, this.OutputFilePath, this.CompilationOptions, this.ParseOptions, this.Documents.Select(d => d.ToDocumentInfo()), this.ProjectReferences, this.MetadataReferences, this.AnalyzerReferences, this.AdditionalDocuments.Select(d => d.ToDocumentInfo()), this.IsSubmission, this.HostObjectType); } // It is identical with the internal extension method 'GetDefaultExtension' defined in OutputKind.cs. // However, we could not apply for InternalVisibleToTest due to other parts of this assembly // complaining about CS0507: "cannot change access modifiers when overriding 'access' inherited member". private static string GetDefaultExtension(OutputKind kind) { switch (kind) { case OutputKind.ConsoleApplication: case OutputKind.WindowsApplication: case OutputKind.WindowsRuntimeApplication: return ".exe"; case OutputKind.DynamicallyLinkedLibrary: return ".dll"; case OutputKind.NetModule: return ".netmodule"; case OutputKind.WindowsRuntimeMetadata: return ".winmdobj"; default: return ".dll"; } } private string GetTestOutputFilePath(string filepath) { string outputFilePath = @"Z:\"; try { outputFilePath = Path.GetDirectoryName(_filePath); } catch (ArgumentException) { } if (string.IsNullOrEmpty(outputFilePath)) { outputFilePath = @"Z:\"; } return this.CompilationOptions == null ? "" : Path.Combine(outputFilePath, this.AssemblyName + GetDefaultExtension(this.CompilationOptions.OutputKind)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Xml; using System.Xml.Linq; using System.Xml.Serialization; using Xunit; namespace System.ServiceModel.Syndication.Tests { public class Atom10ItemFormatterTests { [Fact] public void Ctor_Default() { var formatter = new Formatter(); Assert.Null(formatter.Item); Assert.Equal(typeof(SyndicationItem), formatter.ItemTypeEntryPoint); Assert.True(formatter.PreserveAttributeExtensions); Assert.True(formatter.PreserveElementExtensions); Assert.Equal("Atom10", formatter.Version); } [Fact] public void Ctor_GenericDefault() { var formatter = new GenericFormatter<SyndicationItem>(); Assert.Null(formatter.Item); Assert.Equal(typeof(SyndicationItem), formatter.ItemTypeEntryPoint); Assert.True(formatter.PreserveAttributeExtensions); Assert.True(formatter.PreserveElementExtensions); Assert.Equal("Atom10", formatter.Version); } [Fact] public void Ctor_SyndicationItem() { var item = new SyndicationItem(); var formatter = new Formatter(item); Assert.Equal(typeof(SyndicationItem), formatter.ItemTypeEntryPoint); Assert.Same(item, formatter.Item); Assert.True(formatter.PreserveAttributeExtensions); Assert.True(formatter.PreserveElementExtensions); Assert.Equal("Atom10", formatter.Version); } [Fact] public void Ctor_GenericSyndicationItem() { var item = new SyndicationItem(); var formatter = new GenericFormatter<SyndicationItem>(item); Assert.Same(item, formatter.Item); Assert.Equal(typeof(SyndicationItem), formatter.ItemTypeEntryPoint); Assert.True(formatter.PreserveAttributeExtensions); Assert.True(formatter.PreserveElementExtensions); Assert.Equal("Atom10", formatter.Version); } [Fact] public void Ctor_NullItemToWrite_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("itemToWrite", () => new Atom10ItemFormatter((SyndicationItem)null)); AssertExtensions.Throws<ArgumentNullException>("itemToWrite", () => new Atom10ItemFormatter<SyndicationItem>(null)); } [Theory] [InlineData(typeof(SyndicationItem))] [InlineData(typeof(SyndicationItemSubclass))] public void Ctor_Type(Type itemTypeToCreate) { var formatter = new Formatter(itemTypeToCreate); Assert.Null(formatter.Item); Assert.Equal(itemTypeToCreate, formatter.ItemTypeEntryPoint); Assert.True(formatter.PreserveAttributeExtensions); Assert.True(formatter.PreserveElementExtensions); Assert.Equal("Atom10", formatter.Version); } [Fact] public void Ctor_NullItemTypeToCreate_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("itemTypeToCreate", () => new Atom10ItemFormatter((Type)null)); } [Fact] public void Ctor_InvalidItemTypeToCreate_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>("itemTypeToCreate", () => new Atom10ItemFormatter(typeof(int))); } [Fact] public void GetSchema_Invoke_ReturnsNull() { IXmlSerializable formatter = new Atom10ItemFormatter(); Assert.Null(formatter.GetSchema()); } public static IEnumerable<object[]> WriteTo_TestData() { // Full item. SyndicationPerson CreatePerson(string prefix) { var person = new SyndicationPerson(); person.AttributeExtensions.Add(new XmlQualifiedName(prefix + "_name1"), null); person.AttributeExtensions.Add(new XmlQualifiedName(prefix + "_name2", prefix + "_namespace"), ""); person.AttributeExtensions.Add(new XmlQualifiedName(prefix + "_name3", prefix + "_namespace"), prefix + "_value"); person.AttributeExtensions.Add(new XmlQualifiedName(prefix + "_name4", "xmlns"), ""); person.ElementExtensions.Add(new ExtensionObject { Value = 10 }); person.Email = prefix + "_email"; person.Name = prefix + "_name"; person.Uri = prefix + "_uri"; return person; } TextSyndicationContent CreateContent(string prefix) { var content = new TextSyndicationContent(prefix + "_title", TextSyndicationContentKind.Html); content.AttributeExtensions.Add(new XmlQualifiedName(prefix + "_name1"), null); content.AttributeExtensions.Add(new XmlQualifiedName(prefix + "_name2", prefix + "_namespace"), ""); content.AttributeExtensions.Add(new XmlQualifiedName(prefix + "_name3", prefix + "_namespace"), prefix + "_value"); content.AttributeExtensions.Add(new XmlQualifiedName(prefix + "_name4", "xmlns"), ""); return content; } var fullSyndicationCategory = new SyndicationCategory(); fullSyndicationCategory.AttributeExtensions.Add(new XmlQualifiedName("category_name1"), null); fullSyndicationCategory.AttributeExtensions.Add(new XmlQualifiedName("category_name2", "category_namespace"), ""); fullSyndicationCategory.AttributeExtensions.Add(new XmlQualifiedName("category_name3", "category_namespace"), "category_value"); fullSyndicationCategory.AttributeExtensions.Add(new XmlQualifiedName("category_name4", "xmlns"), ""); fullSyndicationCategory.ElementExtensions.Add(new ExtensionObject { Value = 10 }); fullSyndicationCategory.Label = "category_label"; fullSyndicationCategory.Name = "category_name"; fullSyndicationCategory.Scheme = "category_scheme"; var attributeSyndicationCategory = new SyndicationCategory { Name = "name", Label = "label", Scheme = "scheme" }; attributeSyndicationCategory.AttributeExtensions.Add(new XmlQualifiedName("term"), "term_value"); attributeSyndicationCategory.AttributeExtensions.Add(new XmlQualifiedName("label"), "label_value"); attributeSyndicationCategory.AttributeExtensions.Add(new XmlQualifiedName("scheme"), "scheme_value"); var fullSyndicationLink = new SyndicationLink(); fullSyndicationLink.AttributeExtensions.Add(new XmlQualifiedName("link_name1"), null); fullSyndicationLink.AttributeExtensions.Add(new XmlQualifiedName("link_name2", "link_namespace"), ""); fullSyndicationLink.AttributeExtensions.Add(new XmlQualifiedName("link_name3", "link_namespace"), "link_value"); fullSyndicationLink.AttributeExtensions.Add(new XmlQualifiedName("link_name4", "xmlns"), ""); fullSyndicationLink.BaseUri = new Uri("http://link_url.com"); fullSyndicationLink.ElementExtensions.Add(new ExtensionObject { Value = 10 }); fullSyndicationLink.Length = 10; fullSyndicationLink.MediaType = "link_mediaType"; fullSyndicationLink.RelationshipType = "link_relationshipType"; fullSyndicationLink.Title = "link_title"; fullSyndicationLink.Uri = new Uri("http://link_uri.com"); var attributeSyndicationLink = new SyndicationLink { RelationshipType = "link_relationshipType", MediaType = "link_mediaType", Title = "link_title", Length = 10, Uri = new Uri("http://link_uri.com") }; attributeSyndicationLink.AttributeExtensions.Add(new XmlQualifiedName("rel"), "rel_value"); attributeSyndicationLink.AttributeExtensions.Add(new XmlQualifiedName("type"), "type_value"); attributeSyndicationLink.AttributeExtensions.Add(new XmlQualifiedName("title"), "title_value"); attributeSyndicationLink.AttributeExtensions.Add(new XmlQualifiedName("length"), "100"); attributeSyndicationLink.AttributeExtensions.Add(new XmlQualifiedName("href"), "href_value"); var fullSyndicationItem = new SyndicationItem(); fullSyndicationItem.AttributeExtensions.Add(new XmlQualifiedName("item_name1"), null); fullSyndicationItem.AttributeExtensions.Add(new XmlQualifiedName("item_name2", "item_namespace"), ""); fullSyndicationItem.AttributeExtensions.Add(new XmlQualifiedName("item_name3", "item_namespace"), "item_value"); fullSyndicationItem.AttributeExtensions.Add(new XmlQualifiedName("item_name4", "xmlns"), ""); fullSyndicationItem.Authors.Add(new SyndicationPerson()); fullSyndicationItem.Authors.Add(CreatePerson("author")); fullSyndicationItem.BaseUri = new Uri("/relative", UriKind.Relative); fullSyndicationItem.Categories.Add(new SyndicationCategory()); fullSyndicationItem.Categories.Add(fullSyndicationCategory); fullSyndicationItem.Categories.Add(attributeSyndicationCategory); fullSyndicationItem.Content = CreateContent("content"); fullSyndicationItem.Contributors.Add(new SyndicationPerson()); fullSyndicationItem.Contributors.Add(CreatePerson("contributor")); fullSyndicationItem.Copyright = CreateContent("copyright"); fullSyndicationItem.ElementExtensions.Add(new ExtensionObject { Value = 10 }); fullSyndicationItem.Id = "id"; fullSyndicationItem.LastUpdatedTime = DateTimeOffset.MinValue.AddTicks(100); fullSyndicationItem.Links.Add(new SyndicationLink()); fullSyndicationItem.Links.Add(fullSyndicationLink); fullSyndicationItem.Links.Add(attributeSyndicationLink); fullSyndicationItem.PublishDate = DateTimeOffset.MinValue.AddTicks(200); fullSyndicationItem.Summary = CreateContent("summary"); fullSyndicationItem.Title = CreateContent("title"); yield return new object[] { fullSyndicationItem, @"<entry xml:base=""/relative"" item_name1="""" d1p1:item_name2="""" d1p1:item_name3=""item_value"" d1p2:item_name4="""" xmlns:d1p2=""xmlns"" xmlns:d1p1=""item_namespace"" xmlns=""http://www.w3.org/2005/Atom""> <id>id</id> <title type=""html"" title_name1="""" d2p1:title_name2="""" d2p1:title_name3=""title_value"" d1p2:title_name4="""" xmlns:d2p1=""title_namespace"">title_title</title> <summary type=""html"" summary_name1="""" d2p1:summary_name2="""" d2p1:summary_name3=""summary_value"" d1p2:summary_name4="""" xmlns:d2p1=""summary_namespace"">summary_title</summary> <published>0001-01-01T00:00:00Z</published> <updated>0001-01-01T00:00:00Z</updated> <author /> <author author_name1="""" d2p1:author_name2="""" d2p1:author_name3=""author_value"" d1p2:author_name4="""" xmlns:d2p1=""author_namespace""> <name>author_name</name> <uri>author_uri</uri> <email>author_email</email> <Atom10ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests""> <Value>10</Value> </Atom10ItemFormatterTests.ExtensionObject> </author> <contributor /> <contributor contributor_name1="""" d2p1:contributor_name2="""" d2p1:contributor_name3=""contributor_value"" d1p2:contributor_name4="""" xmlns:d2p1=""contributor_namespace""> <name>contributor_name</name> <uri>contributor_uri</uri> <email>contributor_email</email> <Atom10ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests""> <Value>10</Value> </Atom10ItemFormatterTests.ExtensionObject> </contributor> <link href="""" /> <link xml:base=""http://link_url.com/"" link_name1="""" d2p1:link_name2="""" d2p1:link_name3=""link_value"" d1p2:link_name4="""" rel=""link_relationshipType"" type=""link_mediaType"" title=""link_title"" length=""10"" href=""http://link_uri.com/"" xmlns:d2p1=""link_namespace""> <Atom10ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests""> <Value>10</Value> </Atom10ItemFormatterTests.ExtensionObject> </link> <link rel=""rel_value"" type=""type_value"" title=""title_value"" length=""100"" href=""href_value"" /> <category term="""" /> <category category_name1="""" d2p1:category_name2="""" d2p1:category_name3=""category_value"" d1p2:category_name4="""" term=""category_name"" label=""category_label"" scheme=""category_scheme"" xmlns:d2p1=""category_namespace""> <Atom10ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests""> <Value>10</Value> </Atom10ItemFormatterTests.ExtensionObject> </category> <category term=""term_value"" label=""label_value"" scheme=""scheme_value"" /> <content type=""html"" content_name1="""" d2p1:content_name2="""" d2p1:content_name3=""content_value"" d1p2:content_name4="""" xmlns:d2p1=""content_namespace"">content_title</content> <rights type=""html"" copyright_name1="""" d2p1:copyright_name2="""" d2p1:copyright_name3=""copyright_value"" d1p2:copyright_name4="""" xmlns:d2p1=""copyright_namespace"">copyright_title</rights> <Atom10ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests""> <Value>10</Value> </Atom10ItemFormatterTests.ExtensionObject> </entry>" }; } [Theory] [MemberData(nameof(WriteTo_TestData))] public void WriteTo_HasItem_SerializesExpected(SyndicationItem item, string expected) { var formatter = new Atom10ItemFormatter(item); CompareHelper.AssertEqualWriteOutput(expected, writer => formatter.WriteTo(writer)); CompareHelper.AssertEqualWriteOutput(expected, writer => item.SaveAsAtom10(writer)); CompareHelper.AssertEqualWriteOutput(expected, writer => { writer.WriteStartElement("entry", "http://www.w3.org/2005/Atom"); ((IXmlSerializable)formatter).WriteXml(writer); writer.WriteEndElement(); }); var genericFormatter = new Atom10ItemFormatter<SyndicationItem>(item); CompareHelper.AssertEqualWriteOutput(expected, writer => formatter.WriteTo(writer)); CompareHelper.AssertEqualWriteOutput(expected, writer => item.SaveAsAtom10(writer)); CompareHelper.AssertEqualWriteOutput(expected, writer => { writer.WriteStartElement("entry", "http://www.w3.org/2005/Atom"); ((IXmlSerializable)genericFormatter).WriteXml(writer); writer.WriteEndElement(); }); } [Fact] public void WriteTo_EmptyItem_SerializesExpected() { var formatter = new Atom10ItemFormatter(new SyndicationItem()); var stringBuilder = new StringBuilder(); using (XmlWriter writer = XmlWriter.Create(stringBuilder)) { formatter.WriteTo(writer); } using (var stringReader = new StringReader(stringBuilder.ToString())) { XElement element = XElement.Load(stringReader); Assert.Equal("entry", element.Name.LocalName); Assert.Equal("http://www.w3.org/2005/Atom", element.Attribute("xmlns").Value); XElement[] elements = element.Elements().ToArray(); Assert.Equal(3, elements.Length); Assert.Equal("id", elements[0].Name.LocalName); Assert.StartsWith("uuid:", elements[0].Value); Assert.Equal("title", elements[1].Name.LocalName); Assert.Equal("text", elements[1].Attribute("type").Value); Assert.Empty(elements[1].Value); Assert.Equal("updated", elements[2].Name.LocalName); DateTimeOffset now = DateTimeOffset.UtcNow; Assert.True(now > DateTimeOffset.ParseExact(elements[2].Value, "yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture)); } } [Fact] public void WriteTo_NullWriter_ThrowsArgumentNullException() { var formatter = new Atom10ItemFormatter(new SyndicationItem()); AssertExtensions.Throws<ArgumentNullException>("writer", () => formatter.WriteTo(null)); } [Fact] public void WriteTo_NoItem_ThrowsInvalidOperationException() { using (var stringWriter = new StringWriter()) using (var writer = XmlWriter.Create(stringWriter)) { var formatter = new Atom10ItemFormatter(); Assert.Throws<InvalidOperationException>(() => formatter.WriteTo(writer)); } } [Fact] public void WriteXml_NullWriter_ThrowsArgumentNullException() { IXmlSerializable formatter = new Atom10ItemFormatter(); AssertExtensions.Throws<ArgumentNullException>("writer", () => formatter.WriteXml(null)); } [Fact] public void WriteXml_NoItem_ThrowsInvalidOperationException() { using (var stringWriter = new StringWriter()) using (var writer = XmlWriter.Create(stringWriter)) { IXmlSerializable formatter = new Atom10ItemFormatter(); Assert.Throws<InvalidOperationException>(() => formatter.WriteXml(writer)); } } public static IEnumerable<object[]> CanRead_TestData() { yield return new object[] { @"<entry />", false }; yield return new object[] { @"<entry xmlns=""different"" />", false }; yield return new object[] { @"<different xmlns=""http://www.w3.org/2005/Atom"" />", false }; yield return new object[] { @"<entry xmlns=""http://www.w3.org/2005/Atom"" />", true }; yield return new object[] { @"<entry xmlns=""http://www.w3.org/2005/Atom""></entry>", true }; } [Theory] [MemberData(nameof(CanRead_TestData))] public void CanRead_ValidReader_ReturnsExpected(string xmlString, bool expected) { using (var stringReader = new StringReader(xmlString)) using (XmlReader reader = XmlReader.Create(stringReader)) { var formatter = new Atom10ItemFormatter(); Assert.Equal(expected, formatter.CanRead(reader)); } } [Fact] public void CanRead_NullReader_ThrowsArgumentNullException() { var formatter = new Atom10ItemFormatter(); AssertExtensions.Throws<ArgumentNullException>("reader", () => formatter.CanRead(null)); } [Theory] [InlineData(true, true)] [InlineData(false, false)] public void Read_FullItem_ReturnsExpected(bool preserveAttributeExtensions, bool preserveElementExtensions) { string xmlString = @"<entry xml:base=""/relative"" item_name1="""" d1p1:item_name2="""" d1p1:item_name3=""item_value"" d1p2:item_name4="""" xmlns:d1p2=""xmlns"" xmlns:d1p1=""item_namespace"" xmlns=""http://www.w3.org/2005/Atom""> <id>id</id> <title type=""html"" title_name1="""" d2p1:title_name2="""" d2p1:title_name3=""title_value"" d1p2:title_name4="""" xmlns:d2p1=""title_namespace"">title_title</title> <summary type=""html"" summary_name1="""" d2p1:summary_name2="""" d2p1:summary_name3=""summary_value"" d1p2:summary_name4="""" xmlns:d2p1=""summary_namespace"">summary_title</summary> <published>0001-01-01T00:00:00Z</published> <updated>0001-01-01T00:00:00Z</updated> <author /> <author></author> <author author_name1="""" d2p1:author_name2="""" d2p1:author_name3=""author_value"" d1p2:author_name4="""" xmlns:d2p1=""author_namespace""> <name>author_name</name> <uri>author_uri</uri> <email>author_email</email> <Atom10ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests""> <Value>10</Value> </Atom10ItemFormatterTests.ExtensionObject> </author> <contributor /> <contributor></contributor> <contributor contributor_name1="""" d2p1:contributor_name2="""" d2p1:contributor_name3=""contributor_value"" d1p2:contributor_name4="""" xmlns:d2p1=""contributor_namespace""> <name>contributor_name</name> <uri>contributor_uri</uri> <email>contributor_email</email> <Atom10ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests""> <Value>10</Value> </Atom10ItemFormatterTests.ExtensionObject> </contributor> <link /> <link></link> <link href="""" /> <link xml:base=""http://link_url.com/"" link_name1="""" d2p1:link_name2="""" d2p1:link_name3=""link_value"" d1p2:link_name4="""" rel=""link_relationshipType"" type=""link_mediaType"" title=""link_title"" length=""10"" href=""http://link_uri.com/"" xmlns:d2p1=""link_namespace""> <Atom10ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests""> <Value>10</Value> </Atom10ItemFormatterTests.ExtensionObject> </link> <category /> <category></category> <category term="""" /> <category category_name1="""" d2p1:category_name2="""" d2p1:category_name3=""category_value"" d1p2:category_name4="""" term=""category_name"" label=""category_label"" scheme=""category_scheme"" xmlns:d2p1=""category_namespace""> <Atom10ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests""> <Value>10</Value> </Atom10ItemFormatterTests.ExtensionObject> </category> <content type=""html"" content_name1="""" d2p1:content_name2="""" d2p1:content_name3=""content_value"" d1p2:content_name4="""" xmlns:d2p1=""content_namespace"">content_title</content> <rights type=""html"" copyright_name1="""" d2p1:copyright_name2="""" d2p1:copyright_name3=""copyright_value"" d1p2:copyright_name4="""" xmlns:d2p1=""copyright_namespace"">copyright_title</rights> <Atom10ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests""> <Value>10</Value> </Atom10ItemFormatterTests.ExtensionObject> </entry>"; VerifyRead(xmlString, preserveAttributeExtensions, preserveElementExtensions, item => { if (preserveAttributeExtensions) { Assert.Equal(4, item.AttributeExtensions.Count); Assert.Equal("", item.AttributeExtensions[new XmlQualifiedName("item_name1")]); Assert.Equal("", item.AttributeExtensions[new XmlQualifiedName("item_name2", "item_namespace")]); Assert.Equal("item_value", item.AttributeExtensions[new XmlQualifiedName("item_name3", "item_namespace")]); Assert.Equal("", item.AttributeExtensions[new XmlQualifiedName("item_name4", "xmlns")]); } else { Assert.Empty(item.AttributeExtensions); } Assert.Equal(3, item.Authors.Count); SyndicationPerson firstAuthor = item.Authors[0]; Assert.Empty(firstAuthor.AttributeExtensions); Assert.Empty(firstAuthor.ElementExtensions); Assert.Null(firstAuthor.Email); Assert.Null(firstAuthor.Name); Assert.Null(firstAuthor.Uri); SyndicationPerson secondAuthor = item.Authors[1]; Assert.Empty(secondAuthor.AttributeExtensions); Assert.Empty(secondAuthor.ElementExtensions); Assert.Null(secondAuthor.Email); Assert.Null(secondAuthor.Name); Assert.Null(secondAuthor.Uri); SyndicationPerson thirdAuthor = item.Authors[2]; if (preserveAttributeExtensions) { Assert.Equal(4, thirdAuthor.AttributeExtensions.Count); Assert.Equal("", thirdAuthor.AttributeExtensions[new XmlQualifiedName("author_name1")]); Assert.Equal("", thirdAuthor.AttributeExtensions[new XmlQualifiedName("author_name2", "author_namespace")]); Assert.Equal("author_value", thirdAuthor.AttributeExtensions[new XmlQualifiedName("author_name3", "author_namespace")]); Assert.Equal("", thirdAuthor.AttributeExtensions[new XmlQualifiedName("author_name4", "xmlns")]); } else { Assert.Empty(thirdAuthor.AttributeExtensions); } if (preserveElementExtensions) { Assert.Equal(1, thirdAuthor.ElementExtensions.Count); Assert.Equal(10, thirdAuthor.ElementExtensions[0].GetObject<ExtensionObject>().Value); } else { Assert.Empty(thirdAuthor.ElementExtensions); } Assert.Equal("author_email", thirdAuthor.Email); Assert.Equal("author_name", thirdAuthor.Name); Assert.Equal("author_uri", thirdAuthor.Uri); Assert.Equal(new Uri("/relative", UriKind.Relative), item.BaseUri); Assert.Equal(4, item.Categories.Count); SyndicationCategory firstCategory = item.Categories[0]; Assert.Empty(firstCategory.AttributeExtensions); Assert.Empty(firstCategory.ElementExtensions); Assert.Null(firstCategory.Name); Assert.Null(firstCategory.Scheme); Assert.Null(firstCategory.Label); SyndicationCategory secondCategory = item.Categories[1]; Assert.Empty(secondCategory.AttributeExtensions); Assert.Empty(secondCategory.ElementExtensions); Assert.Null(secondCategory.Name); Assert.Null(secondCategory.Scheme); Assert.Null(secondCategory.Label); SyndicationCategory thircategory = item.Categories[2]; Assert.Empty(thircategory.AttributeExtensions); Assert.Empty(thircategory.ElementExtensions); Assert.Empty(thircategory.Name); Assert.Null(thircategory.Scheme); Assert.Null(thircategory.Label); SyndicationCategory fourthCategory = item.Categories[3]; if (preserveAttributeExtensions) { Assert.Equal(4, fourthCategory.AttributeExtensions.Count); Assert.Equal("", fourthCategory.AttributeExtensions[new XmlQualifiedName("category_name1")]); Assert.Equal("", fourthCategory.AttributeExtensions[new XmlQualifiedName("category_name2", "category_namespace")]); Assert.Equal("category_value", fourthCategory.AttributeExtensions[new XmlQualifiedName("category_name3", "category_namespace")]); Assert.Equal("", fourthCategory.AttributeExtensions[new XmlQualifiedName("category_name4", "xmlns")]); } else { Assert.Empty(fourthCategory.AttributeExtensions); } if (preserveElementExtensions) { Assert.Equal(1, fourthCategory.ElementExtensions.Count); Assert.Equal(10, fourthCategory.ElementExtensions[0].GetObject<ExtensionObject>().Value); } else { Assert.Empty(fourthCategory.ElementExtensions); } Assert.Equal("category_name", fourthCategory.Name); Assert.Equal("category_scheme", fourthCategory.Scheme); Assert.Equal("category_label", fourthCategory.Label); TextSyndicationContent content = Assert.IsType<TextSyndicationContent>(item.Content); if (preserveAttributeExtensions) { Assert.Equal(4, content.AttributeExtensions.Count); Assert.Equal("", content.AttributeExtensions[new XmlQualifiedName("content_name1")]); Assert.Equal("", content.AttributeExtensions[new XmlQualifiedName("content_name2", "content_namespace")]); Assert.Equal("content_value", content.AttributeExtensions[new XmlQualifiedName("content_name3", "content_namespace")]); Assert.Equal("", content.AttributeExtensions[new XmlQualifiedName("content_name4", "xmlns")]); } else { Assert.Empty(content.AttributeExtensions); } Assert.Equal("content_title", content.Text); Assert.Equal("html", content.Type); Assert.Equal(3, item.Contributors.Count); SyndicationPerson firstContributor = item.Contributors[0]; Assert.Empty(firstContributor.AttributeExtensions); Assert.Empty(firstContributor.ElementExtensions); Assert.Null(firstContributor.Email); Assert.Null(firstContributor.Name); Assert.Null(firstContributor.Uri); SyndicationPerson secondContributor = item.Contributors[1]; Assert.Empty(secondContributor.AttributeExtensions); Assert.Empty(secondContributor.ElementExtensions); Assert.Null(secondContributor.Email); Assert.Null(secondContributor.Name); Assert.Null(secondContributor.Uri); SyndicationPerson thirdContributor = item.Contributors[2]; if (preserveAttributeExtensions) { Assert.Equal(4, thirdContributor.AttributeExtensions.Count); Assert.Equal("", thirdContributor.AttributeExtensions[new XmlQualifiedName("contributor_name1")]); Assert.Equal("", thirdContributor.AttributeExtensions[new XmlQualifiedName("contributor_name2", "contributor_namespace")]); Assert.Equal("contributor_value", thirdContributor.AttributeExtensions[new XmlQualifiedName("contributor_name3", "contributor_namespace")]); Assert.Equal("", thirdContributor.AttributeExtensions[new XmlQualifiedName("contributor_name4", "xmlns")]); } else { Assert.Empty(thirdContributor.AttributeExtensions); } if (preserveElementExtensions) { Assert.Equal(1, thirdContributor.ElementExtensions.Count); Assert.Equal(10, thirdContributor.ElementExtensions[0].GetObject<ExtensionObject>().Value); } else { Assert.Empty(thirdContributor.ElementExtensions); } Assert.Equal("contributor_email", thirdContributor.Email); Assert.Equal("contributor_name", thirdContributor.Name); Assert.Equal("contributor_uri", thirdContributor.Uri); if (preserveAttributeExtensions) { Assert.Equal(4, item.Copyright.AttributeExtensions.Count); Assert.Equal("", item.Copyright.AttributeExtensions[new XmlQualifiedName("copyright_name1")]); Assert.Equal("", item.Copyright.AttributeExtensions[new XmlQualifiedName("copyright_name2", "copyright_namespace")]); Assert.Equal("copyright_value", item.Copyright.AttributeExtensions[new XmlQualifiedName("copyright_name3", "copyright_namespace")]); Assert.Equal("", item.Copyright.AttributeExtensions[new XmlQualifiedName("copyright_name4", "xmlns")]); } else { Assert.Empty(item.Copyright.AttributeExtensions); } Assert.Equal("copyright_title", item.Copyright.Text); Assert.Equal("html", item.Copyright.Type); if (preserveElementExtensions) { Assert.Equal(1, item.ElementExtensions.Count); Assert.Equal(10, item.ElementExtensions[0].GetObject<ExtensionObject>().Value); } else { Assert.Empty(item.ElementExtensions); } Assert.Equal("id", item.Id); Assert.Equal(DateTimeOffset.MinValue, item.LastUpdatedTime); Assert.Equal(4, item.Links.Count); SyndicationLink firstLink = item.Links[0]; Assert.Empty(firstLink.AttributeExtensions); Assert.Empty(firstLink.ElementExtensions); Assert.Equal(0, firstLink.Length); Assert.Null(firstLink.MediaType); Assert.Null(firstLink.RelationshipType); Assert.Null(firstLink.Title); Assert.Null(firstLink.Uri); SyndicationLink secondLink = item.Links[1]; Assert.Empty(secondLink.AttributeExtensions); Assert.Empty(secondLink.ElementExtensions); Assert.Equal(0, secondLink.Length); Assert.Null(secondLink.MediaType); Assert.Null(secondLink.RelationshipType); Assert.Null(secondLink.Title); Assert.Null(secondLink.Uri); SyndicationLink thirdLink = item.Links[2]; Assert.Empty(thirdLink.AttributeExtensions); Assert.Empty(thirdLink.ElementExtensions); Assert.Equal(0, thirdLink.Length); Assert.Null(thirdLink.MediaType); Assert.Null(thirdLink.RelationshipType); Assert.Null(thirdLink.Title); Assert.Empty(thirdLink.Uri.OriginalString); SyndicationLink fourthLink = item.Links[3]; if (preserveAttributeExtensions) { Assert.Equal(4, fourthLink.AttributeExtensions.Count); Assert.Equal("", fourthLink.AttributeExtensions[new XmlQualifiedName("link_name1")]); Assert.Equal("", fourthLink.AttributeExtensions[new XmlQualifiedName("link_name2", "link_namespace")]); Assert.Equal("link_value", fourthLink.AttributeExtensions[new XmlQualifiedName("link_name3", "link_namespace")]); Assert.Equal("", fourthLink.AttributeExtensions[new XmlQualifiedName("link_name4", "xmlns")]); } else { Assert.Empty(fourthLink.AttributeExtensions); } if (preserveElementExtensions) { Assert.Equal(1, fourthLink.ElementExtensions.Count); Assert.Equal(10, fourthLink.ElementExtensions[0].GetObject<ExtensionObject>().Value); } else { Assert.Empty(fourthLink.ElementExtensions); } Assert.Equal(new Uri("http://link_url.com"), fourthLink.BaseUri); Assert.Equal(10, fourthLink.Length); Assert.Equal("link_mediaType", fourthLink.MediaType); Assert.Equal("link_relationshipType", fourthLink.RelationshipType); Assert.Equal("link_title", fourthLink.Title); Assert.Equal(new Uri("http://link_uri.com"), fourthLink.Uri); Assert.Equal(DateTimeOffset.MinValue, item.PublishDate); Assert.Null(item.SourceFeed); if (preserveAttributeExtensions) { Assert.Equal(4, item.Summary.AttributeExtensions.Count); Assert.Equal("", item.Summary.AttributeExtensions[new XmlQualifiedName("summary_name1")]); Assert.Equal("", item.Summary.AttributeExtensions[new XmlQualifiedName("summary_name2", "summary_namespace")]); Assert.Equal("summary_value", item.Summary.AttributeExtensions[new XmlQualifiedName("summary_name3", "summary_namespace")]); Assert.Equal("", item.Summary.AttributeExtensions[new XmlQualifiedName("summary_name4", "xmlns")]); } else { Assert.Empty(item.Summary.AttributeExtensions); } Assert.Equal("summary_title", item.Summary.Text); Assert.Equal("html", item.Summary.Type); if (preserveAttributeExtensions) { Assert.Equal(4, item.Title.AttributeExtensions.Count); Assert.Equal("", item.Title.AttributeExtensions[new XmlQualifiedName("title_name1")]); Assert.Equal("", item.Title.AttributeExtensions[new XmlQualifiedName("title_name2", "title_namespace")]); Assert.Equal("title_value", item.Title.AttributeExtensions[new XmlQualifiedName("title_name3", "title_namespace")]); Assert.Equal("", item.Title.AttributeExtensions[new XmlQualifiedName("title_name4", "xmlns")]); } else { Assert.Empty(item.Title.AttributeExtensions); } Assert.Equal("title_title", item.Title.Text); Assert.Equal("html", item.Title.Type); }); } [Theory] [InlineData(@"<content></content>", true, true)] [InlineData(@"<content></content>", false, false)] [InlineData(@"<content />", true, true)] [InlineData(@"<content />", false, false)] [InlineData(@"<content xmlns=""http://www.w3.org/2005/Atom""/>", true, true)] [InlineData(@"<content xmlns=""http://www.w3.org/2005/Atom""/>", false, false)] public void Read_EmptyContent_ReturnsExpected(string contentXmlString, bool preserveAttributeExtensions, bool preserveElementExtensions) { VerifyRead(@"<entry xmlns=""http://www.w3.org/2005/Atom"">" + contentXmlString + "</entry>", preserveAttributeExtensions, preserveElementExtensions, item => { TextSyndicationContent content = Assert.IsType<TextSyndicationContent>(item.Content); Assert.Empty(content.AttributeExtensions); Assert.Empty(content.Text); Assert.Equal("text", content.Type); }); } [Theory] [InlineData(@"<content src=""http://microsoft.com"" item_name1="""" d1p1:item_name2="""" d1p1:item_name3=""item_value"" d1p2:item_name4="""" xmlns:d1p2=""xmlns"" xmlns:d1p1=""item_namespace"" xmlns=""http://www.w3.org/2005/Atom""></content>", true, true)] [InlineData(@"<content src=""http://microsoft.com"" item_name1="""" d1p1:item_name2="""" d1p1:item_name3=""item_value"" d1p2:item_name4="""" xmlns:d1p2=""xmlns"" xmlns:d1p1=""item_namespace"" xmlns=""http://www.w3.org/2005/Atom""></content>", false, false)] [InlineData(@"<content src=""http://microsoft.com"" item_name1="""" d1p1:item_name2="""" d1p1:item_name3=""item_value"" d1p2:item_name4="""" xmlns:d1p2=""xmlns"" xmlns:d1p1=""item_namespace"" xmlns=""http://www.w3.org/2005/Atom"" />", true, true)] [InlineData(@"<content src=""http://microsoft.com"" item_name1="""" d1p1:item_name2="""" d1p1:item_name3=""item_value"" d1p2:item_name4="""" xmlns:d1p2=""xmlns"" xmlns:d1p1=""item_namespace"" xmlns=""http://www.w3.org/2005/Atom"" />", false, false)] public void Read_UriContent_ReturnsExpected(string contentXmlString, bool preserveAttributeExtensions, bool preserveElementExtensions) { VerifyRead(@"<entry xmlns=""http://www.w3.org/2005/Atom"">" + contentXmlString + "</entry>", preserveAttributeExtensions, preserveElementExtensions, item => { UrlSyndicationContent content = Assert.IsType<UrlSyndicationContent>(item.Content); if (preserveAttributeExtensions) { Assert.Equal(4, content.AttributeExtensions.Count); Assert.Equal("", content.AttributeExtensions[new XmlQualifiedName("item_name1")]); Assert.Equal("", content.AttributeExtensions[new XmlQualifiedName("item_name2", "item_namespace")]); Assert.Equal("item_value", content.AttributeExtensions[new XmlQualifiedName("item_name3", "item_namespace")]); Assert.Equal("", content.AttributeExtensions[new XmlQualifiedName("item_name4", "xmlns")]); } else { Assert.Empty(content.AttributeExtensions); } Assert.Equal(new Uri("http://microsoft.com"), content.Url); Assert.Equal("text", content.Type); }); } [Theory] [InlineData(true, true)] [InlineData(false, false)] public void Read_TryParseTrue_ReturnsExpected(bool preserveAttributeExtensions, bool preserveElementExtensions) { using (var stringReader = new StringReader( @"<entry xml:base=""/relative"" item_name1="""" d1p1:item_name2="""" d1p1:item_name3=""item_value"" d1p2:item_name4="""" xmlns:d1p2=""xmlns"" xmlns:d1p1=""item_namespace"" xmlns=""http://www.w3.org/2005/Atom""> <id>id</id> <title type=""html"" title_name1="""" d2p1:title_name2="""" d2p1:title_name3=""title_value"" d1p2:title_name4="""" xmlns:d2p1=""title_namespace"">title_title</title> <summary type=""html"" summary_name1="""" d2p1:summary_name2="""" d2p1:summary_name3=""summary_value"" d1p2:summary_name4="""" xmlns:d2p1=""summary_namespace"">summary_title</summary> <published>0001-01-01T00:00:00Z</published> <updated>0001-01-01T00:00:00Z</updated> <author /> <author></author> <author author_name1="""" d2p1:author_name2="""" d2p1:author_name3=""author_value"" d1p2:author_name4="""" xmlns:d2p1=""author_namespace""> <name>author_name</name> <uri>author_uri</uri> <email>author_email</email> <Atom10ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests""> <Value>10</Value> </Atom10ItemFormatterTests.ExtensionObject> </author> <contributor /> <contributor></contributor> <contributor contributor_name1="""" d2p1:contributor_name2="""" d2p1:contributor_name3=""contributor_value"" d1p2:contributor_name4="""" xmlns:d2p1=""contributor_namespace""> <name>contributor_name</name> <uri>contributor_uri</uri> <email>contributor_email</email> <Atom10ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests""> <Value>10</Value> </Atom10ItemFormatterTests.ExtensionObject> </contributor> <link href="""" /> <link xml:base=""http://link_url.com/"" link_name1="""" d2p1:link_name2="""" d2p1:link_name3=""link_value"" d1p2:link_name4="""" rel=""link_relationshipType"" type=""link_mediaType"" title=""link_title"" length=""10"" href=""http://link_uri.com/"" xmlns:d2p1=""link_namespace""> <Atom10ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests""> <Value>10</Value> </Atom10ItemFormatterTests.ExtensionObject> </link> <category /> <category term="""" /> <category category_name1="""" d2p1:category_name2="""" d2p1:category_name3=""category_value"" d1p2:category_name4="""" term=""category_name"" label=""category_label"" scheme=""category_scheme"" xmlns:d2p1=""category_namespace""> <Atom10ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests""> <Value>10</Value> </Atom10ItemFormatterTests.ExtensionObject> </category> <content type=""html"" content_name1="""" d2p1:content_name2="""" d2p1:content_name3=""content_value"" d1p2:content_name4="""" xmlns:d2p1=""content_namespace"">content_title</content> <rights type=""html"" copyright_name1="""" d2p1:copyright_name2="""" d2p1:copyright_name3=""copyright_value"" d1p2:copyright_name4="""" xmlns:d2p1=""copyright_namespace"">copyright_title</rights> <Atom10ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests""> <Value>10</Value> </Atom10ItemFormatterTests.ExtensionObject> </entry>")) using (XmlReader reader = XmlReader.Create(stringReader)) { var formatter = new Atom10ItemFormatter<SyndicationItemTryParseTrueSubclass>() { PreserveAttributeExtensions = preserveAttributeExtensions, PreserveElementExtensions = preserveElementExtensions }; formatter.ReadFrom(reader); SyndicationItem item = formatter.Item; Assert.Empty(item.AttributeExtensions); Assert.Equal(3, item.Authors.Count); SyndicationPerson firstAuthor = item.Authors[0]; Assert.Empty(firstAuthor.AttributeExtensions); Assert.Empty(firstAuthor.ElementExtensions); Assert.Null(firstAuthor.Email); Assert.Null(firstAuthor.Name); Assert.Null(firstAuthor.Uri); SyndicationPerson secondAuthor = item.Authors[1]; Assert.Empty(secondAuthor.AttributeExtensions); Assert.Empty(secondAuthor.ElementExtensions); Assert.Null(secondAuthor.Email); Assert.Null(secondAuthor.Name); Assert.Null(secondAuthor.Uri); SyndicationPerson thirdAuthor = item.Authors[2]; Assert.Empty(thirdAuthor.AttributeExtensions); Assert.Empty(thirdAuthor.ElementExtensions); Assert.Equal("author_email", thirdAuthor.Email); Assert.Equal("author_name", thirdAuthor.Name); Assert.Equal("author_uri", thirdAuthor.Uri); Assert.Equal(new Uri("/relative", UriKind.Relative), item.BaseUri); SyndicationCategory firstCategory = item.Categories[0]; Assert.Empty(firstCategory.AttributeExtensions); Assert.Empty(firstCategory.ElementExtensions); Assert.Null(firstCategory.Name); Assert.Null(firstCategory.Scheme); Assert.Null(firstCategory.Label); SyndicationCategory secondCategory = item.Categories[1]; Assert.Empty(secondCategory.AttributeExtensions); Assert.Empty(secondCategory.ElementExtensions); Assert.Empty(secondCategory.Name); Assert.Null(secondCategory.Scheme); Assert.Null(secondCategory.Label); SyndicationCategory thirdCategory = item.Categories[2]; Assert.Empty(thirdCategory.AttributeExtensions); Assert.Empty(thirdCategory.ElementExtensions); Assert.Equal("category_name", thirdCategory.Name); Assert.Equal("category_scheme", thirdCategory.Scheme); Assert.Equal("category_label", thirdCategory.Label); TextSyndicationContent content = Assert.IsType<TextSyndicationContent>(item.Content); Assert.Empty(content.AttributeExtensions); Assert.Equal("overriden", content.Text); Assert.Equal("text", content.Type); Assert.Equal(3, item.Contributors.Count); SyndicationPerson firstContributor = item.Contributors[0]; Assert.Empty(firstContributor.AttributeExtensions); Assert.Empty(firstContributor.ElementExtensions); Assert.Null(firstContributor.Email); Assert.Null(firstContributor.Name); Assert.Null(firstContributor.Uri); SyndicationPerson secondContributor = item.Contributors[1]; Assert.Empty(secondContributor.AttributeExtensions); Assert.Empty(secondContributor.ElementExtensions); Assert.Null(secondContributor.Email); Assert.Null(secondContributor.Name); Assert.Null(secondContributor.Uri); SyndicationPerson thirdContributor = item.Contributors[2]; Assert.Empty(thirdContributor.AttributeExtensions); Assert.Empty(thirdContributor.ElementExtensions); Assert.Equal("contributor_email", thirdContributor.Email); Assert.Equal("contributor_name", thirdContributor.Name); Assert.Equal("contributor_uri", thirdContributor.Uri); if (preserveAttributeExtensions) { Assert.Equal(4, item.Copyright.AttributeExtensions.Count); Assert.Equal("", item.Copyright.AttributeExtensions[new XmlQualifiedName("copyright_name1")]); Assert.Equal("", item.Copyright.AttributeExtensions[new XmlQualifiedName("copyright_name2", "copyright_namespace")]); Assert.Equal("copyright_value", item.Copyright.AttributeExtensions[new XmlQualifiedName("copyright_name3", "copyright_namespace")]); Assert.Equal("", item.Copyright.AttributeExtensions[new XmlQualifiedName("copyright_name4", "xmlns")]); } else { Assert.Empty(item.Copyright.AttributeExtensions); } Assert.Equal("copyright_title", item.Copyright.Text); Assert.Equal("html", item.Copyright.Type); Assert.Empty(item.ElementExtensions); Assert.Equal("id", item.Id); Assert.Equal(DateTimeOffset.MinValue, item.LastUpdatedTime); Assert.Equal(2, item.Links.Count); SyndicationLink firstLink = item.Links[0]; Assert.Empty(firstLink.AttributeExtensions); Assert.Empty(firstLink.ElementExtensions); Assert.Equal(0, firstLink.Length); Assert.Null(firstLink.MediaType); Assert.Null(firstLink.RelationshipType); Assert.Null(firstLink.Title); Assert.Empty(firstLink.Uri.OriginalString); SyndicationLink secondLink = item.Links[1]; if (preserveAttributeExtensions) { Assert.Equal(4, secondLink.AttributeExtensions.Count); Assert.Equal("", secondLink.AttributeExtensions[new XmlQualifiedName("link_name1")]); Assert.Equal("", secondLink.AttributeExtensions[new XmlQualifiedName("link_name2", "link_namespace")]); Assert.Equal("link_value", secondLink.AttributeExtensions[new XmlQualifiedName("link_name3", "link_namespace")]); Assert.Equal("", secondLink.AttributeExtensions[new XmlQualifiedName("link_name4", "xmlns")]); } else { Assert.Empty(secondLink.AttributeExtensions); } Assert.Empty(secondLink.ElementExtensions); Assert.Equal(new Uri("http://link_url.com"), secondLink.BaseUri); Assert.Equal(10, secondLink.Length); Assert.Equal("link_mediaType", secondLink.MediaType); Assert.Equal("link_relationshipType", secondLink.RelationshipType); Assert.Equal("link_title", secondLink.Title); Assert.Equal(new Uri("http://link_uri.com"), secondLink.Uri); Assert.Equal(DateTimeOffset.MinValue, item.PublishDate); Assert.Null(item.SourceFeed); if (preserveAttributeExtensions) { Assert.Equal(4, item.Summary.AttributeExtensions.Count); Assert.Equal("", item.Summary.AttributeExtensions[new XmlQualifiedName("summary_name1")]); Assert.Equal("", item.Summary.AttributeExtensions[new XmlQualifiedName("summary_name2", "summary_namespace")]); Assert.Equal("summary_value", item.Summary.AttributeExtensions[new XmlQualifiedName("summary_name3", "summary_namespace")]); Assert.Equal("", item.Summary.AttributeExtensions[new XmlQualifiedName("summary_name4", "xmlns")]); } else { Assert.Empty(item.Summary.AttributeExtensions); } Assert.Equal("summary_title", item.Summary.Text); Assert.Equal("html", item.Summary.Type); if (preserveAttributeExtensions) { Assert.Equal(4, item.Title.AttributeExtensions.Count); Assert.Equal("", item.Title.AttributeExtensions[new XmlQualifiedName("title_name1")]); Assert.Equal("", item.Title.AttributeExtensions[new XmlQualifiedName("title_name2", "title_namespace")]); Assert.Equal("title_value", item.Title.AttributeExtensions[new XmlQualifiedName("title_name3", "title_namespace")]); Assert.Equal("", item.Title.AttributeExtensions[new XmlQualifiedName("title_name4", "xmlns")]); } else { Assert.Empty(item.Title.AttributeExtensions); } Assert.Equal("title_title", item.Title.Text); Assert.Equal("html", item.Title.Type); } } [Theory] [InlineData(@"<entry xmlns=""http://www.w3.org/2005/Atom""></entry>", true)] [InlineData(@"<entry xmlns=""http://www.w3.org/2005/Atom""></entry>", false)] [InlineData(@"<entry xmlns=""http://www.w3.org/2005/Atom"" />", true)] [InlineData(@"<entry xmlns=""http://www.w3.org/2005/Atom"" />", false)] public void Read_EmptyItem_ReturnsExpected(string xmlString, bool preserveElementExtensions) { VerifyRead(xmlString, preserveElementExtensions, preserveElementExtensions, item => { Assert.Empty(item.AttributeExtensions); Assert.Empty(item.Authors); Assert.Null(item.BaseUri); Assert.Empty(item.Categories); Assert.Null(item.Content); Assert.Null(item.Copyright); Assert.Empty(item.ElementExtensions); Assert.Null(item.Id); Assert.Equal(default, item.LastUpdatedTime); Assert.Empty(item.Links); Assert.Equal(default, item.PublishDate); Assert.Null(item.SourceFeed); Assert.Null(item.Summary); Assert.Null(item.Title); }); } private static void VerifyRead(string xmlString, bool preserveAttributeExtensions, bool preserveElementExtensions, Action<SyndicationItem> verifyAction) { // ReadFrom. using (var stringReader = new StringReader(xmlString)) using (XmlReader reader = XmlReader.Create(stringReader)) { var formatter = new Atom10ItemFormatter() { PreserveAttributeExtensions = preserveAttributeExtensions, PreserveElementExtensions = preserveElementExtensions }; formatter.ReadFrom(reader); verifyAction(formatter.Item); } // ReadXml. using (var stringReader = new StringReader(xmlString)) using (XmlReader reader = XmlReader.Create(stringReader)) { reader.MoveToContent(); var formatter = new Atom10ItemFormatter() { PreserveAttributeExtensions = preserveAttributeExtensions, PreserveElementExtensions = preserveElementExtensions }; ((IXmlSerializable)formatter).ReadXml(reader); verifyAction(formatter.Item); } // Derived ReadFrom. using (var stringReader = new StringReader(xmlString)) using (XmlReader reader = XmlReader.Create(stringReader)) { var formatter = new Atom10ItemFormatter(typeof(SyndicationItemSubclass)) { PreserveAttributeExtensions = preserveAttributeExtensions, PreserveElementExtensions = preserveElementExtensions }; formatter.ReadFrom(reader); verifyAction(formatter.Item); } // Derived ReadXml. using (var stringReader = new StringReader(xmlString)) using (XmlReader reader = XmlReader.Create(stringReader)) { reader.MoveToContent(); var formatter = new Atom10ItemFormatter(typeof(SyndicationItemSubclass)) { PreserveAttributeExtensions = preserveAttributeExtensions, PreserveElementExtensions = preserveElementExtensions }; ((IXmlSerializable)formatter).ReadXml(reader); verifyAction(formatter.Item); } // Generic ReadFrom. using (var stringReader = new StringReader(xmlString)) using (XmlReader reader = XmlReader.Create(stringReader)) { var formatter = new Atom10ItemFormatter<SyndicationItem>() { PreserveAttributeExtensions = preserveAttributeExtensions, PreserveElementExtensions = preserveElementExtensions }; formatter.ReadFrom(reader); verifyAction(formatter.Item); } // Generic ReadXml. using (var stringReader = new StringReader(xmlString)) using (XmlReader reader = XmlReader.Create(stringReader)) { reader.MoveToContent(); var formatter = new Atom10ItemFormatter<SyndicationItem>() { PreserveAttributeExtensions = preserveAttributeExtensions, PreserveElementExtensions = preserveElementExtensions }; ((IXmlSerializable)formatter).ReadXml(reader); verifyAction(formatter.Item); } // Generic Derived ReadFrom. using (var stringReader = new StringReader(xmlString)) using (XmlReader reader = XmlReader.Create(stringReader)) { var formatter = new Atom10ItemFormatter<SyndicationItemSubclass>() { PreserveAttributeExtensions = preserveAttributeExtensions, PreserveElementExtensions = preserveElementExtensions }; formatter.ReadFrom(reader); verifyAction(formatter.Item); } // Generic Derived ReadXml. using (var stringReader = new StringReader(xmlString)) using (XmlReader reader = XmlReader.Create(stringReader)) { reader.MoveToContent(); var formatter = new Atom10ItemFormatter<SyndicationItemSubclass>() { PreserveAttributeExtensions = preserveAttributeExtensions, PreserveElementExtensions = preserveElementExtensions }; ((IXmlSerializable)formatter).ReadXml(reader); verifyAction(formatter.Item); } if (preserveAttributeExtensions && preserveElementExtensions) { // Load. using (var stringReader = new StringReader(xmlString)) using (XmlReader reader = XmlReader.Create(stringReader)) { SyndicationItem item = SyndicationItem.Load(reader); verifyAction(item); } // Generic Load. using (var stringReader = new StringReader(xmlString)) using (XmlReader reader = XmlReader.Create(stringReader)) { SyndicationItem item = SyndicationItem.Load<SyndicationItem>(reader); verifyAction(item); } } } [Fact] public void ReadFrom_NullReader_ThrowsArgumentNullException() { var formatter = new Atom10ItemFormatter(); AssertExtensions.Throws<ArgumentNullException>("reader", () => formatter.ReadFrom(null)); } [Fact] public void ReadFrom_NullCreatedItem_ThrowsArgumentNullException() { using (var stringReader = new StringReader(@"<entry xmlns=""http://www.w3.org/2005/Atom""></entry>")) using (XmlReader reader = XmlReader.Create(stringReader)) { var formatter = new NullCreatedItemFormatter(); AssertExtensions.Throws<ArgumentNullException>("item", () => formatter.ReadFrom(reader)); } } [Theory] [InlineData(@"<different xmlns=""http://www.w3.org/2005/Atom""></different>")] [InlineData(@"<entry xmlns=""different""></entry>")] [InlineData(@"<entry></entry>")] [InlineData(@"<entry />")] public void ReadFrom_CantRead_ThrowsXmlException(string xmlString) { using (var stringReader = new StringReader(xmlString)) using (XmlReader reader = XmlReader.Create(stringReader)) { var formatter = new Atom10ItemFormatter(); Assert.Throws<XmlException>(() => formatter.ReadFrom(reader)); } } [Theory] [InlineData("<entry></entry>")] [InlineData(@"<app:entry xmlns:app=""http://www.w3.org/2005/Atom""></app:entry>")] [InlineData(@"<entry xmlns=""different""></entry>")] [InlineData(@"<different xmlns=""http://www.w3.org/2005/Atom""></different>")] public void ReadXml_ValidReader_Success(string xmlString) { using (var stringReader = new StringReader(xmlString)) using (XmlReader reader = XmlReader.Create(stringReader)) { reader.MoveToContent(); var formatter = new Atom10ItemFormatter(); ((IXmlSerializable)formatter).ReadXml(reader); SyndicationItem item = formatter.Item; Assert.Empty(item.AttributeExtensions); Assert.Empty(item.Authors); Assert.Null(item.BaseUri); Assert.Empty(item.Categories); Assert.Null(item.Content); Assert.Null(item.Copyright); Assert.Empty(item.ElementExtensions); Assert.Null(item.Id); Assert.Equal(default, item.LastUpdatedTime); Assert.Empty(item.Links); Assert.Equal(default, item.PublishDate); Assert.Null(item.SourceFeed); Assert.Null(item.Summary); Assert.Null(item.Title); } } [Fact] public void ReadXml_NullReader_ThrowsArgumentNullException() { IXmlSerializable formatter = new Atom10ItemFormatter(); AssertExtensions.Throws<ArgumentNullException>("reader", () => formatter.ReadXml(null)); } [Fact] public void ReadXml_NullCreatedItem_ThrowsArgumentNullException() { using (var stringReader = new StringReader(@"<entry xmlns=""http://www.w3.org/2005/Atom""></entry>")) using (XmlReader reader = XmlReader.Create(stringReader)) { reader.MoveToContent(); IXmlSerializable formatter = new NullCreatedItemFormatter(); AssertExtensions.Throws<ArgumentNullException>("item", () => formatter.ReadXml(reader)); } } [Fact] public void ReadXml_ThrowsArgumentException_RethrowsAsXmlException() { var reader = new ThrowingXmlReader(new ArgumentException()); IXmlSerializable formatter = new Atom10ItemFormatter(); Assert.Throws<XmlException>(() => formatter.ReadXml(reader)); } [Fact] public void ReadXml_ThrowsFormatException_RethrowsAsXmlException() { var reader = new ThrowingXmlReader(new FormatException()); IXmlSerializable formatter = new Atom10ItemFormatter(); Assert.Throws<XmlException>(() => formatter.ReadXml(reader)); } [Theory] [InlineData("")] [InlineData("invalid")] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Custom date parsing added in .NET Core changes this behaviour")] public void Read_InvalidLastUpdatedTime_GetThrowsXmlExcepton(string updated) { using (var stringReader = new StringReader(@"<entry xmlns=""http://www.w3.org/2005/Atom""><updated>" + updated + "</updated></entry>")) using (XmlReader reader = XmlReader.Create(stringReader)) { var formatter = new Atom10ItemFormatter(); formatter.ReadFrom(reader); Assert.Throws<XmlException>(() => formatter.Item.LastUpdatedTime); } } [Theory] [InlineData("")] [InlineData("invalid")] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Custom date parsing added in .NET Core changes this behaviour")] public void Read_InvalidPublishDate_GetThrowsXmlExcepton(string published) { using (var stringReader = new StringReader(@"<entry xmlns=""http://www.w3.org/2005/Atom""><published>" + published + "</published></entry>")) using (XmlReader reader = XmlReader.Create(stringReader)) { var formatter = new Atom10ItemFormatter(); formatter.ReadFrom(reader); Assert.Throws<XmlException>(() => formatter.Item.PublishDate); } } [Theory] [InlineData(true)] [InlineData(false)] public void PreserveAttributeExtensions_Set_GetReturnsExpected(bool preserveAttributeExtensions) { var formatter = new Atom10ItemFormatter() { PreserveAttributeExtensions = preserveAttributeExtensions }; Assert.Equal(preserveAttributeExtensions, formatter.PreserveAttributeExtensions); } [Theory] [InlineData(true)] [InlineData(false)] public void PreserveElementExtensions_Set_GetReturnsExpected(bool preserveElementExtensions) { var formatter = new Atom10ItemFormatter() { PreserveElementExtensions = preserveElementExtensions }; Assert.Equal(preserveElementExtensions, formatter.PreserveElementExtensions); } [Fact] public void CreateItemInstance_NonGeneric_Success() { var formatter = new Formatter(); SyndicationItem item = Assert.IsType<SyndicationItem>(formatter.CreateItemInstanceEntryPoint()); Assert.Empty(item.AttributeExtensions); Assert.Empty(item.Authors); Assert.Null(item.BaseUri); Assert.Empty(item.Categories); Assert.Null(item.Content); Assert.Null(item.Copyright); Assert.Empty(item.ElementExtensions); Assert.Null(item.Id); Assert.Equal(default, item.LastUpdatedTime); Assert.Empty(item.Links); Assert.Equal(default, item.PublishDate); Assert.Null(item.SourceFeed); Assert.Null(item.Summary); Assert.Null(item.Title); var typedFormatter = new Formatter(typeof(SyndicationItemSubclass)); item = Assert.IsType<SyndicationItemSubclass>(typedFormatter.CreateItemInstanceEntryPoint()); Assert.Empty(item.AttributeExtensions); Assert.Empty(item.Authors); Assert.Null(item.BaseUri); Assert.Empty(item.Categories); Assert.Null(item.Content); Assert.Null(item.Copyright); Assert.Empty(item.ElementExtensions); Assert.Null(item.Id); Assert.Equal(default, item.LastUpdatedTime); Assert.Empty(item.Links); Assert.Equal(default, item.PublishDate); Assert.Null(item.SourceFeed); Assert.Null(item.Summary); Assert.Null(item.Title); } [Fact] public void CreateItemInstance_Generic_Success() { var formatter = new GenericFormatter<SyndicationItem>(); SyndicationItem item = Assert.IsType<SyndicationItem>(formatter.CreateItemInstanceEntryPoint()); Assert.Empty(item.AttributeExtensions); Assert.Empty(item.Authors); Assert.Null(item.BaseUri); Assert.Empty(item.Categories); Assert.Null(item.Content); Assert.Null(item.Copyright); Assert.Empty(item.ElementExtensions); Assert.Null(item.Id); Assert.Equal(default, item.LastUpdatedTime); Assert.Empty(item.Links); Assert.Equal(default, item.PublishDate); Assert.Null(item.SourceFeed); Assert.Null(item.Summary); Assert.Null(item.Title); var typedFormatter = new GenericFormatter<SyndicationItemSubclass>(); item = Assert.IsType<SyndicationItemSubclass>(typedFormatter.CreateItemInstanceEntryPoint()); Assert.Empty(item.AttributeExtensions); Assert.Empty(item.Authors); Assert.Null(item.BaseUri); Assert.Empty(item.Categories); Assert.Null(item.Content); Assert.Null(item.Copyright); Assert.Empty(item.ElementExtensions); Assert.Null(item.Id); Assert.Equal(default, item.LastUpdatedTime); Assert.Empty(item.Links); Assert.Equal(default, item.PublishDate); Assert.Null(item.SourceFeed); Assert.Null(item.Summary); Assert.Null(item.Title); } public class SyndicationItemSubclass : SyndicationItem { } public class SyndicationItemTryParseTrueSubclass : SyndicationItem { protected override bool TryParseAttribute(string name, string ns, string value, string version) => true; protected override bool TryParseContent(XmlReader reader, string contentType, string version, out SyndicationContent content) { reader.Skip(); content = new TextSyndicationContent("overriden"); return true; } protected override bool TryParseElement(XmlReader reader, string version) { reader.Skip(); return true; } protected override SyndicationCategory CreateCategory() => new SyndicationCategoryTryParseTrueSubclass(); protected override SyndicationPerson CreatePerson() => new SyndicationPersonTryParseTrueSubclass(); protected override SyndicationLink CreateLink() => new SyndicationLinkTryParseTrueSubclass(); } public class SyndicationCategoryTryParseTrueSubclass : SyndicationCategory { protected override bool TryParseAttribute(string name, string ns, string value, string version) => true; protected override bool TryParseElement(XmlReader reader, string version) { reader.Skip(); return true; } } public class SyndicationPersonTryParseTrueSubclass : SyndicationPerson { protected override bool TryParseAttribute(string name, string ns, string value, string version) => true; protected override bool TryParseElement(XmlReader reader, string version) { reader.Skip(); return true; } } public class SyndicationLinkTryParseTrueSubclass : SyndicationLink { protected override bool TryParseAttribute(string name, string ns, string value, string version) => true; protected override bool TryParseElement(XmlReader reader, string version) { reader.Skip(); return true; } } public class NullCreatedItemFormatter : Atom10ItemFormatter { protected override SyndicationItem CreateItemInstance() => null; } public class Formatter : Atom10ItemFormatter { public Formatter() : base() { } public Formatter(SyndicationItem itemToWrite) : base(itemToWrite) { } public Formatter(Type itemTypeToCreate) : base(itemTypeToCreate) { } public Type ItemTypeEntryPoint => ItemType; public SyndicationItem CreateItemInstanceEntryPoint() => CreateItemInstance(); } public class GenericFormatter<T> : Atom10ItemFormatter<T> where T : SyndicationItem, new() { public GenericFormatter() : base() { } public GenericFormatter(T itemToWrite) : base(itemToWrite) { } public Type ItemTypeEntryPoint => ItemType; public SyndicationItem CreateItemInstanceEntryPoint() => CreateItemInstance(); } [DataContract] public class ExtensionObject { [DataMember] public int Value { get; set; } } } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace EmployeeDirectoryWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
// ******************************************************************************************************** // Product Name: DotSpatial.Projection // Description: The basic module for MapWindow version 6.0 // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The original content was ported from the C language from the 4.6 version of Proj4 libraries. // Frank Warmerdam has released the full content of that version under the MIT license which is // recognized as being approximately equivalent to public domain. The original work was done // mostly by Gerald Evenden. The latest versions of the C libraries can be obtained here: // http://trac.osgeo.org/proj/ // // The Initial Developer of this Original Code is Ted Dunsford. Created 7/31/2009 2:35:46 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // Name | Date | Comment // --------------------|------------|------------------------------------------------------------ // Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL // ******************************************************************************************************** using System; namespace DotSpatial.Projections.Transforms { /// <summary> /// OrthogonalMercator /// </summary> public class ObliqueMercator : Transform { #region Private Variables private const double TOLERANCE = 1E-7; private double _al; private double _alpha; private double _bl; private double _cosgam; private double _cosrot; private double _el; private bool _ellips; private double _gamma; private double _lam1; private double _lam2; private double _lamc; private double _phi1; private double _phi2; private bool _rot; private double _singam; private double _sinrot; private double _u0; #endregion #region Constructors /// <summary> /// Creates a new instance of OrthogonalMercator /// </summary> public ObliqueMercator() { Proj4Name = "omerc"; Name = "Hotine_Oblique_Mercator"; } #endregion #region Methods /// <inheritdoc /> protected override void OnForward(double[] lp, double[] xy, int startIndex, int numPoints) { for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; double ul, us; double vl = Math.Sin(_bl * lp[lam]); if (Math.Abs(Math.Abs(lp[phi]) - Math.PI / 2) <= EPS10) { ul = lp[phi] < 0 ? -_singam : _singam; us = _al * lp[phi] / _bl; } else { double q = _el / (_ellips ? Math.Pow(Proj.Tsfn(lp[phi], Math.Sin(lp[phi]), E), _bl) : Tsfn0(lp[phi])); double s = .5 * (q - 1 / q); ul = 2.0 * (s * _singam - vl * _cosgam) / (q + 1.0 / q); double con = Math.Cos(_bl * lp[lam]); if (Math.Abs(con) >= TOLERANCE) { us = _al * Math.Atan((s * _cosgam + vl * _singam) / con) / _bl; if (con < 0) us += Math.PI * _al / _bl; } else { us = _al * _bl * lp[lam]; } } if (Math.Abs(Math.Abs(ul) - 1.0) <= EPS10) { xy[x] = double.NaN; xy[y] = double.NaN; continue; //ProjectionException(20); } double vs = .5 * _al * Math.Log((1 - ul) / (1 + ul)) / _bl; us -= _u0; if (!_rot) { xy[x] = us; xy[y] = vs; } else { xy[x] = vs * _cosrot + us * _sinrot; xy[y] = us * _cosrot - vs * _sinrot; } } } /// <inheritdoc /> protected override void OnInverse(double[] xy, double[] lp, int startIndex, int numPoints) { for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; double us, vs; if (!_rot) { us = xy[x]; vs = xy[y]; } else { vs = xy[x] * _cosrot - xy[y] * _sinrot; us = xy[y] * _cosrot + xy[x] * _sinrot; } us += _u0; double q = Math.Exp(-_bl * vs / _al); double s = .5 * (q - 1 / q); double vl = Math.Sin(_bl * us / _al); double ul = 2 * (vl * _cosgam + s * _singam) / (q + 1 / q); if (Math.Abs(Math.Abs(ul) - 1) < EPS10) { lp[lam] = 0; lp[phi] = ul < 0 ? -HALF_PI : HALF_PI; } else { lp[phi] = _el / Math.Sqrt((1 + ul) / (1 - ul)); if (_ellips) { if ((lp[phi] = Proj.Phi2(Math.Pow(lp[phi], 1 / _bl), E)) == double.MaxValue) { lp[lam] = double.NaN; lp[phi] = double.NaN; continue; //ProjectionException(20); } } else { lp[phi] = HALF_PI - 2 * Math.Atan(lp[phi]); } lp[lam] = -Math.Atan2((s * _cosgam - vl * _singam), Math.Cos(_bl * us / _al)) / _bl; } } } /// <summary> /// Initializes the transform using the parameters from the specified coordinate system information /// </summary> /// <param name="projInfo">A ProjectionInfo class contains all the standard and custom parameters needed to initialize this transform</param> protected override void OnInit(ProjectionInfo projInfo) { double con; double f; double d; double toRadians = projInfo.GeographicInfo.Unit.Radians; _rot = !projInfo.no_rot.HasValue || projInfo.no_rot.Value == 0; bool azi = projInfo.alpha.HasValue; if (azi) { if (projInfo.lonc.HasValue) _lamc = projInfo.lonc.Value * toRadians; if (projInfo.alpha.HasValue) _alpha = projInfo.alpha.Value * toRadians; if (Math.Abs(_alpha) < TOLERANCE || Math.Abs(Math.Abs(Phi0) - HALF_PI) <= TOLERANCE || Math.Abs(Math.Abs(_alpha) - HALF_PI) <= TOLERANCE) throw new ProjectionException(32); } else { _lam1 = projInfo.Lam1; _phi1 = projInfo.Phi1; _lam2 = projInfo.Lam2; _phi2 = projInfo.Phi2; if (Math.Abs(_phi1 - _phi2) <= TOLERANCE || (con = Math.Abs(_phi1)) <= TOLERANCE || Math.Abs(con - HALF_PI) <= TOLERANCE || Math.Abs(Math.Abs(Phi0) - HALF_PI) <= TOLERANCE || Math.Abs(Math.Abs(_phi2) - HALF_PI) <= TOLERANCE) { throw new ProjectionException(33); } } _ellips = Es > 0; double com = _ellips ? Math.Sqrt(OneEs) : 1; if (Math.Abs(Phi0) > EPS10) { double sinph0 = Math.Sin(Phi0); double cosph0 = Math.Cos(Phi0); if (_ellips) { con = 1 - Es * sinph0 * sinph0; _bl = cosph0 * cosph0; _bl = Math.Sqrt(1 + Es * _bl * _bl / OneEs); _al = _bl * K0 * com / con; d = _bl * com / (cosph0 * Math.Sqrt(con)); } else { _bl = 1; _al = K0; d = 1 / cosph0; } if ((f = d * d - 1) <= 0) { f = 0; } else { f = Math.Sqrt(f); if (Phi0 < 0) f = -f; } _el = f += d; if (_ellips) { _el *= Math.Pow(Proj.Tsfn(Phi0, sinph0, E), _bl); } else { _el *= Tsfn0(Phi0); } } else { _bl = 1 / com; _al = K0; _el = d = f = 1; } if (azi) { _gamma = Math.Asin(Math.Sin(_alpha) / d); Lam0 = _lamc - Math.Asin((.5 * (f - 1 / f)) * Math.Tan(_gamma)) / _bl; projInfo.Lam0 = Lam0; } else { double h; double l; if (_ellips) { h = Math.Pow(Proj.Tsfn(_phi1, Math.Sin(_phi1), E), _bl); l = Math.Pow(Proj.Tsfn(_phi2, Math.Sin(_phi2), E), _bl); } else { h = Tsfn0(_phi1); l = Tsfn0(_phi2); } f = _el / h; double p = (l - h) / (l + h); double j = _el * _el; j = (j - l * h) / (j + l * h); if ((con = _lam1 - _lam2) < -Math.PI) { _lam2 -= Math.PI * 2; } else if (con > Math.PI) { _lam2 += Math.PI * 2; } Lam0 = Proj.Adjlon(.5 * (_lam1 + _lam2) - Math.Atan(j * Math.Tan(.5 * _bl * (_lam1 - _lam2)) / p) / _bl); projInfo.Lam0 = Lam0; _gamma = Math.Atan(2 * Math.Sin(_bl * Proj.Adjlon(_lam1 - Lam0)) / (f - 1 / f)); _alpha = Math.Asin(d * Math.Sin(_gamma)); } _singam = Math.Sin(_gamma); _cosgam = Math.Cos(_gamma); if (projInfo.rot_conv.HasValue) { f = _alpha; } else { f = _gamma; } _sinrot = Math.Sin(f); _cosrot = Math.Cos(f); if (projInfo.no_uoff.HasValue) { _u0 = Math.Abs(_al * Math.Atan(Math.Sqrt(d * d - 1) / _cosrot) / _bl); } else { _u0 = 0; } if (Phi0 < 0) _u0 = -_u0; } #endregion #region Properties #endregion #region private methods private static double Tsfn0(double x) { return Math.Tan(.5 * (HALF_PI - x)); } #endregion } }
enum ShadowMode { [EnumLabel("Fixed Size PCF")] FixedSizePCF = 0, [EnumLabel("Grid PCF")] GridPCF, [EnumLabel("Random Disc PCF")] RandomDiscPCF, [EnumLabel("Optimized PCF")] OptimizedPCF, [EnumLabel("VSM")] VSM, [EnumLabel("EVSM 2 Component")] EVSM2, [EnumLabel("EVSM 4 Component")] EVSM4, [EnumLabel("MSM Hamburger")] MSMHamburger, [EnumLabel("MSM Hausdorff")] MSMHausdorff, } enum Scene { PowerPlant = 0, Tower = 1, Columns = 2, } enum PartitionMode { Manual = 0, Logarithmic = 1, PSSM = 2, } enum FixedFilterSize { [EnumLabel("2x2")] Filter2x2 = 0, [EnumLabel("3x3")] Filter3x3, [EnumLabel("5x5")] Filter5x5, [EnumLabel("7x7")] Filter7x7, [EnumLabel("9x9")] Filter9x9, } enum ShadowMapSize { [EnumLabel("512x512")] SMSize512 = 0, [EnumLabel("1024x1024")] SMSize1024, [EnumLabel("2048x2048")] SMSize2048, } enum ShadowMSAA { [EnumLabel("None")] MSAANone = 0, [EnumLabel("2x")] MSAA2x, [EnumLabel("4x")] MSAA4x, [EnumLabel("8x")] MSAA8x, } enum SMFormat { [EnumLabel("16-bit")] SM16Bit = 0, [EnumLabel("32-bit")] SM32Bit, }; enum ShadowAnisotropy { [EnumLabel("1x")] Anisotropy1x = 0, [EnumLabel("2x")] Anisotropy2x, [EnumLabel("4x")] Anisotropy4x, [EnumLabel("8x")] Anisotropy8x, [EnumLabel("16x")] Anisotropy16x, }; enum CascadeSelectionModes { [EnumLabel("Split Depth")] SplitDepth = 0, [EnumLabel("Projection")] Projection, }; enum DepthBufferFormats { [EnumLabel("16-bit UNORM")] DB16Unorm = 0, [EnumLabel("24-bit UNORM")] DB24Unorm, [EnumLabel("32-bit FLOAT")] DB32Float, } public class Settings { public class SceneControls { [DisplayName("Current Scene")] [HelpText("The scene to render")] [UseAsShaderConstant(false)] Scene CurrentScene = Scene.PowerPlant; [DisplayName("Animate Light")] [HelpText("Automatically rotates the light about the Y axis")] [UseAsShaderConstant(false)] bool AnimateLight = false; [DisplayName("Light Direction")] [HelpText("The direction of the light")] Direction LightDirection = new Direction(1.0f, 1.0f, 1.0f); [DisplayName("Light Color")] [HelpText("The color of the light")] [MinValue(0.0f)] [MaxValue(20.0f)] [StepSize(0.1f)] [HDR(true)] Color LightColor = new Color(10.0f, 8.0f, 5.0f); [DisplayName("Character Orientation")] [HelpText("The orientation of the character model")] [UseAsShaderConstant(false)] Orientation CharacterOrientation; [DisplayName("Enable Albedo Map")] [HelpText("Enables using albedo maps when rendering the scene")] bool EnableAlbedoMap = true; } public class CascadeControls { [DisplayName("Visualize Cascades")] [HelpText("Colors each cascade a different color to visualize their start and end points")] [UseAsShaderConstant(false)] bool VisualizeCascades = false; [DisplayName("Stabilize Cascades")] [HelpText("Keeps consistent sizes for each cascade, and snaps each cascade so that they " + "move in texel-sized increments. Reduces temporal aliasing artifacts, but " + "reduces the effective resolution of the cascades")] bool StabilizeCascades = false; [DisplayName("Filter Across Cascades")] [HelpText("Enables blending across cascade boundaries to reduce the appearance of seams")] [UseAsShaderConstant(false)] bool FilterAcrossCascades = false; [DisplayName("Auto-Compute Depth Bounds")] [HelpText("Automatically fits the cascades to the min and max depth of the scene " + "based on the contents of the depth buffer")] bool AutoComputeDepthBounds = false; [DisplayName("Depth Bounds Readback Latency")] [HelpText("Number of frames to wait before reading back the depth reduction results")] [MinValue(0)] [MaxValue(3)] [UseAsShaderConstant(false)] int ReadbackLatency = 1; [DisplayName("GPU Scene Submission")] [HelpText("Uses compute shaders to handle shadow setup and mesh batching to minimize draw calls " + "and avoid depth readback latency")] [UseAsShaderConstant(false)] bool GPUSceneSubmission = false; [DisplayName("Min Cascade Distance")] [HelpText("The closest depth that is covered by the shadow cascades")] [MinValue(0.0f)] [MaxValue(0.1f)] [StepSize(0.001f)] float MinCascadeDistance = 0.0f; [DisplayName("Max Cascade Distance")] [HelpText("The furthest depth that is covered by the shadow cascades")] [MinValue(0.0f)] [MaxValue(1.0f)] [StepSize(0.01f)] float MaxCascadeDistance = 1.0f; [DisplayName("CSM Partition Model")] [HelpText("Controls how the viewable depth range is partitioned into cascades")] PartitionMode PartitionMode = PartitionMode.Manual; [DisplayName("Split Distance 0")] [HelpText("Normalized distance to the end of the first cascade split")] [MinValue(0.0f)] [MaxValue(1.0f)] [StepSize(0.01f)] float SplitDistance0 = 0.05f; [DisplayName("Split Distance 1")] [HelpText("Normalized distance to the end of the first cascade split")] [MinValue(0.0f)] [MaxValue(1.0f)] [StepSize(0.01f)] float SplitDistance1 = 0.15f; [DisplayName("Split Distance 2")] [HelpText("Normalized distance to the end of the first cascade split")] [MinValue(0.0f)] [MaxValue(1.0f)] [StepSize(0.01f)] float SplitDistance2 = 0.5f; [DisplayName("Split Distance 3")] [HelpText("Normalized distance to the end of the first cascade split")] [MinValue(0.0f)] [MaxValue(1.0f)] [StepSize(0.01f)] float SplitDistance3 = 1.0f; [DisplayName("PSSM Lambda")] [HelpText("Lambda parameter used when PSSM mode is used for generated, " + "blends between a linear and a logarithmic distribution")] [MinValue(0.0f)] [MaxValue(1.0f)] [StepSize(0.01f)] float PSSMLambda = 1.0f; [DisplayName("Cascade Selection Mode")] [HelpText("Controls how cascades are selected per-pixel in the shader")] [UseAsShaderConstant(false)] CascadeSelectionModes CascadeSelectionMode = CascadeSelectionModes.SplitDepth; } public class Shadows { [DisplayName("Shadow Mode")] [HelpText("The shadow mapping technique to use")] [UseAsShaderConstant(false)] ShadowMode ShadowMode = ShadowMode.FixedSizePCF; [DisplayName("Shadow Map Size")] [HelpText("The size of the shadow map")] ShadowMapSize ShadowMapSize = ShadowMapSize.SMSize2048; [DisplayName("Depth Buffer Format")] [HelpText("The surface format used for the shadow depth buffer")] DepthBufferFormats DepthBufferFormat = DepthBufferFormats.DB32Float; [DisplayName("Fixed Filter Size")] [HelpText("Size of the PCF kernel used for Fixed Sized PCF shadow mode")] [UseAsShaderConstant(false)] FixedFilterSize FixedFilterSize = FixedFilterSize.Filter2x2; [DisplayName("Filter Size")] [MinValue(0.0f)] [MaxValue(100.0f)] [StepSize(0.1f)] [HelpText("Width of the filter kernel used for PCF or VSM filtering")] float FilterSize = 0.0f; [DisplayName("Randomize Disc Offsets")] [HelpText("Applies a per-pixel random rotation to the sample locations when using disc PCF")] [UseAsShaderConstant(false)] bool RandomizeDiscOffsets = false; [DisplayName("Num Disc Samples")] [MinValue(1)] [MaxValue(64)] [HelpText("Number of samples to take when using randomized disc PCF")] int NumDiscSamples = 16; [DisplayName("Use Receiver Plane Depth Bias")] [HelpText("Automatically computes a bias value based on the slope of the receiver")] [UseAsShaderConstant(false)] bool UsePlaneDepthBias = true; [DisplayName("Bias")] [HelpText("Bias used for shadow map depth comparisons")] [MinValue(0.0f)] [MaxValue(0.01f)] [StepSize(0.0001f)] float Bias = 0.005f; [DisplayName("VSM Bias (x100)")] [HelpText("Bias used for VSM evaluation")] [MinValue(0.0f)] [MaxValue(100.0f)] [StepSize(0.001f)] float VSMBias = 0.01f; [DisplayName("Normal Offset Scale")] [HelpText("Shadow receiver offset along the surface normal direction")] [MinValue(0.0f)] [MaxValue(100.0f)] [StepSize(0.1f)] float OffsetScale = 0.0f; [DisplayName("Shadow MSAA")] [HelpText("MSAA mode to use for VSM or MSM shadow maps")] [UseAsShaderConstant(false)] ShadowMSAA ShadowMSAA = ShadowMSAA.MSAANone; [DisplayName("VSM/MSM Format")] [HelpText("Texture format to use for VSM or <SM shadow maps")] SMFormat SMFormat = SMFormat.SM32Bit; [DisplayName("Shadow Anisotropy")] [HelpText("Level of anisotropic filtering to use when sampling VSM shadow maps")] [UseAsShaderConstant(false)] ShadowAnisotropy ShadowAnisotropy = ShadowAnisotropy.Anisotropy1x; [DisplayName("Enable Shadow Mip Maps")] [HelpText("Generates mip maps when using VSM or MSM")] [UseAsShaderConstant(false)] bool EnableShadowMips = false; [DisplayName("EVSM Positive Exponent")] [MinValue(0.0f)] [MaxValue(100.0f)] [StepSize(0.1f)] [HelpText("Exponent used for the positive EVSM warp")] float PositiveExponent = 40.0f; [DisplayName("EVSM Negative Exponent")] [MinValue(0.0f)] [MaxValue(100.0f)] [StepSize(0.1f)] [HelpText("Exponent used for the negative EVSM warp")] float NegativeExponent = 5.0f; [DisplayName("Light Bleeding Reduction")] [MinValue(0.0f)] [MaxValue(1.0f)] [StepSize(0.01f)] [HelpText("Light bleeding reduction factor for VSM and EVSM shadows")] float LightBleedingReduction = 0.0f; [DisplayName("MSM Depth Bias (x1000)")] [MinValue(0.0f)] [MaxValue(100.0f)] [StepSize(0.001f)] [HelpText("Depth bias amount for MSM shadows")] float MSMDepthBias = 0.0f; [DisplayName("MSM Moment Bias (x1000)")] [MinValue(0.0f)] [MaxValue(100.0f)] [StepSize(0.001f)] [HelpText("Moment bias amount for MSM shadows")] float MSMMomentBias = 0.003f; } public class PostProcessing { [DisplayName("Bloom Exposure Offset")] [MinValue(0.0f)] [MaxValue(20.0f)] [StepSize(0.01f)] [HelpText("Exposure offset applied to generate the input of the bloom pass")] float BloomThreshold = 3.0f; [DisplayName("Bloom Magnitude")] [MinValue(0.0f)] [MaxValue(2.0f)] [StepSize(0.01f)] [HelpText("Scale factor applied to the bloom results when combined with tone-mapped result")] float BloomMagnitude = 1.0f; [DisplayName("Bloom Blur Sigma")] [MinValue(0.5f)] [MaxValue(1.5f)] [StepSize(0.01f)] [HelpText("Sigma parameter of the Gaussian filter used in the bloom pass")] float BloomBlurSigma = 0.8f; [DisplayName("Auto-Exposure Key Value")] [MinValue(0.0f)] [MaxValue(0.5f)] [StepSize(0.01f)] [HelpText("Parameter that biases the result of the auto-exposure pass")] float KeyValue = 0.115f; [DisplayName("Adaptation Rate")] [MinValue(0.0f)] [MaxValue(4.0f)] [StepSize(0.01f)] [HelpText("Controls how quickly auto-exposure adapts to changes in scene brightness")] float AdaptationRate = 0.5f; } };
//------------------------------------------------------------------------------ // <copyright file="ToolBarButton.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* */ namespace System.Windows.Forms { using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; using System.Runtime.Remoting; using System.ComponentModel; using System.ComponentModel.Design; using System.Diagnostics; using System; using System.Drawing; using System.Text; using System.Drawing.Design; using Marshal = System.Runtime.InteropServices.Marshal; using System.Windows.Forms; using Microsoft.Win32; using System.Globalization; /// <include file='doc\ToolBarButton.uex' path='docs/doc[@for="ToolBarButton"]/*' /> /// <devdoc> /// <para> /// Represents a Windows toolbar button.</para> /// </devdoc> [ Designer("System.Windows.Forms.Design.ToolBarButtonDesigner, " + AssemblyRef.SystemDesign), DefaultProperty("Text"), ToolboxItem(false), DesignTimeVisible(false), ] public class ToolBarButton : Component { string text; string name = null; string tooltipText; bool enabled = true; bool visible = true; bool pushed = false; bool partialPush = false; private int commandId = -1; // the cached command id of the button. private ToolBarButtonImageIndexer imageIndexer; ToolBarButtonStyle style = ToolBarButtonStyle.PushButton; object userData; // These variables below are used by the ToolBar control to help // it manage some information about us. /// <include file='doc\ToolBarButton.uex' path='docs/doc[@for="ToolBarButton.stringIndex"]/*' /> /// <devdoc> /// If this button has a string, what it's index is in the ToolBar's /// internal list of strings. Needs to be package protected. /// </devdoc> /// <internalonly/> internal IntPtr stringIndex = (IntPtr)(-1); /// <include file='doc\ToolBarButton.uex' path='docs/doc[@for="ToolBarButton.parent"]/*' /> /// <devdoc> /// Our parent ToolBar control. /// </devdoc> /// <internalonly/> internal ToolBar parent; /// <include file='doc\ToolBarButton.uex' path='docs/doc[@for="ToolBarButton.dropDownMenu"]/*' /> /// <devdoc> /// For DropDown buttons, we can optionally show a /// context menu when the button is dropped down. /// </devdoc> internal Menu dropDownMenu = null; /// <include file='doc\ToolBarButton.uex' path='docs/doc[@for="ToolBarButton.ToolBarButton"]/*' /> /// <devdoc> /// <para>Initializes a new instance of the <see cref='System.Windows.Forms.ToolBarButton'/> class.</para> /// </devdoc> public ToolBarButton() { } /// <include file='doc\ToolBarButton.uex' path='docs/doc[@for="ToolBarButton.ToolBarButton1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public ToolBarButton(string text) : base() { this.Text = text; } // We need a special way to defer to the ToolBar's image // list for indexing purposes. internal class ToolBarButtonImageIndexer : ImageList.Indexer { private ToolBarButton owner; public ToolBarButtonImageIndexer(ToolBarButton button) { owner = button; } public override ImageList ImageList { get { if ((owner != null) && (owner.parent != null)) { return owner.parent.ImageList; } return null; } set { Debug.Assert(false, "We should never set the image list"); } } } internal ToolBarButtonImageIndexer ImageIndexer { get { if (imageIndexer == null) { imageIndexer = new ToolBarButtonImageIndexer(this); } return imageIndexer; } } /// <include file='doc\ToolBarButton.uex' path='docs/doc[@for="ToolBarButton.DropDownMenu"]/*' /> /// <devdoc> /// <para> /// Indicates the menu to be displayed in /// the drop-down toolbar button.</para> /// </devdoc> [ DefaultValue(null), TypeConverterAttribute(typeof(ReferenceConverter)), SRDescription(SR.ToolBarButtonMenuDescr) ] public Menu DropDownMenu { get { return dropDownMenu; } set { //The dropdownmenu must be of type ContextMenu, Main & Items are invalid. // if (value != null && !(value is ContextMenu)) { throw new ArgumentException(SR.GetString(SR.ToolBarButtonInvalidDropDownMenuType)); } dropDownMenu = value; } } /// <include file='doc\ToolBarButton.uex' path='docs/doc[@for="ToolBarButton.Enabled"]/*' /> /// <devdoc> /// <para>Indicates whether the button is enabled or not.</para> /// </devdoc> [ DefaultValue(true), Localizable(true), SRDescription(SR.ToolBarButtonEnabledDescr) ] public bool Enabled { get { return enabled; } set { if (enabled != value) { enabled = value; if (parent != null && parent.IsHandleCreated) { parent.SendMessage(NativeMethods.TB_ENABLEBUTTON, FindButtonIndex(), enabled ? 1 : 0); } } } } /// <include file='doc\ToolBarButton.uex' path='docs/doc[@for="ToolBarButton.ImageIndex"]/*' /> /// <devdoc> /// <para> Indicates the index /// value of the image assigned to the button.</para> /// </devdoc> [ TypeConverterAttribute(typeof(ImageIndexConverter)), Editor("System.Windows.Forms.Design.ImageIndexEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), DefaultValue(-1), RefreshProperties(RefreshProperties.Repaint), Localizable(true), SRDescription(SR.ToolBarButtonImageIndexDescr) ] public int ImageIndex { get { return ImageIndexer.Index; } set { if (ImageIndexer.Index != value) { if (value < -1) throw new ArgumentOutOfRangeException("ImageIndex", SR.GetString(SR.InvalidLowBoundArgumentEx, "ImageIndex", (value).ToString(CultureInfo.CurrentCulture), -1)); ImageIndexer.Index = value; UpdateButton(false); } } } /// <include file='doc\ToolBarButton.uex' path='docs/doc[@for="ToolBarButton.ImageIndex"]/*' /> /// <devdoc> /// <para> Indicates the index /// value of the image assigned to the button.</para> /// </devdoc> [ TypeConverterAttribute(typeof(ImageKeyConverter)), Editor("System.Windows.Forms.Design.ImageIndexEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), DefaultValue(""), Localizable(true), RefreshProperties(RefreshProperties.Repaint), SRDescription(SR.ToolBarButtonImageIndexDescr) ] public string ImageKey { get { return ImageIndexer.Key; } set { if (ImageIndexer.Key != value) { ImageIndexer.Key = value; UpdateButton(false); } } } /// <include file='doc\ToolBarButton.uex' path='docs/doc[@for="ToolBarButton.Name"]/*' /> /// <devdoc> /// Name of this control. The designer will set this to the same /// as the programatic Id "(name)" of the control - however this /// property has no bearing on the runtime aspects of this control. /// </devdoc> [Browsable(false)] public string Name { get { return WindowsFormsUtils.GetComponentName(this, name); } set { if (value == null || value.Length == 0) { name = null; } else { name = value; } if(Site!= null) { Site.Name = name; } } } /// <include file='doc\ToolBarButton.uex' path='docs/doc[@for="ToolBarButton.Parent"]/*' /> /// <devdoc> /// <para>Indicates the toolbar control that the toolbar button is assigned to. This property is /// read-only.</para> /// </devdoc> [ Browsable(false), ] public ToolBar Parent { get { return parent; } } /// <include file='doc\ToolBarButton.uex' path='docs/doc[@for="ToolBarButton.PartialPush"]/*' /> /// <devdoc> /// <para> /// Indicates whether a toggle-style toolbar button /// is partially pushed.</para> /// </devdoc> [ DefaultValue(false), SRDescription(SR.ToolBarButtonPartialPushDescr) ] public bool PartialPush { get { if (parent == null || !parent.IsHandleCreated) return partialPush; else { if ((int)parent.SendMessage(NativeMethods.TB_ISBUTTONINDETERMINATE, FindButtonIndex(), 0) != 0) partialPush = true; else partialPush = false; return partialPush; } } set { if (partialPush != value) { partialPush = value; UpdateButton(false); } } } /// <include file='doc\ToolBarButton.uex' path='docs/doc[@for="ToolBarButton.Pushed"]/*' /> /// <devdoc> /// <para>Indicates whether a toggle-style toolbar button is currently in the pushed state.</para> /// </devdoc> [ DefaultValue(false), SRDescription(SR.ToolBarButtonPushedDescr) ] public bool Pushed { get { if (parent == null || !parent.IsHandleCreated) return pushed; else { return GetPushedState(); } } set { if (value != Pushed) { // Getting property Pushed updates pushed member variable pushed = value; UpdateButton(false, false, false); } } } /// <include file='doc\ToolBarButton.uex' path='docs/doc[@for="ToolBarButton.Rectangle"]/*' /> /// <devdoc> /// <para>Indicates the bounding rectangle for a toolbar button. This property is /// read-only.</para> /// </devdoc> public Rectangle Rectangle { get { if (parent != null) { NativeMethods.RECT rc = new NativeMethods.RECT(); UnsafeNativeMethods.SendMessage(new HandleRef(parent, parent.Handle), NativeMethods.TB_GETRECT, FindButtonIndex(), ref rc); return Rectangle.FromLTRB(rc.left, rc.top, rc.right, rc.bottom); } return Rectangle.Empty; } } /// <include file='doc\ToolBarButton.uex' path='docs/doc[@for="ToolBarButton.Style"]/*' /> /// <devdoc> /// <para> Indicates the style of the /// toolbar button.</para> /// </devdoc> [ DefaultValue(ToolBarButtonStyle.PushButton), SRDescription(SR.ToolBarButtonStyleDescr), RefreshProperties(RefreshProperties.Repaint) ] public ToolBarButtonStyle Style { get { return style; } set { //valid values are 0x1 to 0x4 if (!ClientUtils.IsEnumValid(value, (int)value, (int)ToolBarButtonStyle.PushButton, (int)ToolBarButtonStyle.DropDownButton)){ throw new InvalidEnumArgumentException("value", (int)value, typeof(ToolBarButtonStyle)); } if (style == value) return; style = value; UpdateButton(true); } } /// <include file='doc\ToolBarButton.uex' path='docs/doc[@for="ToolBarButton.Tag"]/*' /> [ SRCategory(SR.CatData), Localizable(false), Bindable(true), SRDescription(SR.ControlTagDescr), DefaultValue(null), TypeConverter(typeof(StringConverter)), ] public object Tag { get { return userData; } set { userData = value; } } /// <include file='doc\ToolBarButton.uex' path='docs/doc[@for="ToolBarButton.Text"]/*' /> /// <devdoc> /// <para> Indicates the text that is displayed on the toolbar button.</para> /// </devdoc> [ Localizable(true), DefaultValue(""), SRDescription(SR.ToolBarButtonTextDescr) ] public string Text { get { return(text == null) ? "" : text; } set { if (String.IsNullOrEmpty(value)) { value = null; } if ( (value == null && text != null) || (value != null && (text == null || !text.Equals(value)))) { text = value; // 94943 VSWhidbey Adding a mnemonic requires a handle recreate. UpdateButton(WindowsFormsUtils.ContainsMnemonic(text), true, true); } } } /// <include file='doc\ToolBarButton.uex' path='docs/doc[@for="ToolBarButton.ToolTipText"]/*' /> /// <devdoc> /// <para> /// Indicates /// the text that appears as a tool tip for a control.</para> /// </devdoc> [ Localizable(true), DefaultValue(""), SRDescription(SR.ToolBarButtonToolTipTextDescr) ] public string ToolTipText { get { return tooltipText == null ? "" : tooltipText; } set { tooltipText = value; } } /// <include file='doc\ToolBarButton.uex' path='docs/doc[@for="ToolBarButton.Visible"]/*' /> /// <devdoc> /// <para> /// Indicates whether the toolbar button /// is visible.</para> /// </devdoc> [ DefaultValue(true), Localizable(true), SRDescription(SR.ToolBarButtonVisibleDescr) ] public bool Visible { get { return visible; } set { if (visible != value) { visible = value; UpdateButton(false); } } } /// <include file='doc\ToolBarButton.uex' path='docs/doc[@for="ToolBarButton.Width"]/*' /> /// <devdoc> /// This is somewhat nasty -- by default, the windows ToolBar isn't very /// clever about setting the width of buttons, and has a very primitive /// algorithm that doesn't include for things like drop down arrows, etc. /// We need to do a bunch of work here to get all the widths correct. Ugh. /// </devdoc> /// <internalonly/> internal short Width { get { Debug.Assert(parent != null, "Parent should be non-null when button width is requested"); int width = 0; ToolBarButtonStyle style = Style; Size edge = SystemInformation.Border3DSize; if (style != ToolBarButtonStyle.Separator) { // COMPAT: this will force handle creation. // we could use the measurement graphics, but it looks like this has been like this since Everett. using (Graphics g = this.parent.CreateGraphicsInternal()) { Size buttonSize = this.parent.buttonSize; if (!(buttonSize.IsEmpty)) { width = buttonSize.Width; } else { if (this.parent.ImageList != null || !String.IsNullOrEmpty(Text)) { Size imageSize = this.parent.ImageSize; Size textSize = Size.Ceiling(g.MeasureString(Text, parent.Font)); if (this.parent.TextAlign == ToolBarTextAlign.Right) { if (textSize.Width == 0) width = imageSize.Width + edge.Width * 4; else width = imageSize.Width + textSize.Width + edge.Width * 6; } else { if (imageSize.Width > textSize.Width) width = imageSize.Width + edge.Width * 4; else width = textSize.Width + edge.Width * 4; } if (style == ToolBarButtonStyle.DropDownButton && this.parent.DropDownArrows) { width += ToolBar.DDARROW_WIDTH; } } else width = this.parent.ButtonSize.Width; } } } else { width = edge.Width * 2; } return(short)width; } } /// <include file='doc\ToolBarButton.uex' path='docs/doc[@for="ToolBarButton.Dispose"]/*' /> /// <internalonly/> /// <devdoc> /// </devdoc> protected override void Dispose(bool disposing) { if (disposing) { if (parent != null) { int index = FindButtonIndex(); if (index != -1) { parent.Buttons.RemoveAt(index); } } } base.Dispose(disposing); } /// <include file='doc\ToolBarButton.uex' path='docs/doc[@for="ToolBarButton.FindButtonIndex"]/*' /> /// <devdoc> /// Finds out index in the parent. /// </devdoc> /// <internalonly/> private int FindButtonIndex() { for (int x = 0; x < parent.Buttons.Count; x++) { if (parent.Buttons[x] == this) { return x; } } return -1; } // VSWhidbey 177016: This is necessary to get the width of the buttons in the toolbar, // including the width of separators, so that we can accurately position the tooltip adjacent // to the currently hot button when the user uses keyboard navigation to access the toolbar. internal int GetButtonWidth() { // Assume that this button is the same width as the parent's ButtonSize's Width int buttonWidth = Parent.ButtonSize.Width; NativeMethods.TBBUTTONINFO button = new NativeMethods.TBBUTTONINFO(); button.cbSize = Marshal.SizeOf(typeof(NativeMethods.TBBUTTONINFO)); button.dwMask = NativeMethods.TBIF_SIZE; int buttonID = (int)UnsafeNativeMethods.SendMessage(new HandleRef(Parent, Parent.Handle), NativeMethods.TB_GETBUTTONINFO, commandId, ref button); if (buttonID != -1) { buttonWidth = button.cx; } return buttonWidth; } private bool GetPushedState() { if ((int)parent.SendMessage(NativeMethods.TB_ISBUTTONCHECKED, FindButtonIndex(), 0) != 0) { pushed = true; } else { pushed = false; } return pushed; } /// <include file='doc\ToolBarButton.uex' path='docs/doc[@for="ToolBarButton.GetTBBUTTON"]/*' /> /// <devdoc> /// Returns a TBBUTTON object that represents this ToolBarButton. /// </devdoc> internal NativeMethods.TBBUTTON GetTBBUTTON(int commandId) { NativeMethods.TBBUTTON button = new NativeMethods.TBBUTTON(); button.iBitmap = ImageIndexer.ActualIndex; // set up the state of the button // button.fsState = 0; if (enabled) button.fsState |= NativeMethods.TBSTATE_ENABLED; if (partialPush && style == ToolBarButtonStyle.ToggleButton) button.fsState |= NativeMethods.TBSTATE_INDETERMINATE; if (pushed) button.fsState |= NativeMethods.TBSTATE_CHECKED; if (!visible) button.fsState |= NativeMethods.TBSTATE_HIDDEN; // set the button style // switch (style) { case ToolBarButtonStyle.PushButton: button.fsStyle = NativeMethods.TBSTYLE_BUTTON; break; case ToolBarButtonStyle.ToggleButton: button.fsStyle = NativeMethods.TBSTYLE_CHECK; break; case ToolBarButtonStyle.Separator: button.fsStyle = NativeMethods.TBSTYLE_SEP; break; case ToolBarButtonStyle.DropDownButton: button.fsStyle = NativeMethods.TBSTYLE_DROPDOWN; break; } button.dwData = (IntPtr)0; button.iString = this.stringIndex; this.commandId = commandId; button.idCommand = commandId; return button; } /// <include file='doc\ToolBarButton.uex' path='docs/doc[@for="ToolBarButton.GetTBBUTTONINFO"]/*' /> /// <devdoc> /// Returns a TBBUTTONINFO object that represents this ToolBarButton. /// </devdoc> internal NativeMethods.TBBUTTONINFO GetTBBUTTONINFO(bool updateText, int newCommandId) { NativeMethods.TBBUTTONINFO button = new NativeMethods.TBBUTTONINFO(); button.cbSize = Marshal.SizeOf(typeof(NativeMethods.TBBUTTONINFO)); button.dwMask = NativeMethods.TBIF_IMAGE | NativeMethods.TBIF_STATE | NativeMethods.TBIF_STYLE; // Comctl on Win98 interprets null strings as empty strings, which forces // the button to leave space for text. The only workaround is to avoid having comctl // update the text. if (updateText) { button.dwMask |= NativeMethods.TBIF_TEXT; } button.iImage = ImageIndexer.ActualIndex; if (newCommandId != commandId) { commandId = newCommandId; button.idCommand = newCommandId; button.dwMask |= NativeMethods.TBIF_COMMAND; } // set up the state of the button // button.fsState = 0; if (enabled) button.fsState |= NativeMethods.TBSTATE_ENABLED; if (partialPush && style == ToolBarButtonStyle.ToggleButton) button.fsState |= NativeMethods.TBSTATE_INDETERMINATE; if (pushed) button.fsState |= NativeMethods.TBSTATE_CHECKED; if (!visible) button.fsState |= NativeMethods.TBSTATE_HIDDEN; // set the button style // switch (style) { case ToolBarButtonStyle.PushButton: button.fsStyle = NativeMethods.TBSTYLE_BUTTON; break; case ToolBarButtonStyle.ToggleButton: button.fsStyle = NativeMethods.TBSTYLE_CHECK; break; case ToolBarButtonStyle.Separator: button.fsStyle = NativeMethods.TBSTYLE_SEP; break; } if (text == null) { button.pszText = Marshal.StringToHGlobalAuto("\0\0"); } else { string textValue = this.text; PrefixAmpersands(ref textValue); button.pszText = Marshal.StringToHGlobalAuto(textValue); } return button; } private void PrefixAmpersands(ref string value) { // Due to a comctl32 problem, ampersands underline the next letter in the // text string, but the accelerators don't work. // So in this function, we prefix ampersands with another ampersand // so that they actually appear as ampersands. // // Sanity check parameter // if (value == null || value.Length == 0) { return; } // If there are no ampersands, we don't need to do anything here // if (value.IndexOf('&') < 0) { return; } // Insert extra ampersands // StringBuilder newString = new StringBuilder(); for(int i=0; i < value.Length; ++i) { if (value[i] == '&') { if (i < value.Length - 1 && value[i+1] == '&') { ++i; // Skip the second ampersand } newString.Append("&&"); } else { newString.Append(value[i]); } } value = newString.ToString(); } /// <include file='doc\ToolBarButton.uex' path='docs/doc[@for="ToolBarButton.ToString"]/*' /> /// <devdoc> /// </devdoc> /// <internalonly/> public override string ToString() { return "ToolBarButton: " + Text + ", Style: " + Style.ToString("G"); } /// <include file='doc\ToolBarButton.uex' path='docs/doc[@for="ToolBarButton.UpdateButton"]/*' /> /// <devdoc> /// When a button property changes and the parent control is created, /// we need to make sure it gets the new button information. /// If Text was changed, call the next overload. /// </devdoc> internal void UpdateButton(bool recreate) { UpdateButton(recreate, false, true); } /// <include file='doc\ToolBarButton.uex' path='docs/doc[@for="ToolBarButton.UpdateButton1"]/*' /> /// <devdoc> /// When a button property changes and the parent control is created, /// we need to make sure it gets the new button information. /// </devdoc> private void UpdateButton(bool recreate, bool updateText, bool updatePushedState) { // It looks like ToolBarButtons with a DropDownButton tend to // lose the DropDownButton very easily - so we need to recreate // the button each time it changes just to be sure. // if (style == ToolBarButtonStyle.DropDownButton && parent != null && parent.DropDownArrows) { recreate = true; } // we just need to get the Pushed state : this asks the Button its states and sets // the private member "pushed" to right value.. // this member is used in "InternalSetButton" which calls GetTBBUTTONINFO(bool updateText) // the GetButtonInfo method uses the "pushed" variable.. //rather than setting it ourselves .... we asks the button to set it for us.. if (updatePushedState && parent != null && parent.IsHandleCreated) { GetPushedState(); } if (parent != null) { int index = FindButtonIndex(); if (index != -1) parent.InternalSetButton(index, this, recreate, updateText); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // This RegexNode class is internal to the Regex package. // It is built into a parsed tree for a regular expression. // Implementation notes: // // Since the node tree is a temporary data structure only used // during compilation of the regexp to integer codes, it's // designed for clarity and convenience rather than // space efficiency. // // RegexNodes are built into a tree, linked by the _children list. // Each node also has a _parent and _ichild member indicating // its parent and which child # it is in its parent's list. // // RegexNodes come in as many types as there are constructs in // a regular expression, for example, "concatenate", "alternate", // "one", "rept", "group". There are also node types for basic // peephole optimizations, e.g., "onerep", "notsetrep", etc. // // Because perl 5 allows "lookback" groups that scan backwards, // each node also gets a "direction". Normally the value of // boolean _backward = false. // // During parsing, top-level nodes are also stacked onto a parse // stack (a stack of trees). For this purpose we have a _next // pointer. [Note that to save a few bytes, we could overload the // _parent pointer instead.] // // On the parse stack, each tree has a "role" - basically, the // nonterminal in the grammar that the parser has currently // assigned to the tree. That code is stored in _role. // // Finally, some of the different kinds of nodes have data. // Two integers (for the looping constructs) are stored in // _operands, an an object (either a string or a set) // is stored in _data using System.Collections.Generic; using System.Diagnostics; using System.Globalization; namespace System.Text.RegularExpressions { internal sealed class RegexNode { // RegexNode types // The following are leaves, and correspond to primitive operations internal const int Oneloop = RegexCode.Oneloop; // c,n a* internal const int Notoneloop = RegexCode.Notoneloop; // c,n .* internal const int Setloop = RegexCode.Setloop; // set,n \d* internal const int Onelazy = RegexCode.Onelazy; // c,n a*? internal const int Notonelazy = RegexCode.Notonelazy; // c,n .*? internal const int Setlazy = RegexCode.Setlazy; // set,n \d*? internal const int One = RegexCode.One; // char a internal const int Notone = RegexCode.Notone; // char . [^a] internal const int Set = RegexCode.Set; // set [a-z] \w \s \d internal const int Multi = RegexCode.Multi; // string abcdef internal const int Ref = RegexCode.Ref; // index \1 internal const int Bol = RegexCode.Bol; // ^ internal const int Eol = RegexCode.Eol; // $ internal const int Boundary = RegexCode.Boundary; // \b internal const int Nonboundary = RegexCode.Nonboundary; // \B internal const int ECMABoundary = RegexCode.ECMABoundary; // \b internal const int NonECMABoundary = RegexCode.NonECMABoundary; // \B internal const int Beginning = RegexCode.Beginning; // \A internal const int Start = RegexCode.Start; // \G internal const int EndZ = RegexCode.EndZ; // \Z internal const int End = RegexCode.End; // \z // Interior nodes do not correspond to primitive operations, but // control structures compositing other operations // Concat and alternate take n children, and can run forward or backwards internal const int Nothing = 22; // [] internal const int Empty = 23; // () internal const int Alternate = 24; // a|b internal const int Concatenate = 25; // ab internal const int Loop = 26; // m,x * + ? {,} internal const int Lazyloop = 27; // m,x *? +? ?? {,}? internal const int Capture = 28; // n () internal const int Group = 29; // (?:) internal const int Require = 30; // (?=) (?<=) internal const int Prevent = 31; // (?!) (?<!) internal const int Greedy = 32; // (?>) (?<) internal const int Testref = 33; // (?(n) | ) internal const int Testgroup = 34; // (?(...) | ) // RegexNode data members internal int _type; internal List<RegexNode> _children; internal String _str; internal char _ch; internal int _m; internal int _n; internal readonly RegexOptions _options; internal RegexNode _next; internal RegexNode(int type, RegexOptions options) { _type = type; _options = options; } internal RegexNode(int type, RegexOptions options, char ch) { _type = type; _options = options; _ch = ch; } internal RegexNode(int type, RegexOptions options, String str) { _type = type; _options = options; _str = str; } internal RegexNode(int type, RegexOptions options, int m) { _type = type; _options = options; _m = m; } internal RegexNode(int type, RegexOptions options, int m, int n) { _type = type; _options = options; _m = m; _n = n; } internal bool UseOptionR() { return (_options & RegexOptions.RightToLeft) != 0; } internal RegexNode ReverseLeft() { if (UseOptionR() && _type == Concatenate && _children != null) { _children.Reverse(0, _children.Count); } return this; } /// <summary> /// Pass type as OneLazy or OneLoop /// </summary> internal void MakeRep(int type, int min, int max) { _type += (type - One); _m = min; _n = max; } /// <summary> /// Removes redundant nodes from the subtree, and returns a reduced subtree. /// </summary> internal RegexNode Reduce() { RegexNode n; switch (Type()) { case Alternate: n = ReduceAlternation(); break; case Concatenate: n = ReduceConcatenation(); break; case Loop: case Lazyloop: n = ReduceRep(); break; case Group: n = ReduceGroup(); break; case Set: case Setloop: n = ReduceSet(); break; default: n = this; break; } return n; } /// <summary> /// Simple optimization. If a concatenation or alternation has only /// one child strip out the intermediate node. If it has zero children, /// turn it into an empty. /// </summary> internal RegexNode StripEnation(int emptyType) { switch (ChildCount()) { case 0: return new RegexNode(emptyType, _options); case 1: return Child(0); default: return this; } } /// <summary> /// Simple optimization. Once parsed into a tree, noncapturing groups /// serve no function, so strip them out. /// </summary> internal RegexNode ReduceGroup() { RegexNode u; for (u = this; u.Type() == Group;) u = u.Child(0); return u; } /// <summary> /// Nested repeaters just get multiplied with each other if they're not /// too lumpy /// </summary> internal RegexNode ReduceRep() { RegexNode u; RegexNode child; int type; int min; int max; u = this; type = Type(); min = _m; max = _n; for (; ;) { if (u.ChildCount() == 0) break; child = u.Child(0); // multiply reps of the same type only if (child.Type() != type) { int childType = child.Type(); if (!(childType >= Oneloop && childType <= Setloop && type == Loop || childType >= Onelazy && childType <= Setlazy && type == Lazyloop)) break; } // child can be too lumpy to blur, e.g., (a {100,105}) {3} or (a {2,})? // [but things like (a {2,})+ are not too lumpy...] if (u._m == 0 && child._m > 1 || child._n < child._m * 2) break; u = child; if (u._m > 0) u._m = min = ((Int32.MaxValue - 1) / u._m < min) ? Int32.MaxValue : u._m * min; if (u._n > 0) u._n = max = ((Int32.MaxValue - 1) / u._n < max) ? Int32.MaxValue : u._n * max; } return min == Int32.MaxValue ? new RegexNode(Nothing, _options) : u; } /// <summary> /// Simple optimization. If a set is a singleton, an inverse singleton, /// or empty, it's transformed accordingly. /// </summary> internal RegexNode ReduceSet() { // Extract empty-set, one and not-one case as special if (RegexCharClass.IsEmpty(_str)) { _type = Nothing; _str = null; } else if (RegexCharClass.IsSingleton(_str)) { _ch = RegexCharClass.SingletonChar(_str); _str = null; _type += (One - Set); } else if (RegexCharClass.IsSingletonInverse(_str)) { _ch = RegexCharClass.SingletonChar(_str); _str = null; _type += (Notone - Set); } return this; } /// <summary> /// Basic optimization. Single-letter alternations can be replaced /// by faster set specifications, and nested alternations with no /// intervening operators can be flattened: /// /// a|b|c|def|g|h -> [a-c]|def|[gh] /// apple|(?:orange|pear)|grape -> apple|orange|pear|grape /// </summary> internal RegexNode ReduceAlternation() { // Combine adjacent sets/chars bool wasLastSet; bool lastNodeCannotMerge; RegexOptions optionsLast; RegexOptions optionsAt; int i; int j; RegexNode at; RegexNode prev; if (_children == null) return new RegexNode(RegexNode.Nothing, _options); wasLastSet = false; lastNodeCannotMerge = false; optionsLast = 0; for (i = 0, j = 0; i < _children.Count; i++, j++) { at = _children[i]; if (j < i) _children[j] = at; for (; ;) { if (at._type == Alternate) { for (int k = 0; k < at._children.Count; k++) at._children[k]._next = this; _children.InsertRange(i + 1, at._children); j--; } else if (at._type == Set || at._type == One) { // Cannot merge sets if L or I options differ, or if either are negated. optionsAt = at._options & (RegexOptions.RightToLeft | RegexOptions.IgnoreCase); if (at._type == Set) { if (!wasLastSet || optionsLast != optionsAt || lastNodeCannotMerge || !RegexCharClass.IsMergeable(at._str)) { wasLastSet = true; lastNodeCannotMerge = !RegexCharClass.IsMergeable(at._str); optionsLast = optionsAt; break; } } else if (!wasLastSet || optionsLast != optionsAt || lastNodeCannotMerge) { wasLastSet = true; lastNodeCannotMerge = false; optionsLast = optionsAt; break; } // The last node was a Set or a One, we're a Set or One and our options are the same. // Merge the two nodes. j--; prev = _children[j]; RegexCharClass prevCharClass; if (prev._type == RegexNode.One) { prevCharClass = new RegexCharClass(); prevCharClass.AddChar(prev._ch); } else { prevCharClass = RegexCharClass.Parse(prev._str); } if (at._type == RegexNode.One) { prevCharClass.AddChar(at._ch); } else { RegexCharClass atCharClass = RegexCharClass.Parse(at._str); prevCharClass.AddCharClass(atCharClass); } prev._type = RegexNode.Set; prev._str = prevCharClass.ToStringClass(); } else if (at._type == RegexNode.Nothing) { j--; } else { wasLastSet = false; lastNodeCannotMerge = false; } break; } } if (j < i) _children.RemoveRange(j, i - j); return StripEnation(RegexNode.Nothing); } /// <summary> /// Basic optimization. Adjacent strings can be concatenated. /// /// (?:abc)(?:def) -> abcdef /// </summary> internal RegexNode ReduceConcatenation() { // Eliminate empties and concat adjacent strings/chars bool wasLastString; RegexOptions optionsLast; RegexOptions optionsAt; int i; int j; if (_children == null) return new RegexNode(RegexNode.Empty, _options); wasLastString = false; optionsLast = 0; for (i = 0, j = 0; i < _children.Count; i++, j++) { RegexNode at; RegexNode prev; at = _children[i]; if (j < i) _children[j] = at; if (at._type == RegexNode.Concatenate && ((at._options & RegexOptions.RightToLeft) == (_options & RegexOptions.RightToLeft))) { for (int k = 0; k < at._children.Count; k++) at._children[k]._next = this; _children.InsertRange(i + 1, at._children); j--; } else if (at._type == RegexNode.Multi || at._type == RegexNode.One) { // Cannot merge strings if L or I options differ optionsAt = at._options & (RegexOptions.RightToLeft | RegexOptions.IgnoreCase); if (!wasLastString || optionsLast != optionsAt) { wasLastString = true; optionsLast = optionsAt; continue; } prev = _children[--j]; if (prev._type == RegexNode.One) { prev._type = RegexNode.Multi; prev._str = Convert.ToString(prev._ch, CultureInfo.InvariantCulture); } if ((optionsAt & RegexOptions.RightToLeft) == 0) { if (at._type == RegexNode.One) prev._str += at._ch.ToString(); else prev._str += at._str; } else { if (at._type == RegexNode.One) prev._str = at._ch.ToString() + prev._str; else prev._str = at._str + prev._str; } } else if (at._type == RegexNode.Empty) { j--; } else { wasLastString = false; } } if (j < i) _children.RemoveRange(j, i - j); return StripEnation(RegexNode.Empty); } internal RegexNode MakeQuantifier(bool lazy, int min, int max) { RegexNode result; if (min == 0 && max == 0) return new RegexNode(RegexNode.Empty, _options); if (min == 1 && max == 1) return this; switch (_type) { case RegexNode.One: case RegexNode.Notone: case RegexNode.Set: MakeRep(lazy ? RegexNode.Onelazy : RegexNode.Oneloop, min, max); return this; default: result = new RegexNode(lazy ? RegexNode.Lazyloop : RegexNode.Loop, _options, min, max); result.AddChild(this); return result; } } internal void AddChild(RegexNode newChild) { RegexNode reducedChild; if (_children == null) _children = new List<RegexNode>(4); reducedChild = newChild.Reduce(); _children.Add(reducedChild); reducedChild._next = this; } internal RegexNode Child(int i) { return _children[i]; } internal int ChildCount() { return _children == null ? 0 : _children.Count; } internal int Type() { return _type; } #if DEBUG internal static String[] TypeStr = new String[] { "Onerep", "Notonerep", "Setrep", "Oneloop", "Notoneloop", "Setloop", "Onelazy", "Notonelazy", "Setlazy", "One", "Notone", "Set", "Multi", "Ref", "Bol", "Eol", "Boundary", "Nonboundary", "ECMABoundary", "NonECMABoundary", "Beginning", "Start", "EndZ", "End", "Nothing", "Empty", "Alternate", "Concatenate", "Loop", "Lazyloop", "Capture", "Group", "Require", "Prevent", "Greedy", "Testref", "Testgroup"}; internal String Description() { StringBuilder ArgSb = new StringBuilder(); ArgSb.Append(TypeStr[_type]); if ((_options & RegexOptions.ExplicitCapture) != 0) ArgSb.Append("-C"); if ((_options & RegexOptions.IgnoreCase) != 0) ArgSb.Append("-I"); if ((_options & RegexOptions.RightToLeft) != 0) ArgSb.Append("-L"); if ((_options & RegexOptions.Multiline) != 0) ArgSb.Append("-M"); if ((_options & RegexOptions.Singleline) != 0) ArgSb.Append("-S"); if ((_options & RegexOptions.IgnorePatternWhitespace) != 0) ArgSb.Append("-X"); if ((_options & RegexOptions.ECMAScript) != 0) ArgSb.Append("-E"); switch (_type) { case Oneloop: case Notoneloop: case Onelazy: case Notonelazy: case One: case Notone: ArgSb.Append("(Ch = " + RegexCharClass.CharDescription(_ch) + ")"); break; case Capture: ArgSb.Append("(index = " + _m.ToString(CultureInfo.InvariantCulture) + ", unindex = " + _n.ToString(CultureInfo.InvariantCulture) + ")"); break; case Ref: case Testref: ArgSb.Append("(index = " + _m.ToString(CultureInfo.InvariantCulture) + ")"); break; case Multi: ArgSb.Append("(String = " + _str + ")"); break; case Set: case Setloop: case Setlazy: ArgSb.Append("(Set = " + RegexCharClass.SetDescription(_str) + ")"); break; } switch (_type) { case Oneloop: case Notoneloop: case Onelazy: case Notonelazy: case Setloop: case Setlazy: case Loop: case Lazyloop: ArgSb.Append("(Min = " + _m.ToString(CultureInfo.InvariantCulture) + ", Max = " + (_n == Int32.MaxValue ? "inf" : Convert.ToString(_n, CultureInfo.InvariantCulture)) + ")"); break; } return ArgSb.ToString(); } internal const String Space = " "; internal void Dump() { List<int> Stack = new List<int>(); RegexNode CurNode; int CurChild; CurNode = this; CurChild = 0; Debug.WriteLine(CurNode.Description()); for (; ;) { if (CurNode._children != null && CurChild < CurNode._children.Count) { Stack.Add(CurChild + 1); CurNode = CurNode._children[CurChild]; CurChild = 0; int Depth = Stack.Count; if (Depth > 32) Depth = 32; Debug.WriteLine(Space.Substring(0, Depth) + CurNode.Description()); } else { if (Stack.Count == 0) break; CurChild = Stack[Stack.Count - 1]; Stack.RemoveAt(Stack.Count - 1); CurNode = CurNode._next; } } } #endif } }
// Generated by SharpKit.QooxDoo.Generator using System; using System.Collections.Generic; using SharpKit.Html; using SharpKit.JavaScript; using qx.ui.core; namespace qx.ui.toolbar { /// <summary> /// <para>A part is a container for multiple toolbar buttons. Each part comes /// with a handle which may be used in later versions to drag the part /// around and move it to another position. Currently mainly used /// for structuring large toolbars beyond the capabilities of the /// <see cref="Separator"/>.</para> /// </summary> [JsType(JsMode.Prototype, Name = "qx.ui.toolbar.Part", OmitOptionalParameters = true, Export = false)] public partial class Part : qx.ui.core.Widget { #region Events /// <summary> /// Fired on change of the property <see cref="Show"/>. /// </summary> public event Action<qx.eventx.type.Data> OnChangeShow; #endregion Events #region Properties /// <summary> /// <para>The appearance ID. This ID is used to identify the appearance theme /// entry to use for this widget. This controls the styling of the element.</para> /// </summary> [JsProperty(Name = "appearance", NativeField = true)] public string Appearance { get; set; } /// <summary> /// <para>Whether icons, labels, both or none should be shown.</para> /// </summary> /// <remarks> /// Possible values: "both","label","icon" /// </remarks> [JsProperty(Name = "show", NativeField = true)] public object Show { get; set; } /// <summary> /// <para>The spacing between every child of the toolbar</para> /// </summary> /// <remarks> /// Allow nulls: true /// </remarks> [JsProperty(Name = "spacing", NativeField = true)] public double Spacing { get; set; } #endregion Properties #region Methods public Part() { throw new NotImplementedException(); } /// <summary> /// <para>Adds a separator to the toolbar part.</para> /// </summary> [JsMethod(Name = "addSeparator")] public void AddSeparator() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the widget which contains the children and /// is relevant for laying them out. This is from the user point of /// view and may not be identical to the technical structure.</para> /// </summary> /// <returns>Widget which contains the children.</returns> [JsMethod(Name = "getChildrenContainer")] public qx.ui.core.Widget GetChildrenContainer() { throw new NotImplementedException(); } /// <summary> /// <para>Returns all nested buttons which contains a menu to show. This is mainly /// used for keyboard support.</para> /// </summary> /// <returns>List of all menu buttons</returns> [JsMethod(Name = "getMenuButtons")] public JsArray GetMenuButtons() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the (computed) value of the property show.</para> /// </summary> [JsMethod(Name = "getShow")] public object GetShow() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the (computed) value of the property spacing.</para> /// </summary> [JsMethod(Name = "getSpacing")] public double GetSpacing() { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property show /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property show.</param> [JsMethod(Name = "initShow")] public void InitShow(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property spacing /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property spacing.</param> [JsMethod(Name = "initSpacing")] public void InitSpacing(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property show.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetShow")] public void ResetShow() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property spacing.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetSpacing")] public void ResetSpacing() { throw new NotImplementedException(); } /// <summary> /// <para>Sets the user value of the property show.</para> /// </summary> /// <param name="value">New value for property show.</param> [JsMethod(Name = "setShow")] public void SetShow(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Sets the user value of the property spacing.</para> /// </summary> /// <param name="value">New value for property spacing.</param> [JsMethod(Name = "setSpacing")] public void SetSpacing(double value) { throw new NotImplementedException(); } /// <summary> /// <para>Adds a new child widget.</para> /// <para>The supported keys of the layout options map depend on the layout manager /// used to position the widget. The options are documented in the class /// documentation of each layout manager <see cref="qx.ui.layout"/>.</para> /// </summary> /// <param name="child">the item to add.</param> /// <param name="options">Optional layout data for item.</param> /// <returns>This object (for chaining support)</returns> [JsMethod(Name = "add")] public Widget Add(LayoutItem child, object options = null) { throw new NotImplementedException(); } /// <summary> /// <para>Add an item after another already inserted item</para> /// <para>This method works on the widget&#8217;s children list. Some layout managers /// (e.g. <see cref="qx.ui.layout.HBox"/>) use the children order as additional /// layout information. Other layout manager (e.g. <see cref="qx.ui.layout.Grid"/>) /// ignore the children order for the layout process.</para> /// </summary> /// <param name="child">item to add</param> /// <param name="after">item, after which the new item will be inserted</param> /// <param name="options">Optional layout data for item.</param> [JsMethod(Name = "addAfter")] public void AddAfter(LayoutItem child, LayoutItem after, object options = null) { throw new NotImplementedException(); } /// <summary> /// <para>Add a child at the specified index</para> /// <para>This method works on the widget&#8217;s children list. Some layout managers /// (e.g. <see cref="qx.ui.layout.HBox"/>) use the children order as additional /// layout information. Other layout manager (e.g. <see cref="qx.ui.layout.Grid"/>) /// ignore the children order for the layout process.</para> /// </summary> /// <param name="child">item to add</param> /// <param name="index">Index, at which the item will be inserted</param> /// <param name="options">Optional layout data for item.</param> [JsMethod(Name = "addAt")] public void AddAt(LayoutItem child, double index, object options = null) { throw new NotImplementedException(); } /// <summary> /// <para>Add an item before another already inserted item</para> /// <para>This method works on the widget&#8217;s children list. Some layout managers /// (e.g. <see cref="qx.ui.layout.HBox"/>) use the children order as additional /// layout information. Other layout manager (e.g. <see cref="qx.ui.layout.Grid"/>) /// ignore the children order for the layout process.</para> /// </summary> /// <param name="child">item to add</param> /// <param name="before">item before the new item will be inserted.</param> /// <param name="options">Optional layout data for item.</param> [JsMethod(Name = "addBefore")] public void AddBefore(LayoutItem child, LayoutItem before, object options = null) { throw new NotImplementedException(); } /// <summary> /// <para>Returns the children list</para> /// </summary> /// <returns>The children array (Arrays are reference types, please to not modify them in-place)</returns> [JsMethod(Name = "getChildren")] public LayoutItem GetChildren() { throw new NotImplementedException(); } /// <summary> /// <para>Whether the widget contains children.</para> /// </summary> /// <returns>Returns true when the widget has children.</returns> [JsMethod(Name = "hasChildren")] public bool HasChildren() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the index position of the given item if it is /// a child item. Otherwise it returns -1.</para> /// <para>This method works on the widget&#8217;s children list. Some layout managers /// (e.g. <see cref="qx.ui.layout.HBox"/>) use the children order as additional /// layout information. Other layout manager (e.g. <see cref="qx.ui.layout.Grid"/>) /// ignore the children order for the layout process.</para> /// </summary> /// <param name="child">the item to query for</param> /// <returns>The index position or -1 when the given item is no child of this layout.</returns> [JsMethod(Name = "indexOf")] public double IndexOf(LayoutItem child) { throw new NotImplementedException(); } /// <summary> /// <para>Remove the given child item.</para> /// </summary> /// <param name="child">the item to remove</param> /// <returns>This object (for chaining support)</returns> [JsMethod(Name = "remove")] public Widget Remove(LayoutItem child) { throw new NotImplementedException(); } /// <summary> /// <para>Remove all children.</para> /// </summary> /// <returns>An array containing the removed children.</returns> [JsMethod(Name = "removeAll")] public JsArray RemoveAll() { throw new NotImplementedException(); } /// <summary> /// <para>Remove the item at the specified index.</para> /// <para>This method works on the widget&#8217;s children list. Some layout managers /// (e.g. <see cref="qx.ui.layout.HBox"/>) use the children order as additional /// layout information. Other layout manager (e.g. <see cref="qx.ui.layout.Grid"/>) /// ignore the children order for the layout process.</para> /// </summary> /// <param name="index">Index of the item to remove.</param> /// <returns>The removed item</returns> [JsMethod(Name = "removeAt")] public qx.ui.core.LayoutItem RemoveAt(double index) { throw new NotImplementedException(); } #endregion Methods } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel.Composition; using QuantConnect.Interfaces; using QuantConnect.Lean.Engine.DataFeeds; using QuantConnect.Lean.Engine.Setup; using QuantConnect.Lean.Engine.TransactionHandlers; using QuantConnect.Orders; using QuantConnect.Packets; namespace QuantConnect.Lean.Engine.Results { /// <summary> /// Handle the results of the backtest: where should we send the profit, portfolio updates: /// Backtester or the Live trading platform: /// </summary> [InheritedExport(typeof(IResultHandler))] public interface IResultHandler { /// <summary> /// Put messages to process into the queue so they are processed by this thread. /// </summary> ConcurrentQueue<Packet> Messages { get; set; } /// <summary> /// Charts collection for storing the master copy of user charting data. /// </summary> ConcurrentDictionary<string, Chart> Charts { get; set; } /// <summary> /// Sampling period for timespans between resamples of the charting equity. /// </summary> /// <remarks>Specifically critical for backtesting since with such long timeframes the sampled data can get extreme.</remarks> TimeSpan ResamplePeriod { get; } /// <summary> /// How frequently the backtests push messages to the browser. /// </summary> /// <remarks>Update frequency of notification packets</remarks> TimeSpan NotificationPeriod { get; } /// <summary> /// Boolean flag indicating the result hander thread is busy. /// False means it has completely finished and ready to dispose. /// </summary> bool IsActive { get; } /// <summary> /// Initialize the result handler with this result packet. /// </summary> /// <param name="job">Algorithm job packet for this result handler</param> /// <param name="messagingHandler"></param> /// <param name="api"></param> /// <param name="dataFeed"></param> /// <param name="setupHandler"></param> /// <param name="transactionHandler"></param> void Initialize(AlgorithmNodePacket job, IMessagingHandler messagingHandler, IApi api, IDataFeed dataFeed, ISetupHandler setupHandler, ITransactionHandler transactionHandler); /// <summary> /// Primary result thread entry point to process the result message queue and send it to whatever endpoint is set. /// </summary> void Run(); /// <summary> /// Process debug messages with the preconfigured settings. /// </summary> /// <param name="message">String debug message</param> void DebugMessage(string message); /// <summary> /// Send a list of security types to the browser /// </summary> /// <param name="types">Security types list inside algorithm</param> void SecurityType(List<SecurityType> types); /// <summary> /// Send a logging message to the log list for storage. /// </summary> /// <param name="message">Message we'd in the log.</param> void LogMessage(string message); /// <summary> /// Send an error message back to the browser highlighted in red with a stacktrace. /// </summary> /// <param name="error">Error message we'd like shown in console.</param> /// <param name="stacktrace">Stacktrace information string</param> void ErrorMessage(string error, string stacktrace = ""); /// <summary> /// Send a runtime error message back to the browser highlighted with in red /// </summary> /// <param name="message">Error message.</param> /// <param name="stacktrace">Stacktrace information string</param> void RuntimeError(string message, string stacktrace = ""); /// <summary> /// Add a sample to the chart specified by the chartName, and seriesName. /// </summary> /// <param name="chartName">String chart name to place the sample.</param> /// <param name="chartType">Type of chart we should create if it doesn't already exist.</param> /// <param name="seriesName">Series name for the chart.</param> /// <param name="seriesType">Series type for the chart.</param> /// <param name="time">Time for the sample</param> /// <param name="value">Value for the chart sample.</param> /// <param name="unit">Unit for the sample chart</param> /// <remarks>Sample can be used to create new charts or sample equity - daily performance.</remarks> void Sample(string chartName, ChartType chartType, string seriesName, SeriesType seriesType, DateTime time, decimal value, string unit = "$"); /// <summary> /// Wrapper methond on sample to create the equity chart. /// </summary> /// <param name="time">Time of the sample.</param> /// <param name="value">Equity value at this moment in time.</param> /// <seealso cref="Sample(string,ChartType,string,SeriesType,DateTime,decimal,string)"/> void SampleEquity(DateTime time, decimal value); /// <summary> /// Sample the current daily performance directly with a time-value pair. /// </summary> /// <param name="time">Current backtest date.</param> /// <param name="value">Current daily performance value.</param> /// <seealso cref="Sample(string,ChartType,string,SeriesType,DateTime,decimal,string)"/> void SamplePerformance(DateTime time, decimal value); /// <summary> /// Sample the current benchmark performance directly with a time-value pair. /// </summary> /// <param name="time">Current backtest date.</param> /// <param name="value">Current benchmark value.</param> /// <seealso cref="Sample(string,ChartType,string,SeriesType,DateTime,decimal,string)"/> void SampleBenchmark(DateTime time, decimal value); /// <summary> /// Sample the asset prices to generate plots. /// </summary> /// <param name="symbol">Symbol we're sampling.</param> /// <param name="time">Time of sample</param> /// <param name="value">Value of the asset price</param> /// <seealso cref="Sample(string,ChartType,string,SeriesType,DateTime,decimal,string)"/> void SampleAssetPrices(Symbol symbol, DateTime time, decimal value); /// <summary> /// Add a range of samples from the users algorithms to the end of our current list. /// </summary> /// <param name="samples">Chart updates since the last request.</param> /// <seealso cref="Sample(string,ChartType,string,SeriesType,DateTime,decimal,string)"/> void SampleRange(List<Chart> samples); /// <summary> /// Set the algorithm of the result handler after its been initialized. /// </summary> /// <param name="algorithm">Algorithm object matching IAlgorithm interface</param> void SetAlgorithm(IAlgorithm algorithm); /// <summary> /// Save the snapshot of the total results to storage. /// </summary> /// <param name="packet">Packet to store.</param> /// <param name="async">Store the packet asyncronously to speed up the thread.</param> /// <remarks>Async creates crashes in Mono 3.10 if the thread disappears before the upload is complete so it is disabled for now.</remarks> void StoreResult(Packet packet, bool async = false); /// <summary> /// Post the final result back to the controller worker if backtesting, or to console if local. /// </summary> void SendFinalResult(AlgorithmNodePacket job, Dictionary<int, Order> orders, Dictionary<DateTime, decimal> profitLoss, Dictionary<string, Holding> holdings, Dictionary<string, string> statistics, Dictionary<string, string> banner); /// <summary> /// Send a algorithm status update to the user of the algorithms running state. /// </summary> /// <param name="algorithmId">String Id of the algorithm.</param> /// <param name="status">Status enum of the algorithm.</param> /// <param name="message">Optional string message describing reason for status change.</param> void SendStatusUpdate(string algorithmId, AlgorithmStatus status, string message = ""); /// <summary> /// Set the chart name: /// </summary> /// <param name="symbol">Symbol of the chart we want.</param> void SetChartSubscription(string symbol); /// <summary> /// Set a dynamic runtime statistic to show in the (live) algorithm header /// </summary> /// <param name="key">Runtime headline statistic name</param> /// <param name="value">Runtime headline statistic value</param> void RuntimeStatistic(string key, string value); /// <summary> /// Send a new order event. /// </summary> /// <param name="newEvent">Update, processing or cancellation of an order, update the IDE in live mode or ignore in backtesting.</param> void OrderEvent(OrderEvent newEvent); /// <summary> /// Terminate the result thread and apply any required exit proceedures. /// </summary> void Exit(); /// <summary> /// Purge/clear any outstanding messages in message queue. /// </summary> void PurgeQueue(); /// <summary> /// Process any synchronous events in here that are primarily triggered from the algorithm loop /// </summary> void ProcessSynchronousEvents(bool forceProcess = false); } }
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9 #define UNITY_4 #endif #if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_3_5 || UNITY_3_4 || UNITY_3_3 #define UNITY_LE_4_3 #endif using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEditor; using Pathfinding; namespace Pathfinding { /** Simple GUIUtility functions */ public class GUIUtilityx { public static Color prevCol; public static void SetColor (Color col) { prevCol = GUI.color; GUI.color = col; } public static void ResetColor () { GUI.color = prevCol; } } /** Handles fading effects and also some custom GUI functions such as LayerMaskField */ public class EditorGUILayoutx { Rect fadeAreaRect; Rect lastAreaRect; //public static List<Rect> currentRects; //public static List<Rect> lastRects; //public static List<float> values; public Dictionary<string, FadeArea> fadeAreas; //public static Dictionary<string, Rect> lastRects; //public static Dictionary<string, float> values; //public static List<bool> open; public static int currentDepth = 0; public static int currentIndex = 0; public static bool isLayout = false; public static Editor editor; public static GUIStyle defaultAreaStyle; public static GUIStyle defaultLabelStyle; public static GUIStyle stretchStyle; public static GUIStyle stretchStyleThin; public static float speed = 6; public static bool fade = true; public static bool fancyEffects = true; public Stack<FadeArea> stack; public void RemoveID (string id) { if (fadeAreas == null) { return; } fadeAreas.Remove (id); } public bool DrawID (string id) { if (fadeAreas == null) { return false; } //Debug.Log ("Draw "+id+" "+fadeAreas[id].value.ToString ("0.00")); return fadeAreas[id].Show (); /*if (values == null) { return false; } return values[id] > 0.002F;*/ } public FadeArea BeginFadeArea (bool open,string label, string id) { return BeginFadeArea (open,label,id, defaultAreaStyle); } public FadeArea BeginFadeArea (bool open,string label, string id, GUIStyle areaStyle) { return BeginFadeArea (open, label, id, areaStyle, defaultLabelStyle); } public FadeArea BeginFadeArea (bool open,string label, string id, GUIStyle areaStyle, GUIStyle labelStyle) { //Rect r = EditorGUILayout.BeginVertical (areaStyle); Color tmp1 = GUI.color; FadeArea fadeArea = BeginFadeArea (open,id, 20,areaStyle); //GUI.Box (r,"",areaStyle); Color tmp2 = GUI.color; GUI.color = tmp1; if (label != "") { if (GUILayout.Button (label,labelStyle)) { fadeArea.open = !fadeArea.open; editor.Repaint (); } } GUI.color = tmp2; //EditorGUILayout.EndVertical (); return fadeArea; } public class FadeArea { public Rect currentRect; public Rect lastRect; public float value; public float lastUpdate; /** Is this area open. * This is not the same as if any contents are visible, use #Show for that. */ public bool open; public Color preFadeColor; /** Update the visibility in Layout to avoid complications with different events not drawing the same thing */ private bool visibleInLayout; public void Switch () { lastRect = currentRect; } public FadeArea (bool open) { value = open ? 1 : 0; } /** Should anything inside this FadeArea be drawn. * Should be called every frame ( in all events ) for best results. */ public bool Show () { bool v = open || value > 0F; if ( Event.current.type == EventType.Layout ) { visibleInLayout = v; } return visibleInLayout; } public static implicit operator bool (FadeArea o) { return o.open; } } public FadeArea BeginFadeArea (bool open, string id) { return BeginFadeArea (open,id,0); } //openMultiple is set to false if only 1 BeginVertical call needs to be made in the BeginFadeArea (open, id) function. //The EndFadeArea function always closes two BeginVerticals public FadeArea BeginFadeArea (bool open, string id, float minHeight) { return BeginFadeArea (open, id, minHeight, GUIStyle.none); } /** Make sure the stack is cleared at the start of a frame */ public void ClearStack () { if ( stack != null ) stack.Clear (); } public FadeArea BeginFadeArea (bool open, string id, float minHeight, GUIStyle areaStyle) { if (editor == null) { Debug.LogError ("You need to set the 'EditorGUIx.editor' variable before calling this function"); return null; } if (stretchStyle == null) { stretchStyle = new GUIStyle (); stretchStyle.stretchWidth = true; //stretchStyle.padding = new RectOffset (0,0,4,14); //stretchStyle.margin = new RectOffset (0,0,4,4); } if (stack == null) { stack = new Stack<FadeArea>(); } if (fadeAreas == null) { fadeAreas = new Dictionary<string, FadeArea> (); } if (!fadeAreas.ContainsKey (id)) { fadeAreas.Add (id,new FadeArea (open)); } FadeArea fadeArea = fadeAreas[id]; stack.Push (fadeArea); fadeArea.open = open; //Make sure the area fills the full width areaStyle.stretchWidth = true; Rect lastRect = fadeArea.lastRect; if (!fancyEffects) { fadeArea.value = open ? 1F : 0F; lastRect.height -= minHeight; lastRect.height = open ? lastRect.height : 0; lastRect.height += minHeight; } else { //GUILayout.Label (lastRect.ToString ()+"\n"+fadeArea.tmp.ToString (),EditorStyles.miniLabel); lastRect.height = lastRect.height < minHeight ? minHeight : lastRect.height; lastRect.height -= minHeight; float faded = Hermite (0F,1F,fadeArea.value); lastRect.height *= faded; lastRect.height += minHeight; lastRect.height = Mathf.Round (lastRect.height); //lastRect.height *= 2; //if (Event.current.type == EventType.Repaint) { // isLayout = false; //} } Rect gotLastRect = GUILayoutUtility.GetRect (new GUIContent (),areaStyle,GUILayout.Height (lastRect.height)); //The clipping area, also drawing background GUILayout.BeginArea (lastRect,areaStyle); Rect newRect = EditorGUILayout.BeginVertical (); if (Event.current.type == EventType.Repaint || Event.current.type == EventType.ScrollWheel) { newRect.x = gotLastRect.x; newRect.y = gotLastRect.y; newRect.width = gotLastRect.width;//stretchWidthRect.width; newRect.height += areaStyle.padding.top+ areaStyle.padding.bottom; fadeArea.currentRect = newRect; if (fadeArea.lastRect != newRect) { //@Fix - duplicate //fadeArea.lastUpdate = Time.realtimeSinceStartup; editor.Repaint (); } fadeArea.Switch (); } if (Event.current.type == EventType.Repaint) { float value = fadeArea.value; float targetValue = open ? 1F : 0F; float newRectHeight = fadeArea.lastRect.height; float deltaHeight = 400F / newRectHeight; float deltaTime = Mathf.Clamp (Time.realtimeSinceStartup-fadeAreas[id].lastUpdate,0.00001F,0.05F); deltaTime *= Mathf.Lerp (deltaHeight*deltaHeight*0.01F, 0.8F, 0.9F); fadeAreas[id].lastUpdate = Time.realtimeSinceStartup; //Useless, but fun feature if (Event.current.shift) { deltaTime *= 0.05F; } if (Mathf.Abs(targetValue-value) > 0.001F) { float time = Mathf.Clamp01 (deltaTime*speed); value += time*Mathf.Sign (targetValue-value); editor.Repaint (); } else { value = Mathf.Round (value); } fadeArea.value = Mathf.Clamp01 (value); //if (oldValue != value) { // editor.Repaint (); //} } if (fade) { Color c = GUI.color; fadeArea.preFadeColor = c; c.a *= fadeArea.value; GUI.color = c; } fadeArea.open = open; //GUILayout.Label ("Alpha : "+fadeArea.value); //GUILayout.Label ("Alpha : "+fadeArea.value);GUILayout.Label ("Alpha : "+fadeArea.value);GUILayout.Label ("Alpha : "+fadeArea.value);GUILayout.Label ("Alpha : "+fadeArea.value); /*GUILayout.Label ("Testing"); GUILayout.Label ("Testing"); GUILayout.Label ("Testing"); GUILayout.Label ("Testing");*/ return fadeArea; } public void EndFadeArea () { if (stack.Count <= 0) { Debug.LogError ("You are popping more Fade Areas than you are pushing, make sure they are balanced"); return; } FadeArea fadeArea = stack.Pop (); //Debug.Log (r); //fadeArea.tmp = r; //r.width = 10; //r.height = 10; //GUI.Box (r,""); //GUILayout.Label ("HEllo : "); EditorGUILayout.EndVertical (); GUILayout.EndArea (); if (fade) { GUI.color = fadeArea.preFadeColor; } //GUILayout.Label ("Outside"); /*currentDepth--; Rect r = GUILayoutUtility.GetRect (new GUIContent (),stretchStyle,GUILayout.Height (0)); if (Event.current.type == EventType.Repaint || Event.current.type == EventType.ScrollWheel) { Rect currentRect = currentRects[id]; Rect newRect = new Rect (currentRect.x,currentRect.y,currentRect.width,r.y-minHeight); currentRects[id] = newRect; if (lastRects[id] != newRect) { changedDelta = true; lastUpdate = Time.realtimeSinceStartup; editor.Repaint (); } } GUILayout.EndArea ();*/ } /*public static bool BeginFadeAreaSimple (bool open, string id) { if (editor == null) { Debug.LogError ("You need to set the 'EditorGUIx.editor' variable before calling this function"); return open; } if (stretchStyleThin == null) { stretchStyleThin = new GUIStyle (); stretchStyleThin.stretchWidth = true; //stretchStyle.padding = new RectOffset (0,0,4,14); //stretchStyleThin.margin = new RectOffset (0,0,4,4); } if (Event.current.type == EventType.Layout && !isLayout) { if (currentRects == null) { currentRects = new Dictionary<string, Rect> ();//new List<Rect>(); lastRects = new Dictionary<string, Rect> ();//new List<Rect>(); values = new Dictionary<string, float> ();//new List<float>(); //open = new List<bool>(); } if (changedDelta) { deltaTime = Mathf.Min (Time.realtimeSinceStartup-lastUpdate,0.1F); } else { deltaTime = 0.01F; } changedDelta = false; isLayout = true; currentDepth = 0; currentIndex = 0; Dictionary<string, Rect> tmp = lastRects; lastRects = currentRects; currentRects = tmp; currentRects.Clear (); } if (Event.current.type == EventType.Layout) { if (!currentRects.ContainsKey (id)) { currentRects.Add (id,new Rect ()); } } if (!lastRects.ContainsKey (id)) { lastRects.Add (id,new Rect ()); } if (!values.ContainsKey (id)) { values.Add (id, open ? 1.0F : 0.0F); //open.Add (false); } Rect newRect = GUILayoutUtility.GetRect (new GUIContent (),stretchStyleThin,GUILayout.Height (0)); Rect lastRect = lastRects[id]; lastRect.height *= Hermite (0F,1F,values[id]); GUILayoutUtility.GetRect (lastRect.width,lastRect.height); GUI.depth+= 10; GUILayout.BeginArea (lastRect); if (Event.current.type == EventType.Repaint) { isLayout = false; currentRects[id] = newRect; } if (Event.current.type == EventType.Layout) { float value = values[id]; float oldValue = value; float targetValue = open ? 1F : 0; if (Mathf.Abs(targetValue-value) > 0.001F) { float time = Mathf.Clamp01 (deltaTime*speed); value += time*Mathf.Sign (targetValue-value); } values[id] = Mathf.Clamp01 (value); if (oldValue != value) { changedDelta = true; lastUpdate = Time.realtimeSinceStartup; editor.Repaint (); } } return open; }*/ /*public static void EndFadeAreaSimple (string id) { if (editor == null) { Debug.LogError ("You need to set the 'EditorGUIx.editor' variable before calling this function"); return; } Rect r = GUILayoutUtility.GetRect (new GUIContent (),stretchStyleThin,GUILayout.Height (0)); if (Event.current.type == EventType.Repaint || Event.current.type == EventType.ScrollWheel) { Rect currentRect = currentRects[id]; Rect newRect = new Rect (currentRect.x,currentRect.y,currentRect.width,r.y); currentRects[id] = newRect; if (lastRects[id] != newRect) { changedDelta = true; lastUpdate = Time.realtimeSinceStartup; editor.Repaint (); } } GUILayout.EndArea (); }*/ public static void MenuCallback (System.Object ob) { Debug.Log ("Got Callback"); } /** Begin horizontal indent for the next control. * Fake "real" indent when using EditorGUIUtility.LookLikeControls.\n * Forumula used is 13+6*EditorGUI.indentLevel */ public static void BeginIndent () { GUILayout.BeginHorizontal (); GUILayout.Space (IndentWidth()); } /** Returns width of current editor indent. * Unity seems to use 13+6*EditorGUI.indentLevel in U3 * and 15*indent - (indent > 1 ? 2 : 0) or something like that in U4 */ public static int IndentWidth () { #if UNITY_4 //Works well for indent levels 0,1,2 at least return 15*EditorGUI.indentLevel - (EditorGUI.indentLevel > 1 ? 2 : 0); #else return 13+6*EditorGUI.indentLevel; #endif } /** End indent. * Actually just a EndHorizontal call. * \see BeginIndent */ public static void EndIndent () { GUILayout.EndHorizontal (); } public static int SingleTagField (string label, int value) { //GUILayout.BeginHorizontal (); //Debug.Log (value.ToString ()); //EditorGUIUtility.LookLikeControls(); ///EditorGUILayout.PrefixLabel (label,EditorStyles.layerMaskField); //GUILayout.FlexibleSpace (); //Rect r = GUILayoutUtility.GetLastRect (); string[] tagNames = AstarPath.FindTagNames (); value = value < 0 ? 0 : value; value = value >= tagNames.Length ? tagNames.Length-1 : value; //string text = tagNames[value]; /*if (GUILayout.Button (text,EditorStyles.layerMaskField,GUILayout.ExpandWidth (true))) { //Debug.Log ("pre"); GenericMenu menu = new GenericMenu (); for (int i=0;i<tagNames.Length;i++) { bool on = value == i; int result = i; menu.AddItem (new GUIContent (tagNames[i]),on,delegate (System.Object ob) { value = (int)ob; }, result); //value.SetValues (result); } menu.AddItem (new GUIContent ("Edit Tags..."),false,AstarPathEditor.EditTags); menu.ShowAsContext (); Event.current.Use (); //Debug.Log ("Post"); }*/ value = EditorGUILayout.IntPopup (label,value,tagNames,new int[] {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31}); //EditorGUIUtility.LookLikeInspector(); //GUILayout.EndHorizontal (); return value; } public static void SetTagField (GUIContent label, ref Pathfinding.TagMask value) { GUILayout.BeginHorizontal (); //Debug.Log (value.ToString ()); EditorGUIUtility.LookLikeControls(); EditorGUILayout.PrefixLabel (label,EditorStyles.layerMaskField); //GUILayout.FlexibleSpace (); //Rect r = GUILayoutUtility.GetLastRect (); string text = ""; if (value.tagsChange == 0) text = "Nothing"; else if (value.tagsChange == ~0) text = "Everything"; else { text = System.Convert.ToString (value.tagsChange,2); } string[] tagNames = AstarPath.FindTagNames (); if (GUILayout.Button (text,EditorStyles.layerMaskField,GUILayout.ExpandWidth (true))) { //Debug.Log ("pre"); GenericMenu menu = new GenericMenu (); menu.AddItem (new GUIContent ("Everything"),value.tagsChange == ~0, value.SetValues, new Pathfinding.TagMask (~0,value.tagsSet)); menu.AddItem (new GUIContent ("Nothing"),value.tagsChange == 0, value.SetValues, new Pathfinding.TagMask (0,value.tagsSet)); for (int i=0;i<tagNames.Length;i++) { bool on = (value.tagsChange >> i & 0x1) != 0; Pathfinding.TagMask result = new Pathfinding.TagMask (on ? value.tagsChange & ~(1 << i) : value.tagsChange | 1<<i,value.tagsSet); menu.AddItem (new GUIContent (tagNames[i]),on,value.SetValues, result); //value.SetValues (result); } menu.AddItem (new GUIContent ("Edit Tags..."),false,AstarPathEditor.EditTags); menu.ShowAsContext (); Event.current.Use (); //Debug.Log ("Post"); } #if UNITY_LE_4_3 EditorGUIUtility.LookLikeInspector(); #endif GUILayout.EndHorizontal (); } public static void TagsMaskField (GUIContent changeLabel, GUIContent setLabel,ref Pathfinding.TagMask value) { GUILayout.BeginHorizontal (); //Debug.Log (value.ToString ()); EditorGUIUtility.LookLikeControls(); EditorGUILayout.PrefixLabel (changeLabel,EditorStyles.layerMaskField); //GUILayout.FlexibleSpace (); //Rect r = GUILayoutUtility.GetLastRect (); string text = ""; if (value.tagsChange == 0) text = "Nothing"; else if (value.tagsChange == ~0) text = "Everything"; else { text = System.Convert.ToString (value.tagsChange,2); } if (GUILayout.Button (text,EditorStyles.layerMaskField,GUILayout.ExpandWidth (true))) { //Debug.Log ("pre"); GenericMenu menu = new GenericMenu (); menu.AddItem (new GUIContent ("Everything"),value.tagsChange == ~0, value.SetValues, new Pathfinding.TagMask (~0,value.tagsSet)); menu.AddItem (new GUIContent ("Nothing"),value.tagsChange == 0, value.SetValues, new Pathfinding.TagMask (0,value.tagsSet)); for (int i=0;i<32;i++) { bool on = (value.tagsChange >> i & 0x1) != 0; Pathfinding.TagMask result = new Pathfinding.TagMask (on ? value.tagsChange & ~(1 << i) : value.tagsChange | 1<<i,value.tagsSet); menu.AddItem (new GUIContent (""+i),on,value.SetValues, result); //value.SetValues (result); } menu.ShowAsContext (); Event.current.Use (); //Debug.Log ("Post"); } #if UNITY_LE_4_3 EditorGUIUtility.LookLikeInspector(); #endif GUILayout.EndHorizontal (); GUILayout.BeginHorizontal (); //Debug.Log (value.ToString ()); EditorGUIUtility.LookLikeControls(); EditorGUILayout.PrefixLabel (setLabel,EditorStyles.layerMaskField); //GUILayout.FlexibleSpace (); //r = GUILayoutUtility.GetLastRect (); text = ""; if (value.tagsSet == 0) text = "Nothing"; else if (value.tagsSet == ~0) text = "Everything"; else { text = System.Convert.ToString (value.tagsSet,2); } if (GUILayout.Button (text,EditorStyles.layerMaskField,GUILayout.ExpandWidth (true))) { //Debug.Log ("pre"); GenericMenu menu = new GenericMenu (); if (value.tagsChange != 0) menu.AddItem (new GUIContent ("Everything"),value.tagsSet == ~0, value.SetValues, new Pathfinding.TagMask (value.tagsChange,~0)); else menu.AddDisabledItem (new GUIContent ("Everything")); menu.AddItem (new GUIContent ("Nothing"),value.tagsSet == 0, value.SetValues, new Pathfinding.TagMask (value.tagsChange,0)); for (int i=0;i<32;i++) { bool enabled = (value.tagsChange >> i & 0x1) != 0; bool on = (value.tagsSet >> i & 0x1) != 0; Pathfinding.TagMask result = new Pathfinding.TagMask (value.tagsChange, on ? value.tagsSet & ~(1 << i) : value.tagsSet | 1<<i); if (enabled) menu.AddItem (new GUIContent (""+i),on,value.SetValues, result); else menu.AddDisabledItem (new GUIContent (""+i)); //value.SetValues (result); } menu.ShowAsContext (); Event.current.Use (); //Debug.Log ("Post"); } #if UNITY_LE_4_3 EditorGUIUtility.LookLikeInspector(); #endif GUILayout.EndHorizontal (); //return value; } public static int UpDownArrows (GUIContent label, int value, GUIStyle labelStyle, GUIStyle upArrow, GUIStyle downArrow) { GUILayout.BeginHorizontal (); GUILayout.Space (EditorGUI.indentLevel*10); GUILayout.Label (label,labelStyle,GUILayout.Width (170)); if (downArrow == null || upArrow == null) { upArrow = GUI.skin.FindStyle ("Button");//EditorStyles.miniButton;// downArrow = upArrow;//GUI.skin.FindStyle ("Button"); } //GUILayout.BeginHorizontal (); //GUILayout.FlexibleSpace (); if (GUILayout.Button ("",upArrow,GUILayout.Width (16),GUILayout.Height (12))) { value++; } if (GUILayout.Button ("",downArrow,GUILayout.Width (16),GUILayout.Height (12))) { value--; } //GUILayout.EndHorizontal (); GUILayout.Space (100); GUILayout.EndHorizontal (); return value; } public static bool UnityTagMaskList (GUIContent label, bool foldout, List<string> tagMask) { if (tagMask == null) throw new System.ArgumentNullException ("tagMask"); if (EditorGUILayout.Foldout (foldout, label)) { EditorGUI.indentLevel++; GUILayout.BeginVertical(); for (int i=0;i<tagMask.Count;i++) { tagMask[i] = EditorGUILayout.TagField (tagMask[i]); } GUILayout.BeginHorizontal(); if (GUILayout.Button ("Add Tag")) tagMask.Add ("Untagged"); EditorGUI.BeginDisabledGroup (tagMask.Count == 0); if (GUILayout.Button ("Remove Last")) tagMask.RemoveAt (tagMask.Count-1); EditorGUI.EndDisabledGroup(); GUILayout.EndHorizontal(); GUILayout.EndVertical(); EditorGUI.indentLevel--; return true; } return false; } public static LayerMask LayerMaskField (string label, LayerMask selected) { return LayerMaskField (label,selected,true); } public static List<string> layers; public static List<int> layerNumbers; public static string[] layerNames; public static long lastUpdateTick; /** Displays a LayerMask field. * \param label Label to display * \param showSpecial Use the Nothing and Everything selections * \param selected Current LayerMask * \note Unity 3.5 and up will use the EditorGUILayout.MaskField instead of a custom written one. */ public static LayerMask LayerMaskField (string label, LayerMask selected, bool showSpecial) { #if !UNITY_3_4 //Unity 3.5 and up if (layers == null || (System.DateTime.UtcNow.Ticks - lastUpdateTick > 10000000L && Event.current.type == EventType.Layout)) { lastUpdateTick = System.DateTime.UtcNow.Ticks; if (layers == null) { layers = new List<string>(); layerNumbers = new List<int>(); layerNames = new string[4]; } else { layers.Clear (); layerNumbers.Clear (); } int emptyLayers = 0; for (int i=0;i<32;i++) { string layerName = LayerMask.LayerToName (i); if (layerName != "") { for (;emptyLayers>0;emptyLayers--) layers.Add ("Layer "+(i-emptyLayers)); layerNumbers.Add (i); layers.Add (layerName); } else { emptyLayers++; } } if (layerNames.Length != layers.Count) { layerNames = new string[layers.Count]; } for (int i=0;i<layerNames.Length;i++) layerNames[i] = layers[i]; } selected.value = EditorGUILayout.MaskField (label,selected.value,layerNames); return selected; #else if (layers == null) { layers = new List<string>(); layerNumbers = new List<int>(); } else { layers.Clear (); layerNumbers.Clear (); } string selectedLayers = ""; for (int i=0;i<32;i++) { string layerName = LayerMask.LayerToName (i); if (layerName != "") { if (selected == (selected | (1 << i))) { if (selectedLayers == "") { selectedLayers = layerName; } else { selectedLayers = "Mixed"; } } } } if (Event.current.type != EventType.MouseDown && Event.current.type != EventType.ExecuteCommand) { if (selected.value == 0) { layers.Add ("Nothing"); } else if (selected.value == -1) { layers.Add ("Everything"); } else { layers.Add (selectedLayers); } layerNumbers.Add (-1); } if (showSpecial) { layers.Add ((selected.value == 0 ? "[X] " : " ") + "Nothing"); layerNumbers.Add (-2); layers.Add ((selected.value == -1 ? "[X] " : " ") + "Everything"); layerNumbers.Add (-3); } for (int i=0;i<32;i++) { string layerName = LayerMask.LayerToName (i); if (layerName != "") { if (selected == (selected | (1 << i))) { layers.Add ("[X] "+layerName); } else { layers.Add (" "+layerName); } layerNumbers.Add (i); } } bool preChange = GUI.changed; GUI.changed = false; int newSelected = 0; if (Event.current.type == EventType.MouseDown) { newSelected = -1; } newSelected = EditorGUILayout.Popup (label,newSelected,layers.ToArray(),EditorStyles.layerMaskField); if (GUI.changed && newSelected >= 0) { int preSelected = selected; if (showSpecial && newSelected == 0) { selected = 0; } else if (showSpecial && newSelected == 1) { selected = -1; } else { if (selected == (selected | (1 << layerNumbers[newSelected]))) { selected &= ~(1 << layerNumbers[newSelected]); //Debug.Log ("Set Layer "+LayerMask.LayerToName (LayerNumbers[newSelected]) + " To False "+selected.value); } else { //Debug.Log ("Set Layer "+LayerMask.LayerToName (LayerNumbers[newSelected]) + " To True "+selected.value); selected = selected | (1 << layerNumbers[newSelected]); } } if (selected == preSelected) { GUI.changed = false; } else { //Debug.Log ("Difference made"); } } GUI.changed = preChange || GUI.changed; return selected; #endif } public static float Hermite(float start, float end, float value) { return Mathf.Lerp(start, end, value * value * (3.0f - 2.0f * value)); } public static float Sinerp(float start, float end, float value) { return Mathf.Lerp(start, end, Mathf.Sin(value * Mathf.PI * 0.5f)); } public static float Coserp(float start, float end, float value) { return Mathf.Lerp(start, end, 1.0f - Mathf.Cos(value * Mathf.PI * 0.5f)); } public static float Berp(float start, float end, float value) { value = Mathf.Clamp01(value); value = (Mathf.Sin(value * Mathf.PI * (0.2f + 2.5f * value * value * value)) * Mathf.Pow(1f - value, 2.2f) + value) * (1f + (1.2f * (1f - value))); return start + (end - start) * value; } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Management.Automation; using System.Management.Automation.Language; using System.Reflection; using System.Text; using System.Threading; using Microsoft.PowerShell.EditorServices.Services.PowerShell.Runspace; using Microsoft.PowerShell.EditorServices.Utility; namespace Microsoft.PowerShell.EditorServices.Services.DebugAdapter { internal static class BreakpointApiUtils { #region Private Static Fields private const string s_psesGlobalVariableNamePrefix = "__psEditorServices_"; private static readonly Lazy<Func<Debugger, string, int, int, ScriptBlock, int?, LineBreakpoint>> s_setLineBreakpointLazy; private static readonly Lazy<Func<Debugger, string, ScriptBlock, string, int?, CommandBreakpoint>> s_setCommandBreakpointLazy; private static readonly Lazy<Func<Debugger, int?, List<Breakpoint>>> s_getBreakpointsLazy; private static readonly Lazy<Func<Debugger, Breakpoint, int?, bool>> s_removeBreakpointLazy; private static readonly Version s_minimumBreakpointApiPowerShellVersion = new(7, 0, 0, 0); private static int breakpointHitCounter; #endregion #region Static Constructor static BreakpointApiUtils() { // If this version of PowerShell does not support the new Breakpoint APIs introduced in PowerShell 7.0.0, // do nothing as this class will not get used. if (!VersionUtils.IsPS7OrGreater) { return; } s_setLineBreakpointLazy = new Lazy<Func<Debugger, string, int, int, ScriptBlock, int?, LineBreakpoint>>(() => { Type[] setLineBreakpointParameters = new[] { typeof(string), typeof(int), typeof(int), typeof(ScriptBlock), typeof(int?) }; MethodInfo setLineBreakpointMethod = typeof(Debugger).GetMethod("SetLineBreakpoint", setLineBreakpointParameters); return (Func<Debugger, string, int, int, ScriptBlock, int?, LineBreakpoint>)Delegate.CreateDelegate( typeof(Func<Debugger, string, int, int, ScriptBlock, int?, LineBreakpoint>), firstArgument: null, setLineBreakpointMethod); }); s_setCommandBreakpointLazy = new Lazy<Func<Debugger, string, ScriptBlock, string, int?, CommandBreakpoint>>(() => { Type[] setCommandBreakpointParameters = new[] { typeof(string), typeof(ScriptBlock), typeof(string), typeof(int?) }; MethodInfo setCommandBreakpointMethod = typeof(Debugger).GetMethod("SetCommandBreakpoint", setCommandBreakpointParameters); return (Func<Debugger, string, ScriptBlock, string, int?, CommandBreakpoint>)Delegate.CreateDelegate( typeof(Func<Debugger, string, ScriptBlock, string, int?, CommandBreakpoint>), firstArgument: null, setCommandBreakpointMethod); }); s_getBreakpointsLazy = new Lazy<Func<Debugger, int?, List<Breakpoint>>>(() => { Type[] getBreakpointsParameters = new[] { typeof(int?) }; MethodInfo getBreakpointsMethod = typeof(Debugger).GetMethod("GetBreakpoints", getBreakpointsParameters); return (Func<Debugger, int?, List<Breakpoint>>)Delegate.CreateDelegate( typeof(Func<Debugger, int?, List<Breakpoint>>), firstArgument: null, getBreakpointsMethod); }); s_removeBreakpointLazy = new Lazy<Func<Debugger, Breakpoint, int?, bool>>(() => { Type[] removeBreakpointParameters = new[] { typeof(Breakpoint), typeof(int?) }; MethodInfo removeBreakpointMethod = typeof(Debugger).GetMethod("RemoveBreakpoint", removeBreakpointParameters); return (Func<Debugger, Breakpoint, int?, bool>)Delegate.CreateDelegate( typeof(Func<Debugger, Breakpoint, int?, bool>), firstArgument: null, removeBreakpointMethod); }); } #endregion #region Private Static Properties private static Func<Debugger, string, int, int, ScriptBlock, int?, LineBreakpoint> SetLineBreakpointDelegate => s_setLineBreakpointLazy.Value; private static Func<Debugger, string, ScriptBlock, string, int?, CommandBreakpoint> SetCommandBreakpointDelegate => s_setCommandBreakpointLazy.Value; private static Func<Debugger, int?, List<Breakpoint>> GetBreakpointsDelegate => s_getBreakpointsLazy.Value; private static Func<Debugger, Breakpoint, int?, bool> RemoveBreakpointDelegate => s_removeBreakpointLazy.Value; #endregion #region Public Static Properties public static bool SupportsBreakpointApis(IRunspaceInfo targetRunspace) => targetRunspace.PowerShellVersionDetails.Version >= s_minimumBreakpointApiPowerShellVersion; #endregion #region Public Static Methods public static Breakpoint SetBreakpoint(Debugger debugger, BreakpointDetailsBase breakpoint, int? runspaceId = null) { ScriptBlock actionScriptBlock = null; string logMessage = breakpoint is BreakpointDetails bd ? bd.LogMessage : null; // Check if this is a "conditional" line breakpoint. if (!string.IsNullOrWhiteSpace(breakpoint.Condition) || !string.IsNullOrWhiteSpace(breakpoint.HitCondition) || !string.IsNullOrWhiteSpace(logMessage)) { actionScriptBlock = GetBreakpointActionScriptBlock( breakpoint.Condition, breakpoint.HitCondition, logMessage, out string errorMessage); if (!string.IsNullOrEmpty(errorMessage)) { // This is handled by the caller where it will set the 'Message' and 'Verified' on the BreakpointDetails throw new InvalidOperationException(errorMessage); } } return breakpoint switch { BreakpointDetails lineBreakpoint => SetLineBreakpointDelegate( debugger, lineBreakpoint.Source, lineBreakpoint.LineNumber, lineBreakpoint.ColumnNumber ?? 0, actionScriptBlock, runspaceId), CommandBreakpointDetails commandBreakpoint => SetCommandBreakpointDelegate(debugger, commandBreakpoint.Name, null, null, runspaceId), _ => throw new NotImplementedException("Other breakpoints not supported yet"), }; } public static List<Breakpoint> GetBreakpoints(Debugger debugger, int? runspaceId = null) { return GetBreakpointsDelegate(debugger, runspaceId); } public static bool RemoveBreakpoint(Debugger debugger, Breakpoint breakpoint, int? runspaceId = null) { return RemoveBreakpointDelegate(debugger, breakpoint, runspaceId); } /// <summary> /// Inspects the condition, putting in the appropriate scriptblock template /// "if (expression) { break }". If errors are found in the condition, the /// breakpoint passed in is updated to set Verified to false and an error /// message is put into the breakpoint.Message property. /// </summary> /// <param name="condition">The expression that needs to be true for the breakpoint to be triggered.</param> /// <param name="hitCondition">The amount of times this line should be hit til the breakpoint is triggered.</param> /// <param name="logMessage">The log message to write instead of calling 'break'. In VS Code, this is called a 'logPoint'.</param> /// <returns>ScriptBlock</returns> public static ScriptBlock GetBreakpointActionScriptBlock(string condition, string hitCondition, string logMessage, out string errorMessage) { errorMessage = null; try { StringBuilder builder = new( string.IsNullOrEmpty(logMessage) ? "break" : $"Microsoft.PowerShell.Utility\\Write-Host \"{logMessage.Replace("\"","`\"")}\""); // If HitCondition specified, parse and verify it. if (!string.IsNullOrWhiteSpace(hitCondition)) { if (!int.TryParse(hitCondition, out int parsedHitCount)) { throw new InvalidOperationException("Hit Count was not a valid integer."); } if (string.IsNullOrWhiteSpace(condition)) { // In the HitCount only case, this is simple as we can just use the HitCount // property on the breakpoint object which is represented by $_. builder.Insert(0, $"if ($_.HitCount -eq {parsedHitCount}) {{ ") .Append(" }"); } int incrementResult = Interlocked.Increment(ref breakpointHitCounter); string globalHitCountVarName = $"$global:{s_psesGlobalVariableNamePrefix}BreakHitCounter_{incrementResult}"; builder.Insert(0, $"if (++{globalHitCountVarName} -eq {parsedHitCount}) {{ ") .Append(" }"); } if (!string.IsNullOrWhiteSpace(condition)) { ScriptBlock parsed = ScriptBlock.Create(condition); // Check for simple, common errors that ScriptBlock parsing will not catch // e.g. $i == 3 and $i > 3 if (!ValidateBreakpointConditionAst(parsed.Ast, out string message)) { throw new InvalidOperationException(message); } // Check for "advanced" condition syntax i.e. if the user has specified // a "break" or "continue" statement anywhere in their scriptblock, // pass their scriptblock through to the Action parameter as-is. if (parsed.Ast.Find(ast => ast is BreakStatementAst || ast is ContinueStatementAst, true) is not null) { return parsed; } builder.Insert(0, $"if ({condition}) {{ ") .Append(" }"); } return ScriptBlock.Create(builder.ToString()); } catch (ParseException e) { errorMessage = ExtractAndScrubParseExceptionMessage(e, condition); return null; } catch (InvalidOperationException e) { errorMessage = e.Message; return null; } } private static bool ValidateBreakpointConditionAst(Ast conditionAst, out string message) { message = string.Empty; // We are only inspecting a few simple scenarios in the EndBlock only. if (conditionAst is ScriptBlockAst scriptBlockAst && scriptBlockAst.BeginBlock is null && scriptBlockAst.ProcessBlock is null && scriptBlockAst.EndBlock?.Statements.Count == 1) { StatementAst statementAst = scriptBlockAst.EndBlock.Statements[0]; string condition = statementAst.Extent.Text; if (statementAst is AssignmentStatementAst) { message = FormatInvalidBreakpointConditionMessage(condition, "Use '-eq' instead of '=='."); return false; } if (statementAst is PipelineAst pipelineAst && pipelineAst.PipelineElements.Count == 1 && pipelineAst.PipelineElements[0].Redirections.Count > 0) { message = FormatInvalidBreakpointConditionMessage(condition, "Use '-gt' instead of '>'."); return false; } } return true; } private static string ExtractAndScrubParseExceptionMessage(ParseException parseException, string condition) { string[] messageLines = parseException.Message.Split('\n'); // Skip first line - it is a location indicator "At line:1 char: 4" for (int i = 1; i < messageLines.Length; i++) { string line = messageLines[i]; if (line.StartsWith("+")) { continue; } if (!string.IsNullOrWhiteSpace(line)) { // Note '==' and '>" do not generate parse errors if (line.Contains("'!='")) { line += " Use operator '-ne' instead of '!='."; } else if (line.Contains("'<'") && condition.Contains("<=")) { line += " Use operator '-le' instead of '<='."; } else if (line.Contains("'<'")) { line += " Use operator '-lt' instead of '<'."; } else if (condition.Contains(">=")) { line += " Use operator '-ge' instead of '>='."; } return FormatInvalidBreakpointConditionMessage(condition, line); } } // If the message format isn't in a form we expect, just return the whole message. return FormatInvalidBreakpointConditionMessage(condition, parseException.Message); } private static string FormatInvalidBreakpointConditionMessage(string condition, string message) { return $"'{condition}' is not a valid PowerShell expression. {message}"; } #endregion } }
// // Curve.cs // // Author: // Stephane Delcroix <stephane@delcroix.org> // // Copyright (C) 2009 Novell, Inc. // Copyright (C) 2009 Stephane Delcroix // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using Gtk; using Gdk; namespace FSpot.Widgets { public class Curve : DrawingArea { #region public API public Curve () { Events |= EventMask.ExposureMask | EventMask.PointerMotionMask | EventMask.PointerMotionHintMask | EventMask.EnterNotifyMask | EventMask.ButtonPressMask | EventMask.ButtonReleaseMask | EventMask.Button1MotionMask; ResetVector (); } public void Reset () { CurveType old_type = CurveType; CurveType = CurveType.Spline; ResetVector (); EventHandler eh; if (old_type != CurveType.Spline && (eh = CurveTypeChanged) != null) eh (this, EventArgs.Empty); } float min_x = 0f; public float MinX { get { return min_x; } set { SetRange (value, max_x, min_y, max_y); } } float max_x = 1.0f; public float MaxX { get { return max_x; } set { SetRange (min_x, value, min_y, max_y); } } float min_y = 0f; public float MinY { get { return min_y; } set { SetRange (min_x, max_x, value, max_y); } } float max_y = 1.0f; public float MaxY { get { return max_y; } set { SetRange (min_x, max_x, min_y, value); } } public void SetRange (float min_x, float max_x, float min_y, float max_y) { this.min_x = min_x; this.max_x = max_x; this.min_y = min_y; this.max_y = max_y; ResetVector (); QueueDraw (); } CurveType curve_type = CurveType.Spline; public CurveType CurveType { get { return curve_type; } set { curve_type = value; QueueDraw (); } } public float [] GetVector (int len) { if (len <= 0) return null; var vector = new float [len]; var xv = new float [points.Count]; var yv = new float [points.Count]; int i = 0; foreach (var keyval in points) { xv[i] = keyval.Key; yv[i] = keyval.Value; i++; } float rx = MinX; float dx = (MaxX - MinX) / (len - 1.0f); switch (CurveType) { case CurveType.Spline: var y2v = SplineSolve (xv, yv); for (int x = 0; x < len; x++, rx += dx) { float ry = SplineEval (xv, yv, y2v, rx); if (ry < MinY) ry = MinY; if (ry > MaxY) ry = MaxY; vector[x] = ry; } break;; case CurveType.Linear: for (int x = 0; x < len; x++, rx += dx) { float ry = LinearEval (xv, yv, rx); if (ry < MinY) ry = MinY; if (ry > MaxY) ry = MaxY; vector[x] = ry; } break; case CurveType.Free: throw new NotImplementedException (); } return vector; } public void SetVector (float[] vector) { throw new NotImplementedException ("FSpot.Gui.Widgets.Curve SetVector does nothing!!!"); } public void AddPoint (float x, float y) { points.Add (x, y); EventHandler eh = CurveChanged; if (eh != null) eh (this, EventArgs.Empty); } public event EventHandler CurveTypeChanged; public event EventHandler CurveChanged; #endregion #region vector handling SortedDictionary<float, float> points; void ResetVector () { points = new SortedDictionary<float, float> (); points.Add (min_x, min_y); points.Add (max_x, max_y); points.Add (.2f, .1f); points.Add (.5f, .5f); points.Add (.8f, .9f); } #endregion #region math helpers /* Solve the tridiagonal equation system that determines the second derivatives for the interpolation points. (Based on Numerical Recipies 2nd Edition) */ static float [] SplineSolve (float[] x, float[] y) { var y2 = new float [x.Length]; var u = new float [x.Length - 1]; y2[0] = u[0] = 0.0f; //Set lower boundary condition to "natural" for (int i = 1; i < x.Length - 1; ++i) { float sig = (x[i] - x[i - 1]) / (x[i + 1] - x[i - 1]); float p = sig * y2[i - 1] + 2.0f; y2[i] = (sig - 1.0f) / p; u[i] = ((y[i + 1] - y[i]) / (x[i + 1] - x[i]) - (y[i] - y[i - 1]) / (x[i] - x[i - 1])); u[i] = (6.0f * u[i] / (x[i + 1] - x[i - 1]) - sig * u[i - 1]) / p; } y2[x.Length - 1] = 0.0f; for (int k = x.Length - 2; k >= 0; --k) y2[k] = y2[k] * y2[k + 1] + u[k]; return y2; } /* Returns a y value for val, given x[], y[] and y2[] */ static float SplineEval (float[] x, float[] y, float[] y2, float val) { //binary search for the right interval int k_lo = 0; int k_hi = x.Length - 1; while (k_hi - k_lo > 1) { int k = (k_hi + k_lo) / 2; if (x[k] > val) k_hi = k; else k_lo = k; } float h = x[k_hi] - x[k_lo]; float a = (x[k_hi] - val) / h; float b = (val - x[k_lo]) / h; return a * y[k_lo] + b * y[k_hi] + ((a*a*a - a) * y2[k_lo] + (b*b*b - b) * y2[k_hi]) * (h*h)/6.0f; } static float LinearEval (float[] x, float[] y, float val) { //binary search for the right interval int k_lo = 0; int k_hi = x.Length - 1; while (k_hi - k_lo > 1) { int k = (k_hi + k_lo) / 2; if (x[k] > val) k_hi = k; else k_lo = k; } float dx = x[k_hi] - x[k_lo]; float dy = y[k_hi] - y[k_lo]; return val*dy/dx + y[k_lo] - dy/dx*x[k_lo]; } static int Project (float val, float min, float max, int norm) { return (int)((norm - 1) * ((val - min) / (max - min)) + .5f); } static float Unproject (int val, float min, float max, int norm) { return val / (float) (norm - 1) * (max - min) + min; } #endregion #region Gtk widgetry const int radius = 3; //radius of the control points const int min_distance = 8; //min distance between control points int x_offset = radius; int y_offset = radius; int width, height; //the real graph Pixmap pixmap = null; protected override bool OnConfigureEvent (EventConfigure evnt) { pixmap = null; return base.OnConfigureEvent (evnt); } protected override bool OnExposeEvent (EventExpose evnt) { pixmap = new Pixmap (GdkWindow, Allocation.Width, Allocation.Height); Draw (); return base.OnExposeEvent (evnt); } Gdk.Point [] Interpolate (int width, int height) { var vector = GetVector (width); var retval = new Gdk.Point [width]; for (int i = 0; i < width; i++) { retval[i].X = x_offset + i; retval[i].Y = y_offset + height - Project (vector[i], MinY, MaxY, height); } return retval; } void Draw () { if (pixmap == null) return; Style style = Style; StateType state = Sensitive ? StateType.Normal : StateType.Insensitive; if (width <= 0 || height <= 0) return; //clear the pixmap GtkBeans.Style.PaintFlatBox (style, pixmap, StateType.Normal, ShadowType.None, null, this, "curve_bg", 0, 0, Allocation.Width, Allocation.Height); //draw the grid lines for (int i = 0; i < 5; i++) { pixmap.DrawLine (style.DarkGC (state), x_offset, i * (int)(height / 4.0) + y_offset, width + x_offset, i * (int)(height / 4.0) + y_offset); pixmap.DrawLine (style.DarkGC (state), i * (int)(width / 4.0) + x_offset, y_offset, i * (int)(width / 4.0) + x_offset, height + y_offset); } //draw the curve pixmap.DrawPoints (style.ForegroundGC (state), Interpolate (width, height)); //draw the bullets if (CurveType != CurveType.Free) foreach (var keyval in points) { if (keyval.Key < MinX) continue; int x = Project (keyval.Key, MinX, MaxX, width); int y = height - Project (keyval.Value, MinY, MaxY, height); pixmap.DrawArc (style.ForegroundGC (state), true, x, y, radius * 2, radius * 2, 0, 360*64); } GdkWindow.DrawDrawable (style.ForegroundGC (state), pixmap, 0, 0, 0, 0, Allocation.Width, Allocation.Height); } protected override void OnSizeAllocated (Rectangle allocation) { width = allocation.Width - 2 * radius; height = allocation.Height - 2 * radius; base.OnSizeAllocated (allocation); } protected override void OnSizeRequested (ref Requisition requisition) { requisition.Width = 128 + 2 * x_offset; requisition.Height = 128 + 2 * y_offset; } float? grab_point = null; protected override bool OnButtonPressEvent (EventButton evnt) { int px = (int)evnt.X - x_offset; int py = (int)evnt.Y - y_offset; if (px < 0) px = 0; if (px > width - 1) px = width - 1; if (py < 0) py = 0; if (py > height - 1) py = height - 1; //find the closest point float closest_x = MinX - 1; var distance = Int32.MaxValue; foreach (var point in points) { int cx = Project (point.Key, MinX, MaxX, width); if (Math.Abs (px - cx) < distance) { distance = Math.Abs (px - cx); closest_x = point.Key; } } Grab.Add (this); CursorType = CursorType.Tcross; switch (CurveType) { case CurveType.Linear: case CurveType.Spline: if (distance > min_distance) { //insert a new control point AddPoint ((closest_x = Unproject (px, MinX, MaxX, width)), MaxY - Unproject (py, MinY, MaxY, height)); QueueDraw (); } grab_point = closest_x; break; case CurveType.Free: throw new NotImplementedException (); } return true; } protected override bool OnButtonReleaseEvent (EventButton evnt) { Grab.Remove (this); //FIXME: remove inactive points CursorType = CursorType.Fleur; grab_point = null; return true; } protected override bool OnMotionNotifyEvent (EventMotion evnt) { int px = (int)evnt.X - x_offset; int py = (int)evnt.Y - y_offset; if (px < 0) px = 0; if (px > width - 1) px = width - 1; if (py < 0) py = 0; if (py > height - 1) py = height - 1; //find the closest point float closest_x = MinX - 1; var distance = Int32.MaxValue; foreach (var point in points) { int cx = Project (point.Key, MinX, MaxX, width); if (Math.Abs (px - cx) < distance) { distance = Math.Abs (px - cx); closest_x = point.Key; } } switch (CurveType) { case CurveType.Spline: case CurveType.Linear: if (grab_point == null) { //No grabbed point if (distance <= min_distance) CursorType = CursorType.Fleur; else CursorType = CursorType.Tcross; return true; } CursorType = CursorType.Tcross; points.Remove (grab_point.Value); AddPoint ((closest_x = Unproject (px, MinX, MaxX, width)), MaxY - Unproject (py, MinY, MaxY, height)); QueueDraw (); grab_point = closest_x; break; case CurveType.Free: throw new NotImplementedException (); } return true; } Gdk.CursorType cursor_type = Gdk.CursorType.TopLeftArrow; CursorType CursorType { get { return cursor_type; } set { if (value == cursor_type) return; cursor_type = value; GdkWindow.Cursor = new Cursor (CursorType); } } #endregion } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Drawing; using System.Windows.Forms; using OpenLiveWriter.Controls; using OpenLiveWriter.CoreServices; using OpenLiveWriter.Interop.Windows; namespace OpenLiveWriter.ApplicationFramework { /// <summary> /// ContextMenuMiniForm /// </summary> internal class CommandContextMenuMiniForm : BaseForm { /* NOTE: When being shown in the context of the browser (or any non .NET * application) this form will not handle any dialog level keyboard * commands (tab, enter, escape, alt-mnenonics, etc.). This is because * it is a modeless form that does not have its own thread/message-loop. * Because the form was created by our .NET code the main IE frame that * has the message loop has no idea it needs to route keyboard events' * to us. There are several possible workarounds: * * (1) Create and show this form on its own thread with its own * message loop. In this case all calls from the form back * to the main UI thread would need to be marshalled. * * (2) Manually process keyboard events in the low-level * ProcessKeyPreview override (see commented out method below) * * (3) Change the implementation of the mini-form to be a modal * dialog. The only problem here is we would need to capture * mouse input so that clicks outside of the modal dialog onto * the IE window result in the window being dismissed. We were * not able to get this to work (couldn't capture the mouse) * in experimenting with this implementation. * * Our judgement was to leave it as-is for now as it is unlikely that * keyboard input into a mini-form will be a big deal (the only way * to access the mini-form is with a mouse gesture on the toolbar so * the user is still in "mouse-mode" when the form pops up. * */ public CommandContextMenuMiniForm(IWin32Window parentFrame, Command command) { // save a reference to the parent frame _parentFrame = parentFrame; // save a reference to the command and context menu control handler _command = command; _contextMenuControlHandler = command.CommandBarButtonContextMenuControlHandler; // set to top most form (allows us to appear on top of our // owner if the owner is also top-most) TopMost = true; // other window options/configuration ShowInTaskbar = false; FormBorderStyle = FormBorderStyle.None; StartPosition = FormStartPosition.Manual; // Paint performance optimizations User32.SetWindowLong(Handle, GWL.STYLE, User32.GetWindowLong(Handle, GWL.STYLE) & ~WS.CLIPCHILDREN); SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.DoubleBuffer, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); // create and initialize the context menu control Control commandContextMenuControl = _contextMenuControlHandler.CreateControl(); commandContextMenuControl.TabIndex = 0; commandContextMenuControl.BackColor = BACKGROUND_COLOR; commandContextMenuControl.Font = ApplicationManager.ApplicationStyle.NormalApplicationFont; commandContextMenuControl.Left = HORIZONTAL_INSET; commandContextMenuControl.Top = HEADER_INSET + HEADER_HEIGHT + HEADER_INSET + HEADER_INSET; Controls.Add(commandContextMenuControl); // create action button (don't add it yet) _actionButton = new BitmapButton(); _actionButton.TabIndex = 1; _actionButton.Click += new EventHandler(_actionButton_Click); _actionButton.BackColor = BACKGROUND_COLOR; _actionButton.Font = ApplicationManager.ApplicationStyle.NormalApplicationFont; _actionButton.BitmapDisabled = _command.CommandBarButtonBitmapDisabled; _actionButton.BitmapEnabled = _command.CommandBarButtonBitmapEnabled; _actionButton.BitmapPushed = _command.CommandBarButtonBitmapPushed; _actionButton.BitmapSelected = _command.CommandBarButtonBitmapSelected; _actionButton.ButtonText = _contextMenuControlHandler.ButtonText; _actionButton.ToolTip = _contextMenuControlHandler.ButtonText; _actionButton.AutoSizeWidth = true; _actionButton.AutoSizeHeight = true; _actionButton.Size = new Size(0, 0); // dummy call to force auto-size // size the form based on the size of the context menu control and button Width = HORIZONTAL_INSET + commandContextMenuControl.Width + HORIZONTAL_INSET; Height = commandContextMenuControl.Bottom + (BUTTON_VERTICAL_PAD * 3) + miniFormBevelBitmap.Height + _actionButton.Height; // position the action button and add it to the form _actionButton.Top = Height - BUTTON_VERTICAL_PAD - _actionButton.Height; _actionButton.Left = HORIZONTAL_INSET - 4; Controls.Add(_actionButton); } /// <summary> /// Override out Activated event to allow parent form to retains its 'activated' /// look (caption bar color, etc.) even when we are active /// </summary> /// <param name="e"></param> protected override void OnActivated(EventArgs e) { // call base base.OnActivated(e); // send the parent form a WM_NCACTIVATE message to cause it to to retain it's // activated title bar appearance User32.SendMessage(_parentFrame.Handle, WM.NCACTIVATE, new UIntPtr(1), IntPtr.Zero); } /// <summary> /// Automatically close when the form is deactivated /// </summary> /// <param name="e">event args</param> protected override void OnDeactivate(EventArgs e) { base.OnDeactivate(e); // set a timer that will result in the closing of the form // (we do this because if actually call Close right here it // will prevent the mouse event that resulted in the deactivation // of the form from actually triggering in the new target // winodw -- this allows the mouse event to trigger and the // form to go away almost instantly Timer closeDelayTimer = new Timer(); closeDelayTimer.Tick += new EventHandler(closeDelayTimer_Tick); closeDelayTimer.Interval = 10; closeDelayTimer.Start(); } /// <summary> /// Actually close the form /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void closeDelayTimer_Tick(object sender, EventArgs e) { // stop and dispose the timer Timer closeDelayTimer = (Timer)sender; closeDelayTimer.Stop(); closeDelayTimer.Dispose(); // cancel the form Cancel(); } // handle painting protected override void OnPaint(PaintEventArgs e) { // get refrence to graphics context Graphics g = e.Graphics; // fill background using (SolidBrush backgroundBrush = new SolidBrush(BACKGROUND_COLOR)) g.FillRectangle(backgroundBrush, ClientRectangle); // draw outer border Rectangle borderRectangle = ClientRectangle; borderRectangle.Width -= 1; borderRectangle.Height -= 1; using (Pen borderPen = new Pen(ApplicationManager.ApplicationStyle.BorderColor)) g.DrawRectangle(borderPen, borderRectangle); // draw header region background using (SolidBrush headerBrush = new SolidBrush(ApplicationManager.ApplicationStyle.PrimaryWorkspaceTopColor)) g.FillRectangle(headerBrush, HEADER_INSET, HEADER_INSET, Width - (HEADER_INSET * 2), HEADER_HEIGHT); // draw header region text using (SolidBrush textBrush = new SolidBrush(ApplicationManager.ApplicationStyle.ToolWindowTitleBarTextColor)) g.DrawString( _contextMenuControlHandler.CaptionText, ApplicationManager.ApplicationStyle.NormalApplicationFont, textBrush, new PointF(HEADER_INSET + 1, HEADER_INSET + 1)); // draw bottom bevel line g.DrawImage(miniFormBevelBitmap, new Rectangle( HORIZONTAL_INSET - 1, Height - (2 * BUTTON_VERTICAL_PAD) - _actionButton.Height, Width - (HORIZONTAL_INSET * 2), miniFormBevelBitmap.Height)); } /// <summary> /// Prevent background painting (supports double-buffering) /// </summary> /// <param name="pevent"></param> protected override void OnPaintBackground(PaintEventArgs pevent) { } /* protected override bool ProcessKeyPreview(ref Message m) { // NOTE: this is the only keyboard "event" which appears // to get called when our form is shown in the browser. // if we want to support tab, esc, enter, mnemonics, etc. // without creating a new thread/message-loop for this // form (see comment at the top) then this is where we // would do the manual processing return base.ProcessKeyPreview (ref m); } */ /// <summary> /// User clicked the action button /// </summary> /// <param name="sender">sender</param> /// <param name="e">event args</param> private void _actionButton_Click(object sender, EventArgs e) { Execute(); } /// <summary> /// Cancel the mini-form /// </summary> private void Cancel() { Close(); } /// <summary> /// Execute the command /// </summary> private void Execute() { // get the data entered by the user object userInput = _contextMenuControlHandler.GetUserInput(); // close the form Close(); // tell the context menu control to execute using the specified user input _contextMenuControlHandler.Execute(userInput); } /// <summary> /// Handle to parent frame window /// </summary> private IWin32Window _parentFrame; /// <summary> /// Command we are associated with /// </summary> private Command _command; /// <summary> /// Context menu control handler /// </summary> private ICommandContextMenuControlHandler _contextMenuControlHandler; /// <summary> /// Button user clicks to take action /// </summary> private BitmapButton _actionButton; /// <summary> /// Button face bitmap /// </summary> private readonly Bitmap miniFormBevelBitmap = ResourceHelper.LoadAssemblyResourceBitmap("Images.CommandBar.MiniFormBevel.png"); // layout and drawing contants private const int HEADER_INSET = 2; private const int HEADER_HEIGHT = 17; private const int HORIZONTAL_INSET = 10; private const int BUTTON_VERTICAL_PAD = 3; private static readonly Color BACKGROUND_COLOR = Color.FromArgb(244, 243, 238); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.AzureStack.Management.Fabric.Admin { using Microsoft.AzureStack; using Microsoft.AzureStack.Management; using Microsoft.AzureStack.Management.Fabric; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Azure.OData; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// MacAddressPoolsOperations operations. /// </summary> internal partial class MacAddressPoolsOperations : IServiceOperations<FabricAdminClient>, IMacAddressPoolsOperations { /// <summary> /// Initializes a new instance of the MacAddressPoolsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal MacAddressPoolsOperations(FabricAdminClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the FabricAdminClient /// </summary> public FabricAdminClient Client { get; private set; } /// <summary> /// Get a MAC address pool. /// </summary> /// <param name='location'> /// Location of the resource. /// </param> /// <param name='macAddressPool'> /// Name of the MAC address pool. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<MacAddressPool>> GetWithHttpMessagesAsync(string location, string macAddressPool, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (location == null) { throw new ValidationException(ValidationRules.CannotBeNull, "location"); } if (macAddressPool == null) { throw new ValidationException(ValidationRules.CannotBeNull, "macAddressPool"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("location", location); tracingParameters.Add("macAddressPool", macAddressPool); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/System.{location}/providers/Microsoft.Fabric.Admin/fabricLocations/{location}/macAddressPools/{macAddressPool}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{location}", System.Uri.EscapeDataString(location)); _url = _url.Replace("{macAddressPool}", System.Uri.EscapeDataString(macAddressPool)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<MacAddressPool>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<MacAddressPool>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a list of all MAC address pools at a location. /// </summary> /// <param name='location'> /// Location of the resource. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<MacAddressPool>>> ListWithHttpMessagesAsync(string location, ODataQuery<MacAddressPool> odataQuery = default(ODataQuery<MacAddressPool>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (location == null) { throw new ValidationException(ValidationRules.CannotBeNull, "location"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("location", location); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/System.{location}/providers/Microsoft.Fabric.Admin/fabricLocations/{location}/macAddressPools").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{location}", System.Uri.EscapeDataString(location)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<MacAddressPool>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<MacAddressPool>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a list of all MAC address pools at a location. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<MacAddressPool>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<MacAddressPool>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<MacAddressPool>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // // This is used internally to create best fit behavior as per the original windows best fit behavior. // using System.Diagnostics; using System.Globalization; using System.Threading; namespace System.Text { internal class InternalEncoderBestFitFallback : EncoderFallback { // Our variables internal Encoding _encoding = null; internal char[] _arrayBestFit = null; internal InternalEncoderBestFitFallback(Encoding encoding) { // Need to load our replacement characters table. _encoding = encoding; } public override EncoderFallbackBuffer CreateFallbackBuffer() { return new InternalEncoderBestFitFallbackBuffer(this); } // Maximum number of characters that this instance of this fallback could return public override int MaxCharCount { get { return 1; } } public override bool Equals(object value) { if (value is InternalEncoderBestFitFallback that) { return (_encoding.CodePage == that._encoding.CodePage); } return (false); } public override int GetHashCode() { return _encoding.CodePage; } } internal sealed class InternalEncoderBestFitFallbackBuffer : EncoderFallbackBuffer { // Our variables private char _cBestFit = '\0'; private InternalEncoderBestFitFallback _oFallback; private int _iCount = -1; private int _iSize; // Private object for locking instead of locking on a public type for SQL reliability work. private static object s_InternalSyncObject; private static object InternalSyncObject { get { if (s_InternalSyncObject == null) { object o = new object(); Interlocked.CompareExchange<object>(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } } // Constructor public InternalEncoderBestFitFallbackBuffer(InternalEncoderBestFitFallback fallback) { _oFallback = fallback; if (_oFallback._arrayBestFit == null) { // Lock so we don't confuse ourselves. lock (InternalSyncObject) { // Double check before we do it again. if (_oFallback._arrayBestFit == null) _oFallback._arrayBestFit = fallback._encoding.GetBestFitUnicodeToBytesData(); } } } // Fallback methods public override bool Fallback(char charUnknown, int index) { // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. // Shouldn't be able to get here for all of our code pages, table would have to be messed up. Debug.Assert(_iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(non surrogate)] Fallback char " + ((int)_cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback"); _iCount = _iSize = 1; _cBestFit = TryBestFit(charUnknown); if (_cBestFit == '\0') _cBestFit = '?'; return true; } public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index) { // Double check input surrogate pair if (!char.IsHighSurrogate(charUnknownHigh)) throw new ArgumentOutOfRangeException(nameof(charUnknownHigh), SR.Format(SR.ArgumentOutOfRange_Range, 0xD800, 0xDBFF)); if (!char.IsLowSurrogate(charUnknownLow)) throw new ArgumentOutOfRangeException(nameof(charUnknownLow), SR.Format(SR.ArgumentOutOfRange_Range, 0xDC00, 0xDFFF)); // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. 0 is processing last character, < 0 is not falling back // Shouldn't be able to get here, table would have to be messed up. Debug.Assert(_iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(surrogate)] Fallback char " + ((int)_cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback"); // Go ahead and get our fallback, surrogates don't have best fit _cBestFit = '?'; _iCount = _iSize = 2; return true; } // Default version is overridden in EncoderReplacementFallback.cs public override char GetNextChar() { // We want it to get < 0 because == 0 means that the current/last character is a fallback // and we need to detect recursion. We could have a flag but we already have this counter. _iCount--; // Do we have anything left? 0 is now last fallback char, negative is nothing left if (_iCount < 0) return '\0'; // Need to get it out of the buffer. // Make sure it didn't wrap from the fast count-- path if (_iCount == int.MaxValue) { _iCount = -1; return '\0'; } // Return the best fit character return _cBestFit; } public override bool MovePrevious() { // Exception fallback doesn't have anywhere to back up to. if (_iCount >= 0) _iCount++; // Return true if we could do it. return (_iCount >= 0 && _iCount <= _iSize); } // How many characters left to output? public override int Remaining { get { return (_iCount > 0) ? _iCount : 0; } } // Clear the buffer public override unsafe void Reset() { _iCount = -1; charStart = null; bFallingBack = false; } // private helper methods private char TryBestFit(char cUnknown) { // Need to figure out our best fit character, low is beginning of array, high is 1 AFTER end of array int lowBound = 0; int highBound = _oFallback._arrayBestFit.Length; int index; // Binary search the array int iDiff; while ((iDiff = (highBound - lowBound)) > 6) { // Look in the middle, which is complicated by the fact that we have 2 #s for each pair, // so we don't want index to be odd because we want to be on word boundaries. // Also note that index can never == highBound (because diff is rounded down) index = ((iDiff / 2) + lowBound) & 0xFFFE; char cTest = _oFallback._arrayBestFit[index]; if (cTest == cUnknown) { // We found it Debug.Assert(index + 1 < _oFallback._arrayBestFit.Length, "[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array"); return _oFallback._arrayBestFit[index + 1]; } else if (cTest < cUnknown) { // We weren't high enough lowBound = index; } else { // We weren't low enough highBound = index; } } for (index = lowBound; index < highBound; index += 2) { if (_oFallback._arrayBestFit[index] == cUnknown) { // We found it Debug.Assert(index + 1 < _oFallback._arrayBestFit.Length, "[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array"); return _oFallback._arrayBestFit[index + 1]; } } // Char wasn't in our table return '\0'; } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // <OWNER>[....]</OWNER> // using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Xml; namespace System.Security.Cryptography.Xml { /// <summary> /// Trace support for debugging issues signing and verifying XML signatures. /// </summary> internal static class SignedXmlDebugLog { // // In order to enable XML digital signature debug loggging, applications should setup their config // file to be similar to the following: // // <configuration> // <system.diagnostics> // <sources> // <source name="System.Security.Cryptography.Xml.SignedXml" // switchName="XmlDsigLogSwitch"> // <listeners> // <add name="logFile" /> // </listeners> // </source> // </sources> // <switches> // <add name="XmlDsigLogSwitch" value="Verbose" /> // </switches> // <sharedListeners> // <add name="logFile" // type="System.Diagnostics.TextWriterTraceListener" // initializeData="XmlDsigLog.txt"/> // </sharedListeners> // <trace autoflush="true"> // <listeners> // <add name="logFile" /> // </listeners> // </trace> // </system.diagnostics> // </configuration> // private const string NullString = "(null)"; private static TraceSource s_traceSource = new TraceSource("System.Security.Cryptography.Xml.SignedXml"); private static volatile bool s_haveVerboseLogging; private static volatile bool s_verboseLogging; private static volatile bool s_haveInformationLogging; private static volatile bool s_informationLogging; /// <summary> /// Types of events that are logged to the debug log /// </summary> internal enum SignedXmlDebugEvent { /// <summary> /// Canonicalization of input XML has begun /// </summary> BeginCanonicalization, /// <summary> /// Verificaiton of the signature format itself is beginning /// </summary> BeginCheckSignatureFormat, /// <summary> /// Verification of a signed info is beginning /// </summary> BeginCheckSignedInfo, /// <summary> /// Signing is beginning /// </summary> BeginSignatureComputation, /// <summary> /// Signature verification is beginning /// </summary> BeginSignatureVerification, /// <summary> /// Input data has been transformed to its canonicalized form /// </summary> CanonicalizedData, /// <summary> /// The result of signature format validation /// </summary> FormatValidationResult, /// <summary> /// Namespaces are being propigated into the signature /// </summary> NamespacePropagation, /// <summary> /// Output from a Reference /// </summary> ReferenceData, /// <summary> /// The result of a signature verification /// </summary> SignatureVerificationResult, /// <summary> /// Calculating the final signature /// </summary> Signing, /// <summary> /// A reference is being hashed /// </summary> SigningReference, /// <summary> /// A signature has failed to verify /// </summary> VerificationFailure, /// <summary> /// Verify that a reference has the correct hash value /// </summary> VerifyReference, /// <summary> /// Verification is processing the SignedInfo section of the signature /// </summary> VerifySignedInfo, /// <summary> /// Verification status on the x.509 certificate in use /// </summary> X509Verification, /// <summary> /// The signature is being rejected by the signature format verifier due to having /// a canonicalization algorithm which is not on the known valid list. /// </summary> UnsafeCanonicalizationMethod, } /// <summary> /// Check to see if logging should be done in this process /// </summary> private static bool InformationLoggingEnabled { get { if (!s_haveInformationLogging) { s_informationLogging = s_traceSource.Switch.ShouldTrace(TraceEventType.Information); s_haveInformationLogging = true; } return s_informationLogging; } } /// <summary> /// Check to see if verbose log messages should be generated /// </summary> private static bool VerboseLoggingEnabled { get { if (!s_haveVerboseLogging) { s_verboseLogging = s_traceSource.Switch.ShouldTrace(TraceEventType.Verbose); s_haveVerboseLogging = true; } return s_verboseLogging; } } /// <summary> /// Convert the byte array into a hex string /// </summary> private static string FormatBytes(byte[] bytes) { if (bytes == null) return NullString; StringBuilder builder = new StringBuilder(bytes.Length * 2); foreach (byte b in bytes) { builder.Append(b.ToString("x2", CultureInfo.InvariantCulture)); } return builder.ToString(); } /// <summary> /// Map a key to a string describing the key /// </summary> private static string GetKeyName(object key) { Debug.Assert(key != null, "key != null"); ICspAsymmetricAlgorithm cspKey = key as ICspAsymmetricAlgorithm; X509Certificate certificate = key as X509Certificate; X509Certificate2 certificate2 = key as X509Certificate2; // // Use the following sources for key names, if available: // // * CAPI key -> key container name // * X509Certificate2 -> subject simple name // * X509Certificate -> subject name // * All others -> hash code // string keyName = null; if (cspKey != null && cspKey.CspKeyContainerInfo.KeyContainerName != null) { keyName = String.Format(CultureInfo.InvariantCulture, "\"{0}\"", cspKey.CspKeyContainerInfo.KeyContainerName); } else if (certificate2 != null) { keyName = String.Format(CultureInfo.InvariantCulture, "\"{0}\"", certificate2.GetNameInfo(X509NameType.SimpleName, false)); } else if (certificate != null) { keyName = String.Format(CultureInfo.InvariantCulture, "\"{0}\"", certificate.Subject); } else { keyName = key.GetHashCode().ToString("x8", CultureInfo.InvariantCulture); } return String.Format(CultureInfo.InvariantCulture, "{0}#{1}", key.GetType().Name, keyName); } /// <summary> /// Map an object to a string describing the object /// </summary> private static string GetObjectId(object o) { Debug.Assert(o != null, "o != null"); return String.Format(CultureInfo.InvariantCulture, "{0}#{1}", o.GetType().Name, o.GetHashCode().ToString("x8", CultureInfo.InvariantCulture)); } /// <summary> /// Map an OID to the friendliest name possible /// </summary> private static string GetOidName(Oid oid) { Debug.Assert(oid != null, "oid != null"); string friendlyName = oid.FriendlyName; if (String.IsNullOrEmpty(friendlyName)) friendlyName = oid.Value; return friendlyName; } /// <summary> /// Log that canonicalization has begun on input data /// </summary> /// <param name="signedXml">SignedXml object doing the signing or verification</param> /// <param name="canonicalizationTransform">transform canonicalizing the input</param> internal static void LogBeginCanonicalization(SignedXml signedXml, Transform canonicalizationTransform) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(canonicalizationTransform != null, "canonicalizationTransform != null"); if (InformationLoggingEnabled) { string logMessage = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_BeginCanonicalization"), canonicalizationTransform.Algorithm, canonicalizationTransform.GetType().Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.BeginCanonicalization, logMessage); } if (VerboseLoggingEnabled) { string canonicalizationSettings = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_CanonicalizationSettings"), canonicalizationTransform.Resolver.GetType(), canonicalizationTransform.BaseURI); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.BeginCanonicalization, canonicalizationSettings); } } /// <summary> /// Log that we're going to be validating the signature format itself /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="formatValidator">Callback delegate which is being used for format verification</param> internal static void LogBeginCheckSignatureFormat(SignedXml signedXml, Func<SignedXml, bool> formatValidator) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(formatValidator != null, "formatValidator != null"); if (InformationLoggingEnabled) { MethodInfo validationMethod = formatValidator.Method; string logMessage = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_CheckSignatureFormat"), validationMethod.Module.Assembly.FullName, validationMethod.DeclaringType.FullName, validationMethod.Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.BeginCheckSignatureFormat, logMessage); } } /// <summary> /// Log that checking SignedInfo is beginning /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="signedInfo">SignedInfo object being verified</param> internal static void LogBeginCheckSignedInfo(SignedXml signedXml, SignedInfo signedInfo) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(signedInfo != null, " signedInfo != null"); if (InformationLoggingEnabled) { string logMessage = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_CheckSignedInfo"), signedInfo.Id != null ? signedInfo.Id : NullString); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.BeginCheckSignedInfo, logMessage); } } /// <summary> /// Log that signature computation is beginning /// </summary> /// <param name="signedXml">SignedXml object doing the signing</param> /// <param name="context">Context of the signature</param> internal static void LogBeginSignatureComputation(SignedXml signedXml, XmlElement context) { Debug.Assert(signedXml != null, "signedXml != null"); if (InformationLoggingEnabled) { WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.BeginSignatureComputation, SecurityResources.GetResourceString("Log_BeginSignatureComputation")); } if (VerboseLoggingEnabled) { string contextData = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_XmlContext"), context != null ? context.OuterXml : NullString); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.BeginSignatureComputation, contextData); } } /// <summary> /// Log that signature verification is beginning /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="context">Context of the verification</param> internal static void LogBeginSignatureVerification(SignedXml signedXml, XmlElement context) { Debug.Assert(signedXml != null, "signedXml != null"); if (InformationLoggingEnabled) { WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.BeginSignatureVerification, SecurityResources.GetResourceString("Log_BeginSignatureVerification")); } if (VerboseLoggingEnabled) { string contextData = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_XmlContext"), context != null ? context.OuterXml : NullString); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.BeginSignatureVerification, contextData); } } /// <summary> /// Log the canonicalized data /// </summary> /// <param name="signedXml">SignedXml object doing the signing or verification</param> /// <param name="canonicalizationTransform">transform canonicalizing the input</param> internal static void LogCanonicalizedOutput(SignedXml signedXml, Transform canonicalizationTransform) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(canonicalizationTransform != null, "canonicalizationTransform != null"); if (VerboseLoggingEnabled) { using (StreamReader reader = new StreamReader(canonicalizationTransform.GetOutput(typeof(Stream)) as Stream)) { string logMessage = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_CanonicalizedOutput"), reader.ReadToEnd()); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.CanonicalizedData, logMessage); } } } /// <summary> /// Log that the signature format callback has rejected the signature /// </summary> /// <param name="signedXml">SignedXml object doing the signature verification</param> /// <param name="result">result of the signature format verification</param> internal static void LogFormatValidationResult(SignedXml signedXml, bool result) { Debug.Assert(signedXml != null, "signedXml != null"); if (InformationLoggingEnabled) { string logMessage = result ? SecurityResources.GetResourceString("Log_FormatValidationSuccessful") : SecurityResources.GetResourceString("Log_FormatValidationNotSuccessful"); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.FormatValidationResult, logMessage); } } /// <summary> /// Log that a signature is being rejected as having an invalid format due to its canonicalization /// algorithm not being on the valid list. /// </summary> /// <param name="signedXml">SignedXml object doing the signature verification</param> /// <param name="result">result of the signature format verification</param> internal static void LogUnsafeCanonicalizationMethod(SignedXml signedXml, string algorithm, IEnumerable<string> validAlgorithms) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(validAlgorithms != null, "validAlgorithms != null"); if (InformationLoggingEnabled) { StringBuilder validAlgorithmBuilder = new StringBuilder(); foreach (string validAlgorithm in validAlgorithms) { if (validAlgorithmBuilder.Length != 0) { validAlgorithmBuilder.Append(", "); } validAlgorithmBuilder.AppendFormat("\"{0}\"", validAlgorithm); } string logMessage = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_UnsafeCanonicalizationMethod"), algorithm, validAlgorithmBuilder.ToString()); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.UnsafeCanonicalizationMethod, logMessage); } } /// <summary> /// Log namespaces which are being propigated into the singature /// </summary> /// <param name="signedXml">SignedXml doing the signing or verification</param> /// <param name="namespaces">namespaces being propigated</param> internal static void LogNamespacePropagation(SignedXml signedXml, XmlNodeList namespaces) { Debug.Assert(signedXml != null, "signedXml != null"); if (InformationLoggingEnabled) { if (namespaces != null) { foreach (XmlAttribute propagatedNamespace in namespaces) { string propagationMessage = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_PropagatingNamespace"), propagatedNamespace.Name, propagatedNamespace.Value); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.NamespacePropagation, propagationMessage); } } else { WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.NamespacePropagation, SecurityResources.GetResourceString("Log_NoNamespacesPropagated")); } } } /// <summary> /// Log the output of a reference /// </summary> /// <param name="reference">The reference being processed</param> /// <param name="data">Stream containing the output of the reference</param> /// <returns>Stream containing the output of the reference</returns> internal static Stream LogReferenceData(Reference reference, Stream data) { if (VerboseLoggingEnabled) { // // Since the input data stream could be from the network or another source that does not // support rewinding, we will read the stream into a temporary MemoryStream that can be used // to stringify the output and also return to the reference so that it can produce the hash // value. // MemoryStream ms = new MemoryStream(); // First read the input stream into our temporary stream byte[] buffer = new byte[4096]; int readBytes = 0; do { readBytes = data.Read(buffer, 0, buffer.Length); ms.Write(buffer, 0, readBytes); } while (readBytes == buffer.Length); // Log out information about it string logMessage = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_TransformedReferenceContents"), Encoding.UTF8.GetString(ms.ToArray())); WriteLine(reference, TraceEventType.Verbose, SignedXmlDebugEvent.ReferenceData, logMessage); // Rewind to the beginning, so that the entire input stream is hashed ms.Seek(0, SeekOrigin.Begin); return ms; } else { return data; } } /// <summary> /// Log the computation of a signature value when signing with an asymmetric algorithm /// </summary> /// <param name="signedXml">SignedXml object calculating the signature</param> /// <param name="key">key used for signing</param> /// <param name="signatureDescription">signature description being used to create the signature</param> /// <param name="hash">hash algorithm used to digest the output</param> /// <param name="asymmetricSignatureFormatter">signature formatter used to do the signing</param> internal static void LogSigning(SignedXml signedXml, object key, SignatureDescription signatureDescription, HashAlgorithm hash, AsymmetricSignatureFormatter asymmetricSignatureFormatter) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(signatureDescription != null, "signatureDescription != null"); Debug.Assert(hash != null, "hash != null"); Debug.Assert(asymmetricSignatureFormatter != null, "asymmetricSignatureFormatter != null"); if (InformationLoggingEnabled) { string logMessage = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_SigningAsymmetric"), GetKeyName(key), signatureDescription.GetType().Name, hash.GetType().Name, asymmetricSignatureFormatter.GetType().Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.Signing, logMessage); } } /// <summary> /// Log the computation of a signature value when signing with a keyed hash algorithm /// </summary> /// <param name="signedXml">SignedXml object calculating the signature</param> /// <param name="key">key the signature is created with</param> /// <param name="hash">hash algorithm used to digest the output</param> /// <param name="asymmetricSignatureFormatter">signature formatter used to do the signing</param> internal static void LogSigning(SignedXml signedXml, KeyedHashAlgorithm key) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(key != null, "key != null"); if (InformationLoggingEnabled) { string logMessage = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_SigningHmac"), key.GetType().Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.Signing, logMessage); } } /// <summary> /// Log the calculation of a hash value of a reference /// </summary> /// <param name="signedXml">SignedXml object driving the signature</param> /// <param name="reference">Reference being hashed</param> internal static void LogSigningReference(SignedXml signedXml, Reference reference) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(reference != null, "reference != null"); if (VerboseLoggingEnabled) { string logMessage = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_SigningReference"), GetObjectId(reference), reference.Uri, reference.Id, reference.Type, reference.DigestMethod, CryptoConfig.CreateFromName(reference.DigestMethod).GetType().Name); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.SigningReference, logMessage); } } /// <summary> /// Log the specific point where a signature is determined to not be verifiable /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="failureLocation">location that the signature was determined to be invalid</param> internal static void LogVerificationFailure(SignedXml signedXml, string failureLocation) { if (InformationLoggingEnabled) { string logMessage = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_VerificationFailed"), failureLocation); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.VerificationFailure, logMessage); } } /// <summary> /// Log the success or failure of a signature verification operation /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="key">public key used to verify the signature</param> /// <param name="verified">true if the signature verified, false otherwise</param> internal static void LogVerificationResult(SignedXml signedXml, object key, bool verified) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(key != null, "key != null"); if (InformationLoggingEnabled) { string resource = verified ? SecurityResources.GetResourceString("Log_VerificationWithKeySuccessful") : SecurityResources.GetResourceString("Log_VerificationWithKeyNotSuccessful"); string logMessage = String.Format(CultureInfo.InvariantCulture, resource, GetKeyName(key)); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.SignatureVerificationResult, logMessage); } } /// <summary> /// Log the check for appropriate X509 key usage /// </summary> /// <param name="signedXml">SignedXml doing the signature verification</param> /// <param name="certificate">certificate having its key usages checked</param> /// <param name="keyUsages">key usages being examined</param> internal static void LogVerifyKeyUsage(SignedXml signedXml, X509Certificate certificate, X509KeyUsageExtension keyUsages) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(certificate != null, "certificate != null"); if (InformationLoggingEnabled) { string logMessage = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_KeyUsages"), keyUsages.KeyUsages, GetOidName(keyUsages.Oid), GetKeyName(certificate)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, logMessage); } } /// <summary> /// Log that we are verifying a reference /// </summary> /// <param name="signedXml">SignedXMl object doing the verification</param> /// <param name="reference">reference being verified</param> internal static void LogVerifyReference(SignedXml signedXml, Reference reference) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(reference != null, "reference != null"); if (InformationLoggingEnabled) { string logMessage = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_VerifyReference"), GetObjectId(reference), reference.Uri, reference.Id, reference.Type); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifyReference, logMessage); } } /// <summary> /// Log the hash comparison when verifying a reference /// </summary> /// <param name="signedXml">SignedXml object verifying the signature</param> /// <param name="reference">reference being verified</param> /// <param name="actualHash">actual hash value of the reference</param> /// <param name="expectedHash">hash value the signature expected the reference to have</param> internal static void LogVerifyReferenceHash(SignedXml signedXml, Reference reference, byte[] actualHash, byte[] expectedHash) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(reference != null, "reference != null"); Debug.Assert(actualHash != null, "actualHash != null"); Debug.Assert(expectedHash != null, "expectedHash != null"); if (VerboseLoggingEnabled) { string logMessage = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_ReferenceHash"), GetObjectId(reference), reference.DigestMethod, CryptoConfig.CreateFromName(reference.DigestMethod).GetType().Name, FormatBytes(actualHash), FormatBytes(expectedHash)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifyReference, logMessage); } } /// <summary> /// Log the verification parameters when verifying the SignedInfo section of a signature using an /// asymmetric key /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="key">key being used to verify the signed info</param> /// <param name="signatureDescription">type of signature description class used</param> /// <param name="hashAlgorithm">type of hash algorithm used</param> /// <param name="asymmetricSignatureDeformatter">type of signature deformatter used</param> /// <param name="actualHashValue">hash value of the signed info</param> /// <param name="signatureValue">raw signature value</param> internal static void LogVerifySignedInfo(SignedXml signedXml, AsymmetricAlgorithm key, SignatureDescription signatureDescription, HashAlgorithm hashAlgorithm, AsymmetricSignatureDeformatter asymmetricSignatureDeformatter, byte[] actualHashValue, byte[] signatureValue) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(signatureDescription != null, "signatureDescription != null"); Debug.Assert(hashAlgorithm != null, "hashAlgorithm != null"); Debug.Assert(asymmetricSignatureDeformatter != null, "asymmetricSignatureDeformatter != null"); if (InformationLoggingEnabled) { string logMessage = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_VerifySignedInfoAsymmetric"), GetKeyName(key), signatureDescription.GetType().Name, hashAlgorithm.GetType().Name, asymmetricSignatureDeformatter.GetType().Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.VerifySignedInfo, logMessage); } if (VerboseLoggingEnabled) { string hashLog = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_ActualHashValue"), FormatBytes(actualHashValue)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, hashLog); string signatureLog = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_RawSignatureValue"), FormatBytes(signatureValue)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, signatureLog); } } /// <summary> /// Log the verification parameters when verifying the SignedInfo section of a signature using a /// keyed hash algorithm /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="mac">hash algoirthm doing the verification</param> /// <param name="actualHashValue">hash value of the signed info</param> /// <param name="signatureValue">raw signature value</param> internal static void LogVerifySignedInfo(SignedXml signedXml, KeyedHashAlgorithm mac, byte[] actualHashValue, byte[] signatureValue) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(mac != null, "mac != null"); if (InformationLoggingEnabled) { string logMessage = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_VerifySignedInfoHmac"), mac.GetType().Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.VerifySignedInfo, logMessage); } if (VerboseLoggingEnabled) { string hashLog = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_ActualHashValue"), FormatBytes(actualHashValue)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, hashLog); string signatureLog = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_RawSignatureValue"), FormatBytes(signatureValue)); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, signatureLog); } } /// <summary> /// Log that an X509 chain is being built for a certificate /// </summary> /// <param name="signedXml">SignedXml object building the chain</param> /// <param name="chain">chain built for the certificate</param> /// <param name="certificate">certificate having the chain built for it</param> internal static void LogVerifyX509Chain(SignedXml signedXml, X509Chain chain, X509Certificate certificate) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(certificate != null, "certificate != null"); Debug.Assert(chain != null, "chain != null"); if (InformationLoggingEnabled) { string buildMessage = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_BuildX509Chain"), GetKeyName(certificate)); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.X509Verification, buildMessage); } if (VerboseLoggingEnabled) { // Dump out the flags and other miscelanious information used for building string revocationMode = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_RevocationMode"), chain.ChainPolicy.RevocationFlag); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, revocationMode); string revocationFlag = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_RevocationFlag"), chain.ChainPolicy.RevocationFlag); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, revocationFlag); string verificationFlags = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_VerificationFlag"), chain.ChainPolicy.VerificationFlags); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, verificationFlags); string verificationTime = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_VerificationTime"), chain.ChainPolicy.VerificationTime); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, verificationTime); string urlTimeout = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_UrlTimeout"), chain.ChainPolicy.UrlRetrievalTimeout); WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, urlTimeout); } // If there were any errors in the chain, make sure to dump those out if (InformationLoggingEnabled) { foreach (X509ChainStatus status in chain.ChainStatus) { if (status.Status != X509ChainStatusFlags.NoError) { string logMessage = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_X509ChainError"), status.Status, status.StatusInformation); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.X509Verification, logMessage); } } } // Finally, dump out the chain itself if (VerboseLoggingEnabled) { StringBuilder chainElements = new StringBuilder(); chainElements.Append(SecurityResources.GetResourceString("Log_CertificateChain")); foreach (X509ChainElement element in chain.ChainElements) { chainElements.AppendFormat(CultureInfo.InvariantCulture, " {0}", GetKeyName(element.Certificate)); } WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, chainElements.ToString()); } } /// <summary> /// Write informaiton when user hits the Signed XML recursion depth limit issue. /// This is helpful in debugging this kind of issues. /// </summary> /// <param name="signedXml">SignedXml object verifying the signature</param> /// <param name="reference">reference being verified</param> internal static void LogSignedXmlRecursionLimit(SignedXml signedXml, Reference reference) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(reference != null, "reference != null"); if (InformationLoggingEnabled) { string logMessage = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_SignedXmlRecursionLimit"), GetObjectId(reference), reference.DigestMethod, CryptoConfig.CreateFromName(reference.DigestMethod).GetType().Name); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.VerifySignedInfo, logMessage); } } /// <summary> /// Write data to the log /// </summary> /// <param name="source">object doing the trace</param> /// <param name="eventType">severity of the debug event</param> /// <param name="data">data being written</param> /// <param name="eventId">type of event being traced</param> private static void WriteLine(object source, TraceEventType eventType, SignedXmlDebugEvent eventId, string data) { Debug.Assert(source != null, "source != null"); Debug.Assert(!String.IsNullOrEmpty(data), "!String.IsNullOrEmpty(data)"); Debug.Assert(InformationLoggingEnabled, "InformationLoggingEnabled"); s_traceSource.TraceEvent(eventType, (int)eventId, "[{0}, {1}] {2}", GetObjectId(source), eventId, data); } } }
using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Infrastructure; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Migrations; using AllReady.Models; namespace AllReady.Migrations { [DbContext(typeof(AllReadyContext))] [Migration("20160418113633_FeaturedArticleFlag")] partial class FeaturedArticleFlag { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "7.0.0-rc1-16348") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("AllReady.Models.Activity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("EventType"); b.Property<int>("CampaignId"); b.Property<string>("Description"); b.Property<DateTimeOffset>("EndDateTime"); b.Property<string>("ImageUrl"); b.Property<bool>("IsAllowWaitList"); b.Property<bool>("IsLimitVolunteers"); b.Property<int?>("LocationId"); b.Property<string>("Name") .IsRequired(); b.Property<int>("NumberOfVolunteersRequired"); b.Property<string>("OrganizerId"); b.Property<DateTimeOffset>("StartDateTime"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.ActivitySignup", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("ActivityId"); b.Property<string>("AdditionalInfo"); b.Property<DateTime?>("CheckinDateTime"); b.Property<string>("PreferredEmail"); b.Property<string>("PreferredPhoneNumber"); b.Property<DateTime>("SignupDateTime"); b.Property<string>("UserId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.ActivitySkill", b => { b.Property<int>("ActivityId"); b.Property<int>("SkillId"); b.HasKey("ActivityId", "SkillId"); }); modelBuilder.Entity("AllReady.Models.AllReadyTask", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("ActivityId"); b.Property<string>("Description"); b.Property<DateTimeOffset?>("EndDateTime"); b.Property<bool>("IsAllowWaitList"); b.Property<bool>("IsLimitVolunteers"); b.Property<string>("Name") .IsRequired(); b.Property<int>("NumberOfVolunteersRequired"); b.Property<int?>("OrganizationId"); b.Property<DateTimeOffset?>("StartDateTime"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.ApplicationUser", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasAnnotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("Name"); b.Property<string>("NormalizedEmail") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .HasAnnotation("MaxLength", 256); b.Property<int?>("OrganizationId"); b.Property<string>("PasswordHash"); b.Property<string>("PendingNewEmail"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<string>("TimeZoneId") .IsRequired(); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasAnnotation("Relational:Name", "EmailIndex"); b.HasIndex("NormalizedUserName") .HasAnnotation("Relational:Name", "UserNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetUsers"); }); modelBuilder.Entity("AllReady.Models.Campaign", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("CampaignImpactId"); b.Property<string>("Description"); b.Property<DateTimeOffset>("EndDateTime"); b.Property<bool>("Featured"); b.Property<string>("FullDescription"); b.Property<string>("ImageUrl"); b.Property<int?>("LocationId"); b.Property<bool>("Locked"); b.Property<int>("ManagingOrganizationId"); b.Property<string>("Name") .IsRequired(); b.Property<string>("OrganizerId"); b.Property<DateTimeOffset>("StartDateTime"); b.Property<string>("TimeZoneId") .IsRequired(); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.CampaignContact", b => { b.Property<int>("CampaignId"); b.Property<int>("ContactId"); b.Property<int>("ContactType"); b.HasKey("CampaignId", "ContactId", "ContactType"); }); modelBuilder.Entity("AllReady.Models.CampaignImpact", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("CurrentImpactLevel"); b.Property<bool>("Display"); b.Property<int>("ImpactType"); b.Property<int>("NumericImpactGoal"); b.Property<string>("TextualImpactGoal"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.CampaignSponsors", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("CampaignId"); b.Property<int?>("OrganizationId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.ClosestLocation", b => { b.Property<string>("PostalCode"); b.Property<string>("City"); b.Property<double>("Distance"); b.Property<string>("State"); b.HasKey("PostalCode"); }); modelBuilder.Entity("AllReady.Models.Contact", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Email"); b.Property<string>("FirstName"); b.Property<string>("LastName"); b.Property<string>("PhoneNumber"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.Location", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Address1"); b.Property<string>("Address2"); b.Property<string>("City"); b.Property<string>("Country"); b.Property<string>("Name"); b.Property<string>("PhoneNumber"); b.Property<string>("PostalCodePostalCode"); b.Property<string>("State"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.Organization", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("LocationId"); b.Property<string>("LogoUrl"); b.Property<string>("Name") .IsRequired(); b.Property<string>("PrivacyPolicy"); b.Property<string>("WebUrl"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.OrganizationContact", b => { b.Property<int>("OrganizationId"); b.Property<int>("ContactId"); b.Property<int>("ContactType"); b.HasKey("OrganizationId", "ContactId", "ContactType"); }); modelBuilder.Entity("AllReady.Models.PostalCodeGeo", b => { b.Property<string>("PostalCode"); b.Property<string>("City"); b.Property<string>("State"); b.HasKey("PostalCode"); }); modelBuilder.Entity("AllReady.Models.PostalCodeGeoCoordinate", b => { b.Property<double>("Latitude"); b.Property<double>("Longitude"); b.HasKey("Latitude", "Longitude"); }); modelBuilder.Entity("AllReady.Models.Resource", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("CategoryTag"); b.Property<string>("Description"); b.Property<string>("MediaUrl"); b.Property<string>("Name"); b.Property<DateTime>("PublishDateBegin"); b.Property<DateTime>("PublishDateEnd"); b.Property<string>("ResourceUrl"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.Skill", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Description"); b.Property<string>("Name") .IsRequired(); b.Property<int?>("OwningOrganizationId"); b.Property<int?>("ParentSkillId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.TaskSignup", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("AdditionalInfo"); b.Property<string>("PreferredEmail"); b.Property<string>("PreferredPhoneNumber"); b.Property<string>("Status"); b.Property<DateTime>("StatusDateTimeUtc"); b.Property<string>("StatusDescription"); b.Property<int?>("TaskId"); b.Property<string>("UserId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.TaskSkill", b => { b.Property<int>("TaskId"); b.Property<int>("SkillId"); b.HasKey("TaskId", "SkillId"); }); modelBuilder.Entity("AllReady.Models.UserSkill", b => { b.Property<string>("UserId"); b.Property<int>("SkillId"); b.HasKey("UserId", "SkillId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedName") .HasAnnotation("Relational:Name", "RoleNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasAnnotation("Relational:TableName", "AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasAnnotation("Relational:TableName", "AspNetUserRoles"); }); modelBuilder.Entity("AllReady.Models.Activity", b => { b.HasOne("AllReady.Models.Campaign") .WithMany() .HasForeignKey("CampaignId"); b.HasOne("AllReady.Models.Location") .WithMany() .HasForeignKey("LocationId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("OrganizerId"); }); modelBuilder.Entity("AllReady.Models.ActivitySignup", b => { b.HasOne("AllReady.Models.Activity") .WithMany() .HasForeignKey("ActivityId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("AllReady.Models.ActivitySkill", b => { b.HasOne("AllReady.Models.Activity") .WithMany() .HasForeignKey("ActivityId"); b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("SkillId"); }); modelBuilder.Entity("AllReady.Models.AllReadyTask", b => { b.HasOne("AllReady.Models.Activity") .WithMany() .HasForeignKey("ActivityId"); b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("OrganizationId"); }); modelBuilder.Entity("AllReady.Models.ApplicationUser", b => { b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("OrganizationId"); }); modelBuilder.Entity("AllReady.Models.Campaign", b => { b.HasOne("AllReady.Models.CampaignImpact") .WithMany() .HasForeignKey("CampaignImpactId"); b.HasOne("AllReady.Models.Location") .WithMany() .HasForeignKey("LocationId"); b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("ManagingOrganizationId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("OrganizerId"); }); modelBuilder.Entity("AllReady.Models.CampaignContact", b => { b.HasOne("AllReady.Models.Campaign") .WithMany() .HasForeignKey("CampaignId"); b.HasOne("AllReady.Models.Contact") .WithMany() .HasForeignKey("ContactId"); }); modelBuilder.Entity("AllReady.Models.CampaignSponsors", b => { b.HasOne("AllReady.Models.Campaign") .WithMany() .HasForeignKey("CampaignId"); b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("OrganizationId"); }); modelBuilder.Entity("AllReady.Models.Location", b => { b.HasOne("AllReady.Models.PostalCodeGeo") .WithMany() .HasForeignKey("PostalCodePostalCode"); }); modelBuilder.Entity("AllReady.Models.Organization", b => { b.HasOne("AllReady.Models.Location") .WithMany() .HasForeignKey("LocationId"); }); modelBuilder.Entity("AllReady.Models.OrganizationContact", b => { b.HasOne("AllReady.Models.Contact") .WithMany() .HasForeignKey("ContactId"); b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("OrganizationId"); }); modelBuilder.Entity("AllReady.Models.Skill", b => { b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("OwningOrganizationId"); b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("ParentSkillId"); }); modelBuilder.Entity("AllReady.Models.TaskSignup", b => { b.HasOne("AllReady.Models.AllReadyTask") .WithMany() .HasForeignKey("TaskId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("AllReady.Models.TaskSkill", b => { b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("SkillId"); b.HasOne("AllReady.Models.AllReadyTask") .WithMany() .HasForeignKey("TaskId"); }); modelBuilder.Entity("AllReady.Models.UserSkill", b => { b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("SkillId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using OLEDB.Test.ModuleCore; namespace System.Xml.Tests { public partial class TCLinePos : TCXMLReaderBaseGeneral { // Type is System.Xml.Tests.TCLinePos // Test Case public override void AddChildren() { // for function TestLinePos1 { this.AddChild(new CVariation(TestLinePos1) { Attribute = new Variation("LineNumber/LinePos after Read and NodeType = Element") { Priority = 0 } }); } // for function TestLinePos2 { this.AddChild(new CVariation(TestLinePos2) { Attribute = new Variation("LineNumber/LinePos after Read and NodeType = CDATA") { Priority = 0 } }); } // for function TestLinePos4 { this.AddChild(new CVariation(TestLinePos4) { Attribute = new Variation("LineNumber/LinePos after Read and NodeType = Comment") { Priority = 0 } }); } // for function TestLinePos6 { this.AddChild(new CVariation(TestLinePos6) { Attribute = new Variation("LineNumber/LinePos after Read and NodeType = EndElement") { Priority = 0 } }); } // for function TestLinePos7 { this.AddChild(new CVariation(TestLinePos7) { Attribute = new Variation("LineNumber/LinePos after Read and NodeType = EntityReference, not expanded") { Priority = 0 } }); } // for function TestLinePos9 { this.AddChild(new CVariation(TestLinePos9) { Attribute = new Variation("LineNumber/LinePos after Read and NodeType = ProcessingInstruction") { Priority = 0 } }); } // for function TestLinePos10 { this.AddChild(new CVariation(TestLinePos10) { Attribute = new Variation("LineNumber/LinePos after Read and NodeType = SignificantWhitespace") { Priority = 0 } }); } // for function TestLinePos11 { this.AddChild(new CVariation(TestLinePos11) { Attribute = new Variation("LineNumber/LinePos after Read and NodeType = Text") { Priority = 0 } }); } // for function TestLinePos12 { this.AddChild(new CVariation(TestLinePos12) { Attribute = new Variation("LineNumber/LinePos after Read and NodeType = Whitespace") { Priority = 0 } }); } // for function TestLinePos13 { this.AddChild(new CVariation(TestLinePos13) { Attribute = new Variation("LineNumber/LinePos after Read and NodeType = XmlDeclaration") { Priority = 0 } }); } // for function TestLinePos14 { this.AddChild(new CVariation(TestLinePos14) { Attribute = new Variation("LineNumber/LinePos after MoveToElement") }); } // for function TestLinePos15 { this.AddChild(new CVariation(TestLinePos15) { Attribute = new Variation("LineNumber/LinePos after MoveToFirstAttribute/MoveToNextAttribute") }); } // for function TestLinePos16 { this.AddChild(new CVariation(TestLinePos16) { Attribute = new Variation("LineNumber/LinePos after MoveToAttribute") }); } // for function TestLinePos18 { this.AddChild(new CVariation(TestLinePos18) { Attribute = new Variation("LineNumber/LinePos after Skip") }); } // for function TestLinePos19 { this.AddChild(new CVariation(TestLinePos19) { Attribute = new Variation("LineNumber/LinePos after ReadInnerXml") }); } // for function TestLinePos20 { this.AddChild(new CVariation(TestLinePos20) { Attribute = new Variation("LineNumber/LinePos after MoveToContent") }); } // for function TestLinePos21 { this.AddChild(new CVariation(TestLinePos21) { Attribute = new Variation("LineNumber/LinePos after ReadBase64 succesive calls") }); } // for function TestLinePos22 { this.AddChild(new CVariation(TestLinePos22) { Attribute = new Variation("LineNumber/LinePos after ReadBinHex succesive calls") }); } // for function TestLinePos26 { this.AddChild(new CVariation(TestLinePos26) { Attribute = new Variation("LineNumber/LinePos after ReadEndElement") }); } // for function TestLinePos27 { this.AddChild(new CVariation(TestLinePos27) { Attribute = new Variation("LineNumber/LinePos after ReadString") }); } // for function TestLinePos39 { this.AddChild(new CVariation(TestLinePos39) { Attribute = new Variation("LineNumber/LinePos after element containing entities in attribute values") }); } // for function TestLinePos40 { this.AddChild(new CVariation(TestLinePos40) { Attribute = new Variation("LineNumber/LinePos when Read = false") }); } // for function TestLinePos41 { this.AddChild(new CVariation(TestLinePos41) { Attribute = new Variation("XmlTextReader:LineNumber and LinePos don't return the right position after ReadInnerXml is called") }); } // for function TestLinePos42 { this.AddChild(new CVariation(TestLinePos42) { Attribute = new Variation("XmlTextReader: LineNum and LinePosition incorrect for EndTag token and text element") }); } // for function TestLinePos43 { this.AddChild(new CVariation(TestLinePos43) { Attribute = new Variation("Bogus LineNumber value when reading attribute over XmlTextReader") }); } // for function TestLinePos44 { this.AddChild(new CVariation(TestLinePos44) { Attribute = new Variation("LineNumber and LinePosition on attribute with columns") }); } // for function TestLinePos45 { this.AddChild(new CVariation(TestLinePos45) { Attribute = new Variation("HasLineInfo") }); } // for function TestLinePos99 { this.AddChild(new CVariation(TestLinePos99) { Attribute = new Variation("XmlException LineNumber and LinePosition") }); } // for function ReadingNonWellFormedXmlThrows { this.AddChild(new CVariation(ReadingNonWellFormedXmlThrows) { Attribute = new Variation("Check error message on a non-wellformed XML") }); } // for function XmlExceptionAndXmlTextReaderLineNumberShouldBeSameAfterExceptionIsThrown { this.AddChild(new CVariation(XmlExceptionAndXmlTextReaderLineNumberShouldBeSameAfterExceptionIsThrown) { Attribute = new Variation("When an XmlException is thrown both XmlException.LineNumber and XmlTextReader.LineNumber should be same") }); } // for function XmlReaderShouldIncreaseLineNumberAfterNewLineInElementTag { this.AddChild(new CVariation(XmlReaderShouldIncreaseLineNumberAfterNewLineInElementTag) { Attribute = new Variation("Xml(Text)Reader does not increase line number for a new line in element end tag") }); } // for function LineNumberAndLinePositionAreCorrect { this.AddChild(new CVariation(LineNumberAndLinePositionAreCorrect) { Attribute = new Variation("LineNumber and LinePosition are not correct") }); } } } }
// // Copyright (C) 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 System; using System.Collections.Generic; using System.Linq; using Cassandra.Mapping; using Cassandra.Tasks; using Cassandra.Tests.Mapping.Pocos; using Cassandra.Tests.Mapping.TestData; using Moq; using NUnit.Framework; namespace Cassandra.Tests.Mapping { [TestFixture] public class UpdateTests : MappingTestBase { [Test] public void Update_With_Single_PartitionKey() { var song = new Song() { Id = Guid.NewGuid(), Artist = "Nirvana", ReleaseDate = DateTimeOffset.Now, Title = "Come As You Are" }; string query = null; object[] parameters = null; var sessionMock = new Mock<ISession>(MockBehavior.Strict); sessionMock.Setup(s => s.Keyspace).Returns<string>(null); sessionMock .Setup(s => s.ExecuteAsync(It.IsAny<BoundStatement>(), It.IsAny<string>())) .Callback<IStatement, string>((b, profile) => { query = ((BoundStatement)b).PreparedStatement.Cql; parameters = b.QueryValues; }) .Returns(TaskHelper.ToTask(new RowSet())) .Verifiable(); sessionMock .Setup(s => s.PrepareAsync(It.IsAny<string>())) .Returns<string>(cql => TestHelper.DelayedTask(GetPrepared(cql))) .Verifiable(); var mapper = GetMappingClient(sessionMock, new MappingConfiguration() .Define(new Map<Song>().PartitionKey(s => s.Id))); mapper.Update(song); TestHelper.VerifyUpdateCqlColumns("Song", query, new []{"Title", "Artist", "ReleaseDate"}, new [] {"Id"}, new object[] {song.Title, song.Artist, song.ReleaseDate, song.Id}, parameters); sessionMock.Verify(); } [Test] public void Update_With_Multiple_PartitionKeys() { var song = new Song() { Id = Guid.NewGuid(), Artist = "Nirvana", ReleaseDate = DateTimeOffset.Now, Title = "In Bloom" }; string query = null; object[] parameters = null; var sessionMock = new Mock<ISession>(MockBehavior.Strict); sessionMock.Setup(s => s.Keyspace).Returns<string>(null); sessionMock .Setup(s => s.ExecuteAsync(It.IsAny<BoundStatement>(), It.IsAny<string>())) .Callback<IStatement, string>((b, profile) => { query = ((BoundStatement)b).PreparedStatement.Cql; parameters = b.QueryValues; }) .Returns(TaskHelper.ToTask(new RowSet())) .Verifiable(); sessionMock .Setup(s => s.PrepareAsync(It.IsAny<string>())) .Returns<string>(cql => TestHelper.DelayedTask(GetPrepared(cql))) .Verifiable(); var mapper = GetMappingClient(sessionMock, new MappingConfiguration() .Define(new Map<Song>().PartitionKey(s => s.Title, s => s.Id))); mapper.Update(song); TestHelper.VerifyUpdateCqlColumns("Song", query, new []{"Artist", "ReleaseDate"}, new [] {"Title", "Id"}, new object[] {song.Artist, song.ReleaseDate, song.Title, song.Id}, parameters); //Different order in the partition key definitions mapper = GetMappingClient(sessionMock, new MappingConfiguration() .Define(new Map<Song>().PartitionKey(s => s.Id, s => s.Title))); mapper.Update(song); TestHelper.VerifyUpdateCqlColumns("Song", query, new []{"Artist", "ReleaseDate"}, new [] {"Id", "Title"}, new object[] {song.Artist, song.ReleaseDate, song.Id, song.Title}, parameters); sessionMock.Verify(); } [Test] public void Update_With_ClusteringKey() { var song = new Song() { Id = Guid.NewGuid(), Artist = "Dream Theater", ReleaseDate = DateTimeOffset.Now, Title = "A Change of Seasons" }; string query = null; object[] parameters = null; var sessionMock = new Mock<ISession>(MockBehavior.Strict); sessionMock.Setup(s => s.Keyspace).Returns<string>(null); sessionMock .Setup(s => s.ExecuteAsync(It.IsAny<BoundStatement>(), It.IsAny<string>())) .Callback<IStatement, string>((b, profile) => { query = ((BoundStatement)b).PreparedStatement.Cql; parameters = b.QueryValues; }) .Returns(TaskHelper.ToTask(new RowSet())) .Verifiable(); sessionMock .Setup(s => s.PrepareAsync(It.IsAny<string>())) .Returns<string>(cql => TestHelper.DelayedTask(GetPrepared(cql))) .Verifiable(); var mapper = GetMappingClient(sessionMock, new MappingConfiguration() .Define(new Map<Song>().PartitionKey(s => s.Id).ClusteringKey(s => s.ReleaseDate))); mapper.Update(song); TestHelper.VerifyUpdateCqlColumns("Song", query, new []{"Title", "Artist"}, new [] {"Id", "ReleaseDate"}, new object[] {song.Title, song.Artist, song.Id, song.ReleaseDate}, parameters); sessionMock.Verify(); } [Test] public void Update_Sets_Consistency() { var song = new Song() { Id = Guid.NewGuid(), Artist = "Dream Theater", ReleaseDate = DateTimeOffset.Now, Title = "Lines in the Sand" }; ConsistencyLevel? consistency = null; ConsistencyLevel? serialConsistency = null; var sessionMock = new Mock<ISession>(MockBehavior.Strict); sessionMock.Setup(s => s.Keyspace).Returns<string>(null); sessionMock .Setup(s => s.ExecuteAsync(It.IsAny<BoundStatement>(), It.IsAny<string>())) .Callback<IStatement, string>((b, profile) => { consistency = b.ConsistencyLevel; serialConsistency = b.SerialConsistencyLevel; }) .Returns(TestHelper.DelayedTask(new RowSet())) .Verifiable(); sessionMock .Setup(s => s.PrepareAsync(It.IsAny<string>())) .Returns<string>(cql => TestHelper.DelayedTask(GetPrepared(cql))) .Verifiable(); var mapper = GetMappingClient(sessionMock, new MappingConfiguration() .Define(new Map<Song>().PartitionKey(s => s.Title))); mapper.Update(song, new CqlQueryOptions().SetConsistencyLevel(ConsistencyLevel.LocalQuorum)); Assert.AreEqual(ConsistencyLevel.LocalQuorum, consistency); Assert.AreEqual(ConsistencyLevel.Any, serialConsistency); mapper.Update(song, new CqlQueryOptions().SetConsistencyLevel(ConsistencyLevel.Two).SetSerialConsistencyLevel(ConsistencyLevel.LocalSerial)); Assert.AreEqual(ConsistencyLevel.Two, consistency); Assert.AreEqual(ConsistencyLevel.LocalSerial, serialConsistency); sessionMock.Verify(); } [Test] public void Update_Cql_Prepends() { string query = null; object[] parameters = null; var session = GetSession((q, args) => { query = q; parameters = args; }, new RowSet()); var mapper = new Mapper(session, new MappingConfiguration()); mapper.Update<Song>(Cql.New("SET title = ? WHERE id = ?", "White Room")); Assert.AreEqual("UPDATE Song SET title = ? WHERE id = ?", query); } [Test] public void UpdateIf_AppliedInfo_True_Test() { string query = null; var sessionMock = new Mock<ISession>(MockBehavior.Strict); sessionMock.Setup(s => s.Keyspace).Returns<string>(null); object[] parameters = null; sessionMock .Setup(s => s.ExecuteAsync(It.IsAny<BoundStatement>())) .Returns(TestHelper.DelayedTask(TestDataHelper.CreateMultipleValuesRowSet(new[] { "[applied]" }, new [] { true }))) .Callback<BoundStatement>(b => { parameters = b.QueryValues; query = b.PreparedStatement.Cql; }) .Verifiable(); sessionMock .Setup(s => s.PrepareAsync(It.IsAny<string>())) .Returns<string>(cql => TestHelper.DelayedTask(GetPrepared(cql))) .Verifiable(); var mapper = GetMappingClient(sessionMock); const string partialQuery = "SET title = ?, releasedate = ? WHERE id = ? IF artist = ?"; var updateGuid = Guid.NewGuid(); var appliedInfo = mapper.UpdateIf<Song>(Cql.New(partialQuery, "Ramble On", new DateTime(1969, 1, 1), updateGuid, "Led Zeppelin")); sessionMock.Verify(); TestHelper.VerifyUpdateCqlColumns("Song", query, new []{"title", "releasedate"}, new [] {"id"}, new object[] {"Ramble On", new DateTime(1969, 1, 1), updateGuid, "Led Zeppelin"}, parameters, "IF artist = ?"); Assert.True(appliedInfo.Applied); Assert.Null(appliedInfo.Existing); } [Test] public void UpdateIf_AppliedInfo_False_Test() { var id = Guid.NewGuid(); string query = null; object[] parameters = null; var sessionMock = new Mock<ISession>(MockBehavior.Strict); sessionMock.Setup(s => s.Keyspace).Returns<string>(null); sessionMock .Setup(s => s.ExecuteAsync(It.IsAny<BoundStatement>())) .Returns(TestHelper.DelayedTask(TestDataHelper.CreateMultipleValuesRowSet(new [] { "[applied]", "id", "artist" }, new object[] { false, id, "Jimmy Page" }))) .Callback<BoundStatement>(b => { parameters = b.QueryValues; query = b.PreparedStatement.Cql; }) .Verifiable(); sessionMock .Setup(s => s.PrepareAsync(It.IsAny<string>())) .Returns<string>(cql => TestHelper.DelayedTask(GetPrepared(cql))) .Verifiable(); var mapper = GetMappingClient(sessionMock); const string partialQuery = "SET title = ?, releasedate = ? WHERE id = ? IF artist = ?"; var appliedInfo = mapper.UpdateIf<Song>(Cql.New(partialQuery, "Kashmir", new DateTime(1975, 1, 1), id, "Led Zeppelin")); sessionMock.Verify(); TestHelper.VerifyUpdateCqlColumns("Song", query, new []{"title", "releasedate"}, new [] {"id"}, new object[] {"Kashmir", new DateTime(1975, 1, 1), id, "Led Zeppelin"}, parameters, "IF artist = ?"); Assert.False(appliedInfo.Applied); Assert.NotNull(appliedInfo.Existing); Assert.AreEqual("Jimmy Page", appliedInfo.Existing.Artist); } [Test] public void Update_SetTimestamp_Test() { BoundStatement statement = null; var sessionMock = new Mock<ISession>(MockBehavior.Strict); sessionMock.Setup(s => s.Cluster).Returns((ICluster)null); sessionMock.Setup(s => s.Keyspace).Returns<string>(null); sessionMock .Setup(s => s.ExecuteAsync(It.IsAny<BoundStatement>(), It.IsAny<string>())) .Returns(() => TestHelper.DelayedTask(RowSet.Empty())) .Callback<BoundStatement, string>((stmt, profile) => statement = stmt) .Verifiable(); sessionMock .Setup(s => s.ExecuteAsync(It.IsAny<BoundStatement>())) .Returns(() => TestHelper.DelayedTask(RowSet.Empty())) .Callback<BoundStatement>(stmt => statement = stmt) .Verifiable(); sessionMock .Setup(s => s.PrepareAsync(It.IsAny<string>())) .Returns<string>((cql) => TestHelper.DelayedTask(GetPrepared(cql))) .Verifiable(); var mapper = GetMappingClient(sessionMock); var song = new Song { Id = Guid.NewGuid(), Title = "t2", ReleaseDate = DateTimeOffset.Now }; var timestamp = DateTimeOffset.Now.Subtract(TimeSpan.FromDays(1)); mapper.Update(song); Assert.Null(statement.Timestamp); mapper.Update(song, CqlQueryOptions.New().SetTimestamp(timestamp)); Assert.AreEqual(timestamp, statement.Timestamp); timestamp = DateTimeOffset.Now.Subtract(TimeSpan.FromHours(10)); mapper.UpdateIf<Song>(Cql.New("UPDATE tbl1 SET t1 = ? WHERE id = ?", new object[] {1, 2}, CqlQueryOptions.New().SetTimestamp(timestamp))); Assert.AreEqual(timestamp, statement.Timestamp); } [Test] public void Update_Poco_With_Enum_Collections() { object[] parameters = null; var config = new MappingConfiguration().Define(PocoWithEnumCollections.DefaultMapping); var mapper = GetMappingClient(() => TaskHelper.ToTask(RowSet.Empty()), (_, p) => { parameters = p; }, config); var collectionValues = new[]{ HairColor.Blonde, HairColor.Gray }; var expectedCollection = collectionValues.Select(x => (int) x).ToArray(); mapper.Update<PocoWithEnumCollections>("UPDATE tbl1 SET list1 = ? WHERE id = ?", mapper.ConvertCqlArgument<IEnumerable<HairColor>, IEnumerable<int>>(collectionValues), 3L); Assert.AreEqual(new object[]{ expectedCollection, 3L }, parameters); mapper.Update<PocoWithEnumCollections>("UPDATE tbl1 SET list1 = ? WHERE id = ?", mapper.ConvertCqlArgument<HairColor[], IEnumerable<int>>(collectionValues), 3L); Assert.AreEqual(new object[]{ expectedCollection, 3L }, 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.Collections.Generic; using System.Reflection; using Xunit; namespace System.Linq.Expressions.Tests { public static class CallTests { private struct Mutable { private int x; public int X { get { return x; } set { x = value; } } public int this[int i] { get { return x; } set { x = value; } } public int Foo() { return x++; } } private class Wrapper<T> { public const int Zero = 0; public T Field; #pragma warning disable 649 // For testing purposes public readonly T ReadOnlyField; #pragma warning restore public T Property { get { return Field; } set { Field = value; } } } private static class Methods { public static void ByRef(ref int x) { ++x; } } [Theory] [ClassData(typeof(CompilationTypes))] public static void UnboxReturnsReference(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(object)); UnaryExpression unbox = Expression.Unbox(p, typeof(Mutable)); MethodCallExpression call = Expression.Call(unbox, typeof(Mutable).GetMethod("Foo")); Func<object, int> lambda = Expression.Lambda<Func<object, int>>(call, p).Compile(useInterpreter); object boxed = new Mutable(); Assert.Equal(0, lambda(boxed)); Assert.Equal(1, lambda(boxed)); Assert.Equal(2, lambda(boxed)); Assert.Equal(3, lambda(boxed)); } [Theory] [ClassData(typeof(CompilationTypes))] public static void ArrayWriteBack(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(Mutable[])); BinaryExpression indexed = Expression.ArrayIndex(p, Expression.Constant(0)); MethodCallExpression call = Expression.Call(indexed, typeof(Mutable).GetMethod("Foo")); Func<Mutable[], int> lambda = Expression.Lambda<Func<Mutable[], int>>(call, p).Compile(useInterpreter); var array = new Mutable[1]; Assert.Equal(0, lambda(array)); Assert.Equal(1, lambda(array)); Assert.Equal(2, lambda(array)); } [Theory] [ClassData(typeof(CompilationTypes))] public static void MultiRankArrayWriteBack(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(Mutable[,])); MethodCallExpression indexed = Expression.ArrayIndex(p, Expression.Constant(0), Expression.Constant(0)); MethodCallExpression call = Expression.Call(indexed, typeof(Mutable).GetMethod("Foo")); Func<Mutable[,], int> lambda = Expression.Lambda<Func<Mutable[,], int>>(call, p).Compile(useInterpreter); var array = new Mutable[1, 1]; Assert.Equal(0, lambda(array)); Assert.Equal(1, lambda(array)); Assert.Equal(2, lambda(array)); } [Theory] [ClassData(typeof(CompilationTypes))] public static void ArrayAccessWriteBack(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(Mutable[])); IndexExpression indexed = Expression.ArrayAccess(p, Expression.Constant(0)); MethodCallExpression call = Expression.Call(indexed, typeof(Mutable).GetMethod("Foo")); Func<Mutable[], int> lambda = Expression.Lambda<Func<Mutable[], int>>(call, p).Compile(useInterpreter); var array = new Mutable[1]; Assert.Equal(0, lambda(array)); Assert.Equal(1, lambda(array)); Assert.Equal(2, lambda(array)); } [Theory] [ClassData(typeof(CompilationTypes))] public static void MultiRankArrayAccessWriteBack(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(Mutable[,])); IndexExpression indexed = Expression.ArrayAccess(p, Expression.Constant(0), Expression.Constant(0)); MethodCallExpression call = Expression.Call(indexed, typeof(Mutable).GetMethod("Foo")); Func<Mutable[,], int> lambda = Expression.Lambda<Func<Mutable[,], int>>(call, p).Compile(useInterpreter); var array = new Mutable[1, 1]; Assert.Equal(0, lambda(array)); Assert.Equal(1, lambda(array)); Assert.Equal(2, lambda(array)); } [Theory] [ClassData(typeof(CompilationTypes))] public static void IndexedPropertyAccessNoWriteBack(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(List<Mutable>)); IndexExpression indexed = Expression.Property(p, typeof(List<Mutable>).GetProperty("Item"), Expression.Constant(0)); MethodCallExpression call = Expression.Call(indexed, typeof(Mutable).GetMethod("Foo")); Func<List<Mutable>, int> lambda = Expression.Lambda<Func<List<Mutable>, int>>(call, p).Compile(useInterpreter); var list = new List<Mutable> { new Mutable() }; Assert.Equal(0, lambda(list)); Assert.Equal(0, lambda(list)); } [Theory] [ClassData(typeof(CompilationTypes))] public static void FieldAccessWriteBack(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(Wrapper<Mutable>)); MemberExpression member = Expression.Field(p, typeof(Wrapper<Mutable>).GetField("Field")); MethodCallExpression call = Expression.Call(member, typeof(Mutable).GetMethod("Foo")); Func<Wrapper<Mutable>, int> lambda = Expression.Lambda<Func<Wrapper<Mutable>, int>>(call, p).Compile(useInterpreter); var wrapper = new Wrapper<Mutable>(); Assert.Equal(0, lambda(wrapper)); Assert.Equal(1, lambda(wrapper)); Assert.Equal(2, lambda(wrapper)); } [Theory] [ClassData(typeof(CompilationTypes))] public static void PropertyAccessNoWriteBack(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(Wrapper<Mutable>)); MemberExpression member = Expression.Property(p, typeof(Wrapper<Mutable>).GetProperty("Property")); MethodCallExpression call = Expression.Call(member, typeof(Mutable).GetMethod("Foo")); Func<Wrapper<Mutable>, int> lambda = Expression.Lambda<Func<Wrapper<Mutable>, int>>(call, p).Compile(useInterpreter); var wrapper = new Wrapper<Mutable>(); Assert.Equal(0, lambda(wrapper)); Assert.Equal(0, lambda(wrapper)); } [Theory] [ClassData(typeof(CompilationTypes))] public static void ReadonlyFieldAccessWriteBack(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(Wrapper<Mutable>)); MemberExpression member = Expression.Field(p, typeof(Wrapper<Mutable>).GetField("ReadOnlyField")); MethodCallExpression call = Expression.Call(member, typeof(Mutable).GetMethod("Foo")); Func<Wrapper<Mutable>, int> lambda = Expression.Lambda<Func<Wrapper<Mutable>, int>>(call, p).Compile(useInterpreter); var wrapper = new Wrapper<Mutable>(); Assert.Equal(0, lambda(wrapper)); Assert.Equal(0, lambda(wrapper)); Assert.Equal(0, lambda(wrapper)); } [Theory] [ClassData(typeof(CompilationTypes))] public static void ConstFieldAccessWriteBack(bool useInterpreter) { MemberExpression member = Expression.Field(null, typeof(Wrapper<Mutable>).GetField("Zero")); MethodCallExpression call = Expression.Call(member, typeof(int).GetMethod("GetType")); Func<Type> lambda = Expression.Lambda<Func<Type>>(call).Compile(useInterpreter); var wrapper = new Wrapper<Mutable>(); Assert.Equal(typeof(int), lambda()); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CallByRefMutableStructPropertyWriteBack(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(Mutable)); MemberExpression x = Expression.Property(p, "X"); MethodCallExpression call = Expression.Call(typeof(Methods).GetMethod("ByRef"), x); BlockExpression body = Expression.Block(call, x); Func<Mutable, int> lambda = Expression.Lambda<Func<Mutable, int>>(body, p).Compile(useInterpreter); var m = new Mutable() { X = 41 }; Assert.Equal(42, lambda(m)); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CallByRefMutableStructIndexWriteBack(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(Mutable)); IndexExpression x = Expression.MakeIndex(p, typeof(Mutable).GetProperty("Item"), new[] { Expression.Constant(0) }); MethodCallExpression call = Expression.Call(typeof(Methods).GetMethod("ByRef"), x); BlockExpression body = Expression.Block(call, x); Func<Mutable, int> lambda = Expression.Lambda<Func<Mutable, int>>(body, p).Compile(useInterpreter); var m = new Mutable() { X = 41 }; Assert.Equal(42, lambda(m)); } [Theory] [ClassData(typeof(CompilationTypes))] public static void Call_InstanceNullInside_ThrowsNullReferenceExceptionOnInvocation(bool useInterpreter) { Expression call = Expression.Call(Expression.Constant(null, typeof(NonGenericClass)), typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.InstanceMethod))); Action compiledDelegate = Expression.Lambda<Action>(call).Compile(useInterpreter); TargetInvocationException exception = Assert.Throws<TargetInvocationException>(() => compiledDelegate.DynamicInvoke()); Assert.IsType<NullReferenceException>(exception.InnerException); } public static IEnumerable<object[]> Call_NoParameters_TestData() { // Basic yield return new object[] { Expression.Constant(new ClassWithInterface1()), typeof(ClassWithInterface1).GetMethod(nameof(ClassWithInterface1.Method)), 2 }; yield return new object[] { Expression.Constant(new StructWithInterface1()), typeof(StructWithInterface1).GetMethod(nameof(StructWithInterface1.Method)), 2 }; // Object method yield return new object[] { Expression.Constant(new ClassWithInterface1()), typeof(object).GetMethod(nameof(object.GetType)), typeof(ClassWithInterface1) }; yield return new object[] { Expression.Constant(new StructWithInterface1()), typeof(object).GetMethod(nameof(object.GetType)), typeof(StructWithInterface1) }; yield return new object[] { Expression.Constant(Int32Enum.A), typeof(object).GetMethod(nameof(object.GetType)), typeof(Int32Enum) }; // ValueType method from struct yield return new object[] { Expression.Constant(new StructWithInterface1()), typeof(ValueType).GetMethod(nameof(ValueType.ToString)), new StructWithInterface1().ToString() }; // Enum method from enum yield return new object[] { Expression.Constant(Int32Enum.A), typeof(Enum).GetMethod(nameof(Enum.ToString), new Type[0]), "A" }; // Interface method yield return new object[] { Expression.Constant(new ClassWithInterface1()), typeof(Interface1).GetMethod(nameof(Interface1.InterfaceMethod)), 1 }; yield return new object[] { Expression.Constant(new StructWithInterface1()), typeof(Interface1).GetMethod(nameof(Interface1.InterfaceMethod)), 1 }; yield return new object[] { Expression.Constant(new ClassWithCompoundInterface()), typeof(Interface1).GetMethod(nameof(Interface1.InterfaceMethod)), 1 }; yield return new object[] { Expression.Constant(new StructWithCompoundInterface()), typeof(Interface1).GetMethod(nameof(Interface1.InterfaceMethod)), 1 }; // Interface method, interface type yield return new object[] { Expression.Constant(new ClassWithInterface1(), typeof(Interface1)), typeof(Interface1).GetMethod(nameof(Interface1.InterfaceMethod)), 1 }; yield return new object[] { Expression.Constant(new StructWithInterface1(), typeof(Interface1)), typeof(Interface1).GetMethod(nameof(Interface1.InterfaceMethod)), 1 }; } [Theory] [PerCompilationType(nameof(Call_NoParameters_TestData))] public static void Call_NoParameters(Expression instance, MethodInfo method, object expected, bool useInterpreter) { Expression call = Expression.Call(instance, method); Delegate compiledDelegate = Expression.Lambda(call).Compile(useInterpreter); Assert.Equal(expected, compiledDelegate.DynamicInvoke()); } private static Expression s_valid => Expression.Constant(5); private static MethodInfo s_method0 = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.Method0)); private static MethodInfo s_method1 = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.Method1)); private static MethodInfo s_method2 = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.Method2)); private static MethodInfo s_method3 = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.Method3)); private static MethodInfo s_method4 = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.Method4)); private static MethodInfo s_method5 = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.Method5)); private static MethodInfo s_method6 = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.Method6)); private static MethodInfo s_method7 = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.Method7)); public static IEnumerable<object[]> Method_Invalid_TestData() { yield return new object[] { null, typeof(ArgumentNullException) }; yield return new object[] { typeof(GenericClass<>).GetMethod(nameof(GenericClass<string>.NonGenericMethod)), typeof(ArgumentException) }; yield return new object[] { typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.GenericMethod)), typeof(ArgumentException) }; } [Theory] [MemberData(nameof(Method_Invalid_TestData))] public static void Method_Invalid_ThrowsArgumentException(MethodInfo method, Type exceptionType) { AssertArgumentException(() => Expression.Call(null, method), exceptionType, "method"); AssertArgumentException(() => Expression.Call(null, method, s_valid, s_valid), exceptionType, "method"); AssertArgumentException(() => Expression.Call(null, method, s_valid, s_valid, s_valid), exceptionType, "method"); AssertArgumentException(() => Expression.Call(null, method, new Expression[0]), exceptionType, "method"); AssertArgumentException(() => Expression.Call(null, method, (IEnumerable<Expression>)new Expression[0]), exceptionType, "method"); AssertArgumentException(() => Expression.Call(method, s_valid), exceptionType, "method"); AssertArgumentException(() => Expression.Call(method, s_valid, s_valid), exceptionType, "method"); AssertArgumentException(() => Expression.Call(method, s_valid, s_valid, s_valid), exceptionType, "method"); AssertArgumentException(() => Expression.Call(method, s_valid, s_valid, s_valid, s_valid), exceptionType, "method"); AssertArgumentException(() => Expression.Call(method, s_valid, s_valid, s_valid, s_valid, s_valid), exceptionType, "method"); AssertArgumentException(() => Expression.Call(method, new Expression[0]), exceptionType, "method"); AssertArgumentException(() => Expression.Call(method, (IEnumerable<Expression>)new Expression[0]), exceptionType, "method"); } public static IEnumerable<object[]> Method_DoesntBelongToInstance_TestData() { // Different declaring type yield return new object[] { Expression.Constant(new ClassWithInterface1()), typeof(OtherClassWithInterface1).GetMethod(nameof(Interface1.InterfaceMethod)) }; yield return new object[] { Expression.Constant(new StructWithInterface1()), typeof(OtherStructWithInterface1).GetMethod(nameof(Interface1.InterfaceMethod)) }; // Different interface yield return new object[] { Expression.Constant(new ClassWithInterface1()), typeof(Interface2).GetMethod(nameof(Interface2.InterfaceMethod)) }; yield return new object[] { Expression.Constant(new StructWithInterface1()), typeof(Interface2).GetMethod(nameof(Interface2.InterfaceMethod)) }; // Custom type yield return new object[] { Expression.Constant(new ClassWithInterface1(), typeof(object)), typeof(ClassWithInterface1).GetMethod(nameof(ClassWithInterface1.Method)) }; yield return new object[] { Expression.Constant(new StructWithInterface1(), typeof(object)), typeof(ClassWithInterface1).GetMethod(nameof(ClassWithInterface1.Method)) }; } [Theory] [MemberData(nameof(Method_DoesntBelongToInstance_TestData))] public static void Method_DoesntBelongToInstance_ThrowsArgumentException(Expression instance, MethodInfo method) { Assert.Throws<ArgumentException>(null, () => Expression.Call(instance, method)); } [Fact] public static void InstanceMethod_NullInstance_ThrowsArgumentException() { MethodInfo method = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.InstanceMethod)); Assert.Throws<ArgumentException>("method", () => Expression.Call(method, s_valid)); Assert.Throws<ArgumentException>("method", () => Expression.Call(method, s_valid, s_valid)); Assert.Throws<ArgumentException>("method", () => Expression.Call(method, s_valid, s_valid, s_valid)); Assert.Throws<ArgumentException>("method", () => Expression.Call(method, s_valid, s_valid, s_valid, s_valid)); Assert.Throws<ArgumentException>("method", () => Expression.Call(method, s_valid, s_valid, s_valid, s_valid, s_valid)); Assert.Throws<ArgumentException>("method", () => Expression.Call(method, new Expression[0])); Assert.Throws<ArgumentException>("method", () => Expression.Call(method, (IEnumerable<Expression>)new Expression[0])); Assert.Throws<ArgumentException>("method", () => Expression.Call(null, method, s_valid)); Assert.Throws<ArgumentException>("method", () => Expression.Call(null, method, s_valid, s_valid)); Assert.Throws<ArgumentException>("method", () => Expression.Call(null, method, s_valid, s_valid, s_valid)); Assert.Throws<ArgumentException>("method", () => Expression.Call(null, method, new Expression[0])); Assert.Throws<ArgumentException>("method", () => Expression.Call(null, method, (IEnumerable<Expression>)new Expression[0])); } [Fact] public static void StaticMethod_NonNullInstance_ThrowsArgumentException() { Expression instance = Expression.Constant(new NonGenericClass()); MethodInfo method = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.StaticMethod)); Assert.Throws<ArgumentException>("instance", () => Expression.Call(instance, method, s_valid)); Assert.Throws<ArgumentException>("instance", () => Expression.Call(instance, method, s_valid, s_valid)); Assert.Throws<ArgumentException>("instance", () => Expression.Call(instance, method, s_valid, s_valid, s_valid)); Assert.Throws<ArgumentException>("instance", () => Expression.Call(instance, method, new Expression[0])); Assert.Throws<ArgumentException>("instance", () => Expression.Call(instance, method, (IEnumerable<Expression>)new Expression[0])); } public static IEnumerable<object[]> InvalidArg_TestData() { yield return new object[] { null, typeof(ArgumentNullException) }; yield return new object[] { Expression.Property(null, typeof(Unreadable<string>), nameof(Unreadable<string>.WriteOnly)), typeof(ArgumentException) }; yield return new object[] { Expression.Constant("abc"), typeof(ArgumentException) }; } [Theory] [MemberData(nameof(InvalidArg_TestData))] public static void Arg0_Invalid(Expression arg, Type exceptionType) { AssertArgumentException(() => Expression.Call(s_method1, arg), exceptionType, "arg0"); AssertArgumentException(() => Expression.Call(s_method2, arg, s_valid), exceptionType, "arg0"); AssertArgumentException(() => Expression.Call(s_method3, arg, s_valid, s_valid), exceptionType, "arg0"); AssertArgumentException(() => Expression.Call(s_method4, arg, s_valid, s_valid, s_valid), exceptionType, "arg0"); AssertArgumentException(() => Expression.Call(s_method5, arg, s_valid, s_valid, s_valid, s_valid), exceptionType, "arg0"); AssertArgumentException(() => Expression.Call(null, s_method1, arg), exceptionType, "arg0"); AssertArgumentException(() => Expression.Call(null, s_method2, arg, s_valid), exceptionType, "arg0"); AssertArgumentException(() => Expression.Call(null, s_method3, arg, s_valid, s_valid), exceptionType, "arg0"); } [Theory] [MemberData(nameof(InvalidArg_TestData))] public static void Arg1_Invalid(Expression arg, Type exceptionType) { AssertArgumentException(() => Expression.Call(s_method2, s_valid, arg), exceptionType, "arg1"); AssertArgumentException(() => Expression.Call(s_method3, s_valid, arg, s_valid), exceptionType, "arg1"); AssertArgumentException(() => Expression.Call(s_method4, s_valid, arg, s_valid, s_valid), exceptionType, "arg1"); AssertArgumentException(() => Expression.Call(s_method5, s_valid, arg, s_valid, s_valid, s_valid), exceptionType, "arg1"); AssertArgumentException(() => Expression.Call(null, s_method2, s_valid, arg), exceptionType, "arg1"); AssertArgumentException(() => Expression.Call(null, s_method3, s_valid, arg, s_valid), exceptionType, "arg1"); } [Theory] [MemberData(nameof(InvalidArg_TestData))] public static void Arg2_Invalid(Expression arg, Type exceptionType) { AssertArgumentException(() => Expression.Call(s_method3, s_valid, s_valid, arg), exceptionType, "arg2"); AssertArgumentException(() => Expression.Call(s_method4, s_valid, s_valid, arg, s_valid), exceptionType, "arg2"); AssertArgumentException(() => Expression.Call(s_method5, s_valid, s_valid, arg, s_valid, s_valid), exceptionType, "arg2"); AssertArgumentException(() => Expression.Call(null, s_method3, s_valid, s_valid, arg), exceptionType, "arg2"); } [Theory] [MemberData(nameof(InvalidArg_TestData))] public static void Arg3_Invalid(Expression arg, Type exceptionType) { AssertArgumentException(() => Expression.Call(s_method4, s_valid, s_valid, s_valid, arg), exceptionType, "arg3"); AssertArgumentException(() => Expression.Call(s_method5, s_valid, s_valid, s_valid, arg, s_valid), exceptionType, "arg3"); } [Theory] [MemberData(nameof(InvalidArg_TestData))] public static void Arg4_Invalid(Expression arg, Type exceptionType) { AssertArgumentException(() => Expression.Call(s_method5, s_valid, s_valid, s_valid, s_valid, arg), exceptionType, "arg4"); } private static void AssertArgumentException(Action action, Type exceptionType, string paramName) { ArgumentException ex = (ArgumentException)Assert.Throws(exceptionType, action); Assert.Equal(paramName, ex.ParamName); } [Theory] [InlineData(typeof(NonGenericClass), nameof(NonGenericClass.Method0), 0)] [InlineData(typeof(NonGenericClass), nameof(NonGenericClass.Method1), 1)] [InlineData(typeof(NonGenericClass), nameof(NonGenericClass.Method2), 2)] [InlineData(typeof(NonGenericClass), nameof(NonGenericClass.Method3), 3)] [InlineData(typeof(NonGenericClass), nameof(NonGenericClass.Method4), 4)] [InlineData(typeof(NonGenericClass), nameof(NonGenericClass.Method5), 5)] public static void InvalidArgumentCount_ThrowsArgumentException(Type type, string name, int count) { MethodInfo method = type.GetMethod(name); Expression arg = Expression.Constant("abc"); if (count != 0) { Assert.Throws<ArgumentException>("method", () => Expression.Call(method)); Assert.Throws<ArgumentException>("method", () => Expression.Call(null, method)); } if (count != 1) { Assert.Throws<ArgumentException>("method", () => Expression.Call(method, arg)); Assert.Throws<ArgumentException>("method", () => Expression.Call(null, method, arg)); } if (count != 2) { Assert.Throws<ArgumentException>("method", () => Expression.Call(method, arg, arg)); Assert.Throws<ArgumentException>("method", () => Expression.Call(null, method, arg, arg)); } if (count != 3) { Assert.Throws<ArgumentException>("method", () => Expression.Call(method, arg, arg, arg)); Assert.Throws<ArgumentException>("method", () => Expression.Call(null, method, arg, arg, arg)); } if (count != 4) { Assert.Throws<ArgumentException>("method", () => Expression.Call(method, arg, arg, arg, arg)); } if (count != 5) { Assert.Throws<ArgumentException>("method", () => Expression.Call(method, arg, arg, arg, arg, arg)); } Assert.Throws<ArgumentException>("method", () => Expression.Call(method, Enumerable.Repeat(arg, count + 1).ToArray())); Assert.Throws<ArgumentException>("method", () => Expression.Call(method, Enumerable.Repeat(arg, count + 1))); Assert.Throws<ArgumentException>("method", () => Expression.Call(null, method, Enumerable.Repeat(arg, count + 1).ToArray())); Assert.Throws<ArgumentException>("method", () => Expression.Call(null, method, Enumerable.Repeat(arg, count + 1))); } [Fact] public static void MethodName_NullInstance_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("instance", () => Expression.Call((Expression)null, "methodName", new Type[0], new Expression[0])); } [Fact] public static void MethodName_NullType_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("type", () => Expression.Call((Type)null, "methodName", new Type[0], new Expression[0])); } [Fact] public static void NullMethodName_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("methodName", () => Expression.Call(Expression.Constant(new NonGenericClass()), null, new Type[0], new Expression[0])); Assert.Throws<ArgumentNullException>("methodName", () => Expression.Call(typeof(NonGenericClass), null, new Type[0], new Expression[0])); } [Fact] public static void MethodName_DoesNotExist_ThrowsInvalidOperationException() { Assert.Throws<InvalidOperationException>(() => Expression.Call(Expression.Constant(new NonGenericClass()), "NoSuchMethod", null)); Assert.Throws<InvalidOperationException>(() => Expression.Call(typeof(NonGenericClass), "NoSuchMethod", null)); } public static IEnumerable<object[]> InvalidTypeArgs_TestData() { yield return new object[] { null }; yield return new object[] { new Type[0] }; yield return new object[] { new Type[2] }; } [Theory] [MemberData(nameof(InvalidTypeArgs_TestData))] public static void MethodName_NoSuchGenericMethodWithTypeArgs_ThrowsInvalidOperationException(Type[] typeArgs) { Assert.Throws<InvalidOperationException>(() => Expression.Call(Expression.Constant(new NonGenericClass()), nameof(NonGenericClass.GenericInstanceMethod), typeArgs)); Assert.Throws<InvalidOperationException>(() => Expression.Call(typeof(NonGenericClass), nameof(NonGenericClass.GenericStaticMethod), typeArgs)); } [Fact] public static void MethodName_TypeArgsDontMatchConstraints_ThrowsArgumentException() { Assert.Throws<ArgumentException>(null, () => Expression.Call(Expression.Constant(new NonGenericClass()), nameof(NonGenericClass.ConstrainedInstanceMethod), new Type[] { typeof(object) })); Assert.Throws<ArgumentException>(null, () => Expression.Call(typeof(NonGenericClass), nameof(NonGenericClass.ConstrainedStaticMethod), new Type[] { typeof(object) })); } [Fact] public static void MethodName_NonGenericMethodHasTypeArgs_ThrowsInvalidOperationException() { Assert.Throws<InvalidOperationException>(() => Expression.Call(Expression.Constant(new NonGenericClass()), nameof(NonGenericClass.InstanceMethod), new Type[1])); Assert.Throws<InvalidOperationException>(() => Expression.Call(typeof(NonGenericClass), nameof(NonGenericClass.StaticMethod), new Type[1])); } [Fact] public static void MethodName_TypeArgsHasNullValue_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>(null, () => Expression.Call(Expression.Constant(new NonGenericClass()), nameof(NonGenericClass.GenericInstanceMethod), new Type[] { null })); Assert.Throws<ArgumentNullException>(null, () => Expression.Call(typeof(NonGenericClass), nameof(NonGenericClass.GenericStaticMethod), new Type[] { null })); } [Fact] public static void MethodName_ArgumentsHasNullValue_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("arguments", () => Expression.Call(Expression.Constant(new NonGenericClass()), nameof(NonGenericClass.InstanceMethod1), new Type[0], new Expression[] { null })); Assert.Throws<ArgumentNullException>("arguments", () => Expression.Call(typeof(NonGenericClass), nameof(NonGenericClass.StaticMethod1), new Type[0], new Expression[] { null })); } [Fact] public static void MethodName_ArgumentsHasNullValueButDifferentCount_ThrowsInvalidOperationException() { Assert.Throws<InvalidOperationException>(() => Expression.Call(Expression.Constant(new NonGenericClass()), nameof(NonGenericClass.InstanceMethod1), new Type[0], new Expression[] { null, Expression.Constant("") })); Assert.Throws<InvalidOperationException>(() => Expression.Call(typeof(NonGenericClass), nameof(NonGenericClass.StaticMethod1), new Type[0], new Expression[] { null, Expression.Constant("") })); } [Fact] public static void ToStringTest() { // NB: Static methods are inconsistent compared to static members; the declaring type is not included MethodCallExpression e1 = Expression.Call(null, typeof(SomeMethods).GetMethod(nameof(SomeMethods.S0), BindingFlags.Static | BindingFlags.Public)); Assert.Equal("S0()", e1.ToString()); MethodCallExpression e2 = Expression.Call(null, typeof(SomeMethods).GetMethod(nameof(SomeMethods.S1), BindingFlags.Static | BindingFlags.Public), Expression.Parameter(typeof(int), "x")); Assert.Equal("S1(x)", e2.ToString()); MethodCallExpression e3 = Expression.Call(null, typeof(SomeMethods).GetMethod(nameof(SomeMethods.S2), BindingFlags.Static | BindingFlags.Public), Expression.Parameter(typeof(int), "x"), Expression.Parameter(typeof(int), "y")); Assert.Equal("S2(x, y)", e3.ToString()); MethodCallExpression e4 = Expression.Call(Expression.Parameter(typeof(SomeMethods), "o"), typeof(SomeMethods).GetMethod(nameof(SomeMethods.I0), BindingFlags.Instance | BindingFlags.Public)); Assert.Equal("o.I0()", e4.ToString()); MethodCallExpression e5 = Expression.Call(Expression.Parameter(typeof(SomeMethods), "o"), typeof(SomeMethods).GetMethod(nameof(SomeMethods.I1), BindingFlags.Instance | BindingFlags.Public), Expression.Parameter(typeof(int), "x")); Assert.Equal("o.I1(x)", e5.ToString()); MethodCallExpression e6 = Expression.Call(Expression.Parameter(typeof(SomeMethods), "o"), typeof(SomeMethods).GetMethod(nameof(SomeMethods.I2), BindingFlags.Instance | BindingFlags.Public), Expression.Parameter(typeof(int), "x"), Expression.Parameter(typeof(int), "y")); Assert.Equal("o.I2(x, y)", e6.ToString()); MethodCallExpression e7 = Expression.Call(null, typeof(ExtensionMethods).GetMethod(nameof(ExtensionMethods.E0), BindingFlags.Static | BindingFlags.Public), Expression.Parameter(typeof(int), "x")); Assert.Equal("x.E0()", e7.ToString()); MethodCallExpression e8 = Expression.Call(null, typeof(ExtensionMethods).GetMethod(nameof(ExtensionMethods.E1), BindingFlags.Static | BindingFlags.Public), Expression.Parameter(typeof(int), "x"), Expression.Parameter(typeof(int), "y")); Assert.Equal("x.E1(y)", e8.ToString()); MethodCallExpression e9 = Expression.Call(null, typeof(ExtensionMethods).GetMethod(nameof(ExtensionMethods.E2), BindingFlags.Static | BindingFlags.Public), Expression.Parameter(typeof(int), "x"), Expression.Parameter(typeof(int), "y"), Expression.Parameter(typeof(int), "z")); Assert.Equal("x.E2(y, z)", e9.ToString()); } [Fact] public static void GetArguments() { VerifyGetArguments(Expression.Call(null, s_method0)); VerifyGetArguments(Expression.Call(null, s_method1, Expression.Constant(0))); VerifyGetArguments( Expression.Call(null, s_method2, Enumerable.Range(0, 2).Select(i => Expression.Constant(i)))); VerifyGetArguments( Expression.Call(null, s_method3, Enumerable.Range(0, 3).Select(i => Expression.Constant(i)))); VerifyGetArguments( Expression.Call(null, s_method4, Enumerable.Range(0, 4).Select(i => Expression.Constant(i)))); VerifyGetArguments( Expression.Call(null, s_method5, Enumerable.Range(0, 5).Select(i => Expression.Constant(i)))); VerifyGetArguments( Expression.Call(null, s_method6, Enumerable.Range(0, 6).Select(i => Expression.Constant(i)))); VerifyGetArguments( Expression.Call(null, s_method7, Enumerable.Range(0, 7).Select(i => Expression.Constant(i)))); var site = Expression.Default(typeof(NonGenericClass)); VerifyGetArguments(Expression.Call(site, nameof(NonGenericClass.InstanceMethod0), null)); VerifyGetArguments( Expression.Call(site, nameof(NonGenericClass.InstanceMethod1), null, Expression.Constant(0))); VerifyGetArguments( Expression.Call( site, nameof(NonGenericClass.InstanceMethod2), null, Enumerable.Range(0, 2).Select(i => Expression.Constant(i)).ToArray())); VerifyGetArguments( Expression.Call( site, nameof(NonGenericClass.InstanceMethod3), null, Enumerable.Range(0, 3).Select(i => Expression.Constant(i)).ToArray())); VerifyGetArguments( Expression.Call( site, nameof(NonGenericClass.InstanceMethod4), null, Enumerable.Range(0, 4).Select(i => Expression.Constant(i)).ToArray())); } private static void VerifyGetArguments(MethodCallExpression call) { var args = call.Arguments; Assert.Equal(args.Count, call.ArgumentCount); Assert.Throws<ArgumentOutOfRangeException>("index", () => call.GetArgument(-1)); Assert.Throws<ArgumentOutOfRangeException>("index", () => call.GetArgument(args.Count)); for (int i = 0; i != args.Count; ++i) { Assert.Same(args[i], call.GetArgument(i)); Assert.Equal(i, ((ConstantExpression)call.GetArgument(i)).Value); } } public class GenericClass<T> { public static void NonGenericMethod() { } } public static class Unreadable<T> { public static T WriteOnly { set { } } } public class NonGenericClass { public static void GenericMethod<T>() { } public void InstanceMethod() { } public static void StaticMethod() { } public static void Method0() { } public static void Method1(int i1) { } public static void Method2(int i1, int i2) { } public static void Method3(int i1, int i2, int i3) { } public static void Method4(int i1, int i2, int i3, int i4) { } public static void Method5(int i1, int i2, int i3, int i4, int i5) { } public static void Method6(int i1, int i2, int i3, int i4, int i5, int i6) { } public static void Method7(int i1, int i2, int i3, int i4, int i5, int i6, int i7) { } public void staticSameName(uint i1) { } public void instanceSameName(int i1) { } public static void StaticSameName(uint i1) { } public static void staticSameName(int i1) { } public void GenericInstanceMethod<T>(T t1) { } public static void GenericStaticMethod<T>(T t1) { } public void ConstrainedInstanceMethod<T>(T t1) where T : struct { } public static void ConstrainedStaticMethod<T>(T t1) where T : struct { } public void InstanceMethod0() { } public void InstanceMethod1(int i1) { } public void InstanceMethod2(int i1, int i2) { } public void InstanceMethod3(int i1, int i2, int i3) { } public void InstanceMethod4(int i1, int i2, int i3, int i4) { } public static void StaticMethod1(int i1) { } } public interface Interface1 { int InterfaceMethod(); } public interface Interface2 { int InterfaceMethod(); } public interface CompoundInterface : Interface1 { } public class ClassWithInterface1 : Interface1 { public int InterfaceMethod() => 1; public int Method() => 2; } public class OtherClassWithInterface1 : Interface1 { public int InterfaceMethod() => 1; } public struct StructWithInterface1 : Interface1 { public int InterfaceMethod() => 1; public int Method() => 2; } public struct OtherStructWithInterface1 : Interface1 { public int InterfaceMethod() => 1; } public class ClassWithCompoundInterface : CompoundInterface { public int InterfaceMethod() => 1; } public struct StructWithCompoundInterface : CompoundInterface { public int InterfaceMethod() => 1; } } class SomeMethods { public static void S0() { } public static void S1(int x) { } public static void S2(int x, int y) { } public void I0() { } public void I1(int x) { } public void I2(int x, int y) { } } static class ExtensionMethods { public static void E0(this int x) { } public static void E1(this int x, int y) { } public static void E2(this int x, int y, int z) { } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Build.Engine { using System; using System.Collections.Specialized; using System.Linq; using System.Text.RegularExpressions; using System.Web; using Microsoft.DocAsCode.MarkdownLite; using Microsoft.DocAsCode.Plugins; using Microsoft.DocAsCode.Common; internal sealed class XRefDetails { /// <summary> /// TODO: completely move into template /// Must be consistent with template input.replace(/\W/g, '_'); /// </summary> /// <param name="id"></param> /// <returns></returns> private static Regex HtmlEncodeRegex = new Regex(@"\W", RegexOptions.Compiled); public string Uid { get; private set; } public string Anchor { get; private set; } public string Title { get; private set; } public string Href { get; private set; } public string Raw { get; private set; } public string RawSource { get; private set; } public string DisplayProperty { get; private set; } public string AltProperty { get; private set; } public string InnerHtml { get; private set; } public string Text { get; private set; } public string Alt { get; private set; } public XRefSpec Spec { get; private set; } public bool ThrowIfNotResolved { get; private set; } public string SourceFile { get; private set; } public int SourceStartLineNumber { get; private set; } public int SourceEndLineNumber { get; private set; } private XRefDetails() { } public static XRefDetails From(HtmlAgilityPack.HtmlNode node) { if (node.Name != "xref") throw new NotSupportedException("Only xref node is supported!"); var xref = new XRefDetails(); var uid = node.GetAttributeValue("uid", null); var rawHref = node.GetAttributeValue("href", null); NameValueCollection queryString = null; if (!string.IsNullOrEmpty(rawHref)) { if (!string.IsNullOrEmpty(uid)) { Logger.LogWarning($"Both href and uid attribute are defined for {node.OuterHtml}, use href instead of uid."); } string others; var anchorIndex = rawHref.IndexOf("#"); if (anchorIndex == -1) { xref.Anchor = string.Empty; others = rawHref; } else { xref.Anchor = rawHref.Substring(anchorIndex); others = rawHref.Remove(anchorIndex); } var queryIndex = others.IndexOf("?"); if (queryIndex == -1) { xref.Uid = HttpUtility.UrlDecode(others); } else { xref.Uid = HttpUtility.UrlDecode(others.Remove(queryIndex)); queryString = HttpUtility.ParseQueryString(others.Substring(queryIndex)); } } else { xref.Uid = uid; } xref.InnerHtml = node.InnerHtml; xref.DisplayProperty = node.GetAttributeValue("displayProperty", queryString?.Get("displayProperty") ?? XRefSpec.NameKey); xref.AltProperty = node.GetAttributeValue("altProperty", queryString?.Get("altProperty") ?? "fullName"); xref.Text = node.GetAttributeValue("text", node.GetAttributeValue("name", StringHelper.HtmlEncode(queryString?.Get("text")))); xref.Alt = node.GetAttributeValue("alt", node.GetAttributeValue("fullname", StringHelper.HtmlEncode(queryString?.Get("alt")))); xref.Title = node.GetAttributeValue("title", queryString?.Get("title")); xref.SourceFile = node.GetAttributeValue("sourceFile", null); xref.SourceStartLineNumber = node.GetAttributeValue("sourceStartLineNumber", 0); xref.SourceEndLineNumber = node.GetAttributeValue("sourceEndLineNumber", 0); // Both `data-raw-html` and `data-raw-source` are html encoded. Use `data-raw-html` with higher priority. // `data-raw-html` will be decoded then displayed, while `data-raw-source` will be displayed directly. xref.RawSource = node.GetAttributeValue("data-raw-source", null); var raw = node.GetAttributeValue("data-raw-html", null); if (!string.IsNullOrEmpty(raw)) { xref.Raw = StringHelper.HtmlDecode(raw); } else { xref.Raw = xref.RawSource; } xref.ThrowIfNotResolved = node.GetAttributeValue("data-throw-if-not-resolved", false); return xref; } public void ApplyXrefSpec(XRefSpec spec) { if (spec == null) { return; } // TODO: What if href is not html? if (!string.IsNullOrEmpty(spec.Href)) { Href = UriUtility.GetNonFragment(spec.Href); if (string.IsNullOrEmpty(Anchor)) { Anchor = UriUtility.GetFragment(spec.Href); } } Spec = spec; } /// <summary> /// TODO: multi-lang support /// </summary> /// <returns></returns> public HtmlAgilityPack.HtmlNode ConvertToHtmlNode(string language) { // If href exists, return anchor else return text if (!string.IsNullOrEmpty(Href)) { if (!string.IsNullOrEmpty(InnerHtml)) { return GetAnchorNode(Href, Anchor, Title, InnerHtml, RawSource, SourceFile, SourceStartLineNumber, SourceEndLineNumber); } if (!string.IsNullOrEmpty(Text)) { return GetAnchorNode(Href, Anchor, Title, Text, RawSource, SourceFile, SourceStartLineNumber, SourceEndLineNumber); } if (Spec != null) { var value = StringHelper.HtmlEncode(GetLanguageSpecificAttribute(Spec, language, DisplayProperty, "name")); if (!string.IsNullOrEmpty(value)) { return GetAnchorNode(Href, Anchor, Title, value, RawSource, SourceFile, SourceStartLineNumber, SourceEndLineNumber); } } return GetAnchorNode(Href, Anchor, Title, Uid, RawSource, SourceFile, SourceStartLineNumber, SourceEndLineNumber); } else { if (!string.IsNullOrEmpty(Raw)) { return HtmlAgilityPack.HtmlNode.CreateNode(Raw); } if (!string.IsNullOrEmpty(InnerHtml)) { return GetDefaultPlainTextNode(InnerHtml); } if (!string.IsNullOrEmpty(Alt)) { return GetDefaultPlainTextNode(Alt); } if (Spec != null) { var value = StringHelper.HtmlEncode(GetLanguageSpecificAttribute(Spec, language, AltProperty, "name")); if (!string.IsNullOrEmpty(value)) { return GetDefaultPlainTextNode(value); } } return GetDefaultPlainTextNode(Uid); } } private static HtmlAgilityPack.HtmlNode GetAnchorNode(string href, string anchor, string title, string value, string rawSource, string sourceFile, int sourceStartLineNumber, int sourceEndLineNumber) { var anchorNode = $"<a class=\"xref\" href=\"{href}\""; if (!string.IsNullOrEmpty(anchor)) { anchorNode += $" anchor=\"{anchor}\""; } if (!string.IsNullOrEmpty(title)) { anchorNode += $" title=\"{title}\""; } if (!string.IsNullOrEmpty(rawSource)) { anchorNode += $" data-raw-source=\"{rawSource}\""; } if (!string.IsNullOrEmpty(sourceFile)) { anchorNode += $" sourceFile=\"{sourceFile}\""; } if (sourceStartLineNumber != 0) { anchorNode += $" sourceStartLineNumber={sourceStartLineNumber}"; } if (sourceEndLineNumber != 0) { anchorNode += $" sourceEndLineNumber={sourceEndLineNumber}"; } anchorNode += $">{value}</a>"; return HtmlAgilityPack.HtmlNode.CreateNode(anchorNode); } private static HtmlAgilityPack.HtmlNode GetDefaultPlainTextNode(string value) { var spanNode = $"<span class=\"xref\">{value}</span>"; return HtmlAgilityPack.HtmlNode.CreateNode(spanNode); } private static string GetLanguageSpecificAttribute(XRefSpec spec, string language, params string[] keyInFallbackOrder) { if (keyInFallbackOrder == null || keyInFallbackOrder.Length == 0) throw new ArgumentException("key must be provided!", nameof(keyInFallbackOrder)); string suffix = string.Empty; if (!string.IsNullOrEmpty(language)) { suffix = "." + language; } foreach (var key in keyInFallbackOrder) { string value; var keyWithSuffix = key + suffix; if (spec.TryGetValue(keyWithSuffix, out value)) { return value; } if (spec.TryGetValue(key, out value)) { return value; } } return null; } public static HtmlAgilityPack.HtmlNode ConvertXrefLinkNodeToXrefNode(HtmlAgilityPack.HtmlNode node) { var href = node.GetAttributeValue("href", null); if (node.Name != "a" || string.IsNullOrEmpty(href) || !href.StartsWith("xref:")) { throw new NotSupportedException("Only anchor node with href started with \"xref:\" is supported!"); } href = href.Substring("xref:".Length); var raw = StringHelper.HtmlEncode(node.OuterHtml); var xrefNode = $"<xref href=\"{href}\" data-throw-if-not-resolved=\"True\" data-raw-html=\"{raw}\""; foreach (var attr in node.Attributes ?? Enumerable.Empty<HtmlAgilityPack.HtmlAttribute>()) { if (attr.Name == "href" || attr.Name == "data-throw-if-not-resolved" || attr.Name == "data-raw-html") { continue; } xrefNode += $" {attr.Name}=\"{attr.Value}\""; } xrefNode += $">{node.InnerText}</xref>"; return HtmlAgilityPack.HtmlNode.CreateNode(xrefNode); } } }
//System.IO.File.Move("oldfilename", "newfilename"); using System; using System.Drawing; using System.Reflection; using System.Collections.Generic; namespace HelloSpace { public class OP8 { // small images, raster operator ulong[] data; byte it; public OP8() { this.data = new ulong[4]; this.data[0] = 0; this.data[1] = 0; this.data[2] = 0; this.data[3] = 0; this.it = 0; } public OP8(byte[] data,byte it) { this.data = new ulong[4]; this.setBytes(data); this.it = it; } public void setBytes( byte[] data ) { if(data.Length != 32) throw new Exception( "invalid size for this op." ); for(int x = 0; x < 32;x++) { int m = x % 8; int p = ( x - m ) / 8; ulong c = 0xFF; c <<= ( 8 * m ); c = ~c; this.data[p] &= c; c = data[x]; this.data[p] |= ( c << ( 8 * m ) ); } } public byte[] getBytes() { byte[] ret = new byte[32]; int c = 0; for(int x = 0; x < 4;x++) { for(int y = 0; y < 8;y++) { ulong i = 0xFF; ret[c++] = (byte) ( ( this.data[x] & ( i << ( 8 * y ) ) ) >> ( 8 * y ) ); } } return ret; } private float saturation() { // best saturation is 0, worst saturation(1) leads to shortcut byte[] t = this.getBytes(); float r = 0; for(int x = 0; x < 256;x++) { int m = x % 8; int p = ( x - m ) / 8; if( ( t[p] & ( 1 << m ) ) > 0) { r += 1; } } return r/256.0f; } private void next_it() { int i = this.it; i = (i + 1)%256; this.it = (byte)i; } public void include(byte min, byte max) { byte b1 = min < max ? min : max; byte b2 = min < max ? max : min; int m1 = b1 % 64; int p1 = (b1 -m1 ) / 64; int m2 = b2 % 64; int p2 = (b2 -m2) / 64; for(int x = 0; x < 4;x++) { if( x >= p1 && x <= p2) { if(x == p1) { if(p2>p1) for(int y = m1; y < 64;y++) this.data[x] |= (ulong)( (ulong)1 << y ); else for(int y = m1; y < m2;y++) this.data[x] |= (ulong)( (ulong)1 << y ); } else if(x == p2) { for(int y = 0; y < m2;y++) this.data[x] |= (ulong)( (ulong)1 << y); } else { for(int y = 0; y < 64;y++) this.data[x] |= (ulong)( (ulong)1 << y); } } } } public void exclude(byte min, byte max) { byte b1 = min < max ? min : max; byte b2 = min < max ? max : min; int m1 = b1 % 64; int p1 = (b1 -m1 ) / 64; int m2 = b2 % 64; int p2 = (b2 -m2) / 64; for(int x = 0; x < 4;x++) { if( x >= p1 && x <= p2) { if(x == p1) { if(p2>p1) for(int y = m1; y < 64;y++) this.data[x] &= (ulong) ~( (ulong)1 << y ); else for(int y = m1; y < m2;y++) this.data[x] &= (ulong)~( (ulong)1 << y ); } else if(x == p2) { for(int y = 0; y < m2;y++) this.data[x] &= (ulong)~( (ulong)1 << y); } else { for(int y = 0; y < 64;y++) this.data[x] &= (ulong)~( (ulong)1 << y); } } } } public OP8 Mutate() { int at = this.it; next_it(); byte[] t = this.getBytes(); int m = at % 8; int p = ( at - m ) / 8; if( ( t[p] & ( 1 << m ) ) > 0) { // switch to 0 byte b = 1; t[p] &= (byte) ( ~( b << m ) ); } else { // switch to 1 byte b = 1; t[p] |= (byte)( b << m ); } return new OP8(t,this.it); } public string bin() { byte[] t = this.getBytes(); string ret = ""; for(int x = 0; x < 256;x++) { int m = x % 8; int p = ( x - m ) / 8; if( ( t[p] & ( 1 << m ) ) > 0) { ret += "1"; } else { ret += "0"; } } return ret; } public bool eval( byte data ) { int m = data % 64; int p = ( data - m ) / 64; ulong i = 1; bool r = ( this.data[p] & ( i << m ) ) > 0; return r; } } public class Hello { public static string hex(byte b) { string str = BitConverter.ToString(new byte[] { b }); if(str.Length == 1) return "0" + str; return str; } public static void DrawToScreen() { // veen sample to recognize intersection int w = 256; int h = 256; Console.WriteLine("{"); Console.WriteLine("\"type\":\"image\","); Console.WriteLine("\"data\":{"); Console.WriteLine("\"width\":"+w+","); Console.WriteLine("\"height\":"+h+","); Console.Write("\"raw\":\""); Random rnd = new Random(); for(int y = 0; y < w;y++) { for(int x = 0; x < h;x++) { Color c = Color.White; float _x = (float)x; float _y = (float)y; float _dx1 = _x - 256.0f/4.0f; float _dy1 = _y - 256.0f/2.0f; if( _dx1*_dx1 + _dy1*_dy1 < 96*96 ) { if( rnd.Next(64) > 60 ) { c = Color.Red; } } float _dx2 = _x - 3.0f*256.0f/4.0f; float _dy2 = _y - 256.0f/2.0f; if( _dx2*_dx2 + _dy2*_dy2 < 96*96 ) { if( rnd.Next(64) > 60 ) { c = Color.Blue; } } Console.Write("{0}",hex(c.R)); Console.Write("{0}",hex(c.G)); Console.Write("{0}",hex(c.B)); } } Console.WriteLine("\""); Console.WriteLine("}"); Console.WriteLine("}"); } public static byte[] DrawToArray() { int w = 256; int h = 256; byte[] ret = new byte[w*h*4]; Random rnd = new Random(); int p = 0; for(int y = 0; y < w;y++) { for(int x = 0; x < h;x++) { int pos = p*4; Color c = Color.White; float _x = (float)x; float _y = (float)y; float _dx1 = _x - 256.0f/4.0f; float _dy1 = _y - 256.0f/2.0f; if( _dx1*_dx1 + _dy1*_dy1 < 96*96 ) { if( rnd.Next(64) > 60 ) { c = Color.Red; } } float _dx2 = _x - 3.0f*256.0f/4.0f; float _dy2 = _y - 256.0f/2.0f; if( _dx2*_dx2 + _dy2*_dy2 < 96*96 ) { if( rnd.Next(64) > 60 ) { c = Color.Blue; } } ret[pos+0] = c.R; ret[pos+1] = c.G; ret[pos+2] = c.B; ret[pos+3] = 255; p += 1; } } return ret; } public static void Main() { if(false) { DrawToScreen(); } else { try { byte[] data = DrawToArray(); List<Color> clist = new List<Color>(); Dictionary<string,int> dictName2Index = new Dictionary<string,int>(); Dictionary<int,string> dictIndex2Name = new Dictionary<int,string>(); // nearest of Color PropertyInfo[] props = typeof(Color).GetProperties(); //Console.WriteLine(props.Length); int count = 0; Dictionary<byte,List<int>> dictR = new Dictionary<byte,List<int>>(); Dictionary<byte,List<int>> dictG = new Dictionary<byte,List<int>>(); Dictionary<byte,List<int>> dictB = new Dictionary<byte,List<int>>(); Dictionary<byte,List<int>> dictA = new Dictionary<byte,List<int>>(); for(int x = 0; x < 256;x++) { dictR.Add((byte)x,new List<int>()); dictG.Add((byte)x,new List<int>()); dictB.Add((byte)x,new List<int>()); dictA.Add((byte)x,new List<int>()); } foreach(PropertyInfo p in props) { if( p.PropertyType.Name == "Color" ) { Color c = (Color)p.GetValue(null, null); clist.Add(c); int i = clist.Count-1; dictName2Index.Add(p.Name,i); dictIndex2Name.Add(i,p.Name); dictR[ c.R ].Add( i ); dictG[ c.G ].Add( i ); dictB[ c.B ].Add( i ); dictA[ c.A ].Add( i ); //Console.Write("{0},",p.Name); //if(count%5==4) Console.WriteLine(); count += 1; } } // get nearest pallete of image int w = 256; int h = 256; int p2 = 0; int[] img = new int[w*h]; List<int> mlist = new List<int>(); int it = 0; for(int y = 0; y < h;y++) { for(int x = 0; x < w;x++) { int pos = p2*4; int sel = -1; Color c1 = Color.Transparent; Color c2 = Color.FromArgb( data[pos], data[pos+1], data[pos+2], data[pos+3] ); for(int k = 0; k < dictR[ data[pos] ].Count;k++) { it++; Color c3 = clist[ dictR[ data[pos] ][k] ]; if( Math.Abs( c2.GetHue() - c3.GetHue() ) < Math.Abs( c2.GetHue() - c1.GetHue() ) ) { c1 = c3; sel = dictR[ data[pos] ][k]; } } for(int k = 0; k < dictG[ data[pos+1] ].Count;k++) { it++; Color c3 = clist[ dictG[ data[pos+1] ][k] ]; if( Math.Abs( c2.GetHue() - c3.GetHue() ) < Math.Abs( c2.GetHue() - c1.GetHue() ) ) { c1 = c3; sel = dictG[ data[pos+1] ][k]; } } for(int k = 0; k < dictB[ data[pos+2] ].Count;k++) { it++; Color c3 = clist[ dictB[ data[pos+2] ][k] ]; if( Math.Abs( c2.GetHue() - c3.GetHue() ) < Math.Abs( c2.GetHue() - c1.GetHue() ) ) { c1 = c3; sel = dictB[ data[pos+2] ][k]; } } if(sel!=-1) { bool check = false; for(int k = 0; k < mlist.Count;k++) { it++; if(mlist[k] == sel) { check = true; break; } } if(!check) mlist.Add(sel); Console.Write("1"); } else { Console.Write("0"); } p2 += 1; } } Console.WriteLine(); Console.WriteLine("{0}",mlist.Count); // selected shortest discrete colors Console.WriteLine("{0}",it); } catch(Exception e) { Console.WriteLine(e.Message); } } } } }