context
stringlengths
2.52k
185k
gt
stringclasses
1 value
#region File Description //----------------------------------------------------------------------------- // BloomComponent.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; #endregion namespace BloomPostprocess { public class BloomComponent : DrawableGameComponent { #region Fields SpriteBatch spriteBatch; Effect bloomExtractEffect; Effect bloomCombineEffect; Effect gaussianBlurEffect; RenderTarget2D sceneRenderTarget; RenderTarget2D renderTarget1; RenderTarget2D renderTarget2; // Choose what display settings the bloom should use. public BloomSettings Settings { get { return settings; } set { settings = value; } } BloomSettings settings = BloomSettings.PresetSettings[0]; // Optionally displays one of the intermediate buffers used // by the bloom postprocess, so you can see exactly what is // being drawn into each rendertarget. public enum IntermediateBuffer { PreBloom, BlurredHorizontally, BlurredBothWays, FinalResult, } public IntermediateBuffer ShowBuffer { get { return showBuffer; } set { showBuffer = value; } } IntermediateBuffer showBuffer = IntermediateBuffer.FinalResult; #endregion #region Initialization public BloomComponent(Game game) : base(game) { if (game == null) throw new ArgumentNullException("game"); } /// <summary> /// Load your graphics content. /// </summary> protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); bloomExtractEffect = Game.Content.Load<Effect>("BloomExtract"); bloomCombineEffect = Game.Content.Load<Effect>("BloomCombine"); gaussianBlurEffect = Game.Content.Load<Effect>("GaussianBlur"); // Look up the resolution and format of our main backbuffer. PresentationParameters pp = GraphicsDevice.PresentationParameters; int width = pp.BackBufferWidth; int height = pp.BackBufferHeight; SurfaceFormat format = pp.BackBufferFormat; // Create a texture for rendering the main scene, prior to applying bloom. sceneRenderTarget = new RenderTarget2D(GraphicsDevice, width, height, false, format, pp.DepthStencilFormat, pp.MultiSampleCount, RenderTargetUsage.DiscardContents); // Create two rendertargets for the bloom processing. These are half the // size of the backbuffer, in order to minimize fillrate costs. Reducing // the resolution in this way doesn't hurt quality, because we are going // to be blurring the bloom images in any case. width /= 2; height /= 2; renderTarget1 = new RenderTarget2D(GraphicsDevice, width, height, false, format, DepthFormat.None); renderTarget2 = new RenderTarget2D(GraphicsDevice, width, height, false, format, DepthFormat.None); } /// <summary> /// Unload your graphics content. /// </summary> protected override void UnloadContent() { sceneRenderTarget.Dispose(); renderTarget1.Dispose(); renderTarget2.Dispose(); } #endregion #region Draw /// <summary> /// This should be called at the very start of the scene rendering. The bloom /// component uses it to redirect drawing into its custom rendertarget, so it /// can capture the scene image in preparation for applying the bloom filter. /// </summary> public void BeginDraw() { if (Visible) { GraphicsDevice.SetRenderTarget(sceneRenderTarget); } } /// <summary> /// This is where it all happens. Grabs a scene that has already been rendered, /// and uses postprocess magic to add a glowing bloom effect over the top of it. /// </summary> public override void Draw(GameTime gameTime) { GraphicsDevice.SamplerStates[1] = SamplerState.LinearClamp; // Pass 1: draw the scene into rendertarget 1, using a // shader that extracts only the brightest parts of the image. bloomExtractEffect.Parameters["BloomThreshold"].SetValue( Settings.BloomThreshold); DrawFullscreenQuad(sceneRenderTarget, renderTarget1, bloomExtractEffect, IntermediateBuffer.PreBloom); // Pass 2: draw from rendertarget 1 into rendertarget 2, // using a shader to apply a horizontal gaussian blur filter. SetBlurEffectParameters(1.0f / (float)renderTarget1.Width, 0); DrawFullscreenQuad(renderTarget1, renderTarget2, gaussianBlurEffect, IntermediateBuffer.BlurredHorizontally); // Pass 3: draw from rendertarget 2 back into rendertarget 1, // using a shader to apply a vertical gaussian blur filter. SetBlurEffectParameters(0, 1.0f / (float)renderTarget1.Height); DrawFullscreenQuad(renderTarget2, renderTarget1, gaussianBlurEffect, IntermediateBuffer.BlurredBothWays); // Pass 4: draw both rendertarget 1 and the original scene // image back into the main backbuffer, using a shader that // combines them to produce the final bloomed result. GraphicsDevice.SetRenderTarget(null); EffectParameterCollection parameters = bloomCombineEffect.Parameters; parameters["BloomIntensity"].SetValue(Settings.BloomIntensity); parameters["BaseIntensity"].SetValue(Settings.BaseIntensity); parameters["BloomSaturation"].SetValue(Settings.BloomSaturation); parameters["BaseSaturation"].SetValue(Settings.BaseSaturation); GraphicsDevice.Textures[1] = sceneRenderTarget; Viewport viewport = GraphicsDevice.Viewport; DrawFullscreenQuad(renderTarget1, viewport.Width, viewport.Height, bloomCombineEffect, IntermediateBuffer.FinalResult); } /// <summary> /// Helper for drawing a texture into a rendertarget, using /// a custom shader to apply postprocessing effects. /// </summary> void DrawFullscreenQuad(Texture2D texture, RenderTarget2D renderTarget, Effect effect, IntermediateBuffer currentBuffer) { GraphicsDevice.SetRenderTarget(renderTarget); DrawFullscreenQuad(texture, renderTarget.Width, renderTarget.Height, effect, currentBuffer); } /// <summary> /// Helper for drawing a texture into the current rendertarget, /// using a custom shader to apply postprocessing effects. /// </summary> void DrawFullscreenQuad(Texture2D texture, int width, int height, Effect effect, IntermediateBuffer currentBuffer) { // If the user has selected one of the show intermediate buffer options, // we still draw the quad to make sure the image will end up on the screen, // but might need to skip applying the custom pixel shader. if (showBuffer < currentBuffer) { effect = null; } spriteBatch.Begin(0, BlendState.Opaque, null, null, null, effect); spriteBatch.Draw(texture, new Rectangle(0, 0, width, height), Color.White); spriteBatch.End(); } /// <summary> /// Computes sample weightings and texture coordinate offsets /// for one pass of a separable gaussian blur filter. /// </summary> void SetBlurEffectParameters(float dx, float dy) { // Look up the sample weight and offset effect parameters. EffectParameter weightsParameter, offsetsParameter; weightsParameter = gaussianBlurEffect.Parameters["SampleWeights"]; offsetsParameter = gaussianBlurEffect.Parameters["SampleOffsets"]; // Look up how many samples our gaussian blur effect supports. int sampleCount = weightsParameter.Elements.Count; // Create temporary arrays for computing our filter settings. float[] sampleWeights = new float[sampleCount]; Vector2[] sampleOffsets = new Vector2[sampleCount]; // The first sample always has a zero offset. sampleWeights[0] = ComputeGaussian(0); sampleOffsets[0] = new Vector2(0); // Maintain a sum of all the weighting values. float totalWeights = sampleWeights[0]; // Add pairs of additional sample taps, positioned // along a line in both directions from the center. for (int i = 0; i < sampleCount / 2; i++) { // Store weights for the positive and negative taps. float weight = ComputeGaussian(i + 1); sampleWeights[i * 2 + 1] = weight; sampleWeights[i * 2 + 2] = weight; totalWeights += weight * 2; // To get the maximum amount of blurring from a limited number of // pixel shader samples, we take advantage of the bilinear filtering // hardware inside the texture fetch unit. If we position our texture // coordinates exactly halfway between two texels, the filtering unit // will average them for us, giving two samples for the price of one. // This allows us to step in units of two texels per sample, rather // than just one at a time. The 1.5 offset kicks things off by // positioning us nicely in between two texels. float sampleOffset = i * 2 + 1.5f; Vector2 delta = new Vector2(dx, dy) * sampleOffset; // Store texture coordinate offsets for the positive and negative taps. sampleOffsets[i * 2 + 1] = delta; sampleOffsets[i * 2 + 2] = -delta; } // Normalize the list of sample weightings, so they will always sum to one. for (int i = 0; i < sampleWeights.Length; i++) { sampleWeights[i] /= totalWeights; } // Tell the effect about our new filter settings. weightsParameter.SetValue(sampleWeights); offsetsParameter.SetValue(sampleOffsets); } /// <summary> /// Evaluates a single point on the gaussian falloff curve. /// Used for setting up the blur filter weightings. /// </summary> float ComputeGaussian(float n) { float theta = Settings.BlurAmount; return (float)((1.0 / Math.Sqrt(2 * Math.PI * theta)) * Math.Exp(-(n * n) / (2 * theta * theta))); } #endregion } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Specialized; using System.IO; using System.Text; using System.Linq; using Gallio.Common.Markup; using Gallio.Common.Policies; using Gallio.Reports; using Gallio.Reports.Vtl; using Gallio.Runtime.ProgressMonitoring; using Gallio.Runtime; using Gallio.Framework; using Gallio.Common.Reflection; using Gallio.Runner.Reports; using Gallio.Tests; using MbUnit.Framework; using Rhino.Mocks; using Rhino.Mocks.Constraints; using Gallio.Common.Collections; using Gallio.Runner.Reports.Schema; using NVelocity.App; using NVelocity.Runtime; using System.Reflection; using Gallio.Common.Markup.Tags; using Gallio.Model.Schema; using System.Collections.Generic; using Gallio.Model; namespace Gallio.Tests.Reports.Vtl { [TestFixture] [TestsOn(typeof(TestStepRunNode))] public class TestStepRunNodeTest { [Test] [ExpectedArgumentNullException] public void Constructs_with_null_run_should_throw_exception() { new TestStepRunNode(null, null, 0); } [Test] public void Constructs_root_element() // i.e. without any parent { var run = CreateFakeTestStepRun("123", true, TestOutcome.Passed); var node = new TestStepRunNode(run, null, 0); Assert.AreSame(run, node.Run); Assert.IsNull(node.Parent); Assert.AreEqual(0, node.Index); Assert.IsEmpty(node.Children); Assert.AreEqual(1, node.Count); } [Test] public void Constructs_not_root_element() { var runParent = CreateFakeTestStepRun("123", false, TestOutcome.Passed); var parent = new TestStepRunNode(runParent, null, 0); var run = CreateFakeTestStepRun("456", true, TestOutcome.Passed); var node = new TestStepRunNode(run, parent, 1); Assert.AreSame(run, node.Run); Assert.AreSame(parent, node.Parent); Assert.AreEqual(1, node.Index); Assert.IsEmpty(node.Children); Assert.AreEqual(1, node.Count); } [Test] public void BuildTreeFromRoot_with_null_root() { var tree = TestStepRunNode.BuildTreeFromRoot(null); Assert.AreEqual(1, tree.Count); } private TestStepRun CreateFakeTestStepRun(string id, bool isTestCase, TestOutcome outcome, params TestStepRun[] children) { var step = new TestStepData(id, "Name-" + id, "FullName-" + id, "Test-" + id); step.IsTestCase = isTestCase; var run = new TestStepRun(step); run.Result = new TestResult() { Outcome = outcome }; run.Children.AddRange(children); return run; } private TestStepRunNode BuildFakeTree() { // Root // +- Child1 // +- Child2 // +- Child3 // +- Child31 // +- Child32 // +- Child321 // +- Child322 // +- Child323 // +- Child324 // +- Child33 // +- Child331 // +- Child332 // +- Child333 var child1 = CreateFakeTestStepRun("1", true, TestOutcome.Passed); var child2 = CreateFakeTestStepRun("2", true, TestOutcome.Passed); var child331 = CreateFakeTestStepRun("331", true, TestOutcome.Passed); var child332 = CreateFakeTestStepRun("332", true, TestOutcome.Pending); var child333 = CreateFakeTestStepRun("333", true, TestOutcome.Passed); var child33 = CreateFakeTestStepRun("33", false, TestOutcome.Passed, child331, child332, child333); var child321 = CreateFakeTestStepRun("321", true, TestOutcome.Inconclusive); var child322 = CreateFakeTestStepRun("322", true, TestOutcome.Passed); var child323 = CreateFakeTestStepRun("323", true, TestOutcome.Failed); var child324 = CreateFakeTestStepRun("324", true, TestOutcome.Ignored); var child32 = CreateFakeTestStepRun("32", false, TestOutcome.Failed, child321, child322, child323, child324); var child31 = CreateFakeTestStepRun("31", true, TestOutcome.Passed); var child3 = CreateFakeTestStepRun("3", false, TestOutcome.Failed, child31, child32, child33); var root = CreateFakeTestStepRun("Root", false, TestOutcome.Failed, child1, child2, child3); return TestStepRunNode.BuildTreeFromRoot(root); } [Test] public void Count() { TestStepRunNode tree = BuildFakeTree(); Assert.AreEqual(14, tree.Count); } [Test] public void GetSummaryChildren_condensed() { TestStepRunNode tree = BuildFakeTree(); IEnumerable<TestStepRunNode> nodes = tree.GetSummaryChildren(true); Assert.AreElementsEqual(new[] { "3" }, nodes.Select(x => x.Run.Step.Id)); nodes = nodes.ElementAt(0).GetSummaryChildren(true); Assert.AreElementsEqual(new[] { "32" }, nodes.Select(x => x.Run.Step.Id)); nodes = nodes.ElementAt(0).GetSummaryChildren(true); Assert.IsEmpty(nodes); } [Test] public void GetSummaryChildren_not_condensed() { TestStepRunNode tree = BuildFakeTree(); IEnumerable<TestStepRunNode> nodes = tree.GetSummaryChildren(false); Assert.AreElementsEqual(new[] { "3" }, nodes.Select(x => x.Run.Step.Id)); nodes = nodes.ElementAt(0).GetSummaryChildren(false); Assert.AreElementsEqual(new[] { "32", "33" }, nodes.Select(x => x.Run.Step.Id)); nodes = nodes.ElementAt(0).GetSummaryChildren(false); Assert.IsEmpty(nodes); } [Test] public void GetDetailsChildren_condensed() { TestStepRunNode tree = BuildFakeTree(); IEnumerable<TestStepRunNode> nodes = tree.GetDetailsChildren(true); Assert.AreElementsEqual(new[] { "3" }, nodes.Select(x => x.Run.Step.Id)); nodes = nodes.ElementAt(0).GetDetailsChildren(true); Assert.AreElementsEqual(new[] { "32" }, nodes.Select(x => x.Run.Step.Id)); nodes = nodes.ElementAt(0).GetDetailsChildren(true); Assert.AreElementsEqual(new[] { "321", "323", "324" }, nodes.Select(x => x.Run.Step.Id)); } [Test] public void GetDetailsChildren_not_condensed() { TestStepRunNode tree = BuildFakeTree(); IEnumerable<TestStepRunNode> nodes = tree.GetDetailsChildren(false); Assert.AreElementsEqual(new[] { "1", "2", "3" }, nodes.Select(x => x.Run.Step.Id)); nodes = nodes.ElementAt(2).GetDetailsChildren(false); Assert.AreElementsEqual(new[] { "31", "32", "33" }, nodes.Select(x => x.Run.Step.Id)); nodes = nodes.ElementAt(1).GetDetailsChildren(false); Assert.AreElementsEqual(new[] { "321", "322", "323", "324" }, nodes.Select(x => x.Run.Step.Id)); } [Test] public void GetNavigatorChildren() { TestStepRunNode tree = BuildFakeTree(); IEnumerable<TestStepRunNode> nodes = tree.GetNavigatorChildren(); Assert.AreElementsEqual(new[] { "321", "323", "324", "332" }, nodes.Select(x => x.Run.Step.Id)); } [Test] public void GetSelfAndAncestorIds() { TestStepRunNode tree = BuildFakeTree(); var child321 = tree.Children[2].Children[1].Children[0]; Assert.AreElementsEqual(new[] { "Test-321", "Test-32", "Test-3", "Test-Root" }, child321.GetSelfAndAncestorIds()); } [Test] [Row(0, 1, false)] [Row(123, 1, true)] [Row(999, 1, true)] [Row(1000, 1, true)] [Row(1000, 2, false)] [Row(1001, 2, true)] [Row(3500, 4, true)] [Row(3500, 5, false)] public void IsVisibleInPage(int index, int pageIndex, bool expectedVisible) { var run = CreateFakeTestStepRun("123", true, TestOutcome.Passed); var node = new TestStepRunNode(run, null, index); bool actualVisible = node.IsVisibleInPage(pageIndex, 1000); Assert.AreEqual(expectedVisible, actualVisible); } } }
// Copyright 2016 Jacob Trimble // // 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.Diagnostics.CodeAnalysis; using ModMaker.Lua.Runtime; using NUnit.Framework; namespace UnitTests.Runtime.LuaLibraries { [TestFixture] [SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Names match Lua versions")] public class Bit32 : LibraryTestBase { #region arshift [Test] public void arshift() { _lua.DoText(@" -- Positive displacements. assertEquals(0xf0, bit32.arshift(0xf00, 4), 'arshift: normal') assertEquals(0xf0, bit32.arshift(0xf00, 4, 33), 'arshift: extra args') assertEquals(0xf0, bit32.arshift(0xff00000f00, 4), 'arshift: larger than 32-bit') assertEquals(0xff015600, bit32.arshift(0x80ab0000, 7), 'arshift: high-bit fill') assertEquals(0xffffff00, bit32.arshift(0x80000000, 23), 'arshift: high-bit fill small value') assertEquals(0x0, bit32.arshift(0x724624, 35), 'arshift: all shifted out') assertEquals(0xffffffff, bit32.arshift(0x824624, 35), 'arshift: all shifted out (negative)') assertEquals(0xfffffffc, bit32.arshift(-0xf, 2), 'arshift: negative source') -- Negative displacements. assertEquals(0xf0, bit32.arshift(0xf, -4), 'arshift(left): normal') assertEquals(0xf00000a0, bit32.arshift(0x0f00000a, -4), 'arshift(left): becomes negative') assertEquals(0xf0, bit32.arshift(0xff0000000f, -4), 'arshift(left): larger than 32-bit') assertEquals(0xff000000, bit32.arshift(0x1155ff, -24), 'arshift(left): drop high bits') assertEquals(0x0, bit32.arshift(0x924624, -35), 'arshift(left): all shifted out') assertEquals(0xffffff88, bit32.arshift(-0xf, -3), 'arshift(left): negative source') "); } [Test] public void arshift_InvalidTypes() { _runInvalidTypeTests(LuaValueType.Number, "bit32.arshift({0}, 2)"); _runInvalidTypeTests(LuaValueType.Number, "bit32.arshift(2, {0})"); } [Test] public void arshift_NotEnoughArgs() { Assert.Throws<ArgumentException>(delegate { _lua.DoText(@"bit32.arshift(0xf00)"); }); } #endregion #region band [Test] public void band() { _lua.DoText(@" assertEquals(0xea, bit32.band(0xff, 0xea), 'band: normal') assertEquals(0xffffffff, bit32.band(), 'band: zero arguments') assertEquals(0xea, bit32.band(0xea), 'band: one argument') assertEquals(0x22, bit32.band(0xff, 0xea, 0x7f, 0xa3), 'band: more than two') assertEquals(0x00, bit32.band(0x42, 0xea, 0x7a, 0xa1), 'band: clears out') assertEquals(0xaa000000, bit32.band(0xfa0000aa, 0xaf00aa00), 'band: large number') assertEquals(0x0f, bit32.band(0xff0000000f, 0xff0000000f), 'band: >32-bits') "); } [Test] public void band_InvalidTypes() { _runInvalidTypeTests(LuaValueType.Number, "bit32.band({0})"); _runInvalidTypeTests(LuaValueType.Number, "bit32.band(23, 4, {0}, 5)"); } #endregion #region bnot [Test] public void bnot() { _lua.DoText(@" assertEquals(0xff005533, bit32.bnot(0x00ffaacc), 'bnot: normal') assertEquals(0xff005533, bit32.bnot(0x00ffaacc, 'cat'), 'bnot: extra args') assertEquals(0x00ffaa66, bit32.bnot(0xff005599), 'bnot: high-bit set') assertEquals(11, bit32.bnot(-12), 'bnot: negative') assertEquals(0xffffffff, bit32.bnot(0), 'bnot: zero') assertEquals(0xffffefdb, bit32.bnot(0x4500001024), 'bnot: >32-bits') "); } [Test] public void bnot_InvalidTypes() { _runInvalidTypeTests(LuaValueType.Number, "bit32.bnot({0})"); } [Test] public void bnot_NotEnoughArgs() { Assert.Throws<ArgumentException>(() => { _lua.DoText(@"bit32.bnot()"); }); } #endregion #region bor [Test] public void bor() { _lua.DoText(@" assertEquals(0xff, bit32.bor(0xaa, 0x55), 'bor: normal') assertEquals(0x0, bit32.bor(), 'bor: zero arguments') assertEquals(0xea, bit32.bor(0xea), 'bor: one argument') assertEquals(0xab, bit32.bor(0x01, 0x83, 0x21, 0x2a), 'bor: more than two') assertEquals(0xff00aaaa, bit32.bor(0xfa0000aa, 0xaf00aa00), 'bor: large number') assertEquals(0xff, bit32.bor(0xff000000f0, 0xff0000000f), 'bor: >32-bits') "); } [Test] public void bor_InvalidTypes() { _runInvalidTypeTests(LuaValueType.Number, "bit32.bor({0})"); _runInvalidTypeTests(LuaValueType.Number, "bit32.bor(23, 4, {0}, 5)"); } #endregion #region btest [Test] public void btest() { _lua.DoText(@" assertEquals(false, bit32.btest(0xaa, 0x55), 'btest: normal') assertEquals(true, bit32.btest(), 'btest: zero arguments') assertEquals(true, bit32.btest(0xea), 'btest: one argument') assertEquals(false, bit32.btest(0x01, 0x83, 0x21, 0x2a), 'btest: more than two') assertEquals(true, bit32.btest(0xfa0000aa, 0xaf00aa00), 'btest: large number') assertEquals(false, bit32.btest(0xff000000f0, 0xff0000000f), 'btest: >32-bits') "); } [Test] public void btest_InvalidTypes() { _runInvalidTypeTests(LuaValueType.Number, "bit32.btest({0})"); _runInvalidTypeTests(LuaValueType.Number, "bit32.btest(23, 4, {0}, 5)"); } #endregion #region bxor [Test] public void bxor() { _lua.DoText(@" assertEquals(0x82, bit32.bxor(0x24, 0xa6), 'bxor: normal') assertEquals(0x0, bit32.bxor(), 'bxor: zero arguments') assertEquals(0xea, bit32.bxor(0xea), 'bxor: one argument') assertEquals(0x89, bit32.bxor(0x01, 0x83, 0x21, 0x2a), 'bxor: more than two') assertEquals(0x5500f848, bit32.bxor(0xfa005a1e, 0xaf00a256), 'bxor: large number') assertEquals(0xff, bit32.bxor(0xff000000f0, 0xff0000000f), 'bxor: >32-bits') "); } [Test] public void bxor_InvalidTypes() { _runInvalidTypeTests(LuaValueType.Number, "bit32.bxor({0})"); _runInvalidTypeTests(LuaValueType.Number, "bit32.bxor(23, 4, {0}, 5)"); } #endregion #region extract [Test] public void extract() { _lua.DoText(@" assertEquals(0x3a28, bit32.extract(0xa74e8a28, 6, 16), 'extract: normal') assertEquals(0x0, bit32.extract(0xa74e8a28, 6), 'extract: default width') assertEquals(0x4fe3a, bit32.extract(0x913f8ea, 2, 21, 'cat'), 'extract: extra args') assertEquals(0x1e, bit32.extract(0xff0305d2f0, 3, 6), 'extract: >32-bits') "); } [Test] public void extract_InvalidTypes() { _runInvalidTypeTests(LuaValueType.Number, "bit32.extract({0}, 0)"); _runInvalidTypeTests(LuaValueType.Number, "bit32.extract(4, {0})"); _runInvalidTypeTests(LuaValueType.Number, "bit32.extract(4, 3, {0})"); } [Test] public void extract_TooLargeIndex() { Assert.Throws<ArgumentException>(() => { _lua.DoText(@"bit32.extract(0x3, 34)"); }); } [Test] public void extract_TooLargeSize() { Assert.Throws<ArgumentException>(() => { _lua.DoText(@"bit32.extract(0x3, 3, 42)"); }); } [Test] public void extract_TooLargeIndexPlusSize() { Assert.Throws<ArgumentException>(() => { _lua.DoText(@"bit32.extract(0x3, 21, 12)"); }); } [Test] public void extract_NotEnoughArgs() { Assert.Throws<ArgumentException>(() => { _lua.DoText(@"bit32.extract()"); }); } [Test] public void extract_NotEnoughArgs2() { Assert.Throws<ArgumentException>(() => { _lua.DoText(@"bit32.extract(0xf00)"); }); } #endregion #region replace [Test] public void replace() { _lua.DoText(@" assertEquals(0xa74a4a28, bit32.replace(0xa74e8a28, 0x452, 13, 6), 'replace: normal') assertEquals(0xa74e8a20, bit32.replace(0xa74e8a28, 6, 3), 'replace: defaults to 1 width') assertEquals(0xffff4c47, bit32.replace(-45625, 34, 5, 4), 'replace: negative source') assertEquals(0xa74eca, bit32.replace(0xa74e8a, -42, 5, 4), 'replace: negative repl') assertEquals(0x918aa, bit32.replace(0x918ea, 0x2462a, 2, 10, 'cat'), 'replace: extra args') assertEquals(0xd0f0, bit32.replace(0xff0000d2f0, 0x23, 6, 4), 'replace: >32-bits') "); } [Test] public void replace_InvalidTypes() { _runInvalidTypeTests(LuaValueType.Number, "bit32.replace({0}, 0)"); _runInvalidTypeTests(LuaValueType.Number, "bit32.replace(4, {0})"); _runInvalidTypeTests(LuaValueType.Number, "bit32.replace(4, 3, {0})"); _runInvalidTypeTests(LuaValueType.Number, "bit32.replace(4, 3, 4, {0})"); } [Test] public void replace_TooLargeIndex() { Assert.Throws<ArgumentException>(() => { _lua.DoText(@"bit32.replace(0x3, 0x0, 34)"); }); } [Test] public void replace_TooLargeSize() { Assert.Throws<ArgumentException>(() => { _lua.DoText(@"bit32.replace(0x3, 0x0, 3, 42)"); }); } [Test] public void replace_TooLargeIndexPlusSize() { Assert.Throws<ArgumentException>(() => { _lua.DoText(@"bit32.replace(0x3, 0x0, 21, 12)"); }); } [Test] public void replace_NotEnoughArgs() { Assert.Throws<ArgumentException>(() => { _lua.DoText(@"bit32.replace()"); }); } [Test] public void replace_NotEnoughArgs2() { Assert.Throws<ArgumentException>(() => { _lua.DoText(@"bit32.replace(0xf00)"); }); } [Test] public void replace_NotEnoughArgs3() { Assert.Throws<ArgumentException>(() => { _lua.DoText(@"bit32.replace(0xf00, 0x00)"); }); } #endregion #region lrotate [Test] public void lrotate() { _lua.DoText(@" assertEquals(0xd3a28a29, bit32.lrotate(0xa74e8a28, 6), 'lrotate: normal') assertEquals(0x4e9d1451, bit32.lrotate(0xa74e8a28, 65), 'lrotate: > 32') assertEquals(0x4e9d1451, bit32.lrotate(0xa74e8a28, 65, 'cat'), 'lrotate: > 32') assertEquals(0xc25a789e, bit32.lrotate(0x5a789ec2, -8), 'lrotate: negative') assertEquals(0x27b0969e, bit32.lrotate(0x5a789ec2, -82), 'lrotate: negative < -32') assertEquals(0xffff216f, bit32.lrotate(-3562, 4), 'lrotate: negative source') assertEquals(0xd2f00, bit32.lrotate(0xff0000d2f0, 4), 'lrotate: >32-bits') "); } [Test] public void lrotate_InvalidTypes() { _runInvalidTypeTests(LuaValueType.Number, "bit32.lrotate({0}, 0)"); _runInvalidTypeTests(LuaValueType.Number, "bit32.lrotate(4, {0})"); } [Test] public void lrotate_NotEnoughArgs() { Assert.Throws<ArgumentException>(() => { _lua.DoText(@"bit32.lrotate()"); }); } [Test] public void lrotate_NotEnoughArgs2() { Assert.Throws<ArgumentException>(() => { _lua.DoText(@"bit32.lrotate(0xf00)"); }); } #endregion #region lshift [Test] public void lshift() { _lua.DoText(@" assertEquals(0xd3a28a00, bit32.lshift(0xa74e8a28, 6), 'lshift: normal') assertEquals(0, bit32.lshift(0xa74e8a28, 65), 'lshift: > 32') assertEquals(0, bit32.lshift(0xa74e8a28, 65, 'cat'), 'lshift: extra args') assertEquals(0x5a789e, bit32.lshift(0x5a789ec2, -8), 'lshift: negative') assertEquals(0, bit32.lshift(0x5a789ec2, -82), 'lshift: negative < -32') assertEquals(0xffff2160, bit32.lshift(-3562, 4), 'lshift: negative source') assertEquals(0xd2f00, bit32.lshift(0xff0000d2f0, 4), 'lshift: >32-bits') "); } [Test] public void lshift_InvalidTypes() { _runInvalidTypeTests(LuaValueType.Number, "bit32.lshift({0}, 0)"); _runInvalidTypeTests(LuaValueType.Number, "bit32.lshift(4, {0})"); } [Test] public void lshift_NotEnoughArgs() { Assert.Throws<ArgumentException>(() => { _lua.DoText(@"bit32.lshift()"); }); } [Test] public void lshift_NotEnoughArgs2() { Assert.Throws<ArgumentException>(() => { _lua.DoText(@"bit32.lshift(0xf00)"); }); } #endregion #region rrotate [Test] public void rrotate() { _lua.DoText(@" assertEquals(0xa29d3a28, bit32.rrotate(0xa74e8a28, 6), 'rrotate: normal') assertEquals(0x53a74514, bit32.rrotate(0xa74e8a28, 65), 'rrotate: > 32') assertEquals(0x53a74514, bit32.rrotate(0xa74e8a28, 65, 'cat'), 'rrotate: extra args') assertEquals(0x789ec25a, bit32.rrotate(0x5a789ec2, -8), 'rrotate: negative') assertEquals(0x7b0969e2, bit32.rrotate(0x5a789ec2, -82), 'rrotate: negative < -32') assertEquals(0x6fffff21, bit32.rrotate(-3562, 4), 'rrotate: negative source') assertEquals(0xd2f, bit32.rrotate(0xff0000d2f0, 4), 'rrotate: >32-bits') "); } [Test] public void rrotate_InvalidTypes() { _runInvalidTypeTests(LuaValueType.Number, "bit32.rrotate({0}, 0)"); _runInvalidTypeTests(LuaValueType.Number, "bit32.rrotate(4, {0})"); } [Test] public void rrotate_NotEnoughArgs() { Assert.Throws<ArgumentException>(() => { _lua.DoText(@"bit32.rrotate()"); }); } [Test] public void rrotate_NotEnoughArgs2() { Assert.Throws<ArgumentException>(() => { _lua.DoText(@"bit32.rrotate(0xf00)"); }); } #endregion #region rshift [Test] public void rshift() { _lua.DoText(@" assertEquals(0x29d3a28, bit32.rshift(0xa74e8a28, 6), 'rshift: normal') assertEquals(0, bit32.rshift(0xa74e8a28, 65), 'rshift: > 32') assertEquals(0, bit32.rshift(0xa74e8a28, 65, 'cat'), 'rshift: extra args') assertEquals(0x789ec200, bit32.rshift(0x5a789ec2, -8), 'rshift: negative') assertEquals(0, bit32.rshift(0x5a789ec2, -82), 'rshift: negative < -32') assertEquals(0xfffff21, bit32.rshift(-3562, 4), 'rshift: negative source') assertEquals(0xd2f, bit32.rshift(0xff0000d2f0, 4), 'rshift: >32-bits') "); } [Test] public void rshift_InvalidTypes() { _runInvalidTypeTests(LuaValueType.Number, "bit32.rshift({0}, 0)"); _runInvalidTypeTests(LuaValueType.Number, "bit32.rshift(4, {0})"); } [Test] public void rshift_NotEnoughArgs() { Assert.Throws<ArgumentException>(() => { _lua.DoText(@"bit32.rshift()"); }); } [Test] public void rshift_NotEnoughArgs2() { Assert.Throws<ArgumentException>(() => { _lua.DoText(@"bit32.rshift(0xf00)"); }); } #endregion [Ignore("Disabled until coalesce is supported")] [Test] public void coalesce() { _lua.DoText(@" assertEquals(10, bit32.arshift('43', 2), 'arshift: coalesce args') assertEquals(0xaa, bit32.band('0xfa', 0xaf), 'band: coalesce args') assertEquals(0xf0, bit32.bnot('0xffffff0f'), 'bnot: coalesce args') assertEquals(0xff, bit32.bor('0xfa', 0xaf), 'bor: coalesce args') assertEquals(true, bit32.btest('0xfa', 0x12), 'btest: coalesce args') assertEquals(0x55, bit32.bxor('0xfa', 0xaf), 'bxor: coalesce args') assertEquals(0x3, bit32.extract('0xfa', 4, 2), 'extract: coalesce args') assertEquals(0xfe, bit32.replace('0xfa', 0x3, 2, 2), 'replace: coalesce args') assertEquals(0x3e8, bit32.lrotate('0xfa', 2), 'lrotate: coalesce args') assertEquals(0x3e8, bit32.lshift('0xfa', 2), 'lshift: coalesce args') assertEquals(0x3d, bit32.rrotate('0xf4', 2), 'rrotate: coalesce args') assertEquals(0x3e, bit32.rshift('0xfa', 2), 'rshift: coalesce args') "); } } }
/* * BSD Licence: * Copyright (c) 2001, 2002 Ben Houston [ [email protected] ] * Exocortex Technologies [ www.exocortex.org ] * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the <ORGANIZATION> 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 REGENTS 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.Diagnostics; using System.IO; using System.Text; //using Exocortex.Imaging; namespace Exocortex.DSP { // Comments? Questions? Bugs? Tell Ben Houston at [email protected] // Version: May 4, 2002 /// <summary> /// <p>Static functions for doing various Fourier Operations.</p> /// </summary> public class Fourier { //====================================================================================== private Fourier() { } //====================================================================================== static private void Swap(ref float a, ref float b) { float temp = a; a = b; b = temp; } static private void Swap(ref double a, ref double b) { double temp = a; a = b; b = temp; } //------------------------------------------------------------------------------------- private const int cMaxLength = 4096; private const int cMinLength = 1; private const int cMaxBits = 12; private const int cMinBits = 0; static public bool IsPowerOf2(int x) { return (x & (x - 1)) == 0; //return ( x == Pow2( Log2( x ) ) ); } static private int Pow2(int exponent) { if (exponent >= 0 && exponent < 31) { return 1 << exponent; } return 0; } static private int Log2(int x) { if (x <= 65536) { if (x <= 256) { if (x <= 16) { if (x <= 4) { if (x <= 2) { if (x <= 1) { return 0; } return 1; } return 2; } if (x <= 8) return 3; return 4; } if (x <= 64) { if (x <= 32) return 5; return 6; } if (x <= 128) return 7; return 8; } if (x <= 4096) { if (x <= 1024) { if (x <= 512) return 9; return 10; } if (x <= 2048) return 11; return 12; } if (x <= 16384) { if (x <= 8192) return 13; return 14; } if (x <= 32768) return 15; return 16; } if (x <= 16777216) { if (x <= 1048576) { if (x <= 262144) { if (x <= 131072) return 17; return 18; } if (x <= 524288) return 19; return 20; } if (x <= 4194304) { if (x <= 2097152) return 21; return 22; } if (x <= 8388608) return 23; return 24; } if (x <= 268435456) { if (x <= 67108864) { if (x <= 33554432) return 25; return 26; } if (x <= 134217728) return 27; return 28; } if (x <= 1073741824) { if (x <= 536870912) return 29; return 30; } // since int is unsigned it can never be higher than 2,147,483,647 // if( x <= 2147483648 ) // return 31; // return 32; return 31; } //------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------- static private int ReverseBits(int index, int numberOfBits) { Debug.Assert(numberOfBits >= cMinBits); Debug.Assert(numberOfBits <= cMaxBits); int reversedIndex = 0; for (int i = 0; i < numberOfBits; i++) { reversedIndex = (reversedIndex << 1) | (index & 1); index = (index >> 1); } return reversedIndex; } //------------------------------------------------------------------------------------- static private int[][] _reversedBits = new int[cMaxBits][]; static private int[] GetReversedBits(int numberOfBits) { Debug.Assert(numberOfBits >= cMinBits); Debug.Assert(numberOfBits <= cMaxBits); if (_reversedBits[numberOfBits - 1] == null) { int maxBits = Fourier.Pow2(numberOfBits); int[] reversedBits = new int[maxBits]; for (int i = 0; i < maxBits; i++) { int oldBits = i; int newBits = 0; for (int j = 0; j < numberOfBits; j++) { newBits = (newBits << 1) | (oldBits & 1); oldBits = (oldBits >> 1); } reversedBits[i] = newBits; } _reversedBits[numberOfBits - 1] = reversedBits; } return _reversedBits[numberOfBits - 1]; } //------------------------------------------------------------------------------------- static private void ReorderArray(float[] data) { Debug.Assert(data != null); int length = data.Length / 2; Debug.Assert(Fourier.IsPowerOf2(length) == true); Debug.Assert(length >= cMinLength); Debug.Assert(length <= cMaxLength); int[] reversedBits = Fourier.GetReversedBits(Fourier.Log2(length)); for (int i = 0; i < length; i++) { int swap = reversedBits[i]; if (swap > i) { Fourier.Swap(ref data[(i << 1)], ref data[(swap << 1)]); Fourier.Swap(ref data[(i << 1) + 1], ref data[(swap << 1) + 1]); } } } static private void ReorderArray(double[] data) { Debug.Assert(data != null); int length = data.Length / 2; Debug.Assert(Fourier.IsPowerOf2(length) == true); Debug.Assert(length >= cMinLength); Debug.Assert(length <= cMaxLength); int[] reversedBits = Fourier.GetReversedBits(Fourier.Log2(length)); for (int i = 0; i < length; i++) { int swap = reversedBits[i]; if (swap > i) { Fourier.Swap(ref data[i << 1], ref data[swap << 1]); Fourier.Swap(ref data[i << 1 + 1], ref data[swap << 1 + 1]); } } } //====================================================================================== private static int[][] _reverseBits = null; private static int _ReverseBits(int bits, int n) { int bitsReversed = 0; for (int i = 0; i < n; i++) { bitsReversed = (bitsReversed << 1) | (bits & 1); bits = (bits >> 1); } return bitsReversed; } private static void InitializeReverseBits(int levels) { _reverseBits = new int[levels + 1][]; for (int j = 0; j < (levels + 1); j++) { int count = (int)Math.Pow(2, j); _reverseBits[j] = new int[count]; for (int i = 0; i < count; i++) { _reverseBits[j][i] = _ReverseBits(i, j); } } } private static int _lookupTabletLength = -1; private static double[,][] _uRLookup = null; private static double[,][] _uILookup = null; private static float[,][] _uRLookupF = null; private static float[,][] _uILookupF = null; private static void SyncLookupTableLength(int length) { Debug.Assert(length < 1024 * 10); Debug.Assert(length >= 0); if (length > _lookupTabletLength) { int level = (int)Math.Ceiling(Math.Log(length, 2)); Fourier.InitializeReverseBits(level); Fourier.InitializeComplexRotations(level); //_cFFTData = new Complex[ Math2.CeilingBase( length, 2 ) ]; //_cFFTDataF = new ComplexF[ Math2.CeilingBase( length, 2 ) ]; _lookupTabletLength = length; } } private static int GetLookupTableLength() { return _lookupTabletLength; } private static void ClearLookupTables() { _uRLookup = null; _uILookup = null; _uRLookupF = null; _uILookupF = null; _lookupTabletLength = -1; } private static void InitializeComplexRotations(int levels) { int ln = levels; //_wRLookup = new float[ levels + 1, 2 ]; //_wILookup = new float[ levels + 1, 2 ]; _uRLookup = new double[levels + 1, 2][]; _uILookup = new double[levels + 1, 2][]; _uRLookupF = new float[levels + 1, 2][]; _uILookupF = new float[levels + 1, 2][]; int N = 1; for (int level = 1; level <= ln; level++) { int M = N; N <<= 1; //float scale = (float)( 1 / Math.Sqrt( 1 << ln ) ); // positive sign ( i.e. [M,0] ) { double uR = 1; double uI = 0; double angle = (double)Math.PI / M * 1; double wR = (double)Math.Cos(angle); double wI = (double)Math.Sin(angle); _uRLookup[level, 0] = new double[M]; _uILookup[level, 0] = new double[M]; _uRLookupF[level, 0] = new float[M]; _uILookupF[level, 0] = new float[M]; for (int j = 0; j < M; j++) { _uRLookupF[level, 0][j] = (float)(_uRLookup[level, 0][j] = uR); _uILookupF[level, 0][j] = (float)(_uILookup[level, 0][j] = uI); double uwI = uR * wI + uI * wR; uR = uR * wR - uI * wI; uI = uwI; } } { // negative sign ( i.e. [M,1] ) double uR = 1; double uI = 0; double angle = (double)Math.PI / M * -1; double wR = (double)Math.Cos(angle); double wI = (double)Math.Sin(angle); _uRLookup[level, 1] = new double[M]; _uILookup[level, 1] = new double[M]; _uRLookupF[level, 1] = new float[M]; _uILookupF[level, 1] = new float[M]; for (int j = 0; j < M; j++) { _uRLookupF[level, 1][j] = (float)(_uRLookup[level, 1][j] = uR); _uILookupF[level, 1][j] = (float)(_uILookup[level, 1][j] = uI); double uwI = uR * wI + uI * wR; uR = uR * wR - uI * wI; uI = uwI; } } } } //====================================================================================== //====================================================================================== #pragma warning disable 0414 static private bool _bufferFLocked = false; static private float[] _bufferF = new float[0]; #pragma warning restore 0414 static private void LockBufferF(int length, ref float[] buffer) { Debug.Assert(_bufferFLocked == false); _bufferFLocked = true; if (length >= _bufferF.Length) { _bufferF = new float[length]; } buffer = _bufferF; } static private void UnlockBufferF(ref float[] buffer) { Debug.Assert(_bufferF == buffer); Debug.Assert(_bufferFLocked == true); _bufferFLocked = false; buffer = null; } private static void LinearFFT(float[] data, int start, int inc, int length, FourierDirection direction) { Debug.Assert(data != null); Debug.Assert(start >= 0); Debug.Assert(inc >= 1); Debug.Assert(length >= 1); Debug.Assert((start + inc * (length - 1)) * 2 < data.Length); // copy to buffer float[] buffer = null; LockBufferF(length * 2, ref buffer); int j = start; for (int i = 0; i < length * 2; i++) { buffer[i] = data[j]; j += inc; } FFT(buffer, length, direction); // copy from buffer j = start; for (int i = 0; i < length; i++) { data[j] = buffer[i]; j += inc; } UnlockBufferF(ref buffer); } private static void LinearFFT_Quick(float[] data, int start, int inc, int length, FourierDirection direction) { /*Debug.Assert( data != null ); Debug.Assert( start >= 0 ); Debug.Assert( inc >= 1 ); Debug.Assert( length >= 1 ); Debug.Assert( ( start + inc * ( length - 1 ) ) * 2 < data.Length );*/ // copy to buffer float[] buffer = null; LockBufferF(length * 2, ref buffer); int j = start; for (int i = 0; i < length * 2; i++) { buffer[i] = data[j]; j += inc; } FFT_Quick(buffer, length, direction); // copy from buffer j = start; for (int i = 0; i < length; i++) { data[j] = buffer[i]; j += inc; } UnlockBufferF(ref buffer); } //====================================================================================== //====================================================================================== #pragma warning disable 0414 static private bool _bufferCFLocked = false; //====================================================================================== //====================================================================================== static private bool _bufferCLocked = false; #pragma warning restore 0414 //====================================================================================== //====================================================================================== /// <summary> /// Compute a 1D fast Fourier transform of a dataset of complex numbers (as pairs of float's). /// </summary> /// <param name="data"></param> /// <param name="length"></param> /// <param name="direction"></param> public static void FFT(float[] data, int length, FourierDirection direction) { Debug.Assert(data != null); Debug.Assert(data.Length >= length * 2); Debug.Assert(Fourier.IsPowerOf2(length) == true); Fourier.SyncLookupTableLength(length); int ln = Fourier.Log2(length); // reorder array Fourier.ReorderArray(data); // successive doubling int N = 1; int signIndex = (direction == FourierDirection.Forward) ? 0 : 1; for (int level = 1; level <= ln; level++) { int M = N; N <<= 1; float[] uRLookup = _uRLookupF[level, signIndex]; float[] uILookup = _uILookupF[level, signIndex]; for (int j = 0; j < M; j++) { float uR = uRLookup[j]; float uI = uILookup[j]; for (int evenT = j; evenT < length; evenT += N) { int even = evenT << 1; int odd = (evenT + M) << 1; float r = data[odd]; float i = data[odd + 1]; float odduR = r * uR - i * uI; float odduI = r * uI + i * uR; r = data[even]; i = data[even + 1]; data[even] = r + odduR; data[even + 1] = i + odduI; data[odd] = r - odduR; data[odd + 1] = i - odduI; } } } } /// <summary> /// Compute a 1D fast Fourier transform of a dataset of complex numbers (as pairs of float's). /// </summary> /// <param name="data"></param> /// <param name="length"></param> /// <param name="direction"></param> public static void FFT_Quick(float[] data, int length, FourierDirection direction) { /*Debug.Assert( data != null ); Debug.Assert( data.Length >= length*2 ); Debug.Assert( Fourier.IsPowerOf2( length ) == true ); Fourier.SyncLookupTableLength( length );*/ int ln = Fourier.Log2(length); // reorder array Fourier.ReorderArray(data); // successive doubling int N = 1; int signIndex = (direction == FourierDirection.Forward) ? 0 : 1; for (int level = 1; level <= ln; level++) { int M = N; N <<= 1; float[] uRLookup = _uRLookupF[level, signIndex]; float[] uILookup = _uILookupF[level, signIndex]; for (int j = 0; j < M; j++) { float uR = uRLookup[j]; float uI = uILookup[j]; for (int evenT = j; evenT < length; evenT += N) { int even = evenT << 1; int odd = (evenT + M) << 1; float r = data[odd]; float i = data[odd + 1]; float odduR = r * uR - i * uI; float odduI = r * uI + i * uR; r = data[even]; i = data[even + 1]; data[even] = r + odduR; data[even + 1] = i + odduI; data[odd] = r - odduR; data[odd + 1] = i - odduI; } } } } /// <summary> /// Compute a 1D real-symmetric fast fourier transform. /// </summary> /// <param name="data"></param> /// <param name="direction"></param> public static void RFFT(float[] data, FourierDirection direction) { if (data == null) { throw new ArgumentNullException("data"); } Fourier.RFFT(data, data.Length, direction); } /// <summary> /// Compute a 1D real-symmetric fast fourier transform. /// </summary> /// <param name="data"></param> /// <param name="length"></param> /// <param name="direction"></param> public static void RFFT(float[] data, int length, FourierDirection direction) { if (data == null) { throw new ArgumentNullException("data"); } if (data.Length < length) { throw new ArgumentOutOfRangeException("length", length, "must be at least as large as 'data.Length' parameter"); } if (Fourier.IsPowerOf2(length) == false) { throw new ArgumentOutOfRangeException("length", length, "must be a power of 2"); } float c1 = 0.5f, c2; float theta = (float)Math.PI / (length / 2); if (direction == FourierDirection.Forward) { c2 = -0.5f; FFT(data, length / 2, direction); } else { c2 = 0.5f; theta = -theta; } float wtemp = (float)Math.Sin(0.5 * theta); float wpr = -2 * wtemp * wtemp; float wpi = (float)Math.Sin(theta); float wr = 1 + wpr; float wi = wpi; // do / undo packing for (int i = 1; i < length / 4; i++) { int a = 2 * i; int b = length - 2 * i; float h1r = c1 * (data[a] + data[b]); float h1i = c1 * (data[a + 1] - data[b + 1]); float h2r = -c2 * (data[a + 1] + data[b + 1]); float h2i = c2 * (data[a] - data[b]); data[a] = h1r + wr * h2r - wi * h2i; data[a + 1] = h1i + wr * h2i + wi * h2r; data[b] = h1r - wr * h2r + wi * h2i; data[b + 1] = -h1i + wr * h2i + wi * h2r; wr = (wtemp = wr) * wpr - wi * wpi + wr; wi = wi * wpr + wtemp * wpi + wi; } if (direction == FourierDirection.Forward) { float hir = data[0]; data[0] = hir + data[1]; data[1] = hir - data[1]; } else { float hir = data[0]; data[0] = c1 * (hir + data[1]); data[1] = c1 * (hir - data[1]); Fourier.FFT(data, length / 2, direction); } } /// <summary> /// Compute a 2D fast fourier transform on a data set of complex numbers (represented as pairs of floats) /// </summary> /// <param name="data"></param> /// <param name="xLength"></param> /// <param name="yLength"></param> /// <param name="direction"></param> public static void FFT2(float[] data, int xLength, int yLength, FourierDirection direction) { if (data == null) { throw new ArgumentNullException("data"); } if (data.Length < xLength * yLength * 2) { throw new ArgumentOutOfRangeException("data.Length", data.Length, "must be at least as large as 'xLength * yLength * 2' parameter"); } if (Fourier.IsPowerOf2(xLength) == false) { throw new ArgumentOutOfRangeException("xLength", xLength, "must be a power of 2"); } if (Fourier.IsPowerOf2(yLength) == false) { throw new ArgumentOutOfRangeException("yLength", yLength, "must be a power of 2"); } int xInc = 1; int yInc = xLength; if (xLength > 1) { Fourier.SyncLookupTableLength(xLength); for (int y = 0; y < yLength; y++) { int xStart = y * yInc; Fourier.LinearFFT_Quick(data, xStart, xInc, xLength, direction); } } if (yLength > 1) { Fourier.SyncLookupTableLength(yLength); for (int x = 0; x < xLength; x++) { int yStart = x * xInc; Fourier.LinearFFT_Quick(data, yStart, yInc, yLength, direction); } } } } // Comments? Questions? Bugs? Tell Ben Houston at [email protected] // Version: May 4, 2002 /// <summary> /// <p>The direction of the fourier transform.</p> /// </summary> public enum FourierDirection : int { /// <summary> /// Forward direction. Usually in reference to moving from temporal /// representation to frequency representation /// </summary> Forward = 1, /// <summary> /// Backward direction. Usually in reference to moving from frequency /// representation to temporal representation /// </summary> Backward = -1, } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using NBitcoin.BouncyCastle.Math; using NBitcoin.DataEncoders; using NBitcoin.Networks; using Stratis.Bitcoin.Networks; using Stratis.Bitcoin.Networks.Deployments; using Stratis.Bitcoin.Tests.Common; using Xunit; namespace NBitcoin.Tests { public class NetworkTests { private readonly Network networkMain; private readonly Network stratisMain; private readonly Network stratisTest; private readonly Network stratisRegTest; public NetworkTests() { this.networkMain = KnownNetworks.Main; this.stratisMain = KnownNetworks.StratisMain; this.stratisTest = KnownNetworks.StratisTest; this.stratisRegTest = KnownNetworks.StratisRegTest; } [Fact] [Trait("UnitTest", "UnitTest")] public void CanGetNetworkFromName() { Network bitcoinMain = KnownNetworks.Main; Network bitcoinTestnet = KnownNetworks.TestNet; Network bitcoinRegtest = KnownNetworks.RegTest; Assert.Equal(NetworkRegistration.GetNetwork("main"), bitcoinMain); Assert.Equal(NetworkRegistration.GetNetwork("mainnet"), bitcoinMain); Assert.Equal(NetworkRegistration.GetNetwork("MainNet"), bitcoinMain); Assert.Equal(NetworkRegistration.GetNetwork("test"), bitcoinTestnet); Assert.Equal(NetworkRegistration.GetNetwork("testnet"), bitcoinTestnet); Assert.Equal(NetworkRegistration.GetNetwork("regtest"), bitcoinRegtest); Assert.Equal(NetworkRegistration.GetNetwork("reg"), bitcoinRegtest); Assert.Equal(NetworkRegistration.GetNetwork("stratismain"), this.stratisMain); Assert.Equal(NetworkRegistration.GetNetwork("StratisMain"), this.stratisMain); Assert.Equal(NetworkRegistration.GetNetwork("StratisTest"), this.stratisTest); Assert.Equal(NetworkRegistration.GetNetwork("stratistest"), this.stratisTest); Assert.Equal(NetworkRegistration.GetNetwork("StratisRegTest"), this.stratisRegTest); Assert.Equal(NetworkRegistration.GetNetwork("stratisregtest"), this.stratisRegTest); Assert.Null(NetworkRegistration.GetNetwork("invalid")); } [Fact] [Trait("UnitTest", "UnitTest")] public void RegisterNetworkTwiceReturnsSameNetwork() { Network main = KnownNetworks.Main; Network reregistered = NetworkRegistration.Register(main); Assert.Equal(main, reregistered); } [Fact] [Trait("UnitTest", "UnitTest")] public void ReadMagicByteWithFirstByteDuplicated() { List<byte> bytes = this.networkMain.MagicBytes.ToList(); bytes.Insert(0, bytes.First()); using (var memstrema = new MemoryStream(bytes.ToArray())) { bool found = this.networkMain.ReadMagic(memstrema, new CancellationToken()); Assert.True(found); } } [Fact] [Trait("UnitTest", "UnitTest")] public void BitcoinMainnetIsInitializedCorrectly() { Assert.Equal(15, this.networkMain.Checkpoints.Count); Assert.Equal(6, this.networkMain.DNSSeeds.Count); Assert.Equal(512, this.networkMain.SeedNodes.Count); Assert.Equal(NetworkRegistration.GetNetwork("main"), this.networkMain); Assert.Equal(NetworkRegistration.GetNetwork("mainnet"), this.networkMain); Assert.Equal("Main", this.networkMain.Name); Assert.Equal(BitcoinMain.BitcoinRootFolderName, this.networkMain.RootFolderName); Assert.Equal(BitcoinMain.BitcoinDefaultConfigFilename, this.networkMain.DefaultConfigFilename); Assert.Equal(0xD9B4BEF9, this.networkMain.Magic); Assert.Equal(8333, this.networkMain.DefaultPort); Assert.Equal(8332, this.networkMain.RPCPort); Assert.Equal(BitcoinMain.BitcoinMaxTimeOffsetSeconds, this.networkMain.MaxTimeOffsetSeconds); Assert.Equal(BitcoinMain.BitcoinDefaultMaxTipAgeInSeconds, this.networkMain.MaxTipAge); Assert.Equal(1000, this.networkMain.MinTxFee); Assert.Equal(20000, this.networkMain.FallbackFee); Assert.Equal(1000, this.networkMain.MinRelayTxFee); Assert.Equal("BTC", this.networkMain.CoinTicker); Assert.Equal(2, this.networkMain.Bech32Encoders.Length); Assert.Equal(new Bech32Encoder("bc").ToString(), this.networkMain.Bech32Encoders[(int)Bech32Type.WITNESS_PUBKEY_ADDRESS].ToString()); Assert.Equal(new Bech32Encoder("bc").ToString(), this.networkMain.Bech32Encoders[(int)Bech32Type.WITNESS_SCRIPT_ADDRESS].ToString()); Assert.Equal(12, this.networkMain.Base58Prefixes.Length); Assert.Equal(new byte[] { 0 }, this.networkMain.Base58Prefixes[(int)Base58Type.PUBKEY_ADDRESS]); Assert.Equal(new byte[] { (5) }, this.networkMain.Base58Prefixes[(int)Base58Type.SCRIPT_ADDRESS]); Assert.Equal(new byte[] { (128) }, this.networkMain.Base58Prefixes[(int)Base58Type.SECRET_KEY]); Assert.Equal(new byte[] { 0x01, 0x42 }, this.networkMain.Base58Prefixes[(int)Base58Type.ENCRYPTED_SECRET_KEY_NO_EC]); Assert.Equal(new byte[] { 0x01, 0x43 }, this.networkMain.Base58Prefixes[(int)Base58Type.ENCRYPTED_SECRET_KEY_EC]); Assert.Equal(new byte[] { (0x04), (0x88), (0xB2), (0x1E) }, this.networkMain.Base58Prefixes[(int)Base58Type.EXT_PUBLIC_KEY]); Assert.Equal(new byte[] { (0x04), (0x88), (0xAD), (0xE4) }, this.networkMain.Base58Prefixes[(int)Base58Type.EXT_SECRET_KEY]); Assert.Equal(new byte[] { 0x2C, 0xE9, 0xB3, 0xE1, 0xFF, 0x39, 0xE2 }, this.networkMain.Base58Prefixes[(int)Base58Type.PASSPHRASE_CODE]); Assert.Equal(new byte[] { 0x64, 0x3B, 0xF6, 0xA8, 0x9A }, this.networkMain.Base58Prefixes[(int)Base58Type.CONFIRMATION_CODE]); Assert.Equal(new byte[] { 0x2a }, this.networkMain.Base58Prefixes[(int)Base58Type.STEALTH_ADDRESS]); Assert.Equal(new byte[] { 23 }, this.networkMain.Base58Prefixes[(int)Base58Type.ASSET_ID]); Assert.Equal(new byte[] { 0x13 }, this.networkMain.Base58Prefixes[(int)Base58Type.COLORED_ADDRESS]); Assert.Equal(210000, this.networkMain.Consensus.SubsidyHalvingInterval); Assert.Equal(750, this.networkMain.Consensus.MajorityEnforceBlockUpgrade); Assert.Equal(950, this.networkMain.Consensus.MajorityRejectBlockOutdated); Assert.Equal(1000, this.networkMain.Consensus.MajorityWindow); Assert.Equal(227931, this.networkMain.Consensus.BuriedDeployments[BuriedDeployments.BIP34]); Assert.Equal(388381, this.networkMain.Consensus.BuriedDeployments[BuriedDeployments.BIP65]); Assert.Equal(363725, this.networkMain.Consensus.BuriedDeployments[BuriedDeployments.BIP66]); Assert.Equal(new uint256("0x000000000000024b89b42a942fe0d9fea3bb44ab7bd1b19115dd6a759c0808b8"), this.networkMain.Consensus.BIP34Hash); Assert.Equal(new Target(new uint256("00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), this.networkMain.Consensus.PowLimit); Assert.Equal(new uint256("0x0000000000000000000000000000000000000000002cb971dd56d1c583c20f90"), this.networkMain.Consensus.MinimumChainWork); Assert.Equal(TimeSpan.FromSeconds(14 * 24 * 60 * 60), this.networkMain.Consensus.PowTargetTimespan); Assert.Equal(TimeSpan.FromSeconds(10 * 60), this.networkMain.Consensus.PowTargetSpacing); Assert.False(this.networkMain.Consensus.PowAllowMinDifficultyBlocks); Assert.False(this.networkMain.Consensus.PowNoRetargeting); Assert.Equal(1916, this.networkMain.Consensus.RuleChangeActivationThreshold); Assert.Equal(2016, this.networkMain.Consensus.MinerConfirmationWindow); Assert.Equal(28, this.networkMain.Consensus.BIP9Deployments[BitcoinBIP9Deployments.TestDummy].Bit); Assert.Equal(Utils.UnixTimeToDateTime(1199145601), this.networkMain.Consensus.BIP9Deployments[BitcoinBIP9Deployments.TestDummy].StartTime); Assert.Equal(Utils.UnixTimeToDateTime(1230767999), this.networkMain.Consensus.BIP9Deployments[BitcoinBIP9Deployments.TestDummy].Timeout); Assert.Equal(0, this.networkMain.Consensus.BIP9Deployments[BitcoinBIP9Deployments.CSV].Bit); Assert.Equal(Utils.UnixTimeToDateTime(1462060800), this.networkMain.Consensus.BIP9Deployments[BitcoinBIP9Deployments.CSV].StartTime); Assert.Equal(Utils.UnixTimeToDateTime(1493596800), this.networkMain.Consensus.BIP9Deployments[BitcoinBIP9Deployments.CSV].Timeout); Assert.Equal(1, this.networkMain.Consensus.BIP9Deployments[BitcoinBIP9Deployments.Segwit].Bit); Assert.Equal(Utils.UnixTimeToDateTime(1479168000), this.networkMain.Consensus.BIP9Deployments[BitcoinBIP9Deployments.Segwit].StartTime); Assert.Equal(Utils.UnixTimeToDateTime(1510704000), this.networkMain.Consensus.BIP9Deployments[BitcoinBIP9Deployments.Segwit].Timeout); Assert.Equal(0, this.networkMain.Consensus.CoinType); Assert.False(this.networkMain.Consensus.IsProofOfStake); Assert.Equal(new uint256("0x000000000000000000174f783cc20c1415f90c4d17c9a5bcd06ba67207c9bc80"), this.networkMain.Consensus.DefaultAssumeValid); Assert.Equal(100, this.networkMain.Consensus.CoinbaseMaturity); Assert.Equal(0, this.networkMain.Consensus.PremineReward); Assert.Equal(0, this.networkMain.Consensus.PremineHeight); Assert.Equal(Money.Coins(50), this.networkMain.Consensus.ProofOfWorkReward); Assert.Equal(Money.Zero, this.networkMain.Consensus.ProofOfStakeReward); Assert.Equal((uint)0, this.networkMain.Consensus.MaxReorgLength); Assert.Equal(21000000 * Money.COIN, this.networkMain.Consensus.MaxMoney); Block genesis = this.networkMain.GetGenesis(); Assert.Equal(uint256.Parse("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"), genesis.GetHash()); Assert.Equal(uint256.Parse("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"), genesis.Header.HashMerkleRoot); } [Fact] [Trait("UnitTest", "UnitTest")] public void BitcoinTestnetIsInitializedCorrectly() { Network network = KnownNetworks.TestNet; Assert.Equal(12, network.Checkpoints.Count); Assert.Equal(3, network.DNSSeeds.Count); Assert.Empty(network.SeedNodes); Assert.Equal("TestNet", network.Name); Assert.Equal(BitcoinMain.BitcoinRootFolderName, network.RootFolderName); Assert.Equal(BitcoinMain.BitcoinDefaultConfigFilename, network.DefaultConfigFilename); Assert.Equal(0x0709110B.ToString(), network.Magic.ToString()); Assert.Equal(18333, network.DefaultPort); Assert.Equal(18332, network.RPCPort); Assert.Equal(BitcoinMain.BitcoinMaxTimeOffsetSeconds, network.MaxTimeOffsetSeconds); Assert.Equal(BitcoinMain.BitcoinDefaultMaxTipAgeInSeconds, network.MaxTipAge); Assert.Equal(1000, network.MinTxFee); Assert.Equal(20000, network.FallbackFee); Assert.Equal(1000, network.MinRelayTxFee); Assert.Equal("TBTC", network.CoinTicker); Assert.Equal(2, network.Bech32Encoders.Length); Assert.Equal(new Bech32Encoder("tb").ToString(), network.Bech32Encoders[(int)Bech32Type.WITNESS_PUBKEY_ADDRESS].ToString()); Assert.Equal(new Bech32Encoder("tb").ToString(), network.Bech32Encoders[(int)Bech32Type.WITNESS_SCRIPT_ADDRESS].ToString()); Assert.Equal(12, network.Base58Prefixes.Length); Assert.Equal(new byte[] { 111 }, network.Base58Prefixes[(int)Base58Type.PUBKEY_ADDRESS]); Assert.Equal(new byte[] { (196) }, network.Base58Prefixes[(int)Base58Type.SCRIPT_ADDRESS]); Assert.Equal(new byte[] { (239) }, network.Base58Prefixes[(int)Base58Type.SECRET_KEY]); Assert.Equal(new byte[] { 0x01, 0x42 }, network.Base58Prefixes[(int)Base58Type.ENCRYPTED_SECRET_KEY_NO_EC]); Assert.Equal(new byte[] { 0x01, 0x43 }, network.Base58Prefixes[(int)Base58Type.ENCRYPTED_SECRET_KEY_EC]); Assert.Equal(new byte[] { (0x04), (0x35), (0x87), (0xCF) }, network.Base58Prefixes[(int)Base58Type.EXT_PUBLIC_KEY]); Assert.Equal(new byte[] { (0x04), (0x35), (0x83), (0x94) }, network.Base58Prefixes[(int)Base58Type.EXT_SECRET_KEY]); Assert.Equal(new byte[] { 0x2C, 0xE9, 0xB3, 0xE1, 0xFF, 0x39, 0xE2 }, network.Base58Prefixes[(int)Base58Type.PASSPHRASE_CODE]); Assert.Equal(new byte[] { 0x64, 0x3B, 0xF6, 0xA8, 0x9A }, network.Base58Prefixes[(int)Base58Type.CONFIRMATION_CODE]); Assert.Equal(new byte[] { 0x2b }, network.Base58Prefixes[(int)Base58Type.STEALTH_ADDRESS]); Assert.Equal(new byte[] { 115 }, network.Base58Prefixes[(int)Base58Type.ASSET_ID]); Assert.Equal(new byte[] { 0x13 }, network.Base58Prefixes[(int)Base58Type.COLORED_ADDRESS]); Assert.Equal(210000, network.Consensus.SubsidyHalvingInterval); Assert.Equal(51, network.Consensus.MajorityEnforceBlockUpgrade); Assert.Equal(75, network.Consensus.MajorityRejectBlockOutdated); Assert.Equal(100, network.Consensus.MajorityWindow); Assert.Equal(21111, network.Consensus.BuriedDeployments[BuriedDeployments.BIP34]); Assert.Equal(581885, network.Consensus.BuriedDeployments[BuriedDeployments.BIP65]); Assert.Equal(330776, network.Consensus.BuriedDeployments[BuriedDeployments.BIP66]); Assert.Equal(new uint256("0x0000000023b3a96d3484e5abb3755c413e7d41500f8e2a5c3f0dd01299cd8ef8"), network.Consensus.BIP34Hash); Assert.Equal(new Target(new uint256("00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), network.Consensus.PowLimit); Assert.Equal(new uint256("0x0000000000000000000000000000000000000000000000198b4def2baa9338d6"), network.Consensus.MinimumChainWork); Assert.Equal(TimeSpan.FromSeconds(14 * 24 * 60 * 60), network.Consensus.PowTargetTimespan); Assert.Equal(TimeSpan.FromSeconds(10 * 60), network.Consensus.PowTargetSpacing); Assert.True(network.Consensus.PowAllowMinDifficultyBlocks); Assert.False(network.Consensus.PowNoRetargeting); Assert.Equal(1512, network.Consensus.RuleChangeActivationThreshold); Assert.Equal(2016, network.Consensus.MinerConfirmationWindow); Assert.Equal(28, network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.TestDummy].Bit); Assert.Equal(Utils.UnixTimeToDateTime(1199145601), network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.TestDummy].StartTime); Assert.Equal(Utils.UnixTimeToDateTime(1230767999), network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.TestDummy].Timeout); Assert.Equal(0, network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.CSV].Bit); Assert.Equal(Utils.UnixTimeToDateTime(1456790400), network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.CSV].StartTime); Assert.Equal(Utils.UnixTimeToDateTime(1493596800), network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.CSV].Timeout); Assert.Equal(1, network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.Segwit].Bit); Assert.Equal(Utils.UnixTimeToDateTime(1462060800), network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.Segwit].StartTime); Assert.Equal(Utils.UnixTimeToDateTime(1493596800), network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.Segwit].Timeout); Assert.Equal(1, network.Consensus.CoinType); Assert.False(network.Consensus.IsProofOfStake); Assert.Equal(new uint256("0x000000000000015682a21fc3b1e5420435678cba99cace2b07fe69b668467651"), network.Consensus.DefaultAssumeValid); Assert.Equal(100, network.Consensus.CoinbaseMaturity); Assert.Equal(0, network.Consensus.PremineReward); Assert.Equal(0, network.Consensus.PremineHeight); Assert.Equal(Money.Coins(50), network.Consensus.ProofOfWorkReward); Assert.Equal(Money.Zero, network.Consensus.ProofOfStakeReward); Assert.Equal((uint)0, network.Consensus.MaxReorgLength); Assert.Equal(21000000 * Money.COIN, network.Consensus.MaxMoney); Block genesis = network.GetGenesis(); Assert.Equal(uint256.Parse("0x000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943"), genesis.GetHash()); Assert.Equal(uint256.Parse("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"), genesis.Header.HashMerkleRoot); } [Fact] [Trait("UnitTest", "UnitTest")] public void BitcoinRegTestIsInitializedCorrectly() { Network network = KnownNetworks.RegTest; Assert.Empty(network.Checkpoints); Assert.Empty(network.DNSSeeds); Assert.Empty(network.SeedNodes); Assert.Equal("RegTest", network.Name); Assert.Equal(BitcoinMain.BitcoinRootFolderName, network.RootFolderName); Assert.Equal(BitcoinMain.BitcoinDefaultConfigFilename, network.DefaultConfigFilename); Assert.Equal(0xDAB5BFFA, network.Magic); Assert.Equal(18444, network.DefaultPort); Assert.Equal(18332, network.RPCPort); Assert.Equal(BitcoinMain.BitcoinMaxTimeOffsetSeconds, network.MaxTimeOffsetSeconds); Assert.Equal(BitcoinMain.BitcoinDefaultMaxTipAgeInSeconds, network.MaxTipAge); Assert.Equal(1000, network.MinTxFee); Assert.Equal(20000, network.FallbackFee); Assert.Equal(1000, network.MinRelayTxFee); Assert.Equal("TBTC", network.CoinTicker); Assert.Equal(2, network.Bech32Encoders.Length); Assert.Equal(new Bech32Encoder("tb").ToString(), network.Bech32Encoders[(int)Bech32Type.WITNESS_PUBKEY_ADDRESS].ToString()); Assert.Equal(new Bech32Encoder("tb").ToString(), network.Bech32Encoders[(int)Bech32Type.WITNESS_SCRIPT_ADDRESS].ToString()); Assert.Equal(12, network.Base58Prefixes.Length); Assert.Equal(new byte[] { 111 }, network.Base58Prefixes[(int)Base58Type.PUBKEY_ADDRESS]); Assert.Equal(new byte[] { (196) }, network.Base58Prefixes[(int)Base58Type.SCRIPT_ADDRESS]); Assert.Equal(new byte[] { (239) }, network.Base58Prefixes[(int)Base58Type.SECRET_KEY]); Assert.Equal(new byte[] { 0x01, 0x42 }, network.Base58Prefixes[(int)Base58Type.ENCRYPTED_SECRET_KEY_NO_EC]); Assert.Equal(new byte[] { 0x01, 0x43 }, network.Base58Prefixes[(int)Base58Type.ENCRYPTED_SECRET_KEY_EC]); Assert.Equal(new byte[] { (0x04), (0x35), (0x87), (0xCF) }, network.Base58Prefixes[(int)Base58Type.EXT_PUBLIC_KEY]); Assert.Equal(new byte[] { (0x04), (0x35), (0x83), (0x94) }, network.Base58Prefixes[(int)Base58Type.EXT_SECRET_KEY]); Assert.Equal(new byte[] { 0x2C, 0xE9, 0xB3, 0xE1, 0xFF, 0x39, 0xE2 }, network.Base58Prefixes[(int)Base58Type.PASSPHRASE_CODE]); Assert.Equal(new byte[] { 0x64, 0x3B, 0xF6, 0xA8, 0x9A }, network.Base58Prefixes[(int)Base58Type.CONFIRMATION_CODE]); Assert.Equal(new byte[] { 0x2b }, network.Base58Prefixes[(int)Base58Type.STEALTH_ADDRESS]); Assert.Equal(new byte[] { 115 }, network.Base58Prefixes[(int)Base58Type.ASSET_ID]); Assert.Equal(new byte[] { 0x13 }, network.Base58Prefixes[(int)Base58Type.COLORED_ADDRESS]); Assert.Equal(150, network.Consensus.SubsidyHalvingInterval); Assert.Equal(750, network.Consensus.MajorityEnforceBlockUpgrade); Assert.Equal(950, network.Consensus.MajorityRejectBlockOutdated); Assert.Equal(1000, network.Consensus.MajorityWindow); Assert.Equal(100000000, network.Consensus.BuriedDeployments[BuriedDeployments.BIP34]); Assert.Equal(100000000, network.Consensus.BuriedDeployments[BuriedDeployments.BIP65]); Assert.Equal(100000000, network.Consensus.BuriedDeployments[BuriedDeployments.BIP66]); Assert.Equal(new uint256(), network.Consensus.BIP34Hash); Assert.Equal(new Target(new uint256("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), network.Consensus.PowLimit); Assert.Equal(uint256.Zero, network.Consensus.MinimumChainWork); Assert.Equal(TimeSpan.FromSeconds(14 * 24 * 60 * 60), network.Consensus.PowTargetTimespan); Assert.Equal(TimeSpan.FromSeconds(10 * 60), network.Consensus.PowTargetSpacing); Assert.True(network.Consensus.PowAllowMinDifficultyBlocks); Assert.True(network.Consensus.PowNoRetargeting); Assert.Equal(108, network.Consensus.RuleChangeActivationThreshold); Assert.Equal(144, network.Consensus.MinerConfirmationWindow); Assert.Equal(28, network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.TestDummy].Bit); Assert.Equal(Utils.UnixTimeToDateTime(0), network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.TestDummy].StartTime); Assert.Equal(Utils.UnixTimeToDateTime(999999999), network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.TestDummy].Timeout); Assert.Equal(0, network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.CSV].Bit); Assert.Equal(Utils.UnixTimeToDateTime(0), network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.CSV].StartTime); Assert.Equal(Utils.UnixTimeToDateTime(999999999), network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.CSV].Timeout); Assert.Equal(1, network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.Segwit].Bit); Assert.Equal(Utils.UnixTimeToDateTime(BIP9DeploymentsParameters.AlwaysActive), network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.Segwit].StartTime); Assert.Equal(Utils.UnixTimeToDateTime(999999999), network.Consensus.BIP9Deployments[BitcoinBIP9Deployments.Segwit].Timeout); Assert.Equal(0, network.Consensus.CoinType); Assert.False(network.Consensus.IsProofOfStake); Assert.Null(network.Consensus.DefaultAssumeValid); Assert.Equal(100, network.Consensus.CoinbaseMaturity); Assert.Equal(0, network.Consensus.PremineReward); Assert.Equal(0, network.Consensus.PremineHeight); Assert.Equal(Money.Coins(50), network.Consensus.ProofOfWorkReward); Assert.Equal(Money.Zero, network.Consensus.ProofOfStakeReward); Assert.Equal((uint)0, network.Consensus.MaxReorgLength); Assert.Equal(21000000 * Money.COIN, network.Consensus.MaxMoney); Block genesis = network.GetGenesis(); Assert.Equal(uint256.Parse("0x0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206"), genesis.GetHash()); Assert.Equal(uint256.Parse("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"), genesis.Header.HashMerkleRoot); } [Fact] public void StratisMainIsInitializedCorrectly() { Network network = this.stratisMain; Assert.Equal(29, network.Checkpoints.Count); Assert.Equal(4, network.DNSSeeds.Count); Assert.Equal(5, network.SeedNodes.Count); Assert.Equal("StratisMain", network.Name); Assert.Equal(StratisMain.StratisRootFolderName, network.RootFolderName); Assert.Equal(StratisMain.StratisDefaultConfigFilename, network.DefaultConfigFilename); Assert.Equal(0x5223570.ToString(), network.Magic.ToString()); Assert.Equal(16178, network.DefaultPort); Assert.Equal(16174, network.RPCPort); Assert.Equal(StratisMain.StratisMaxTimeOffsetSeconds, network.MaxTimeOffsetSeconds); Assert.Equal(StratisMain.StratisDefaultMaxTipAgeInSeconds, network.MaxTipAge); Assert.Equal(10000, network.MinTxFee); Assert.Equal(10000, network.FallbackFee); Assert.Equal(10000, network.MinRelayTxFee); Assert.Equal("STRAT", network.CoinTicker); Assert.Equal(2, network.Bech32Encoders.Length); Assert.Equal(new Bech32Encoder("bc").ToString(), network.Bech32Encoders[(int)Bech32Type.WITNESS_PUBKEY_ADDRESS].ToString()); Assert.Equal(new Bech32Encoder("bc").ToString(), network.Bech32Encoders[(int)Bech32Type.WITNESS_SCRIPT_ADDRESS].ToString()); Assert.Equal(12, network.Base58Prefixes.Length); Assert.Equal(new byte[] { (63) }, network.Base58Prefixes[(int)Base58Type.PUBKEY_ADDRESS]); Assert.Equal(new byte[] { (125) }, network.Base58Prefixes[(int)Base58Type.SCRIPT_ADDRESS]); Assert.Equal(new byte[] { (63 + 128) }, network.Base58Prefixes[(int)Base58Type.SECRET_KEY]); Assert.Equal(new byte[] { 0x01, 0x42 }, network.Base58Prefixes[(int)Base58Type.ENCRYPTED_SECRET_KEY_NO_EC]); Assert.Equal(new byte[] { 0x01, 0x43 }, network.Base58Prefixes[(int)Base58Type.ENCRYPTED_SECRET_KEY_EC]); Assert.Equal(new byte[] { (0x04), (0x88), (0xB2), (0x1E) }, network.Base58Prefixes[(int)Base58Type.EXT_PUBLIC_KEY]); Assert.Equal(new byte[] { (0x04), (0x88), (0xAD), (0xE4) }, network.Base58Prefixes[(int)Base58Type.EXT_SECRET_KEY]); Assert.Equal(new byte[] { 0x2C, 0xE9, 0xB3, 0xE1, 0xFF, 0x39, 0xE2 }, network.Base58Prefixes[(int)Base58Type.PASSPHRASE_CODE]); Assert.Equal(new byte[] { 0x64, 0x3B, 0xF6, 0xA8, 0x9A }, network.Base58Prefixes[(int)Base58Type.CONFIRMATION_CODE]); Assert.Equal(new byte[] { 0x2a }, network.Base58Prefixes[(int)Base58Type.STEALTH_ADDRESS]); Assert.Equal(new byte[] { 23 }, network.Base58Prefixes[(int)Base58Type.ASSET_ID]); Assert.Equal(new byte[] { 0x13 }, network.Base58Prefixes[(int)Base58Type.COLORED_ADDRESS]); Assert.Equal(210000, network.Consensus.SubsidyHalvingInterval); Assert.Equal(750, network.Consensus.MajorityEnforceBlockUpgrade); Assert.Equal(950, network.Consensus.MajorityRejectBlockOutdated); Assert.Equal(1000, network.Consensus.MajorityWindow); Assert.Equal(0, network.Consensus.BuriedDeployments[BuriedDeployments.BIP34]); Assert.Equal(0, network.Consensus.BuriedDeployments[BuriedDeployments.BIP65]); Assert.Equal(0, network.Consensus.BuriedDeployments[BuriedDeployments.BIP66]); Assert.Equal(new uint256("0x000000000000024b89b42a942fe0d9fea3bb44ab7bd1b19115dd6a759c0808b8"), network.Consensus.BIP34Hash); Assert.Equal(new Target(new uint256("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), network.Consensus.PowLimit); Assert.Null(network.Consensus.MinimumChainWork); Assert.Equal(TimeSpan.FromSeconds(14 * 24 * 60 * 60), network.Consensus.PowTargetTimespan); Assert.Equal(TimeSpan.FromSeconds(10 * 60), network.Consensus.PowTargetSpacing); Assert.False(network.Consensus.PowAllowMinDifficultyBlocks); Assert.False(network.Consensus.PowNoRetargeting); Assert.Equal(1916, network.Consensus.RuleChangeActivationThreshold); Assert.Equal(2016, network.Consensus.MinerConfirmationWindow); Assert.Null(network.Consensus.BIP9Deployments[StratisBIP9Deployments.TestDummy]); Assert.Equal(12500, network.Consensus.LastPOWBlock); Assert.True(network.Consensus.IsProofOfStake); Assert.Equal(105, network.Consensus.CoinType); Assert.Equal(new BigInteger(uint256.Parse("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").ToBytes(false)), network.Consensus.ProofOfStakeLimit); Assert.Equal(new BigInteger(uint256.Parse("000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffff").ToBytes(false)), network.Consensus.ProofOfStakeLimitV2); Assert.Equal(new uint256("0x55a8205ae4bbf18f4d238c43f43005bd66e0b1f679b39e2c5c62cf6903693a5e"), network.Consensus.DefaultAssumeValid); Assert.Equal(50, network.Consensus.CoinbaseMaturity); Assert.Equal(Money.Coins(98000000), network.Consensus.PremineReward); Assert.Equal(2, network.Consensus.PremineHeight); Assert.Equal(Money.Coins(4), network.Consensus.ProofOfWorkReward); Assert.Equal(Money.Coins(1), network.Consensus.ProofOfStakeReward); Assert.Equal((uint)500, network.Consensus.MaxReorgLength); Assert.Equal(long.MaxValue, network.Consensus.MaxMoney); Block genesis = network.GetGenesis(); Assert.Equal(uint256.Parse("0x0000066e91e46e5a264d42c89e1204963b2ee6be230b443e9159020539d972af"), genesis.GetHash()); Assert.Equal(uint256.Parse("0x65a26bc20b0351aebf05829daefa8f7db2f800623439f3c114257c91447f1518"), genesis.Header.HashMerkleRoot); } [Fact] [Trait("UnitTest", "UnitTest")] public void StratisTestnetIsInitializedCorrectly() { Network network = this.stratisTest; Assert.Equal(11, network.Checkpoints.Count); Assert.Equal(4, network.DNSSeeds.Count); Assert.Equal(4, network.SeedNodes.Count); Assert.Equal("StratisTest", network.Name); Assert.Equal(StratisMain.StratisRootFolderName, network.RootFolderName); Assert.Equal(StratisMain.StratisDefaultConfigFilename, network.DefaultConfigFilename); Assert.Equal(0x11213171.ToString(), network.Magic.ToString()); Assert.Equal(26178, network.DefaultPort); Assert.Equal(26174, network.RPCPort); Assert.Equal(StratisMain.StratisMaxTimeOffsetSeconds, network.MaxTimeOffsetSeconds); Assert.Equal(StratisMain.StratisDefaultMaxTipAgeInSeconds, network.MaxTipAge); Assert.Equal(10000, network.MinTxFee); Assert.Equal(10000, network.FallbackFee); Assert.Equal(10000, network.MinRelayTxFee); Assert.Equal("TSTRAT", network.CoinTicker); Assert.Equal(2, network.Bech32Encoders.Length); Assert.Equal(new Bech32Encoder("bc").ToString(), network.Bech32Encoders[(int)Bech32Type.WITNESS_PUBKEY_ADDRESS].ToString()); Assert.Equal(new Bech32Encoder("bc").ToString(), network.Bech32Encoders[(int)Bech32Type.WITNESS_SCRIPT_ADDRESS].ToString()); Assert.Equal(12, network.Base58Prefixes.Length); Assert.Equal(new byte[] { (65) }, network.Base58Prefixes[(int)Base58Type.PUBKEY_ADDRESS]); Assert.Equal(new byte[] { (196) }, network.Base58Prefixes[(int)Base58Type.SCRIPT_ADDRESS]); Assert.Equal(new byte[] { (65 + 128) }, network.Base58Prefixes[(int)Base58Type.SECRET_KEY]); Assert.Equal(new byte[] { 0x01, 0x42 }, network.Base58Prefixes[(int)Base58Type.ENCRYPTED_SECRET_KEY_NO_EC]); Assert.Equal(new byte[] { 0x01, 0x43 }, network.Base58Prefixes[(int)Base58Type.ENCRYPTED_SECRET_KEY_EC]); Assert.Equal(new byte[] { (0x04), (0x88), (0xB2), (0x1E) }, network.Base58Prefixes[(int)Base58Type.EXT_PUBLIC_KEY]); Assert.Equal(new byte[] { (0x04), (0x88), (0xAD), (0xE4) }, network.Base58Prefixes[(int)Base58Type.EXT_SECRET_KEY]); Assert.Equal(new byte[] { 0x2C, 0xE9, 0xB3, 0xE1, 0xFF, 0x39, 0xE2 }, network.Base58Prefixes[(int)Base58Type.PASSPHRASE_CODE]); Assert.Equal(new byte[] { 0x64, 0x3B, 0xF6, 0xA8, 0x9A }, network.Base58Prefixes[(int)Base58Type.CONFIRMATION_CODE]); Assert.Equal(new byte[] { 0x2a }, network.Base58Prefixes[(int)Base58Type.STEALTH_ADDRESS]); Assert.Equal(new byte[] { 23 }, network.Base58Prefixes[(int)Base58Type.ASSET_ID]); Assert.Equal(new byte[] { 0x13 }, network.Base58Prefixes[(int)Base58Type.COLORED_ADDRESS]); Assert.Equal(210000, network.Consensus.SubsidyHalvingInterval); Assert.Equal(750, network.Consensus.MajorityEnforceBlockUpgrade); Assert.Equal(950, network.Consensus.MajorityRejectBlockOutdated); Assert.Equal(1000, network.Consensus.MajorityWindow); Assert.Equal(0, network.Consensus.BuriedDeployments[BuriedDeployments.BIP34]); Assert.Equal(0, network.Consensus.BuriedDeployments[BuriedDeployments.BIP65]); Assert.Equal(0, network.Consensus.BuriedDeployments[BuriedDeployments.BIP66]); Assert.Equal(new uint256("0x000000000000024b89b42a942fe0d9fea3bb44ab7bd1b19115dd6a759c0808b8"), network.Consensus.BIP34Hash); Assert.Equal(new Target(new uint256("0000ffff00000000000000000000000000000000000000000000000000000000")), network.Consensus.PowLimit); Assert.Null(network.Consensus.MinimumChainWork); Assert.Equal(TimeSpan.FromSeconds(14 * 24 * 60 * 60), network.Consensus.PowTargetTimespan); Assert.Equal(TimeSpan.FromSeconds(10 * 60), network.Consensus.PowTargetSpacing); Assert.False(network.Consensus.PowAllowMinDifficultyBlocks); Assert.False(network.Consensus.PowNoRetargeting); Assert.Equal(1916, network.Consensus.RuleChangeActivationThreshold); Assert.Equal(2016, network.Consensus.MinerConfirmationWindow); Assert.Null(network.Consensus.BIP9Deployments[StratisBIP9Deployments.TestDummy]); Assert.Equal(12500, network.Consensus.LastPOWBlock); Assert.True(network.Consensus.IsProofOfStake); Assert.Equal(105, network.Consensus.CoinType); Assert.Equal(new BigInteger(uint256.Parse("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").ToBytes(false)), network.Consensus.ProofOfStakeLimit); Assert.Equal(new BigInteger(uint256.Parse("000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffff").ToBytes(false)), network.Consensus.ProofOfStakeLimitV2); Assert.Equal(new uint256("0x98fa6ef0bca5b431f15fd79dc6f879dc45b83ed4b1bbe933a383ef438321958e"), network.Consensus.DefaultAssumeValid); Assert.Equal(10, network.Consensus.CoinbaseMaturity); Assert.Equal(Money.Coins(98000000), network.Consensus.PremineReward); Assert.Equal(2, network.Consensus.PremineHeight); Assert.Equal(Money.Coins(4), network.Consensus.ProofOfWorkReward); Assert.Equal(Money.Coins(1), network.Consensus.ProofOfStakeReward); Assert.Equal((uint)500, network.Consensus.MaxReorgLength); Assert.Equal(long.MaxValue, network.Consensus.MaxMoney); Block genesis = network.GetGenesis(); Assert.Equal(uint256.Parse("0x00000e246d7b73b88c9ab55f2e5e94d9e22d471def3df5ea448f5576b1d156b9"), genesis.GetHash()); Assert.Equal(uint256.Parse("0x65a26bc20b0351aebf05829daefa8f7db2f800623439f3c114257c91447f1518"), genesis.Header.HashMerkleRoot); } [Fact] [Trait("UnitTest", "UnitTest")] public void StratisRegTestIsInitializedCorrectly() { Network network = this.stratisRegTest; Assert.Empty(network.Checkpoints); Assert.Empty(network.DNSSeeds); Assert.Empty(network.SeedNodes); Assert.Equal("StratisRegTest", network.Name); Assert.Equal(StratisMain.StratisRootFolderName, network.RootFolderName); Assert.Equal(StratisMain.StratisDefaultConfigFilename, network.DefaultConfigFilename); Assert.Equal(0xefc0f2cd, network.Magic); Assert.Equal(18444, network.DefaultPort); Assert.Equal(18442, network.RPCPort); Assert.Equal(StratisMain.StratisMaxTimeOffsetSeconds, network.MaxTimeOffsetSeconds); Assert.Equal(StratisMain.StratisDefaultMaxTipAgeInSeconds, network.MaxTipAge); Assert.Equal(10000, network.MinTxFee); Assert.Equal(10000, network.FallbackFee); Assert.Equal(10000, network.MinRelayTxFee); Assert.Equal("TSTRAT", network.CoinTicker); Assert.Equal(2, network.Bech32Encoders.Length); Assert.Equal(new Bech32Encoder("bc").ToString(), network.Bech32Encoders[(int)Bech32Type.WITNESS_PUBKEY_ADDRESS].ToString()); Assert.Equal(new Bech32Encoder("bc").ToString(), network.Bech32Encoders[(int)Bech32Type.WITNESS_SCRIPT_ADDRESS].ToString()); Assert.Equal(12, network.Base58Prefixes.Length); Assert.Equal(new byte[] { (65) }, network.Base58Prefixes[(int)Base58Type.PUBKEY_ADDRESS]); Assert.Equal(new byte[] { (196) }, network.Base58Prefixes[(int)Base58Type.SCRIPT_ADDRESS]); Assert.Equal(new byte[] { (65 + 128) }, network.Base58Prefixes[(int)Base58Type.SECRET_KEY]); Assert.Equal(new byte[] { 0x01, 0x42 }, network.Base58Prefixes[(int)Base58Type.ENCRYPTED_SECRET_KEY_NO_EC]); Assert.Equal(new byte[] { 0x01, 0x43 }, network.Base58Prefixes[(int)Base58Type.ENCRYPTED_SECRET_KEY_EC]); Assert.Equal(new byte[] { (0x04), (0x88), (0xB2), (0x1E) }, network.Base58Prefixes[(int)Base58Type.EXT_PUBLIC_KEY]); Assert.Equal(new byte[] { (0x04), (0x88), (0xAD), (0xE4) }, network.Base58Prefixes[(int)Base58Type.EXT_SECRET_KEY]); Assert.Equal(new byte[] { 0x2C, 0xE9, 0xB3, 0xE1, 0xFF, 0x39, 0xE2 }, network.Base58Prefixes[(int)Base58Type.PASSPHRASE_CODE]); Assert.Equal(new byte[] { 0x64, 0x3B, 0xF6, 0xA8, 0x9A }, network.Base58Prefixes[(int)Base58Type.CONFIRMATION_CODE]); Assert.Equal(new byte[] { 0x2a }, network.Base58Prefixes[(int)Base58Type.STEALTH_ADDRESS]); Assert.Equal(new byte[] { 23 }, network.Base58Prefixes[(int)Base58Type.ASSET_ID]); Assert.Equal(new byte[] { 0x13 }, network.Base58Prefixes[(int)Base58Type.COLORED_ADDRESS]); Assert.Equal(210000, network.Consensus.SubsidyHalvingInterval); Assert.Equal(750, network.Consensus.MajorityEnforceBlockUpgrade); Assert.Equal(950, network.Consensus.MajorityRejectBlockOutdated); Assert.Equal(1000, network.Consensus.MajorityWindow); Assert.Equal(0, network.Consensus.BuriedDeployments[BuriedDeployments.BIP34]); Assert.Equal(0, network.Consensus.BuriedDeployments[BuriedDeployments.BIP65]); Assert.Equal(0, network.Consensus.BuriedDeployments[BuriedDeployments.BIP66]); Assert.Equal(new uint256("0x000000000000024b89b42a942fe0d9fea3bb44ab7bd1b19115dd6a759c0808b8"), network.Consensus.BIP34Hash); Assert.Equal(new Target(new uint256("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), network.Consensus.PowLimit); Assert.Null(network.Consensus.MinimumChainWork); Assert.Equal(TimeSpan.FromSeconds(14 * 24 * 60 * 60), network.Consensus.PowTargetTimespan); Assert.Equal(TimeSpan.FromSeconds(10 * 60), network.Consensus.PowTargetSpacing); Assert.True(network.Consensus.PowAllowMinDifficultyBlocks); Assert.True(network.Consensus.PowNoRetargeting); Assert.Equal(1916, network.Consensus.RuleChangeActivationThreshold); Assert.Equal(2016, network.Consensus.MinerConfirmationWindow); Assert.Null(network.Consensus.BIP9Deployments[StratisBIP9Deployments.TestDummy]); Assert.Equal(12500, network.Consensus.LastPOWBlock); Assert.True(network.Consensus.IsProofOfStake); Assert.Equal(105, network.Consensus.CoinType); Assert.Equal(new BigInteger(uint256.Parse("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").ToBytes(false)), network.Consensus.ProofOfStakeLimit); Assert.Equal(new BigInteger(uint256.Parse("000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffff").ToBytes(false)), network.Consensus.ProofOfStakeLimitV2); Assert.Null(network.Consensus.DefaultAssumeValid); Assert.Equal(10, network.Consensus.CoinbaseMaturity); Assert.Equal(Money.Coins(98000000), network.Consensus.PremineReward); Assert.Equal(2, network.Consensus.PremineHeight); Assert.Equal(Money.Coins(4), network.Consensus.ProofOfWorkReward); Assert.Equal(Money.Coins(1), network.Consensus.ProofOfStakeReward); Assert.Equal((uint)500, network.Consensus.MaxReorgLength); Assert.Equal(long.MaxValue, network.Consensus.MaxMoney); Block genesis = network.GetGenesis(); Assert.Equal(uint256.Parse("0x93925104d664314f581bc7ecb7b4bad07bcfabd1cfce4256dbd2faddcf53bd1f"), genesis.GetHash()); Assert.Equal(uint256.Parse("0x65a26bc20b0351aebf05829daefa8f7db2f800623439f3c114257c91447f1518"), genesis.Header.HashMerkleRoot); } [Fact] [Trait("UnitTest", "UnitTest")] public void MineGenesisBlockWithMissingParametersThrowsException() { Assert.Throws<ArgumentException>(() => Network.MineGenesisBlock(null, "some string", new Target(new uint256()), Money.Zero)); Assert.Throws<ArgumentException>(() => Network.MineGenesisBlock(new ConsensusFactory(), "", new Target(new uint256()), Money.Zero)); Assert.Throws<ArgumentException>(() => Network.MineGenesisBlock(new ConsensusFactory(), "some string", null, Money.Zero)); Assert.Throws<ArgumentException>(() => Network.MineGenesisBlock(new ConsensusFactory(), "some string", new Target(new uint256()), null)); } [Fact] [Trait("UnitTest", "UnitTest")] public void MineGenesisBlockWithLongCoinbaseTextThrowsException() { string coinbaseText100Long = "1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"; Assert.Throws<ArgumentException>(() => Network.MineGenesisBlock(new ConsensusFactory(), coinbaseText100Long, new Target(new uint256()), Money.Zero)); } } }
// 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.CodeDom.Compiler; using System.Collections.Generic; using System.Runtime.Serialization; using Microsoft.CodeAnalysis.Sarif.Readers; namespace Microsoft.CodeAnalysis.Sarif { /// <summary> /// The runtime environment of the analysis tool run. /// </summary> [DataContract] [GeneratedCode("Microsoft.Json.Schema.ToDotNet", "0.42.0.0")] public partial class Invocation : PropertyBagHolder, ISarifNode { public static IEqualityComparer<Invocation> ValueComparer => InvocationEqualityComparer.Instance; public bool ValueEquals(Invocation other) => ValueComparer.Equals(this, other); public int ValueGetHashCode() => ValueComparer.GetHashCode(this); /// <summary> /// Gets a value indicating the type of object implementing <see cref="ISarifNode" />. /// </summary> public SarifNodeKind SarifNodeKind { get { return SarifNodeKind.Invocation; } } /// <summary> /// The command line used to invoke the tool. /// </summary> [DataMember(Name = "commandLine", IsRequired = false, EmitDefaultValue = false)] public string CommandLine { get; set; } /// <summary> /// The contents of any response files specified on the tool's command line. /// </summary> [DataMember(Name = "responseFiles", IsRequired = false, EmitDefaultValue = false)] public IDictionary<string, string> ResponseFiles { get; set; } /// <summary> /// The date and time at which the run started. See "Date/time properties" in the SARIF spec for the required format. /// </summary> [DataMember(Name = "startTime", IsRequired = false, EmitDefaultValue = false)] public DateTime StartTime { get; set; } /// <summary> /// The date and time at which the run ended. See "Date/time properties" in the SARIF spec for the required format. /// </summary> [DataMember(Name = "endTime", IsRequired = false, EmitDefaultValue = false)] public DateTime EndTime { get; set; } /// <summary> /// The machine that hosted the analysis tool run. /// </summary> [DataMember(Name = "machine", IsRequired = false, EmitDefaultValue = false)] public string Machine { get; set; } /// <summary> /// The account that ran the analysis tool. /// </summary> [DataMember(Name = "account", IsRequired = false, EmitDefaultValue = false)] public string Account { get; set; } /// <summary> /// The process id for the analysis tool run. /// </summary> [DataMember(Name = "processId", IsRequired = false, EmitDefaultValue = false)] public int ProcessId { get; set; } /// <summary> /// The fully qualified path to the analysis tool. /// </summary> [DataMember(Name = "fileName", IsRequired = false, EmitDefaultValue = false)] public string FileName { get; set; } /// <summary> /// The working directory for the analysis rool run. /// </summary> [DataMember(Name = "workingDirectory", IsRequired = false, EmitDefaultValue = false)] public string WorkingDirectory { get; set; } /// <summary> /// The environment variables associated with the analysis tool process, expressed as key/value pairs. /// </summary> [DataMember(Name = "environmentVariables", IsRequired = false, EmitDefaultValue = false)] public IDictionary<string, string> EnvironmentVariables { get; set; } /// <summary> /// Key/value pairs that provide additional information about the run. /// </summary> [DataMember(Name = "properties", IsRequired = false, EmitDefaultValue = false)] internal override IDictionary<string, SerializedPropertyInfo> Properties { get; set; } /// <summary> /// Initializes a new instance of the <see cref="Invocation" /> class. /// </summary> public Invocation() { } /// <summary> /// Initializes a new instance of the <see cref="Invocation" /> class from the supplied values. /// </summary> /// <param name="commandLine"> /// An initialization value for the <see cref="P: CommandLine" /> property. /// </param> /// <param name="responseFiles"> /// An initialization value for the <see cref="P: ResponseFiles" /> property. /// </param> /// <param name="startTime"> /// An initialization value for the <see cref="P: StartTime" /> property. /// </param> /// <param name="endTime"> /// An initialization value for the <see cref="P: EndTime" /> property. /// </param> /// <param name="machine"> /// An initialization value for the <see cref="P: Machine" /> property. /// </param> /// <param name="account"> /// An initialization value for the <see cref="P: Account" /> property. /// </param> /// <param name="processId"> /// An initialization value for the <see cref="P: ProcessId" /> property. /// </param> /// <param name="fileName"> /// An initialization value for the <see cref="P: FileName" /> property. /// </param> /// <param name="workingDirectory"> /// An initialization value for the <see cref="P: WorkingDirectory" /> property. /// </param> /// <param name="environmentVariables"> /// An initialization value for the <see cref="P: EnvironmentVariables" /> property. /// </param> /// <param name="properties"> /// An initialization value for the <see cref="P: Properties" /> property. /// </param> public Invocation(string commandLine, IDictionary<string, string> responseFiles, DateTime startTime, DateTime endTime, string machine, string account, int processId, string fileName, string workingDirectory, IDictionary<string, string> environmentVariables, IDictionary<string, SerializedPropertyInfo> properties) { Init(commandLine, responseFiles, startTime, endTime, machine, account, processId, fileName, workingDirectory, environmentVariables, properties); } /// <summary> /// Initializes a new instance of the <see cref="Invocation" /> class from the specified instance. /// </summary> /// <param name="other"> /// The instance from which the new instance is to be initialized. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown if <paramref name="other" /> is null. /// </exception> public Invocation(Invocation other) { if (other == null) { throw new ArgumentNullException(nameof(other)); } Init(other.CommandLine, other.ResponseFiles, other.StartTime, other.EndTime, other.Machine, other.Account, other.ProcessId, other.FileName, other.WorkingDirectory, other.EnvironmentVariables, other.Properties); } ISarifNode ISarifNode.DeepClone() { return DeepCloneCore(); } /// <summary> /// Creates a deep copy of this instance. /// </summary> public Invocation DeepClone() { return (Invocation)DeepCloneCore(); } private ISarifNode DeepCloneCore() { return new Invocation(this); } private void Init(string commandLine, IDictionary<string, string> responseFiles, DateTime startTime, DateTime endTime, string machine, string account, int processId, string fileName, string workingDirectory, IDictionary<string, string> environmentVariables, IDictionary<string, SerializedPropertyInfo> properties) { CommandLine = commandLine; if (responseFiles != null) { ResponseFiles = new Dictionary<string, string>(responseFiles); } StartTime = startTime; EndTime = endTime; Machine = machine; Account = account; ProcessId = processId; FileName = fileName; WorkingDirectory = workingDirectory; if (environmentVariables != null) { EnvironmentVariables = new Dictionary<string, string>(environmentVariables); } if (properties != null) { Properties = new Dictionary<string, SerializedPropertyInfo>(properties); } } } }
// 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.Reflection; using System.Collections.Generic; namespace Internal.Reflection.Extensions.NonPortable { public static class MemberEnumerator { // // Enumerates members, optionally filtered by a name, in the given class and its base classes (but not implemented interfaces.) // Basically emulates the old Type.GetFoo(BindingFlags) api. // public static IEnumerable<M> GetMembers<M>(this Type type, Object nameFilterOrAnyName, BindingFlags bindingFlags) where M : MemberInfo { // Do all the up-front argument validation here so that the exception occurs on call rather than on the first move. if (type == null) { throw new ArgumentNullException(); } if (nameFilterOrAnyName == null) { throw new ArgumentNullException(); } String optionalNameFilter; if (nameFilterOrAnyName == AnyName) { optionalNameFilter = null; } else { optionalNameFilter = (String)nameFilterOrAnyName; } return GetMembersWorker<M>(type, optionalNameFilter, bindingFlags); } // // The iterator worker for GetMember<M>() // private static IEnumerable<M> GetMembersWorker<M>(Type type, String optionalNameFilter, BindingFlags bindingFlags) where M : MemberInfo { Type reflectedType = type; Type typeOfM = typeof(M); Type typeOfEventInfo = typeof(EventInfo); MemberPolicies<M> policies = MemberPolicies<M>.Default; bindingFlags = policies.ModifyBindingFlags(bindingFlags); LowLevelList<M> overridingMembers = new LowLevelList<M>(); StringComparison comparisonType = (0 != (bindingFlags & BindingFlags.IgnoreCase)) ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture; bool inBaseClass = false; bool nameFilterIsPrefix = false; if (optionalNameFilter != null && optionalNameFilter.EndsWith("*", StringComparison.Ordinal)) { nameFilterIsPrefix = true; optionalNameFilter = optionalNameFilter.Substring(0, optionalNameFilter.Length - 1); } while (type != null) { TypeInfo typeInfo = type.GetTypeInfo(); foreach (M member in policies.GetDeclaredMembers(typeInfo)) { if (optionalNameFilter != null) { if (nameFilterIsPrefix) { if (!member.Name.StartsWith(optionalNameFilter, comparisonType)) { continue; } } else if (!member.Name.Equals(optionalNameFilter, comparisonType)) { continue; } } MethodAttributes visibility; bool isStatic; bool isVirtual; bool isNewSlot; policies.GetMemberAttributes(member, out visibility, out isStatic, out isVirtual, out isNewSlot); BindingFlags memberBindingFlags = (BindingFlags)0; memberBindingFlags |= (isStatic ? BindingFlags.Static : BindingFlags.Instance); memberBindingFlags |= ((visibility == MethodAttributes.Public) ? BindingFlags.Public : BindingFlags.NonPublic); if ((bindingFlags & memberBindingFlags) != memberBindingFlags) { continue; } bool passesVisibilityScreen = true; if (inBaseClass && visibility == MethodAttributes.Private) { passesVisibilityScreen = false; } bool passesStaticScreen = true; if (inBaseClass && isStatic && (0 == (bindingFlags & BindingFlags.FlattenHierarchy))) { passesStaticScreen = false; } // // Desktop compat: The order in which we do checks is important. // if (!passesVisibilityScreen) { continue; } if ((!passesStaticScreen) && !(typeOfM.Equals(typeOfEventInfo))) { continue; } bool isImplicitlyOverridden = false; if (isVirtual) { if (isNewSlot) { // A new virtual member definition. for (int i = 0; i < overridingMembers.Count; i++) { if (policies.AreNamesAndSignatureEqual(member, overridingMembers[i])) { // This member is overridden by a more derived class. isImplicitlyOverridden = true; overridingMembers.RemoveAt(i); break; } } } else { for (int i = 0; i < overridingMembers.Count; i++) { if (policies.AreNamesAndSignatureEqual(overridingMembers[i], member)) { // This member overrides another, *and* is overridden by yet another method. isImplicitlyOverridden = true; break; } } if (!isImplicitlyOverridden) { // This member overrides another and is the most derived instance of it we've fonud. overridingMembers.Add(member); } } } if (isImplicitlyOverridden) { continue; } if (!passesStaticScreen) { continue; } if (inBaseClass) { yield return policies.GetInheritedMemberInfo(member, reflectedType); } else { yield return member; } } if (0 != (bindingFlags & BindingFlags.DeclaredOnly)) { break; } inBaseClass = true; type = typeInfo.BaseType; } } // // If member is a virtual member that implicitly overrides a member in a base class, return the overridden member. // Otherwise, return null. // // - MethodImpls ignored. (I didn't say it made sense, this is just how the desktop api we're porting behaves.) // - Implemented interfaces ignores. (I didn't say it made sense, this is just how the desktop api we're porting behaves.) // public static M GetImplicitlyOverriddenBaseClassMember<M>(this M member) where M : MemberInfo { MemberPolicies<M> policies = MemberPolicies<M>.Default; MethodAttributes visibility; bool isStatic; bool isVirtual; bool isNewSlot; policies.GetMemberAttributes(member, out visibility, out isStatic, out isVirtual, out isNewSlot); if (isNewSlot || !isVirtual) { return null; } String name = member.Name; TypeInfo typeInfo = member.DeclaringType.GetTypeInfo(); for (; ;) { Type baseType = typeInfo.BaseType; if (baseType == null) { return null; } typeInfo = baseType.GetTypeInfo(); foreach (M candidate in policies.GetDeclaredMembers(typeInfo)) { if (candidate.Name != name) { continue; } MethodAttributes candidateVisibility; bool isCandidateStatic; bool isCandidateVirtual; bool isCandidateNewSlot; policies.GetMemberAttributes(member, out candidateVisibility, out isCandidateStatic, out isCandidateVirtual, out isCandidateNewSlot); if (!isCandidateVirtual) { continue; } if (!policies.AreNamesAndSignatureEqual(member, candidate)) { continue; } return candidate; } } } // Uniquely allocated sentinel "string" // - can't use null as that may be an app-supplied null, which we have to throw ArgumentNullException for. // - risky to use a proper String as the FX or toolchain can unexpectedly give you back a shared string // even when you'd swear you were allocating a new one. public static readonly Object AnyName = new Object(); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using CURLAUTH = Interop.libcurl.CURLAUTH; using CURLcode = Interop.libcurl.CURLcode; using CurlFeatures = Interop.libcurl.CURL_VERSION_Features; using CURLMcode = Interop.libcurl.CURLMcode; using CURLoption = Interop.libcurl.CURLoption; using CurlVersionInfoData = Interop.libcurl.curl_version_info_data; namespace System.Net.Http { internal partial class CurlHandler : HttpMessageHandler { #region Constants private const string VerboseDebuggingConditional = "CURLHANDLER_VERBOSE"; private const string HttpPrefix = "HTTP/"; private const char SpaceChar = ' '; private const int StatusCodeLength = 3; private const string UriSchemeHttp = "http"; private const string UriSchemeHttps = "https"; private const string EncodingNameGzip = "gzip"; private const string EncodingNameDeflate = "deflate"; private const int RequestBufferSize = 16384; // Default used by libcurl private const string NoTransferEncoding = HttpKnownHeaderNames.TransferEncoding + ":"; private const string NoContentType = HttpKnownHeaderNames.ContentType + ":"; private const int CurlAge = 5; private const int MinCurlAge = 3; #endregion #region Fields private readonly static char[] s_newLineCharArray = new char[] { HttpRuleParser.CR, HttpRuleParser.LF }; private readonly static string[] s_authenticationSchemes = { "Negotiate", "Digest", "Basic" }; // the order in which libcurl goes over authentication schemes private readonly static ulong[] s_authSchemePriorityOrder = { CURLAUTH.Negotiate, CURLAUTH.Digest, CURLAUTH.Basic }; private readonly static CurlVersionInfoData s_curlVersionInfoData; private readonly static bool s_supportsAutomaticDecompression; private readonly static bool s_supportsSSL; private readonly MultiAgent _agent = new MultiAgent(); private volatile bool _anyOperationStarted; private volatile bool _disposed; private IWebProxy _proxy = null; private ICredentials _serverCredentials = null; private ProxyUsePolicy _proxyPolicy = ProxyUsePolicy.UseDefaultProxy; private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression; private bool _preAuthenticate = HttpHandlerDefaults.DefaultPreAuthenticate; private CredentialCache _credentialCache = null; // protected by LockObject private CookieContainer _cookieContainer = new CookieContainer(); private bool _useCookie = HttpHandlerDefaults.DefaultUseCookies; private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection; private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections; private object LockObject { get { return _agent; } } #endregion static CurlHandler() { // curl_global_init call handled by Interop.libcurl's cctor // Verify the version of curl we're using is new enough s_curlVersionInfoData = Marshal.PtrToStructure<CurlVersionInfoData>(Interop.libcurl.curl_version_info(CurlAge)); if (s_curlVersionInfoData.age < MinCurlAge) { throw new InvalidOperationException(SR.net_http_unix_https_libcurl_too_old); } // Feature detection s_supportsSSL = (CurlFeatures.CURL_VERSION_SSL & s_curlVersionInfoData.features) != 0; s_supportsAutomaticDecompression = (CurlFeatures.CURL_VERSION_LIBZ & s_curlVersionInfoData.features) != 0; } #region Properties internal bool AutomaticRedirection { get { return _automaticRedirection; } set { CheckDisposedOrStarted(); _automaticRedirection = value; } } internal bool SupportsProxy { get { return true; } } internal bool SupportsRedirectConfiguration { get { return true; } } internal bool UseProxy { get { return _proxyPolicy != ProxyUsePolicy.DoNotUseProxy; } set { CheckDisposedOrStarted(); _proxyPolicy = value ? ProxyUsePolicy.UseCustomProxy : ProxyUsePolicy.DoNotUseProxy; } } internal IWebProxy Proxy { get { return _proxy; } set { CheckDisposedOrStarted(); _proxy = value; } } internal ICredentials Credentials { get { return _serverCredentials; } set { _serverCredentials = value; } } internal ClientCertificateOption ClientCertificateOptions { get { return ClientCertificateOption.Manual; } set { if (ClientCertificateOption.Manual != value) { throw new PlatformNotSupportedException(SR.net_http_unix_invalid_client_cert_option); } } } internal bool SupportsAutomaticDecompression { get { return s_supportsAutomaticDecompression; } } internal DecompressionMethods AutomaticDecompression { get { return _automaticDecompression; } set { CheckDisposedOrStarted(); _automaticDecompression = value; } } internal bool PreAuthenticate { get { return _preAuthenticate; } set { CheckDisposedOrStarted(); _preAuthenticate = value; if (value && _credentialCache == null) { _credentialCache = new CredentialCache(); } } } internal bool UseCookie { get { return _useCookie; } set { CheckDisposedOrStarted(); _useCookie = value; } } internal CookieContainer CookieContainer { get { return _cookieContainer; } set { CheckDisposedOrStarted(); _cookieContainer = value; } } internal int MaxAutomaticRedirections { get { return _maxAutomaticRedirections; } set { if (value <= 0) { throw new ArgumentOutOfRangeException( "value", value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxAutomaticRedirections = value; } } /// <summary> /// <b> UseDefaultCredentials is a no op on Unix </b> /// </summary> internal bool UseDefaultCredentials { get { return false; } set { } } #endregion protected override void Dispose(bool disposing) { _disposed = true; base.Dispose(disposing); } protected internal override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { if (request == null) { throw new ArgumentNullException("request", SR.net_http_handler_norequest); } if (request.RequestUri.Scheme == UriSchemeHttps) { if (!s_supportsSSL) { throw new PlatformNotSupportedException(SR.net_http_unix_https_support_unavailable_libcurl); } } else { Debug.Assert(request.RequestUri.Scheme == UriSchemeHttp, "HttpClient expected to validate scheme as http or https."); } if (request.Headers.TransferEncodingChunked.GetValueOrDefault() && (request.Content == null)) { throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content); } if (_useCookie && _cookieContainer == null) { throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer); } CheckDisposed(); SetOperationStarted(); // Do an initial cancellation check to avoid initiating the async operation if // cancellation has already been requested. After this, we'll rely on CancellationToken.Register // to notify us of cancellation requests and shut down the operation if possible. if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<HttpResponseMessage>(cancellationToken); } // Create the easy request. This associates the easy request with this handler and configures // it based on the settings configured for the handler. var easy = new EasyRequest(this, request, cancellationToken); try { easy.InitializeCurl(); if (easy._requestContentStream != null) { easy._requestContentStream.Run(); } _agent.Queue(new MultiAgent.IncomingRequest { Easy = easy, Type = MultiAgent.IncomingRequestType.New }); } catch (Exception exc) { easy.FailRequest(exc); easy.Cleanup(); // no active processing remains, so we can cleanup } return easy.Task; } #region Private methods private void SetOperationStarted() { if (!_anyOperationStarted) { _anyOperationStarted = true; } } private NetworkCredential GetNetworkCredentials(ICredentials credentials, Uri requestUri) { if (_preAuthenticate) { NetworkCredential nc = null; lock (LockObject) { Debug.Assert(_credentialCache != null, "Expected non-null credential cache"); nc = GetCredentials(_credentialCache, requestUri); } if (nc != null) { return nc; } } return GetCredentials(credentials, requestUri); } private void AddCredentialToCache(Uri serverUri, ulong authAvail, NetworkCredential nc) { lock (LockObject) { for (int i=0; i < s_authSchemePriorityOrder.Length; i++) { if ((authAvail & s_authSchemePriorityOrder[i]) != 0) { Debug.Assert(_credentialCache != null, "Expected non-null credential cache"); _credentialCache.Add(serverUri, s_authenticationSchemes[i], nc); } } } } private void AddResponseCookies(Uri serverUri, HttpResponseMessage response) { if (!_useCookie) { return; } if (response.Headers.Contains(HttpKnownHeaderNames.SetCookie)) { IEnumerable<string> cookieHeaders = response.Headers.GetValues(HttpKnownHeaderNames.SetCookie); foreach (var cookieHeader in cookieHeaders) { try { _cookieContainer.SetCookies(serverUri, cookieHeader); } catch (CookieException e) { string msg = string.Format("Malformed cookie: SetCookies Failed with {0}, server: {1}, cookie:{2}", e.Message, serverUri.OriginalString, cookieHeader); VerboseTrace(msg); } } } } private static NetworkCredential GetCredentials(ICredentials credentials, Uri requestUri) { if (credentials == null) { return null; } foreach (var authScheme in s_authenticationSchemes) { NetworkCredential networkCredential = credentials.GetCredential(requestUri, authScheme); if (networkCredential != null) { return networkCredential; } } return null; } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } } private void CheckDisposedOrStarted() { CheckDisposed(); if (_anyOperationStarted) { throw new InvalidOperationException(SR.net_http_operation_started); } } private static void ThrowIfCURLEError(int error) { if (error != CURLcode.CURLE_OK) { var inner = new CurlException(error, isMulti: false); VerboseTrace(inner.Message); throw inner; } } private static void ThrowIfCURLMError(int error) { if (error != CURLMcode.CURLM_OK) { string msg = CurlException.GetCurlErrorString(error, true); VerboseTrace(msg); switch (error) { case CURLMcode.CURLM_ADDED_ALREADY: case CURLMcode.CURLM_BAD_EASY_HANDLE: case CURLMcode.CURLM_BAD_HANDLE: case CURLMcode.CURLM_BAD_SOCKET: throw new ArgumentException(msg); case CURLMcode.CURLM_UNKNOWN_OPTION: throw new ArgumentOutOfRangeException(msg); case CURLMcode.CURLM_OUT_OF_MEMORY: throw new OutOfMemoryException(msg); case CURLMcode.CURLM_INTERNAL_ERROR: default: throw new CurlException(error, msg); } } } [Conditional(VerboseDebuggingConditional)] private static void VerboseTrace(string text = null, [CallerMemberName] string memberName = null, EasyRequest easy = null, MultiAgent agent = null) { // If we weren't handed a multi agent, see if we can get one from the EasyRequest if (agent == null && easy != null && easy._associatedMultiAgent != null) { agent = easy._associatedMultiAgent; } int? agentId = agent != null ? agent.RunningWorkerId : null; // Get an ID string that provides info about which MultiAgent worker and which EasyRequest this trace is about string ids = ""; if (agentId != null || easy != null) { ids = "(" + (agentId != null ? "M#" + agentId : "") + (agentId != null && easy != null ? ", " : "") + (easy != null ? "E#" + easy.Task.Id : "") + ")"; } // Create the message and trace it out string msg = string.Format("[{0, -30}]{1, -16}: {2}", memberName, ids, text); Interop.Sys.PrintF("%s\n", msg); } [Conditional(VerboseDebuggingConditional)] private static void VerboseTraceIf(bool condition, string text = null, [CallerMemberName] string memberName = null, EasyRequest easy = null) { if (condition) { VerboseTrace(text, memberName, easy, agent: null); } } private static Exception CreateHttpRequestException(Exception inner = null) { return new HttpRequestException(SR.net_http_client_execution_error, inner); } private static bool TryParseStatusLine(HttpResponseMessage response, string responseHeader, EasyRequest state) { if (!responseHeader.StartsWith(HttpPrefix, StringComparison.OrdinalIgnoreCase)) { return false; } // Clear the header if status line is recieved again. This signifies that there are multiple response headers (like in redirection). response.Headers.Clear(); response.Content.Headers.Clear(); int responseHeaderLength = responseHeader.Length; // Check if line begins with HTTP/1.1 or HTTP/1.0 int prefixLength = HttpPrefix.Length; int versionIndex = prefixLength + 2; if ((versionIndex < responseHeaderLength) && (responseHeader[prefixLength] == '1') && (responseHeader[prefixLength + 1] == '.')) { response.Version = responseHeader[versionIndex] == '1' ? HttpVersion.Version11 : responseHeader[versionIndex] == '0' ? HttpVersion.Version10 : new Version(0, 0); } else { response.Version = new Version(0, 0); } // TODO: Parsing errors are treated as fatal. Find right behaviour int spaceIndex = responseHeader.IndexOf(SpaceChar); if (spaceIndex > -1) { int codeStartIndex = spaceIndex + 1; int statusCode = 0; // Parse first 3 characters after a space as status code if (TryParseStatusCode(responseHeader, codeStartIndex, out statusCode)) { response.StatusCode = (HttpStatusCode)statusCode; int codeEndIndex = codeStartIndex + StatusCodeLength; int reasonPhraseIndex = codeEndIndex + 1; if (reasonPhraseIndex < responseHeaderLength && responseHeader[codeEndIndex] == SpaceChar) { int newLineCharIndex = responseHeader.IndexOfAny(s_newLineCharArray, reasonPhraseIndex); int reasonPhraseEnd = newLineCharIndex >= 0 ? newLineCharIndex : responseHeaderLength; response.ReasonPhrase = responseHeader.Substring(reasonPhraseIndex, reasonPhraseEnd - reasonPhraseIndex); } state._isRedirect = state._handler.AutomaticRedirection && (response.StatusCode == HttpStatusCode.Redirect || response.StatusCode == HttpStatusCode.RedirectKeepVerb || response.StatusCode == HttpStatusCode.RedirectMethod) ; } } return true; } private static bool TryParseStatusCode(string responseHeader, int statusCodeStartIndex, out int statusCode) { if (statusCodeStartIndex + StatusCodeLength > responseHeader.Length) { statusCode = 0; return false; } char c100 = responseHeader[statusCodeStartIndex]; char c10 = responseHeader[statusCodeStartIndex + 1]; char c1 = responseHeader[statusCodeStartIndex + 2]; if (c100 < '0' || c100 > '9' || c10 < '0' || c10 > '9' || c1 < '0' || c1 > '9') { statusCode = 0; return false; } statusCode = (c100 - '0') * 100 + (c10 - '0') * 10 + (c1 - '0'); return true; } private static void HandleRedirectLocationHeader(EasyRequest state, string locationValue) { Debug.Assert(state._isRedirect); Debug.Assert(state._handler.AutomaticRedirection); string location = locationValue.Trim(); //only for absolute redirects Uri forwardUri; if (Uri.TryCreate(location, UriKind.RelativeOrAbsolute, out forwardUri) && forwardUri.IsAbsoluteUri) { NetworkCredential newCredential = GetCredentials(state._handler.Credentials as CredentialCache, forwardUri); if (newCredential != null) { state.SetCredentialsOptions(newCredential); } else { state.SetCurlOption(CURLoption.CURLOPT_USERNAME, IntPtr.Zero); state.SetCurlOption(CURLoption.CURLOPT_PASSWORD, IntPtr.Zero); } // reset proxy - it is possible that the proxy has different credentials for the new URI state.SetProxyOptions(forwardUri); if (state._handler._useCookie) { // reset cookies. state.SetCurlOption(CURLoption.CURLOPT_COOKIE, IntPtr.Zero); // set cookies again state.SetCookieOption(forwardUri); } } } private static void SetChunkedModeForSend(HttpRequestMessage request) { bool chunkedMode = request.Headers.TransferEncodingChunked.GetValueOrDefault(); HttpContent requestContent = request.Content; Debug.Assert(requestContent != null, "request is null"); // Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics. // libcurl adds a Tranfer-Encoding header by default and the request fails if both are set. if (requestContent.Headers.ContentLength.HasValue) { if (chunkedMode) { // Same behaviour as WinHttpHandler requestContent.Headers.ContentLength = null; } else { // Prevent libcurl from adding Transfer-Encoding header request.Headers.TransferEncodingChunked = false; } } else if (!chunkedMode) { // Make sure Transfer-Encoding: chunked header is set, // as we have content to send but no known length for it. request.Headers.TransferEncodingChunked = true; } } #endregion private enum ProxyUsePolicy { DoNotUseProxy = 0, // Do not use proxy. Ignores the value set in the environment. UseDefaultProxy = 1, // Do not set the proxy parameter. Use the value of environment variable, if any. UseCustomProxy = 2 // Use The proxy specified by the user. } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace System.Collections.Generic { [DebuggerTypeProxy(typeof(ICollectionDebugView<>))] [DebuggerDisplay("Count = {Count}")] public class LinkedList<T> : ICollection<T>, ICollection, IReadOnlyCollection<T> { // This LinkedList is a doubly-Linked circular list. internal LinkedListNode<T> head; internal int count; internal int version; private object _syncRoot; public LinkedList() { } public LinkedList(IEnumerable<T> collection) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } foreach (T item in collection) { AddLast(item); } } public int Count { get { return count; } } public LinkedListNode<T> First { get { return head; } } public LinkedListNode<T> Last { get { return head == null ? null : head.prev; } } bool ICollection<T>.IsReadOnly { get { return false; } } void ICollection<T>.Add(T value) { AddLast(value); } public LinkedListNode<T> AddAfter(LinkedListNode<T> node, T value) { ValidateNode(node); LinkedListNode<T> result = new LinkedListNode<T>(node.list, value); InternalInsertNodeBefore(node.next, result); return result; } public void AddAfter(LinkedListNode<T> node, LinkedListNode<T> newNode) { ValidateNode(node); ValidateNewNode(newNode); InternalInsertNodeBefore(node.next, newNode); newNode.list = this; } public LinkedListNode<T> AddBefore(LinkedListNode<T> node, T value) { ValidateNode(node); LinkedListNode<T> result = new LinkedListNode<T>(node.list, value); InternalInsertNodeBefore(node, result); if (node == head) { head = result; } return result; } public void AddBefore(LinkedListNode<T> node, LinkedListNode<T> newNode) { ValidateNode(node); ValidateNewNode(newNode); InternalInsertNodeBefore(node, newNode); newNode.list = this; if (node == head) { head = newNode; } } public LinkedListNode<T> AddFirst(T value) { LinkedListNode<T> result = new LinkedListNode<T>(this, value); if (head == null) { InternalInsertNodeToEmptyList(result); } else { InternalInsertNodeBefore(head, result); head = result; } return result; } public void AddFirst(LinkedListNode<T> node) { ValidateNewNode(node); if (head == null) { InternalInsertNodeToEmptyList(node); } else { InternalInsertNodeBefore(head, node); head = node; } node.list = this; } public LinkedListNode<T> AddLast(T value) { LinkedListNode<T> result = new LinkedListNode<T>(this, value); if (head == null) { InternalInsertNodeToEmptyList(result); } else { InternalInsertNodeBefore(head, result); } return result; } public void AddLast(LinkedListNode<T> node) { ValidateNewNode(node); if (head == null) { InternalInsertNodeToEmptyList(node); } else { InternalInsertNodeBefore(head, node); } node.list = this; } public void Clear() { LinkedListNode<T> current = head; while (current != null) { LinkedListNode<T> temp = current; current = current.Next; // use Next the instead of "next", otherwise it will loop forever temp.Invalidate(); } head = null; count = 0; version++; } public bool Contains(T value) { return Find(value) != null; } public void CopyTo(T[] array, int index) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); } if (index > array.Length) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_BiggerThanCollection); } if (array.Length - index < Count) { throw new ArgumentException(SR.Arg_InsufficientSpace); } LinkedListNode<T> node = head; if (node != null) { do { array[index++] = node.item; node = node.next; } while (node != head); } } public LinkedListNode<T> Find(T value) { LinkedListNode<T> node = head; EqualityComparer<T> c = EqualityComparer<T>.Default; if (node != null) { if (value != null) { do { if (c.Equals(node.item, value)) { return node; } node = node.next; } while (node != head); } else { do { if (node.item == null) { return node; } node = node.next; } while (node != head); } } return null; } public LinkedListNode<T> FindLast(T value) { if (head == null) return null; LinkedListNode<T> last = head.prev; LinkedListNode<T> node = last; EqualityComparer<T> c = EqualityComparer<T>.Default; if (node != null) { if (value != null) { do { if (c.Equals(node.item, value)) { return node; } node = node.prev; } while (node != last); } else { do { if (node.item == null) { return node; } node = node.prev; } while (node != last); } } return null; } public Enumerator GetEnumerator() { return new Enumerator(this); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return GetEnumerator(); } public bool Remove(T value) { LinkedListNode<T> node = Find(value); if (node != null) { InternalRemoveNode(node); return true; } return false; } public void Remove(LinkedListNode<T> node) { ValidateNode(node); InternalRemoveNode(node); } public void RemoveFirst() { if (head == null) { throw new InvalidOperationException(SR.LinkedListEmpty); } InternalRemoveNode(head); } public void RemoveLast() { if (head == null) { throw new InvalidOperationException(SR.LinkedListEmpty); } InternalRemoveNode(head.prev); } private void InternalInsertNodeBefore(LinkedListNode<T> node, LinkedListNode<T> newNode) { newNode.next = node; newNode.prev = node.prev; node.prev.next = newNode; node.prev = newNode; version++; count++; } private void InternalInsertNodeToEmptyList(LinkedListNode<T> newNode) { Debug.Assert(head == null && count == 0, "LinkedList must be empty when this method is called!"); newNode.next = newNode; newNode.prev = newNode; head = newNode; version++; count++; } internal void InternalRemoveNode(LinkedListNode<T> node) { Debug.Assert(node.list == this, "Deleting the node from another list!"); Debug.Assert(head != null, "This method shouldn't be called on empty list!"); if (node.next == node) { Debug.Assert(count == 1 && head == node, "this should only be true for a list with only one node"); head = null; } else { node.next.prev = node.prev; node.prev.next = node.next; if (head == node) { head = node.next; } } node.Invalidate(); count--; version++; } internal void ValidateNewNode(LinkedListNode<T> node) { if (node == null) { throw new ArgumentNullException(nameof(node)); } if (node.list != null) { throw new InvalidOperationException(SR.LinkedListNodeIsAttached); } } internal void ValidateNode(LinkedListNode<T> node) { if (node == null) { throw new ArgumentNullException(nameof(node)); } if (node.list != this) { throw new InvalidOperationException(SR.ExternalLinkedListNode); } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (_syncRoot == null) { Threading.Interlocked.CompareExchange<object>(ref _syncRoot, new object(), null); } return _syncRoot; } } void ICollection.CopyTo(Array array, int index) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); } if (array.GetLowerBound(0) != 0) { throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < Count) { throw new ArgumentException(SR.Arg_InsufficientSpace); } T[] tArray = array as T[]; if (tArray != null) { CopyTo(tArray, index); } else { // No need to use reflection to verify that the types are compatible because it isn't 100% correct and we can rely // on the runtime validation during the cast that happens below (i.e. we will get an ArrayTypeMismatchException). object[] objects = array as object[]; if (objects == null) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } LinkedListNode<T> node = head; try { if (node != null) { do { objects[index++] = node.item; node = node.next; } while (node != head); } } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")] public struct Enumerator : IEnumerator<T>, IEnumerator { private LinkedList<T> _list; private LinkedListNode<T> _node; private int _version; private T _current; private int _index; internal Enumerator(LinkedList<T> list) { _list = list; _version = list.version; _node = list.head; _current = default(T); _index = 0; } public T Current { get { return _current; } } object IEnumerator.Current { get { if (_index == 0 || (_index == _list.Count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return _current; } } public bool MoveNext() { if (_version != _list.version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } if (_node == null) { _index = _list.Count + 1; return false; } ++_index; _current = _node.item; _node = _node.next; if (_node == _list.head) { _node = null; } return true; } void IEnumerator.Reset() { if (_version != _list.version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } _current = default(T); _node = _list.head; _index = 0; } public void Dispose() { } } } // Note following class is not serializable since we customized the serialization of LinkedList. public sealed class LinkedListNode<T> { internal LinkedList<T> list; internal LinkedListNode<T> next; internal LinkedListNode<T> prev; internal T item; public LinkedListNode(T value) { item = value; } internal LinkedListNode(LinkedList<T> list, T value) { this.list = list; item = value; } public LinkedList<T> List { get { return list; } } public LinkedListNode<T> Next { get { return next == null || next == list.head ? null : next; } } public LinkedListNode<T> Previous { get { return prev == null || this == list.head ? null : prev; } } public T Value { get { return item; } set { item = value; } } internal void Invalidate() { list = null; next = null; prev = null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //------------------------------------------------------------------------------ namespace System.Data.SqlClient { /// <devdoc> Class of variables for the Tds connection. /// </devdoc> internal static class TdsEnums { // internal tdsparser constants public const string SQL_PROVIDER_NAME = Common.DbConnectionStringDefaults.ApplicationName; public static readonly decimal SQL_SMALL_MONEY_MIN = new decimal(-214748.3648); public static readonly decimal SQL_SMALL_MONEY_MAX = new decimal(214748.3647); // HACK!!! // Constant for SqlDbType.SmallVarBinary... store internal variable here instead of on // SqlDbType so that it is not surfaced to the user!!! Related to dtc and the fact that // the TransactionManager TDS stream is the only token left that uses VarBinarys instead of // BigVarBinarys. public const SqlDbType SmallVarBinary = (SqlDbType)(SqlDbType.Variant) + 1; // network protocol string constants public const string TCP = "tcp"; public const string NP = "np"; public const string RPC = "rpc"; public const string BV = "bv"; public const string ADSP = "adsp"; public const string SPX = "spx"; public const string VIA = "via"; public const string LPC = "lpc"; public const string ADMIN = "admin"; // network function string constants public const string INIT_SSPI_PACKAGE = "InitSSPIPackage"; public const string INIT_SESSION = "InitSession"; public const string CONNECTION_GET_SVR_USER = "ConnectionGetSvrUser"; public const string GEN_CLIENT_CONTEXT = "GenClientContext"; // tdsparser packet handling constants public const byte SOFTFLUSH = 0; public const byte HARDFLUSH = 1; public const byte IGNORE = 2; // header constants public const int HEADER_LEN = 8; public const int HEADER_LEN_FIELD_OFFSET = 2; public const int YUKON_HEADER_LEN = 12; //Yukon headers also include a MARS session id public const int MARS_ID_OFFSET = 8; public const int HEADERTYPE_QNOTIFICATION = 1; public const int HEADERTYPE_MARS = 2; public const int HEADERTYPE_TRACE = 3; // other various constants public const int SUCCEED = 1; public const int FAIL = 0; public const short TYPE_SIZE_LIMIT = 8000; public const int MIN_PACKET_SIZE = 512; // Login packet can be no greater than 4k until server sends us env-change // increasing packet size. public const int DEFAULT_LOGIN_PACKET_SIZE = 4096; public const int MAX_PRELOGIN_PAYLOAD_LENGTH = 1024; public const int MAX_PACKET_SIZE = 32768; public const int MAX_SERVER_USER_NAME = 256; // obtained from luxor // Severity 0 - 10 indicates informational (non-error) messages // Severity 11 - 16 indicates errors that can be corrected by user (syntax errors, etc...) // Severity 17 - 19 indicates failure due to insufficient resources in the server // (max locks exceeded, not enough memory, other internal server limits reached, etc..) // Severity 20 - 25 Severe problems with the server, connection terminated. public const byte MIN_ERROR_CLASS = 11; // webdata 100667: This should actually be 11 public const byte MAX_USER_CORRECTABLE_ERROR_CLASS = 16; public const byte FATAL_ERROR_CLASS = 20; // Message types public const byte MT_SQL = 1; // SQL command batch public const byte MT_LOGIN = 2; // Login message for pre-Sphinx (before version 7.0) public const byte MT_RPC = 3; // Remote procedure call public const byte MT_TOKENS = 4; // Table response data stream public const byte MT_BINARY = 5; // Unformatted binary response data (UNUSED) public const byte MT_ATTN = 6; // Attention (break) signal public const byte MT_BULK = 7; // Bulk load data public const byte MT_OPEN = 8; // Set up subchannel (UNUSED) public const byte MT_CLOSE = 9; // Close subchannel (UNUSED) public const byte MT_ERROR = 10; // Protocol error detected public const byte MT_ACK = 11; // Protocol acknowledgement (UNUSED) public const byte MT_ECHO = 12; // Echo data (UNUSED) public const byte MT_LOGOUT = 13; // Logout message (UNUSED) public const byte MT_TRANS = 14; // Transaction Manager Interface public const byte MT_OLEDB = 15; // ? (UNUSED) public const byte MT_LOGIN7 = 16; // Login message for Sphinx (version 7) or later public const byte MT_SSPI = 17; // SSPI message public const byte MT_PRELOGIN = 18; // Pre-login handshake // Message status bits public const byte ST_EOM = 0x1; // Packet is end-of-message public const byte ST_AACK = 0x2; // Packet acknowledges attention (server to client) public const byte ST_IGNORE = 0x2; // Ignore this event (client to server) public const byte ST_BATCH = 0x4; // Message is part of a batch. public const byte ST_RESET_CONNECTION = 0x8; // Exec sp_reset_connection prior to processing message public const byte ST_RESET_CONNECTION_PRESERVE_TRANSACTION = 0x10; // reset prior to processing, with preserving local tx // TDS control tokens public const byte SQLCOLFMT = 0xa1; public const byte SQLPROCID = 0x7c; public const byte SQLCOLNAME = 0xa0; public const byte SQLTABNAME = 0xa4; public const byte SQLCOLINFO = 0xa5; public const byte SQLALTNAME = 0xa7; public const byte SQLALTFMT = 0xa8; public const byte SQLERROR = 0xaa; public const byte SQLINFO = 0xab; public const byte SQLRETURNVALUE = 0xac; public const byte SQLRETURNSTATUS = 0x79; public const byte SQLRETURNTOK = 0xdb; public const byte SQLALTCONTROL = 0xaf; public const byte SQLROW = 0xd1; public const byte SQLNBCROW = 0xd2; // same as ROW with null-bit-compression support public const byte SQLALTROW = 0xd3; public const byte SQLDONE = 0xfd; public const byte SQLDONEPROC = 0xfe; public const byte SQLDONEINPROC = 0xff; public const byte SQLOFFSET = 0x78; public const byte SQLORDER = 0xa9; public const byte SQLDEBUG_CMD = 0x60; public const byte SQLLOGINACK = 0xad; public const byte SQLFEATUREEXTACK = 0xae; // TDS 7.4 - feature ack public const byte SQLSESSIONSTATE = 0xe4; // TDS 7.4 - connection resiliency session state public const byte SQLENVCHANGE = 0xe3; // Environment change notification public const byte SQLSECLEVEL = 0xed; // Security level token ??? public const byte SQLROWCRC = 0x39; // ROWCRC datastream??? public const byte SQLCOLMETADATA = 0x81; // Column metadata including name public const byte SQLALTMETADATA = 0x88; // Alt column metadata including name public const byte SQLSSPI = 0xed; // SSPI data // Environment change notification streams // TYPE on TDS ENVCHANGE token stream (from sql\ntdbms\include\odsapi.h) // public const byte ENV_DATABASE = 1; // Database changed public const byte ENV_LANG = 2; // Language changed public const byte ENV_CHARSET = 3; // Character set changed public const byte ENV_PACKETSIZE = 4; // Packet size changed public const byte ENV_LOCALEID = 5; // Unicode data sorting locale id public const byte ENV_COMPFLAGS = 6; // Unicode data sorting comparison flags public const byte ENV_COLLATION = 7; // SQL Collation // The following are environment change tokens valid for Yukon or later. public const byte ENV_BEGINTRAN = 8; // Transaction began public const byte ENV_COMMITTRAN = 9; // Transaction committed public const byte ENV_ROLLBACKTRAN = 10; // Transaction rolled back public const byte ENV_ENLISTDTC = 11; // Enlisted in Distributed Transaction public const byte ENV_DEFECTDTC = 12; // Defected from Distributed Transaction public const byte ENV_LOGSHIPNODE = 13; // Realtime Log shipping primary node public const byte ENV_PROMOTETRANSACTION = 15; // Promote Transaction public const byte ENV_TRANSACTIONMANAGERADDRESS = 16; // Transaction Manager Address public const byte ENV_TRANSACTIONENDED = 17; // Transaction Ended public const byte ENV_SPRESETCONNECTIONACK = 18; // SP_Reset_Connection ack public const byte ENV_USERINSTANCE = 19; // User Instance public const byte ENV_ROUTING = 20; // Routing (ROR) information public enum EnvChangeType : byte { ENVCHANGE_DATABASE = ENV_DATABASE, ENVCHANGE_LANG = ENV_LANG, ENVCHANGE_CHARSET = ENV_CHARSET, ENVCHANGE_PACKETSIZE = ENV_PACKETSIZE, ENVCHANGE_LOCALEID = ENV_LOCALEID, ENVCHANGE_COMPFLAGS = ENV_COMPFLAGS, ENVCHANGE_COLLATION = ENV_COLLATION, ENVCHANGE_BEGINTRAN = ENV_BEGINTRAN, ENVCHANGE_COMMITTRAN = ENV_COMMITTRAN, ENVCHANGE_ROLLBACKTRAN = ENV_ROLLBACKTRAN, ENVCHANGE_ENLISTDTC = ENV_ENLISTDTC, ENVCHANGE_DEFECTDTC = ENV_DEFECTDTC, ENVCHANGE_LOGSHIPNODE = ENV_LOGSHIPNODE, ENVCHANGE_PROMOTETRANSACTION = ENV_PROMOTETRANSACTION, ENVCHANGE_TRANSACTIONMANAGERADDRESS = ENV_TRANSACTIONMANAGERADDRESS, ENVCHANGE_TRANSACTIONENDED = ENV_TRANSACTIONENDED, ENVCHANGE_SPRESETCONNECTIONACK = ENV_SPRESETCONNECTIONACK, ENVCHANGE_USERINSTANCE = ENV_USERINSTANCE, ENVCHANGE_ROUTING = ENV_ROUTING } // done status stream bit masks public const int DONE_MORE = 0x0001; // more command results coming public const int DONE_ERROR = 0x0002; // error in command batch public const int DONE_INXACT = 0x0004; // transaction in progress public const int DONE_PROC = 0x0008; // done from stored proc public const int DONE_COUNT = 0x0010; // count in done info public const int DONE_ATTN = 0x0020; // oob ack public const int DONE_INPROC = 0x0040; // like DONE_PROC except proc had error public const int DONE_RPCINBATCH = 0x0080; // Done from RPC in batch public const int DONE_SRVERROR = 0x0100; // Severe error in which resultset should be discarded public const int DONE_FMTSENT = 0x8000; // fmt message sent, done_inproc req'd // Feature Extension public const byte FEATUREEXT_TERMINATOR = 0xFF; public const byte FEATUREEXT_SRECOVERY = 0x01; public const byte FEATUREEXT_GLOBALTRANSACTIONS = 0x05; [Flags] public enum FeatureExtension : uint { None = 0, SessionRecovery = 1, GlobalTransactions = 8, } // Loginrec defines public const byte MAX_LOG_NAME = 30; // TDS 4.2 login rec max name length public const byte MAX_PROG_NAME = 10; // max length of loginrec program name public const byte SEC_COMP_LEN = 8; // length of security compartments public const byte MAX_PK_LEN = 6; // max length of TDS packet size public const byte MAX_NIC_SIZE = 6; // The size of a MAC or client address public const byte SQLVARIANT_SIZE = 2; // size of the fixed portion of a sql variant (type, cbPropBytes) public const byte VERSION_SIZE = 4; // size of the tds version (4 unsigned bytes) public const int CLIENT_PROG_VER = 0x06000000; // Client interface version public const int YUKON_LOG_REC_FIXED_LEN = 0x5e; // misc public const int TEXT_TIME_STAMP_LEN = 8; public const int COLLATION_INFO_LEN = 4; /* public const byte INT4_LSB_HI = 0; // lsb is low byte (e.g. 68000) // public const byte INT4_LSB_LO = 1; // lsb is low byte (e.g. VAX) public const byte INT2_LSB_HI = 2; // lsb is low byte (e.g. 68000) // public const byte INT2_LSB_LO = 3; // lsb is low byte (e.g. VAX) public const byte FLT_IEEE_HI = 4; // lsb is low byte (e.g. 68000) public const byte CHAR_ASCII = 6; // ASCII character set public const byte TWO_I4_LSB_HI = 8; // lsb is low byte (e.g. 68000 // public const byte TWO_I4_LSB_LO = 9; // lsb is low byte (e.g. VAX) // public const byte FLT_IEEE_LO = 10; // lsb is low byte (e.g. MSDOS) public const byte FLT4_IEEE_HI = 12; // IEEE 4-byte floating point -lsb is high byte // public const byte FLT4_IEEE_LO = 13; // IEEE 4-byte floating point -lsb is low byte public const byte TWO_I2_LSB_HI = 16; // lsb is high byte // public const byte TWO_I2_LSB_LO = 17; // lsb is low byte public const byte LDEFSQL = 0; // server sends its default public const byte LDEFUSER = 0; // regular old user public const byte LINTEGRATED = 8; // integrated security login */ /* Versioning scheme table: Client sends: 0x70000000 -> Sphinx 0x71000000 -> Shiloh RTM 0x71000001 -> Shiloh SP1 0x72xx0002 -> Yukon RTM Server responds: 0x07000000 -> Sphinx // Notice server response format is different for bwd compat 0x07010000 -> Shiloh RTM // Notice server response format is different for bwd compat 0x71000001 -> Shiloh SP1 0x72xx0002 -> Yukon RTM */ // Shiloh SP1 and beyond versioning scheme: // Majors: public const int YUKON_MAJOR = 0x72; // the high-byte is sufficient to distinguish later versions public const int KATMAI_MAJOR = 0x73; public const int DENALI_MAJOR = 0x74; // Increments: public const int YUKON_INCREMENT = 0x09; public const int KATMAI_INCREMENT = 0x0b; public const int DENALI_INCREMENT = 0x00; // Minors: public const int YUKON_RTM_MINOR = 0x0002; public const int KATMAI_MINOR = 0x0003; public const int DENALI_MINOR = 0x0004; public const int ORDER_68000 = 1; public const int USE_DB_ON = 1; public const int INIT_DB_FATAL = 1; public const int SET_LANG_ON = 1; public const int INIT_LANG_FATAL = 1; public const int ODBC_ON = 1; public const int SSPI_ON = 1; public const int REPL_ON = 3; // send the read-only intent to the server public const int READONLY_INTENT_ON = 1; // Token masks public const byte SQLLenMask = 0x30; // mask to check for length tokens public const byte SQLFixedLen = 0x30; // Mask to check for fixed token public const byte SQLVarLen = 0x20; // Value to check for variable length token public const byte SQLZeroLen = 0x10; // Value to check for zero length token public const byte SQLVarCnt = 0x00; // Value to check for variable count token // Token masks for COLINFO status public const byte SQLDifferentName = 0x20; // column name different than select list name public const byte SQLExpression = 0x4; // column was result of an expression public const byte SQLKey = 0x8; // column is part of the key for the table public const byte SQLHidden = 0x10; // column not part of select list but added because part of key // Token masks for COLMETADATA flags // first byte public const byte Nullable = 0x1; public const byte Identity = 0x10; public const byte Updatability = 0xb; // mask off bits 3 and 4 // second byte public const byte ClrFixedLen = 0x1; // Fixed length CLR type public const byte IsColumnSet = 0x4; // Column is an XML representation of an aggregation of other columns // null values public const uint VARLONGNULL = 0xffffffff; // null value for text and image types public const int VARNULL = 0xffff; // null value for character and binary types public const int MAXSIZE = 8000; // max size for any column public const byte FIXEDNULL = 0; public const ulong UDTNULL = 0xffffffffffffffff; // SQL Server Data Type Tokens. public const int SQLVOID = 0x1f; public const int SQLTEXT = 0x23; public const int SQLVARBINARY = 0x25; public const int SQLINTN = 0x26; public const int SQLVARCHAR = 0x27; public const int SQLBINARY = 0x2d; public const int SQLIMAGE = 0x22; public const int SQLCHAR = 0x2f; public const int SQLINT1 = 0x30; public const int SQLBIT = 0x32; public const int SQLINT2 = 0x34; public const int SQLINT4 = 0x38; public const int SQLMONEY = 0x3c; public const int SQLDATETIME = 0x3d; public const int SQLFLT8 = 0x3e; public const int SQLFLTN = 0x6d; public const int SQLMONEYN = 0x6e; public const int SQLDATETIMN = 0x6f; public const int SQLFLT4 = 0x3b; public const int SQLMONEY4 = 0x7a; public const int SQLDATETIM4 = 0x3a; public const int SQLDECIMALN = 0x6a; public const int SQLNUMERICN = 0x6c; public const int SQLUNIQUEID = 0x24; public const int SQLBIGCHAR = 0xaf; public const int SQLBIGVARCHAR = 0xa7; public const int SQLBIGBINARY = 0xad; public const int SQLBIGVARBINARY = 0xa5; public const int SQLBITN = 0x68; public const int SQLNCHAR = 0xef; public const int SQLNVARCHAR = 0xe7; public const int SQLNTEXT = 0x63; public const int SQLUDT = 0xF0; // aggregate operator type TDS tokens, used by compute statements: public const int AOPCNTB = 0x09; public const int AOPSTDEV = 0x30; public const int AOPSTDEVP = 0x31; public const int AOPVAR = 0x32; public const int AOPVARP = 0x33; public const int AOPCNT = 0x4b; public const int AOPSUM = 0x4d; public const int AOPAVG = 0x4f; public const int AOPMIN = 0x51; public const int AOPMAX = 0x52; public const int AOPANY = 0x53; public const int AOPNOOP = 0x56; // SQL Server user-defined type tokens we care about public const int SQLTIMESTAMP = 0x50; public const int MAX_NUMERIC_LEN = 0x11; // 17 bytes of data for max numeric/decimal length public const int DEFAULT_NUMERIC_PRECISION = 0x1D; // 29 is the default max numeric precision(Decimal.MaxValue) if not user set public const int SPHINX_DEFAULT_NUMERIC_PRECISION = 0x1C; // 28 is the default max numeric precision for Sphinx(Decimal.MaxValue doesn't work for sphinx) public const int MAX_NUMERIC_PRECISION = 0x26; // 38 is max numeric precision; public const byte UNKNOWN_PRECISION_SCALE = 0xff; // -1 is value for unknown precision or scale // The following datatypes are specific to SHILOH (version 8) and later. public const int SQLINT8 = 0x7f; public const int SQLVARIANT = 0x62; // The following datatypes are specific to Yukon (version 9) or later public const int SQLXMLTYPE = 0xf1; public const int XMLUNICODEBOM = 0xfeff; public static readonly byte[] XMLUNICODEBOMBYTES = { 0xff, 0xfe }; // The following datatypes are specific to Katmai (version 10) or later public const int SQLTABLE = 0xf3; public const int SQLDATE = 0x28; public const int SQLTIME = 0x29; public const int SQLDATETIME2 = 0x2a; public const int SQLDATETIMEOFFSET = 0x2b; public const int DEFAULT_VARTIME_SCALE = 7; //Partially length prefixed datatypes constants. These apply to XMLTYPE, BIGVARCHRTYPE, // NVARCHARTYPE, and BIGVARBINTYPE. Valid for Yukon or later public const ulong SQL_PLP_NULL = 0xffffffffffffffff; // Represents null value public const ulong SQL_PLP_UNKNOWNLEN = 0xfffffffffffffffe; // Data coming in chunks, total length unknown public const int SQL_PLP_CHUNK_TERMINATOR = 0x00000000; // Represents end of chunked data. public const ushort SQL_USHORTVARMAXLEN = 0xffff; // Second ushort in TDS stream is this value if one of max types // TVPs require some new in-value control tokens: public const byte TVP_ROWCOUNT_ESTIMATE = 0x12; public const byte TVP_ROW_TOKEN = 0x01; public const byte TVP_END_TOKEN = 0x00; public const ushort TVP_NOMETADATA_TOKEN = 0xFFFF; public const byte TVP_ORDER_UNIQUE_TOKEN = 0x10; // TvpColumnMetaData flags public const int TVP_DEFAULT_COLUMN = 0x200; // TVP_ORDER_UNIQUE_TOKEN flags public const byte TVP_ORDERASC_FLAG = 0x1; public const byte TVP_ORDERDESC_FLAG = 0x2; public const byte TVP_UNIQUE_FLAG = 0x4; // RPC function names public const string SP_EXECUTESQL = "sp_executesql"; // used against 7.0 servers public const string SP_PREPEXEC = "sp_prepexec"; // used against 7.5 servers public const string SP_PREPARE = "sp_prepare"; // used against 7.0 servers public const string SP_EXECUTE = "sp_execute"; public const string SP_UNPREPARE = "sp_unprepare"; public const string SP_PARAMS = "sp_procedure_params_rowset"; public const string SP_PARAMS_MANAGED = "sp_procedure_params_managed"; public const string SP_PARAMS_MGD10 = "sp_procedure_params_100_managed"; // RPC ProcID's // NOTE: It is more efficient to call these procs using ProcID's instead of names public const ushort RPC_PROCID_CURSOR = 1; public const ushort RPC_PROCID_CURSOROPEN = 2; public const ushort RPC_PROCID_CURSORPREPARE = 3; public const ushort RPC_PROCID_CURSOREXECUTE = 4; public const ushort RPC_PROCID_CURSORPREPEXEC = 5; public const ushort RPC_PROCID_CURSORUNPREPARE = 6; public const ushort RPC_PROCID_CURSORFETCH = 7; public const ushort RPC_PROCID_CURSOROPTION = 8; public const ushort RPC_PROCID_CURSORCLOSE = 9; public const ushort RPC_PROCID_EXECUTESQL = 10; public const ushort RPC_PROCID_PREPARE = 11; public const ushort RPC_PROCID_EXECUTE = 12; public const ushort RPC_PROCID_PREPEXEC = 13; public const ushort RPC_PROCID_PREPEXECRPC = 14; public const ushort RPC_PROCID_UNPREPARE = 15; // For Transactions public const string TRANS_BEGIN = "BEGIN TRANSACTION"; public const string TRANS_COMMIT = "COMMIT TRANSACTION"; public const string TRANS_ROLLBACK = "ROLLBACK TRANSACTION"; public const string TRANS_IF_ROLLBACK = "IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION"; public const string TRANS_SAVE = "SAVE TRANSACTION"; // For Transactions - isolation levels public const string TRANS_READ_COMMITTED = "SET TRANSACTION ISOLATION LEVEL READ COMMITTED"; public const string TRANS_READ_UNCOMMITTED = "SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED"; public const string TRANS_REPEATABLE_READ = "SET TRANSACTION ISOLATION LEVEL REPEATABLE READ"; public const string TRANS_SERIALIZABLE = "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE"; public const string TRANS_SNAPSHOT = "SET TRANSACTION ISOLATION LEVEL SNAPSHOT"; // Batch RPC flags public const byte SHILOH_RPCBATCHFLAG = 0x80; public const byte YUKON_RPCBATCHFLAG = 0xFF; // RPC flags public const byte RPC_RECOMPILE = 0x1; public const byte RPC_NOMETADATA = 0x2; // RPC parameter class public const byte RPC_PARAM_BYREF = 0x1; public const byte RPC_PARAM_DEFAULT = 0x2; public const byte RPC_PARAM_IS_LOB_COOKIE = 0x8; // SQL parameter list text public const string PARAM_OUTPUT = "output"; // SQL Parameter constants public const int MAX_PARAMETER_NAME_LENGTH = 128; // metadata options (added around an existing sql statement) // prefixes public const string FMTONLY_ON = " SET FMTONLY ON;"; public const string FMTONLY_OFF = " SET FMTONLY OFF;"; // suffixes public const string BROWSE_ON = " SET NO_BROWSETABLE ON;"; public const string BROWSE_OFF = " SET NO_BROWSETABLE OFF;"; // generic table name public const string TABLE = "Table"; public const int EXEC_THRESHOLD = 0x3; // if the number of commands we execute is > than this threshold, than do prep/exec/unprep instead // of executesql. // dbnetlib error values public const short TIMEOUT_EXPIRED = -2; public const short ENCRYPTION_NOT_SUPPORTED = 20; // CAUTION: These are not error codes returned by SNI. This is used for backward compatibility // since netlib (now removed from sqlclient) returned these codes. // SQL error values (from sqlerrorcodes.h) public const int LOGON_FAILED = 18456; public const int PASSWORD_EXPIRED = 18488; public const int IMPERSONATION_FAILED = 1346; public const int P_TOKENTOOLONG = 103; // SNI\Win32 error values // NOTE: these are simply windows system error codes, not SNI specific public const uint SNI_UNINITIALIZED = unchecked((uint)-1); public const uint SNI_SUCCESS = 0; // The operation completed successfully. public const uint SNI_ERROR = 1; // Error public const uint SNI_WAIT_TIMEOUT = 258; // The wait operation timed out. public const uint SNI_SUCCESS_IO_PENDING = 997; // Overlapped I/O operation is in progress. // Windows Sockets Error Codes public const short SNI_WSAECONNRESET = 10054; // An existing connection was forcibly closed by the remote host. // SNI internal errors (shouldn't overlap with Win32 / socket errors) public const uint SNI_QUEUE_FULL = 1048576; // Packet queue is full // SNI flags public const uint SNI_SSL_VALIDATE_CERTIFICATE = 1; // This enables validation of server certificate public const uint SNI_SSL_USE_SCHANNEL_CACHE = 2; // This enables schannel session cache public const uint SNI_SSL_IGNORE_CHANNEL_BINDINGS = 0x10; // Used with SSL Provider, sent to SNIAddProvider in case of SQL Authentication & Encrypt. public const string DEFAULT_ENGLISH_CODE_PAGE_STRING = "iso_1"; public const short DEFAULT_ENGLISH_CODE_PAGE_VALUE = 1252; public const short CHARSET_CODE_PAGE_OFFSET = 2; internal const int MAX_SERVERNAME = 255; // Sql Statement Tokens in the DONE packet // (see ntdbms\ntinc\tokens.h) // internal const ushort SELECT = 0xc1; internal const ushort INSERT = 0xc3; internal const ushort DELETE = 0xc4; internal const ushort UPDATE = 0xc5; internal const ushort ABORT = 0xd2; internal const ushort BEGINXACT = 0xd4; internal const ushort ENDXACT = 0xd5; internal const ushort BULKINSERT = 0xf0; internal const ushort OPENCURSOR = 0x20; internal const ushort MERGE = 0x117; // Login data validation Rules // internal const ushort MAXLEN_HOSTNAME = 128; // the client machine name internal const ushort MAXLEN_USERNAME = 128; // the client user id internal const ushort MAXLEN_PASSWORD = 128; // the password supplied by the client internal const ushort MAXLEN_APPNAME = 128; // the client application name internal const ushort MAXLEN_SERVERNAME = 128; // the server name internal const ushort MAXLEN_CLIENTINTERFACE = 128; // the interface library name internal const ushort MAXLEN_LANGUAGE = 128; // the initial language internal const ushort MAXLEN_DATABASE = 128; // the initial database internal const ushort MAXLEN_ATTACHDBFILE = 260; // the filename for a database that is to be attached during the connection process internal const ushort MAXLEN_NEWPASSWORD = 128; // new password for the specified login. // array copied directly from tdssort.h from luxor public static readonly ushort[] CODE_PAGE_FROM_SORT_ID = { 0, /* 0 */ 0, /* 1 */ 0, /* 2 */ 0, /* 3 */ 0, /* 4 */ 0, /* 5 */ 0, /* 6 */ 0, /* 7 */ 0, /* 8 */ 0, /* 9 */ 0, /* 10 */ 0, /* 11 */ 0, /* 12 */ 0, /* 13 */ 0, /* 14 */ 0, /* 15 */ 0, /* 16 */ 0, /* 17 */ 0, /* 18 */ 0, /* 19 */ 0, /* 20 */ 0, /* 21 */ 0, /* 22 */ 0, /* 23 */ 0, /* 24 */ 0, /* 25 */ 0, /* 26 */ 0, /* 27 */ 0, /* 28 */ 0, /* 29 */ 437, /* 30 */ 437, /* 31 */ 437, /* 32 */ 437, /* 33 */ 437, /* 34 */ 0, /* 35 */ 0, /* 36 */ 0, /* 37 */ 0, /* 38 */ 0, /* 39 */ 850, /* 40 */ 850, /* 41 */ 850, /* 42 */ 850, /* 43 */ 850, /* 44 */ 0, /* 45 */ 0, /* 46 */ 0, /* 47 */ 0, /* 48 */ 850, /* 49 */ 1252, /* 50 */ 1252, /* 51 */ 1252, /* 52 */ 1252, /* 53 */ 1252, /* 54 */ 850, /* 55 */ 850, /* 56 */ 850, /* 57 */ 850, /* 58 */ 850, /* 59 */ 850, /* 60 */ 850, /* 61 */ 0, /* 62 */ 0, /* 63 */ 0, /* 64 */ 0, /* 65 */ 0, /* 66 */ 0, /* 67 */ 0, /* 68 */ 0, /* 69 */ 0, /* 70 */ 1252, /* 71 */ 1252, /* 72 */ 1252, /* 73 */ 1252, /* 74 */ 1252, /* 75 */ 0, /* 76 */ 0, /* 77 */ 0, /* 78 */ 0, /* 79 */ 1250, /* 80 */ 1250, /* 81 */ 1250, /* 82 */ 1250, /* 83 */ 1250, /* 84 */ 1250, /* 85 */ 1250, /* 86 */ 1250, /* 87 */ 1250, /* 88 */ 1250, /* 89 */ 1250, /* 90 */ 1250, /* 91 */ 1250, /* 92 */ 1250, /* 93 */ 1250, /* 94 */ 1250, /* 95 */ 1250, /* 96 */ 1250, /* 97 */ 1250, /* 98 */ 0, /* 99 */ 0, /* 100 */ 0, /* 101 */ 0, /* 102 */ 0, /* 103 */ 1251, /* 104 */ 1251, /* 105 */ 1251, /* 106 */ 1251, /* 107 */ 1251, /* 108 */ 0, /* 109 */ 0, /* 110 */ 0, /* 111 */ 1253, /* 112 */ 1253, /* 113 */ 1253, /* 114 */ 0, /* 115 */ 0, /* 116 */ 0, /* 117 */ 0, /* 118 */ 0, /* 119 */ 1253, /* 120 */ 1253, /* 121 */ 1253, /* 122 */ 0, /* 123 */ 1253, /* 124 */ 0, /* 125 */ 0, /* 126 */ 0, /* 127 */ 1254, /* 128 */ 1254, /* 129 */ 1254, /* 130 */ 0, /* 131 */ 0, /* 132 */ 0, /* 133 */ 0, /* 134 */ 0, /* 135 */ 1255, /* 136 */ 1255, /* 137 */ 1255, /* 138 */ 0, /* 139 */ 0, /* 140 */ 0, /* 141 */ 0, /* 142 */ 0, /* 143 */ 1256, /* 144 */ 1256, /* 145 */ 1256, /* 146 */ 0, /* 147 */ 0, /* 148 */ 0, /* 149 */ 0, /* 150 */ 0, /* 151 */ 1257, /* 152 */ 1257, /* 153 */ 1257, /* 154 */ 1257, /* 155 */ 1257, /* 156 */ 1257, /* 157 */ 1257, /* 158 */ 1257, /* 159 */ 1257, /* 160 */ 0, /* 161 */ 0, /* 162 */ 0, /* 163 */ 0, /* 164 */ 0, /* 165 */ 0, /* 166 */ 0, /* 167 */ 0, /* 168 */ 0, /* 169 */ 0, /* 170 */ 0, /* 171 */ 0, /* 172 */ 0, /* 173 */ 0, /* 174 */ 0, /* 175 */ 0, /* 176 */ 0, /* 177 */ 0, /* 178 */ 0, /* 179 */ 0, /* 180 */ 0, /* 181 */ 0, /* 182 */ 1252, /* 183 */ 1252, /* 184 */ 1252, /* 185 */ 1252, /* 186 */ 0, /* 187 */ 0, /* 188 */ 0, /* 189 */ 0, /* 190 */ 0, /* 191 */ 932, /* 192 */ 932, /* 193 */ 949, /* 194 */ 949, /* 195 */ 950, /* 196 */ 950, /* 197 */ 936, /* 198 */ 936, /* 199 */ 932, /* 200 */ 949, /* 201 */ 950, /* 202 */ 936, /* 203 */ 874, /* 204 */ 874, /* 205 */ 874, /* 206 */ 0, /* 207 */ 0, /* 208 */ 0, /* 209 */ 1252, /* 210 */ 1252, /* 211 */ 1252, /* 212 */ 1252, /* 213 */ 1252, /* 214 */ 1252, /* 215 */ 1252, /* 216 */ 1252, /* 217 */ 0, /* 218 */ 0, /* 219 */ 0, /* 220 */ 0, /* 221 */ 0, /* 222 */ 0, /* 223 */ 0, /* 224 */ 0, /* 225 */ 0, /* 226 */ 0, /* 227 */ 0, /* 228 */ 0, /* 229 */ 0, /* 230 */ 0, /* 231 */ 0, /* 232 */ 0, /* 233 */ 0, /* 234 */ 0, /* 235 */ 0, /* 236 */ 0, /* 237 */ 0, /* 238 */ 0, /* 239 */ 0, /* 240 */ 0, /* 241 */ 0, /* 242 */ 0, /* 243 */ 0, /* 244 */ 0, /* 245 */ 0, /* 246 */ 0, /* 247 */ 0, /* 248 */ 0, /* 249 */ 0, /* 250 */ 0, /* 251 */ 0, /* 252 */ 0, /* 253 */ 0, /* 254 */ 0, /* 255 */ }; internal enum TransactionManagerRequestType { GetDTCAddress = 0, Propagate = 1, Begin = 5, Promote = 6, Commit = 7, Rollback = 8, Save = 9 }; internal enum TransactionManagerIsolationLevel { Unspecified = 0x00, ReadUncommitted = 0x01, ReadCommitted = 0x02, RepeatableRead = 0x03, Serializable = 0x04, Snapshot = 0x05 } internal enum GenericType { MultiSet = 131, }; // Date, Time, DateTime2, DateTimeOffset specific constants internal static readonly long[] TICKS_FROM_SCALE = { 10000000, 1000000, 100000, 10000, 1000, 100, 10, 1, }; internal const int WHIDBEY_DATE_LENGTH = 10; internal static readonly int[] WHIDBEY_TIME_LENGTH = { 8, 10, 11, 12, 13, 14, 15, 16 }; internal static readonly int[] WHIDBEY_DATETIME2_LENGTH = { 19, 21, 22, 23, 24, 25, 26, 27 }; internal static readonly int[] WHIDBEY_DATETIMEOFFSET_LENGTH = { 26, 28, 29, 30, 31, 32, 33, 34 }; } internal enum SniContext { Undefined = 0, Snix_Connect, Snix_PreLoginBeforeSuccessfullWrite, Snix_PreLogin, Snix_LoginSspi, Snix_ProcessSspi, Snix_Login, Snix_EnableMars, Snix_AutoEnlist, Snix_GetMarsSession, Snix_Execute, Snix_Read, Snix_Close, Snix_SendRows, } }
using System; using System.Collections; using System.Linq; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using Microsoft.VisualStudio.TestTools.UnitTesting; using Prism.Regions; using Prism.Regions.Behaviors; using Prism.Wpf.Tests.Mocks; namespace Prism.Wpf.Tests.Regions.Behaviors { [TestClass] public class SelectorItemsSourceSyncRegionBehaviorFixture { [TestMethod] public void CanAttachToSelector() { SelectorItemsSourceSyncBehavior behavior = CreateBehavior(); behavior.Attach(); Assert.IsTrue(behavior.IsAttached); } [TestMethod] public void AttachSetsItemsSourceOfSelector() { SelectorItemsSourceSyncBehavior behavior = CreateBehavior(); var v1 = new Button(); var v2 = new Button(); behavior.Region.Add(v1); behavior.Region.Add(v2); behavior.Attach(); Assert.AreEqual(2, (behavior.HostControl as Selector).Items.Count); } [TestMethod] public void IfViewsHaveSortHintThenViewsAreProperlySorted() { SelectorItemsSourceSyncBehavior behavior = CreateBehavior(); var v1 = new MockSortableView1(); var v2 = new MockSortableView2(); var v3 = new MockSortableView3(); behavior.Attach(); behavior.Region.Add(v3); behavior.Region.Add(v2); behavior.Region.Add(v1); Assert.AreEqual(3, (behavior.HostControl as Selector).Items.Count); Assert.AreSame(v1, (behavior.HostControl as Selector).Items[0]); Assert.AreSame(v2, (behavior.HostControl as Selector).Items[1]); Assert.AreSame(v3, (behavior.HostControl as Selector).Items[2]); } [TestMethod] public void SelectionChangedShouldChangeActiveViews() { SelectorItemsSourceSyncBehavior behavior = CreateBehavior(); var v1 = new Button(); var v2 = new Button(); behavior.Region.Add(v1); behavior.Region.Add(v2); behavior.Attach(); (behavior.HostControl as Selector).SelectedItem = v1; var activeViews = behavior.Region.ActiveViews; Assert.AreEqual(1, activeViews.Count()); Assert.AreEqual(v1, activeViews.First()); (behavior.HostControl as Selector).SelectedItem = v2; Assert.AreEqual(1, activeViews.Count()); Assert.AreEqual(v2, activeViews.First()); } [TestMethod] public void ActiveViewChangedShouldChangeSelectedItem() { SelectorItemsSourceSyncBehavior behavior = CreateBehavior(); var v1 = new Button(); var v2 = new Button(); behavior.Region.Add(v1); behavior.Region.Add(v2); behavior.Attach(); behavior.Region.Activate(v1); Assert.AreEqual(v1, (behavior.HostControl as Selector).SelectedItem); behavior.Region.Activate(v2); Assert.AreEqual(v2, (behavior.HostControl as Selector).SelectedItem); } [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void ItemsSourceSetThrows() { SelectorItemsSourceSyncBehavior behavior = CreateBehavior(); (behavior.HostControl as Selector).ItemsSource = new[] {new Button()}; behavior.Attach(); } [TestMethod] public void ControlWithExistingBindingOnItemsSourceWithNullValueThrows() { var behavor = CreateBehavior(); Binding binding = new Binding("Enumerable"); binding.Source = new SimpleModel() { Enumerable = null }; (behavor.HostControl as Selector).SetBinding(ItemsControl.ItemsSourceProperty, binding); try { behavor.Attach(); } catch (Exception ex) { Assert.IsInstanceOfType(ex, typeof(InvalidOperationException)); StringAssert.Contains(ex.Message, "ItemsControl's ItemsSource property is not empty."); } } [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void AddingViewToTwoRegionsThrows() { var behavior1 = CreateBehavior(); var behavior2 = CreateBehavior(); behavior1.Attach(); behavior2.Attach(); var v1 = new Button(); behavior1.Region.Add(v1); behavior2.Region.Add(v1); } [TestMethod] public void ReactivatingViewAddsViewToTab() { var behavior1 = CreateBehavior(); behavior1.Attach(); var v1 = new Button(); var v2 = new Button(); behavior1.Region.Add(v1); behavior1.Region.Add(v2); behavior1.Region.Activate(v1); Assert.IsTrue(behavior1.Region.ActiveViews.First() == v1); behavior1.Region.Activate(v2); Assert.IsTrue(behavior1.Region.ActiveViews.First() == v2); behavior1.Region.Activate(v1); Assert.IsTrue(behavior1.Region.ActiveViews.First() == v1); } [TestMethod] public void ShouldAllowMultipleSelectedItemsForListBox() { var behavior1 = CreateBehavior(); ListBox listBox = new ListBox(); listBox.SelectionMode = SelectionMode.Multiple; behavior1.HostControl = listBox; behavior1.Attach(); var v1 = new Button(); var v2 = new Button(); behavior1.Region.Add(v1); behavior1.Region.Add(v2); listBox.SelectedItems.Add(v1); listBox.SelectedItems.Add(v2); Assert.IsTrue(behavior1.Region.ActiveViews.Contains(v1)); Assert.IsTrue(behavior1.Region.ActiveViews.Contains(v2)); } private SelectorItemsSourceSyncBehavior CreateBehavior() { Region region = new Region(); Selector selector = new TabControl(); var behavior = new SelectorItemsSourceSyncBehavior(); behavior.HostControl = selector; behavior.Region = region; return behavior; } private class SimpleModel { public IEnumerable Enumerable { get; set; } } } }
// $Id: mxPerimeter.cs,v 1.17 2012-01-11 09:06:56 gaudenz Exp $ // Copyright (c) 2007-2008, Gaudenz Alder using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace com.mxgraph { /// <summary> /// Defines the requirements for a perimeter function. /// </summary> /// <param name="bounds">Rectangle that represents the absolute bounds of the /// vertex.</param> /// <param name="vertex">Cell state that represents the vertex.</param> /// <param name="next">Point that represents the nearest neighbour point on the /// given edge.</param> /// <param name="orthogonal">Boolean that specifies if the orthogonal projection onto /// the perimeter should be returned. If this is false then the intersection /// of the perimeter and the line between the next and the center point is /// returned.</param> public delegate mxPoint mxPerimeterFunction(mxRectangle bounds, mxCellState vertex, mxPoint next, bool orthogonal); /// <summary> /// Provides various perimeter functions to be used in a style /// as the value of mxConstants.STYLE_PERIMETER. /// </summary> public class mxPerimeter { /// <summary> /// Describes a rectangular perimeter for the given bounds. /// </summary> public static mxPerimeterFunction RectanglePerimeter = delegate( mxRectangle bounds, mxCellState vertex, mxPoint next, bool orthogonal) { double cx = bounds.GetCenterX(); double cy = bounds.GetCenterY(); double dx = next.X - cx; double dy = next.Y - cy; double alpha = Math.Atan2(dy, dx); mxPoint p = new mxPoint(); double pi = Math.PI; double pi2 = Math.PI / 2; double beta = pi2 - alpha; double t = Math.Atan2(bounds.Height, bounds.Width); if (alpha < -pi + t || alpha > pi - t) { // Left edge p.X = bounds.X; p.Y = cy - bounds.Width * Math.Tan(alpha) / 2; } else if (alpha < -t) { // Top Edge p.Y = bounds.Y; p.X = cx - bounds.Height * Math.Tan(beta) / 2; } else if (alpha < t) { // Right Edge p.X = bounds.X + bounds.Width; p.Y = cy + bounds.Width * Math.Tan(alpha) / 2; } else { // Bottom Edge p.Y = bounds.Y + bounds.Height; p.X = cx + bounds.Height * Math.Tan(beta) / 2; } if (orthogonal) { if (next.X >= bounds.X && next.X <= bounds.X + bounds.Width) { p.X = next.X; } else if (next.Y >= bounds.Y && next.Y <= bounds.Y + bounds.Height) { p.Y = next.Y; } if (next.X < bounds.X) { p.X = bounds.X; } else if (next.X > bounds.X + bounds.Width) { p.X = bounds.X + bounds.Width; } if (next.Y < bounds.Y) { p.Y = bounds.Y; } else if (next.Y > bounds.Y + bounds.Height) { p.Y = bounds.Y + bounds.Height; } } return p; }; /// <summary> /// Describes an elliptic perimeter. /// </summary> public static mxPerimeterFunction EllipsePerimeter = delegate( mxRectangle bounds, mxCellState vertex, mxPoint next, bool orthogonal) { double x = bounds.X; double y = bounds.Y; double a = bounds.Width / 2; double b = bounds.Height / 2; double cx = x + a; double cy = y + b; double px = next.X; double py = next.Y; // Calculates straight line equation through // point and ellipse center y = d * x + h long dx = (long)(px - cx); long dy = (long)(py - cy); if (dx == 0 && dy != 0) { return new mxPoint(cx, cy + b * dy / Math.Abs(dy)); } else if (dx == 0 && dy == 0) { return new mxPoint(px, py); } if (orthogonal) { if (py >= y && py <= y + bounds.Height) { double ty = py - cy; double tx = Math.Sqrt(a * a * (1 - (ty * ty) / (b * b))); if (Double.IsNaN(tx)) { tx = 0; } if (px <= x) { tx = -tx; } return new mxPoint(cx + tx, py); } if (px >= x && px <= x + bounds.Width) { double tx = px - cx; double ty = Math.Sqrt(b * b * (1 - (tx * tx) / (a * a))); if (Double.IsNaN(ty)) { ty = 0; } if (py <= y) { ty = -ty; } return new mxPoint(px, cy + ty); } } // Calculates intersection double d = dy / dx; double h = cy - d * cx; double e = a * a * d * d + b * b; double f = -2 * cx * e; double g = a * a * d * d * cx * cx + b * b * cx * cx - a * a * b * b; double det = Math.Sqrt(f * f - 4 * e * g); // Two solutions (perimeter points) double xout1 = (-f + det) / (2 * e); double xout2 = (-f - det) / (2 * e); double yout1 = d * xout1 + h; double yout2 = d * xout2 + h; double dist1 = Math.Sqrt(Math.Pow((xout1 - px), 2) + Math.Pow((yout1 - py), 2)); double dist2 = Math.Sqrt(Math.Pow((xout2 - px), 2) + Math.Pow((yout2 - py), 2)); // Correct solution double xout = 0; double yout = 0; if (dist1 < dist2) { xout = xout1; yout = yout1; } else { xout = xout2; yout = yout2; } return new mxPoint(xout, yout); }; /// <summary> /// Describes a rhombus (aka diamond) perimeter. /// </summary> public static mxPerimeterFunction RhombusPerimeter = delegate( mxRectangle bounds, mxCellState vertex, mxPoint next, bool orthogonal) { double x = bounds.X; double y = bounds.Y; double w = bounds.Width; double h = bounds.Height; double cx = x + w / 2; double cy = y + h / 2; double px = next.X; double py = next.Y; // Special case for intersecting the diamond's corners if (cx == px) { if (cy > py) { return new mxPoint(cx, y); // top } else { return new mxPoint(cx, y + h); // bottom } } else if (cy == py) { if (cx > px) { return new mxPoint(x, cy); // left } else { return new mxPoint(x + w, cy); // right } } double tx = cx; double ty = cy; if (orthogonal) { if (px >= x && px <= x + w) { tx = px; } else if (py >= y && py <= y + h) { ty = py; } } // In which quadrant will the intersection be? // set the slope and offset of the border line accordingly if (px < cx) { if (py < cy) { return mxUtils.Intersection(px, py, tx, ty, cx, y, x, cy); } else { return mxUtils.Intersection(px, py, tx, ty, cx, y + h, x, cy); } } else if (py < cy) { return mxUtils.Intersection(px, py, tx, ty, cx, y, x + w, cy); } else { return mxUtils.Intersection(px, py, tx, ty, cx, y + h, x + w, cy); } }; /// <summary> /// Describes a triangle perimeter. /// </summary> public static mxPerimeterFunction TrianglePerimeter = delegate( mxRectangle bounds, mxCellState vertex, mxPoint next, bool orthogonal) { string direction = (vertex != null) ? mxUtils.GetString( vertex.Style, mxConstants.STYLE_DIRECTION, mxConstants.DIRECTION_EAST) : mxConstants.DIRECTION_EAST; bool vertical = direction.Equals(mxConstants.DIRECTION_NORTH) || direction.Equals(mxConstants.DIRECTION_SOUTH); double x = bounds.X; double y = bounds.Y; double w = bounds.Width; double h = bounds.Height; double cx = x + w / 2; double cy = y + h / 2; mxPoint start = new mxPoint(x, y); mxPoint corner = new mxPoint(x + w, cy); mxPoint end = new mxPoint(x, y + h); if (direction.Equals(mxConstants.DIRECTION_NORTH)) { start = end; corner = new mxPoint(cx, y); end = new mxPoint(x + w, y + h); } else if (direction.Equals(mxConstants.DIRECTION_SOUTH)) { corner = new mxPoint(cx, y + h); end = new mxPoint(x + w, y); } else if (direction.Equals(mxConstants.DIRECTION_WEST)) { start = new mxPoint(x + w, y); corner = new mxPoint(x, cy); end = new mxPoint(x + w, y + h); } // Compute angle double dx = next.X - cx; double dy = next.Y - cy; double alpha = (vertical) ? Math.Atan2(dx, dy) : Math.Atan2(dy, dx); double t = (vertical) ? Math.Atan2(w, h) : Math.Atan2(h, w); bool baseSide = false; if (direction.Equals(mxConstants.DIRECTION_NORTH) || direction.Equals(mxConstants.DIRECTION_WEST)) { baseSide = alpha > -t && alpha < t; } else { baseSide = alpha < -Math.PI + t || alpha > Math.PI - t; } mxPoint result = null; if (baseSide) { if (orthogonal && ((vertical && next.X >= start.X && next.X <= end.X) || (!vertical && next.Y >= start.Y && next.Y <= end.Y))) { if (vertical) { result = new mxPoint(next.X, start.Y); } else { result = new mxPoint(start.X, next.Y); } } else { if (direction.Equals(mxConstants.DIRECTION_EAST)) { result = new mxPoint(x, y + h / 2 - w * Math.Tan(alpha) / 2); } else if (direction.Equals(mxConstants.DIRECTION_NORTH)) { result = new mxPoint(x + w / 2 + h * Math.Tan(alpha) / 2, y + h); } else if (direction.Equals(mxConstants.DIRECTION_SOUTH)) { result = new mxPoint(x + w / 2 - h * Math.Tan(alpha) / 2, y); } else if (direction.Equals(mxConstants.DIRECTION_WEST)) { result = new mxPoint(x + w, y + h / 2 + w * Math.Tan(alpha) / 2); } else { } } } else { if (orthogonal) { mxPoint pt = new mxPoint(cx, cy); if (next.Y >= y && next.Y <= y + h) { pt.X = (vertical) ? cx : ( (direction.Equals(mxConstants.DIRECTION_WEST)) ? x + w : x); pt.Y = next.Y; } else if (next.X >= x && next.X <= x + w) { pt.X = next.X; pt.Y = (!vertical) ? cy : ( (direction.Equals(mxConstants.DIRECTION_NORTH)) ? y + h : y); } // Compute angle dx = next.X - pt.X; dy = next.Y - pt.Y; cx = pt.X; cy = pt.Y; } if ((vertical && next.X <= x + w / 2) || (!vertical && next.Y <= y + h / 2)) { result = mxUtils.Intersection(next.X, next.Y, cx, cy, start.X, start.Y, corner.X, corner.Y); } else { result = mxUtils.Intersection(next.X, next.Y, cx, cy, corner.X, corner.Y, end.X, end.Y); } } if (result == null) { result = new mxPoint(cx, cy); } return result; }; } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Sprites; using osu.Framework.Input.Events; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osuTK; using osuTK.Input; namespace osu.Game.Screens.Edit.Compose.Components { public class SelectionBox : CompositeDrawable { public const float BORDER_RADIUS = 3; public Func<float, bool> OnRotation; public Func<Vector2, Anchor, bool> OnScale; public Func<Direction, bool> OnFlip; public Func<bool> OnReverse; public Action OperationStarted; public Action OperationEnded; private bool canReverse; /// <summary> /// Whether pattern reversing support should be enabled. /// </summary> public bool CanReverse { get => canReverse; set { if (canReverse == value) return; canReverse = value; recreate(); } } private bool canRotate; /// <summary> /// Whether rotation support should be enabled. /// </summary> public bool CanRotate { get => canRotate; set { if (canRotate == value) return; canRotate = value; recreate(); } } private bool canScaleX; /// <summary> /// Whether vertical scale support should be enabled. /// </summary> public bool CanScaleX { get => canScaleX; set { if (canScaleX == value) return; canScaleX = value; recreate(); } } private bool canScaleY; /// <summary> /// Whether horizontal scale support should be enabled. /// </summary> public bool CanScaleY { get => canScaleY; set { if (canScaleY == value) return; canScaleY = value; recreate(); } } private string text; public string Text { get => text; set { if (value == text) return; text = value; if (selectionDetailsText != null) selectionDetailsText.Text = value; } } private SelectionBoxDragHandleContainer dragHandles; private FillFlowContainer buttons; private OsuSpriteText selectionDetailsText; [Resolved] private OsuColour colours { get; set; } [BackgroundDependencyLoader] private void load() => recreate(); protected override bool OnKeyDown(KeyDownEvent e) { if (e.Repeat || !e.ControlPressed) return false; bool runOperationFromHotkey(Func<bool> operation) { operationStarted(); bool result = operation?.Invoke() ?? false; operationEnded(); return result; } switch (e.Key) { case Key.G: return CanReverse && runOperationFromHotkey(OnReverse); case Key.H: return CanScaleX && runOperationFromHotkey(() => OnFlip?.Invoke(Direction.Horizontal) ?? false); case Key.J: return CanScaleY && runOperationFromHotkey(() => OnFlip?.Invoke(Direction.Vertical) ?? false); } return base.OnKeyDown(e); } private void recreate() { if (LoadState < LoadState.Loading) return; InternalChildren = new Drawable[] { new Container { Name = "info text", AutoSizeAxes = Axes.Both, Children = new Drawable[] { new Box { Colour = colours.YellowDark, RelativeSizeAxes = Axes.Both, }, selectionDetailsText = new OsuSpriteText { Padding = new MarginPadding(2), Colour = colours.Gray0, Font = OsuFont.Default.With(size: 11), Text = text, } } }, new Container { Masking = true, BorderThickness = BORDER_RADIUS, BorderColour = colours.YellowDark, RelativeSizeAxes = Axes.Both, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, AlwaysPresent = true, Alpha = 0 }, } }, dragHandles = new SelectionBoxDragHandleContainer { RelativeSizeAxes = Axes.Both, // ensures that the centres of all drag handles line up with the middle of the selection box border. Padding = new MarginPadding(BORDER_RADIUS / 2) }, buttons = new FillFlowContainer { Y = 20, AutoSizeAxes = Axes.Both, Direction = FillDirection.Horizontal, Anchor = Anchor.BottomCentre, Origin = Anchor.Centre } }; if (CanScaleX) addXScaleComponents(); if (CanScaleX && CanScaleY) addFullScaleComponents(); if (CanScaleY) addYScaleComponents(); if (CanRotate) addRotationComponents(); if (CanReverse) addButton(FontAwesome.Solid.Backward, "Reverse pattern (Ctrl-G)", () => OnReverse?.Invoke()); } private void addRotationComponents() { addButton(FontAwesome.Solid.Undo, "Rotate 90 degrees counter-clockwise", () => OnRotation?.Invoke(-90)); addButton(FontAwesome.Solid.Redo, "Rotate 90 degrees clockwise", () => OnRotation?.Invoke(90)); addRotateHandle(Anchor.TopLeft); addRotateHandle(Anchor.TopRight); addRotateHandle(Anchor.BottomLeft); addRotateHandle(Anchor.BottomRight); } private void addYScaleComponents() { addButton(FontAwesome.Solid.ArrowsAltV, "Flip vertically (Ctrl-J)", () => OnFlip?.Invoke(Direction.Vertical)); addScaleHandle(Anchor.TopCentre); addScaleHandle(Anchor.BottomCentre); } private void addFullScaleComponents() { addScaleHandle(Anchor.TopLeft); addScaleHandle(Anchor.TopRight); addScaleHandle(Anchor.BottomLeft); addScaleHandle(Anchor.BottomRight); } private void addXScaleComponents() { addButton(FontAwesome.Solid.ArrowsAltH, "Flip horizontally (Ctrl-H)", () => OnFlip?.Invoke(Direction.Horizontal)); addScaleHandle(Anchor.CentreLeft); addScaleHandle(Anchor.CentreRight); } private void addButton(IconUsage icon, string tooltip, Action action) { var button = new SelectionBoxButton(icon, tooltip) { Action = action }; button.OperationStarted += operationStarted; button.OperationEnded += operationEnded; buttons.Add(button); } private void addScaleHandle(Anchor anchor) { var handle = new SelectionBoxScaleHandle { Anchor = anchor, HandleDrag = e => OnScale?.Invoke(e.Delta, anchor) }; handle.OperationStarted += operationStarted; handle.OperationEnded += operationEnded; dragHandles.AddScaleHandle(handle); } private void addRotateHandle(Anchor anchor) { var handle = new SelectionBoxRotationHandle { Anchor = anchor, HandleDrag = e => OnRotation?.Invoke(convertDragEventToAngleOfRotation(e)) }; handle.OperationStarted += operationStarted; handle.OperationEnded += operationEnded; dragHandles.AddRotationHandle(handle); } private int activeOperations; private float convertDragEventToAngleOfRotation(DragEvent e) { // Adjust coordinate system to the center of SelectionBox float startAngle = MathF.Atan2(e.LastMousePosition.Y - DrawHeight / 2, e.LastMousePosition.X - DrawWidth / 2); float endAngle = MathF.Atan2(e.MousePosition.Y - DrawHeight / 2, e.MousePosition.X - DrawWidth / 2); return (endAngle - startAngle) * 180 / MathF.PI; } private void operationEnded() { if (--activeOperations == 0) OperationEnded?.Invoke(); } private void operationStarted() { if (activeOperations++ == 0) OperationStarted?.Invoke(); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using SmartCalendar.API.Areas.HelpPage.ModelDescriptions; using SmartCalendar.API.Areas.HelpPage.Models; namespace SmartCalendar.API.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.IO; using NUnit.Framework; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.IO; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Encoders; using Org.BouncyCastle.Utilities.Test; namespace Org.BouncyCastle.Tests { /// <remarks> /// Basic FIPS test class for a block cipher, just to make sure ECB/CBC/OFB/CFB are behaving /// correctly. Tests from <a href="http://www.itl.nist.gov/fipspubs/fip81.htm">FIPS 81</a>. /// </remarks> [TestFixture] public class FipsDesTest : ITest { private static readonly string[] fips1Tests = { "DES/ECB/NoPadding", "3fa40e8a984d48156a271787ab8883f9893d51ec4b563b53", "DES/CBC/NoPadding", "e5c7cdde872bf27c43e934008c389c0f683788499a7c05f6", "DES/CFB/NoPadding", "f3096249c7f46e51a69e839b1a92f78403467133898ea622" }; private static readonly string[] fips2Tests = { "DES/CFB8/NoPadding", "f31fda07011462ee187f", "DES/OFB8/NoPadding", "f34a2850c9c64985d684" }; private static readonly byte[] input1 = Hex.Decode("4e6f77206973207468652074696d6520666f7220616c6c20"); private static readonly byte[] input2 = Hex.Decode("4e6f7720697320746865"); public string Name { get { return "FIPSDES"; } } public ITestResult doTest( string algorithm, byte[] input, byte[] output) { KeyParameter key; IBufferedCipher inCipher, outCipher; CipherStream cIn, cOut; MemoryStream bIn, bOut; // IvParameterSpec spec = new IvParameterSpec(); byte[] spec = Hex.Decode("1234567890abcdef"); try { key = new DesParameters(Hex.Decode("0123456789abcdef")); inCipher = CipherUtilities.GetCipher(algorithm); outCipher = CipherUtilities.GetCipher(algorithm); if (algorithm.StartsWith("DES/ECB")) { outCipher.Init(true, key); } else { outCipher.Init(true, new ParametersWithIV(key, spec)); } } catch (Exception e) { return new SimpleTestResult(false, Name + ": " + algorithm + " failed initialisation - " + e.ToString(), e); } try { if (algorithm.StartsWith("DES/ECB")) { inCipher.Init(false, key); } else { inCipher.Init(false, new ParametersWithIV(key, spec)); } } catch (Exception e) { return new SimpleTestResult(false, Name + ": " + algorithm + " failed initialisation - " + e.ToString(), e); } // // encryption pass // bOut = new MemoryStream(); cOut = new CipherStream(bOut, null, outCipher); try { for (int i = 0; i != input.Length / 2; i++) { cOut.WriteByte(input[i]); } cOut.Write(input, input.Length / 2, input.Length - input.Length / 2); cOut.Close(); } catch (IOException e) { return new SimpleTestResult(false, Name + ": " + algorithm + " failed encryption - " + e.ToString()); } byte[] bytes = bOut.ToArray(); if (!Arrays.AreEqual(bytes, output)) { return new SimpleTestResult(false, Name + ": " + algorithm + " failed encryption - expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(bytes)); } // // decryption pass // bIn = new MemoryStream(bytes, false); cIn = new CipherStream(bIn, inCipher, null); try { BinaryReader dIn = new BinaryReader(cIn); bytes = new byte[input.Length]; for (int i = 0; i != input.Length / 2; i++) { bytes[i] = dIn.ReadByte(); } int remaining = bytes.Length - input.Length / 2; byte[] extra = dIn.ReadBytes(remaining); if (extra.Length < remaining) throw new EndOfStreamException(); extra.CopyTo(bytes, input.Length / 2); } catch (Exception e) { return new SimpleTestResult(false, Name + ": " + algorithm + " failed encryption - " + e.ToString()); } if (!Arrays.AreEqual(bytes, input)) { return new SimpleTestResult(false, Name + ": " + algorithm + " failed decryption - expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(bytes)); } return new SimpleTestResult(true, Name + ": " + algorithm + " Okay"); } public ITestResult Perform() { for (int i = 0; i != fips1Tests.Length; i += 2) { ITestResult result = doTest(fips1Tests[i], input1, Hex.Decode(fips1Tests[i + 1])); if (!result.IsSuccessful()) { return result; } } for (int i = 0; i != fips2Tests.Length; i += 2) { ITestResult result = doTest(fips2Tests[i], input2, Hex.Decode(fips2Tests[i + 1])); if (!result.IsSuccessful()) { return result; } } return new SimpleTestResult(true, Name + ": Okay"); } public static void Main( string[] args) { ITest test = new FipsDesTest(); ITestResult result = test.Perform(); Console.WriteLine(result); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } } }
// http://www.darkfader.net/toolbox/convert/ test units using libaxolotl; using libaxolotl.protocol; using libaxolotl.state; using System; using System.Collections.Generic; using System.Linq; // for ExtraFunctions using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using libaxolotl.ecc; using libaxolotl.util; using System.Security.Cryptography; // temporary oly for testing using libaxolotl.state.impl; namespace WhatsAppApi.Helper { public class AxolotlManager : WhatsAppBase, AxolotlStore { Dictionary<string, List<ProtocolTreeNode>> pending_nodes = new Dictionary<string, List<ProtocolTreeNode>>(); Dictionary<string, ProtocolTreeNode> retryNodes = new Dictionary<string, ProtocolTreeNode>(); Dictionary<string, int> retryCounters = new Dictionary<string,int>(); Dictionary<string, SessionCipher> sessionCiphers = new Dictionary<string, SessionCipher>(); List<string> cipherKeys = new List<string>(); List<string> v2Jids = new List<string>(); bool replaceKey = false; /// <summary> /// /// </summary> public AxolotlManager() { } /// <summary> /// intercept iq and precess the keys /// </summary> /// <param name="node"></param> public ProtocolTreeNode[] ProcessIqTreeNode(ProtocolTreeNode node) { try { if (cipherKeys.Contains(node.GetAttribute("id"))) { cipherKeys.Remove(node.GetAttribute("id")); foreach (var child in node.children) { string jid = child.GetChild("user").GetAttribute("jid"); uint registrationId = deAdjustId(child.GetChild("registration").GetData()); IdentityKey identityKey = new IdentityKey(new DjbECPublicKey(child.GetChild("identity").GetData())); uint signedPreKeyId = deAdjustId(child.GetChild("skey").GetChild("id").GetData()); DjbECPublicKey signedPreKeyPub = new DjbECPublicKey(child.GetChild("skey").GetChild("value").GetData()); byte[] signedPreKeySig = child.GetChild("skey").GetChild("signature").GetData(); uint preKeyId = deAdjustId(child.GetChild("key").GetChild("id").GetData()); DjbECPublicKey preKeyPublic = new DjbECPublicKey(child.GetChild("key").GetChild("value").GetData()); PreKeyBundle preKeyBundle = new PreKeyBundle(registrationId, 1, preKeyId, preKeyPublic, signedPreKeyId, signedPreKeyPub, signedPreKeySig, identityKey); SessionBuilder sessionBuilder = new SessionBuilder(this, this, this, this, new AxolotlAddress(ExtractNumber(jid), 1)); // now do the work return nodelist sessionBuilder.process(preKeyBundle); if (pending_nodes.ContainsKey(ExtractNumber(jid))){ var pendingNodes = pending_nodes[ExtractNumber(jid)].ToArray(); pending_nodes.Remove(ExtractNumber(jid)); return pendingNodes; } } } } catch (Exception e) { } finally { } return null; } /// <summary> /// /// </summary> /// <param name="node"></param> /// <returns></returns> public ProtocolTreeNode processEncryptedNode(ProtocolTreeNode node) { string from = node.GetAttribute("from"); string author = string.Empty; string version = string.Empty; string encType = string.Empty; byte[] encMsg = null; ProtocolTreeNode rtnNode = null; if (from.IndexOf("s.whatsapp.net", 0) > -1) { author = ExtractNumber(node.GetAttribute("from")); version = node.GetChild("enc").GetAttribute("v"); encType = node.GetChild("enc").GetAttribute("type"); encMsg = node.GetChild("enc").GetData(); if (!ContainsSession(new AxolotlAddress(author, 1))) { //we don't have the session to decrypt, save it in pending and process it later addPendingNode(node); Helper.DebugAdapter.Instance.fireOnPrintDebug("info : Requesting cipher keys from " + author); sendGetCipherKeysFromUser(author); } else { //decrypt the message with the session if (node.GetChild("enc").GetAttribute("count") == "") setRetryCounter(node.GetAttribute("id"), 1); if (version == "2"){ if (!v2Jids.Contains(author)) v2Jids.Add(author); } object plaintext = decryptMessage(from, encMsg, encType, node.GetAttribute("id"), node.GetAttribute("t")); if (plaintext.GetType() == typeof(bool) && false == (bool)plaintext) { sendRetry(node, from, node.GetAttribute("id"), node.GetAttribute("t")); Helper.DebugAdapter.Instance.fireOnPrintDebug("info : " + string.Format("Couldn't decrypt message id {0} from {1}. Retrying.", node.GetAttribute("id"), author)); return node; // could not decrypt } // success now lets clear all setting and return node if (retryCounters.ContainsKey(node.GetAttribute("id"))) retryCounters.Remove(node.GetAttribute("id")); if (retryNodes.ContainsKey(node.GetAttribute("id"))) retryNodes.Remove(node.GetAttribute("id")); switch (node.GetAttribute("type")) { case "text": //Convert to list. List<ProtocolTreeNode> children = node.children.ToList(); List<KeyValue> attributeHash = node.attributeHash.ToList(); children.Add(new ProtocolTreeNode("body", null, null, (byte[])plaintext)); rtnNode = new ProtocolTreeNode(node.tag, attributeHash.ToArray(), children.ToArray(), node.data); break; case "media": // NOT IMPLEMENTED YET break; } Helper.DebugAdapter.Instance.fireOnPrintDebug("info : " + string.Format("Decrypted message with {0} id from {1}", node.GetAttribute("id"), author)); return rtnNode; } } return node; } /// <summary> /// decrypt an incomming message /// </summary> /// <param name="from"></param> /// <param name="ciphertext"></param> /// <param name="type"></param> /// <param name="id"></param> /// <param name="t"></param> /// <param name="retry_from"></param> /// <param name="skip_unpad"></param> public object decryptMessage(string from, byte[] ciphertext, string type, string id, string t, string retry_from = null, bool skip_unpad = false){ string version = "2"; #region pkmsg routine if (type == "pkmsg") { if (v2Jids.Contains(ExtractNumber(from))) version = "2"; try { PreKeyWhisperMessage preKeyWhisperMessage = new PreKeyWhisperMessage(ciphertext); SessionCipher sessionCipher = getSessionCipher(ExtractNumber(from)); byte[] plaintext = sessionCipher.decrypt(preKeyWhisperMessage); String text = WhatsApp.SYSEncoding.GetString(plaintext); if (version == "2" && !skip_unpad) return unpadV2Plaintext(text); } catch (Exception e){ // ErrorAxolotl(e.Message); return false; } } #endregion #region WhisperMessage routine if (type == "msg") { if (v2Jids.Contains(ExtractNumber(from))) version = "2"; try { PreKeyWhisperMessage preKeyWhisperMessage = new PreKeyWhisperMessage(ciphertext); SessionCipher sessionCipher = getSessionCipher(ExtractNumber(from)); byte[] plaintext = sessionCipher.decrypt(preKeyWhisperMessage); String text = WhatsApp.SYSEncoding.GetString(plaintext); if (version == "2" && !skip_unpad) return unpadV2Plaintext(text); } catch (Exception e) { } } #endregion #region Group message Cipher routine if (type == "skmsg") { throw new NotImplementedException(); } #endregion return false; } /// <summary> /// Send a request to get cipher keys from an user /// </summary> /// <param name="number">Phone number of the user you want to get the cipher keys</param> /// <param name="replaceKey"></param> public void sendGetCipherKeysFromUser(string number, bool replaceKeyIn = false) { replaceKey = replaceKeyIn; var msgId = TicketManager.GenerateId(); cipherKeys.Add(msgId); ProtocolTreeNode user = new ProtocolTreeNode("user", new[] { new KeyValue("jid", ApiBase.GetJID(number)), }, null, null); ProtocolTreeNode keyNode = new ProtocolTreeNode("key", null, new ProtocolTreeNode[] { user }, null); ProtocolTreeNode Node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", msgId), new KeyValue("xmlns", "encrypt"), new KeyValue("type", "get"), new KeyValue("to", "s.whatsapp.net") }, new ProtocolTreeNode[] { keyNode }, null); this.SendNode(Node); } /// <summary> /// return the stored session cypher for this number /// </summary> public SessionCipher getSessionCipher(string number) { if (sessionCiphers.ContainsKey(number)) { return sessionCiphers[number]; }else{ AxolotlAddress address = new AxolotlAddress(number, 1); sessionCiphers.Add(number, new SessionCipher(this, this, this, this, address)); return sessionCiphers[number]; } } /// <summary> /// Generate the keysets for ourself /// </summary> /// <returns></returns> public bool sendSetPreKeys(bool isnew = false) { uint registrationId = 0; if (!isnew) registrationId = (uint)this.GetLocalRegistrationId(); else registrationId = libaxolotl.util.KeyHelper.generateRegistrationId(true); Random random = new Random(); uint randomid = (uint)libaxolotl.util.KeyHelper.getRandomSequence(5000);//65536 IdentityKeyPair identityKeyPair = libaxolotl.util.KeyHelper.generateIdentityKeyPair(); byte[] privateKey = identityKeyPair.getPrivateKey().serialize(); byte[] publicKey = identityKeyPair.getPublicKey().getPublicKey().serialize(); IList<PreKeyRecord> preKeys = libaxolotl.util.KeyHelper.generatePreKeys((uint)random.Next(), 200); SignedPreKeyRecord signedPreKey = libaxolotl.util.KeyHelper.generateSignedPreKey(identityKeyPair, randomid); PreKeyRecord lastResortKey = libaxolotl.util.KeyHelper.generateLastResortPreKey(); this.StorePreKeys(preKeys); this.StoreLocalData(registrationId, identityKeyPair.getPublicKey().serialize(), identityKeyPair.getPrivateKey().serialize()); this.StoreSignedPreKey(signedPreKey.getId(), signedPreKey); // FOR INTERNAL TESTING ONLY //this.InMemoryTestSetup(identityKeyPair, registrationId); ProtocolTreeNode[] preKeyNodes = new ProtocolTreeNode[200]; for (int i = 0; i < 200; i++) { byte[] prekeyId = adjustId(preKeys[i].getId().ToString()).Skip(1).ToArray(); byte[] prekey = preKeys[i].getKeyPair().getPublicKey().serialize().Skip(1).ToArray(); ProtocolTreeNode NodeId = new ProtocolTreeNode("id", null, null, prekeyId); ProtocolTreeNode NodeValue = new ProtocolTreeNode("value", null, null, prekey); preKeyNodes[i] = new ProtocolTreeNode("key", null, new ProtocolTreeNode[] { NodeId, NodeValue }, null); } ProtocolTreeNode registration = new ProtocolTreeNode("registration", null, null, adjustId(registrationId.ToString())); ProtocolTreeNode type = new ProtocolTreeNode("type", null, null, new byte[] { Curve.DJB_TYPE }); ProtocolTreeNode list = new ProtocolTreeNode("list", null, preKeyNodes, null); ProtocolTreeNode sid = new ProtocolTreeNode("id", null, null, adjustId(signedPreKey.getId().ToString(), true)); ProtocolTreeNode identity = new ProtocolTreeNode("identity", null, null, identityKeyPair.getPublicKey().getPublicKey().serialize().Skip(1).ToArray()); ProtocolTreeNode value = new ProtocolTreeNode("value", null, null, signedPreKey.getKeyPair().getPublicKey().serialize().Skip(1).ToArray()); ProtocolTreeNode signature = new ProtocolTreeNode("signature", null, null, signedPreKey.getSignature()); ProtocolTreeNode secretKey = new ProtocolTreeNode("skey", null, new ProtocolTreeNode[] { sid, value, signature }, null); String id = TicketManager.GenerateId(); Helper.DebugAdapter.Instance.fireOnPrintDebug(string.Format("axolotl id = {0}", id)); ProtocolTreeNode Node = new ProtocolTreeNode("iq", new KeyValue[] { new KeyValue("id", id), new KeyValue("to", "s.whatsapp.net"), new KeyValue("type", "set"), new KeyValue("xmlns", "encrypt") }, new ProtocolTreeNode[] { identity, registration, type, list, secretKey }, null); this.SendNode(Node); return true; } /// <summary> /// /// </summary> public void resetEncryption() { } /// <summary> /// jid from address /// </summary> /// <param name="from"></param> /// <returns></returns> public string ExtractNumber(string from) { return new StringBuilder(from).Replace("@s.whatsapp.net", "").Replace("@g.us", "").ToString(); } /// <summary> /// add a node to the queue for latter processing /// due to missing cyper keys /// </summary> /// <param name="node"></param> public void addPendingNode(ProtocolTreeNode node) { string number = string.Empty; string from = node.GetAttribute("from"); if (from.IndexOf("s.whatsapp.net", 0) > -1) number = ExtractNumber(node.GetAttribute("from")); else number = ExtractNumber(node.GetAttribute("participant")); if (pending_nodes.ContainsKey(number)) { pending_nodes[number].Add(node); } else { pending_nodes.Add(number, new List<ProtocolTreeNode> { node }); } } /// <summary> /// increment the retry counters base /// </summary> /// <param name="id"></param> /// <param name="counter"></param> public void setRetryCounter(string id, int counter) { // retryCounters[$id] = $counter; } /// <summary> /// send a retry to reget this node /// </summary> /// <param name="nod"></param> /// <param name="to"></param> /// <param name="id"></param> /// <param name="t"></param> /// <param name="participant"></param> public void sendRetry(ProtocolTreeNode node, string to, string id, string t, string participant = null) { ProtocolTreeNode returnNode = null; #region update retry counters if (!retryCounters.ContainsKey(id)) { retryCounters.Add(id, 1); }else{ if (retryNodes.ContainsKey(id)) { retryNodes[id] = node; }else{ retryNodes.Add(id, node); } } #endregion if (retryCounters[id] > 2) resetEncryption(); retryCounters[id]++; ProtocolTreeNode retryNode = new ProtocolTreeNode("retry", new[] { new KeyValue("v", "1"), new KeyValue("count", retryCounters[id].ToString()), new KeyValue("id", id), new KeyValue("t", t) }, null, null); byte[] regid = adjustId(GetLocalRegistrationId().ToString()); ProtocolTreeNode registrationNode = new ProtocolTreeNode("registration", null, null, regid); // if (participant != null) //isgroups group retry // attrGrp.Add(new KeyValue("participant", participant)); returnNode = new ProtocolTreeNode("receipt", new[] { new KeyValue("id", id), new KeyValue("to", to), new KeyValue("type", "retry"), new KeyValue("t", t) }, new ProtocolTreeNode[] { retryNode, registrationNode }, null); this.SendNode(returnNode); } /// <summary> /// /// </summary> /// <param name="val"></param> /// <returns></returns> public uint deAdjustId(byte[] val) { byte[] newval = null; byte[] bytebase = new byte[] { (byte) 0x00 }; byte[] rv = bytebase.Concat(val).ToArray(); if (val.Length < 4) newval = rv; else newval = val; byte[] reversed = newval.Reverse().ToArray(); return BitConverter.ToUInt32(reversed, 0); } /// <summary> /// /// </summary> /// <param name="id"></param> public byte[] adjustId(String id, bool limitsix = false) { uint idx = uint.Parse(id); byte[] bytes = BitConverter.GetBytes(idx); uint atomSize = BitConverter.ToUInt32(bytes, 0); Array.Reverse(bytes, 0, bytes.Length); string data = bin2Hex(bytes); if (!string.IsNullOrEmpty(data) && limitsix) data = (data.Length <= 6) ? data : data.Substring(data.Length - 6); while (data.Length < 6){ data = "0" + data; } return hex2Bin(data); } /// <summary> /// /// </summary> /// <param name="hex"></param> /// <returns></returns> public byte[] hex2Bin(String hex) { // return (from i in Enumerable.Range(0, hex.Length / 2) // select Convert.ToByte(hex.Substring(i * 2, 2), 16)).ToArray(); int NumberChars = hex.Length; byte[] bytes = new byte[NumberChars / 2]; for (int i = 0; i < NumberChars; i += 2) bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16); return bytes; } static string bin2Hex(byte[] bin) { return BitConverter.ToString(bin).Replace("-", string.Empty).ToLower(); #region old code /* StringBuilder sb = new StringBuilder(bin.Length *2); foreach (byte b in bin) { sb.Append(b.ToString("x").PadLeft(2, '0')); } return sb.ToString(); */ #endregion } /// <summary> /// /// </summary> /// <param name="strBin"></param> /// <returns></returns> public string bin2HexXX(string strBin) { int decNumber = Convert.ToInt16(strBin, 2); return decNumber.ToString("X"); } /// <summary> /// /// </summary> /// <param name="v2plaintext"></param> /// <returns></returns> public string unpadV2Plaintext(string v2plaintext) { //if(v2plaintext.Length < 128) // return v2plaintext.Substring(2,-1); //else // return v2plaintext.Substring(3,-1); String ret = SubStr(v2plaintext, 2, -1); return FixPadding(ret); } public static String FixPadding(String result) { /* From Chat-API Php Code */ Char lastChar = result[result.Length - 1]; String unpadded = result.TrimEnd(lastChar); /* From Chat-API Php Code */ return unpadded; } //Php SubStr public static string SubStr(String value, int startIndex, int length = 0) { if (length == 0) return value.Substring(startIndex); if (length< 0) length = value.Length - 1 + length; return value.Substring(startIndex, length); } #region raise a delegates error event to the main aplication public event OnErrorAxolotlDelegate OnErrorAxolotl; public void ErrorAxolotl(String ErrorMessage) { if (this.OnErrorAxolotl != null) { this.OnErrorAxolotl(ErrorMessage); } } public delegate void OnErrorAxolotlDelegate(string ErrorMessage); #endregion #region Public Interfaces for AxolotlStore #region session event and delegates ISessionStore public event OnstoreSessionDataDelegate OnstoreSession; public void StoreSession(AxolotlAddress address, SessionRecord record) { if (this.OnstoreSession != null) { this.OnstoreSession(address.getName(), address.getDeviceId(), record.serialize()); } } public event OnloadSessionDelegate OnloadSession; public SessionRecord LoadSession(AxolotlAddress address) { if (this.OnloadSession != null) { byte[] session = this.OnloadSession(address.getName(), address.getDeviceId()); if(session == null) return new SessionRecord(); else return new SessionRecord(session); } return null; } public event OngetSubDeviceSessionsDelegate OngetSubDeviceSessions; public List<UInt32> GetSubDeviceSessions(string recipientId) { if (this.OngetSubDeviceSessions != null) { return this.OngetSubDeviceSessions(recipientId); } return null; } public event OncontainsSessionDelegate OncontainsSession; public bool ContainsSession(AxolotlAddress address) { if (this.OncontainsSession != null) { return this.OncontainsSession(address.getName(), address.getDeviceId()); } return false; } public event OndeleteSessionDelegate OndeleteSession; public void DeleteSession(AxolotlAddress address) { if (this.OndeleteSession != null) { this.OndeleteSession(address.getName(), address.getDeviceId()); } } public event OndeleteAllSessionsDelegate OndeleteAllSessions; public void DeleteAllSessions(string name) { if (this.OndeleteAllSessions != null) { this.OndeleteAllSessions(name); } } //event delegates public delegate void OnstoreSessionDataDelegate(string recipientId, uint deviceId, byte[] sessionRecord); public delegate byte[] OnloadSessionDelegate(string recipientId, uint deviceId); public delegate List<UInt32> OngetSubDeviceSessionsDelegate(string recipientId); public delegate bool OncontainsSessionDelegate(string recipientId, uint deviceId); public delegate void OndeleteAllSessionsDelegate(string recipientId); public delegate void OndeleteSessionDelegate(string recipientId, uint deviceId); #endregion #region PreKeys event and delegates IPreKeyStore // internat store all generatet keys public void StorePreKeys(IList<PreKeyRecord> keys) { foreach (PreKeyRecord key in keys) StorePreKey((uint)key.getId(), key); } public event OnstorePreKeyDelegate OnstorePreKey; public void StorePreKey(uint preKeyId, PreKeyRecord record) { if (this.OnstorePreKey != null) { this.OnstorePreKey(preKeyId, record.serialize()); } } public event OnloadPreKeyDelegate OnloadPreKey; public PreKeyRecord LoadPreKey(uint preKeyId) { if (this.OnloadPreKey != null) { return new PreKeyRecord(this.OnloadPreKey(preKeyId)); } return null; } public event OncontainsPreKeyDelegate OncontainsPreKey; public bool ContainsPreKey(uint preKeyId) { if (this.OncontainsPreKey != null) { return this.OncontainsPreKey(preKeyId); } return false; } public event OnremovePreKeyDelegate OnremovePreKey; public void RemovePreKey(uint preKeyId) { if (this.OnremovePreKey != null) { this.OnremovePreKey(preKeyId); } } public event OnloadPreKeysDelegate OnloadPreKeys; public List<byte[]> LoadPreKeys() { if (this.OnloadPreKeys != null) { return this.OnloadPreKeys(); } return null; } public event OnremoveAllPreKeysDelegate OnremoveAllPreKeys; protected void RemoveAllPreKeys() { if (this.OnremoveAllPreKeys != null) { this.OnremoveAllPreKeys(); } } //event delegates public delegate void OnstorePreKeyDelegate(uint prekeyId, byte[] preKeyRecord); public delegate byte[] OnloadPreKeyDelegate(uint preKeyId); public delegate List<byte[]> OnloadPreKeysDelegate(); public delegate bool OncontainsPreKeyDelegate(uint preKeyId); public delegate void OnremovePreKeyDelegate(uint preKeyId); public delegate void OnremoveAllPreKeysDelegate(); #endregion #region signedPreKey event and delegates ISignedPreKeyStore public event OnstoreSignedPreKeyDelegate OnstoreSignedPreKey; public void StoreSignedPreKey(UInt32 signedPreKeyId, SignedPreKeyRecord record) { if (this.OnstoreSignedPreKey != null){ this.OnstoreSignedPreKey(signedPreKeyId, record.serialize()); } } public event OnloadSignedPreKeyDelegate OnloadSignedPreKey; public SignedPreKeyRecord LoadSignedPreKey(UInt32 signedPreKeyId) { if (this.OnloadSignedPreKey != null){ return new SignedPreKeyRecord(this.OnloadSignedPreKey(signedPreKeyId)); } return null; } public event OnloadSignedPreKeysDelegate OnloadSignedPreKeys; public List<SignedPreKeyRecord> LoadSignedPreKeys() { if (this.OnloadSignedPreKeys != null){ List<byte[]> inputList = this.OnloadSignedPreKeys(); return inputList.Select(x => new SignedPreKeyRecord(x)).ToList(); } return null; } public event OncontainsSignedPreKeyDelegate OncontainsSignedPreKey; public bool ContainsSignedPreKey(UInt32 signedPreKeyId) { if (this.OncontainsSignedPreKey != null){ return this.OncontainsSignedPreKey(signedPreKeyId); } return false; } public event OnremoveSignedPreKeyDelegate OnremoveSignedPreKey; public void RemoveSignedPreKey(UInt32 signedPreKeyId) { if (this.OnremoveSignedPreKey != null){ this.OnremoveSignedPreKey(signedPreKeyId); } } //event delegates public delegate void OnstoreSignedPreKeyDelegate(UInt32 signedPreKeyId, byte[] signedPreKeyRecord); public delegate byte[] OnloadSignedPreKeyDelegate(UInt32 preKeyId); public delegate List<byte[]> OnloadSignedPreKeysDelegate(); public delegate void OnremoveSignedPreKeyDelegate(UInt32 preKeyId); public delegate bool OncontainsSignedPreKeyDelegate(UInt32 preKeyId); #endregion #region identity event and delegates IIdentityKeyStore public event OngetIdentityKeyPairDelegate OngetIdentityKeyPair; public IdentityKeyPair GetIdentityKeyPair() { if (this.OngetIdentityKeyPair != null){ List<byte[]> pair = this.OngetIdentityKeyPair(); return new IdentityKeyPair(new IdentityKey(new DjbECPublicKey(pair[0])), new DjbECPrivateKey(pair[1])); } return null; } public event OngetLocalRegistrationIdDelegate OngetLocalRegistrationId; public UInt32 GetLocalRegistrationId() { if (this.OngetLocalRegistrationId != null){ return this.OngetLocalRegistrationId(); } return 0; // FIXME: this isn't correct workaround only } /// <summary> /// Determine whether a remote client's identity is trusted. Convention is /// that the TextSecure protocol is 'trust on first use.' This means that /// an identity key is considered 'trusted' if there is no entry for the recipient /// in the local store, or if it matches the saved key for a recipient in the local /// store.Only if it mismatches an entry in the local store is it considered /// 'untrusted.' /// </summary> public event OnisTrustedIdentityDelegate OnisTrustedIdentity; public bool IsTrustedIdentity(string name, IdentityKey identityKey) { if (this.OnisTrustedIdentity != null){ return this.OnisTrustedIdentity(name, identityKey.serialize()); } return false; // FIXME: this isn't correct workaround only } public event OnsaveIdentityDelegate OnsaveIdentity; public bool SaveIdentity(string name, IdentityKey identityKey) { if (this.OnsaveIdentity != null){ return this.OnsaveIdentity(name, identityKey.serialize()); } return false; } public event OnstoreLocalDataDelegate OnstoreLocalData; public void StoreLocalData(uint registrationId, byte[] publickey, byte[] privatekey) { if (this.OnstoreLocalData != null) { this.OnstoreLocalData(registrationId, publickey, privatekey); } } //event delegates public delegate void OnstoreLocalDataDelegate(uint registrationId, byte[] publickey, byte[] privatekey); public delegate List<byte[]> OngetIdentityKeyPairDelegate(); public delegate UInt32 OngetLocalRegistrationIdDelegate(); public delegate bool OnisTrustedIdentityDelegate(string recipientId, byte[] identityKey); public delegate bool OnsaveIdentityDelegate(string recipientId, byte[] identityKey); #endregion #region sender_keys event and delegates public event OnstoreSenderKeyDelegate OnstoreSenderKey; protected void firestoreSenderKey(int senderKeyId, byte[] senderKeyRecord) { if (this.OnstoreSenderKey != null){ this.OnstoreSenderKey( senderKeyId, senderKeyRecord); } } public event OnloadSenderKeyDelegate OnloadSenderKey; protected byte[] fireloadSenderKey(int senderKeyId) { if (this.OnloadSenderKey != null){ return this.OnloadSenderKey(senderKeyId); } return null; } public event OnremoveSenderKeyDelegate OnremoveSenderKey; protected void fireremoveSenderKey(int senderKeyId) { if (this.OnremoveSenderKey != null){ this.OnremoveSenderKey(senderKeyId); } } public event OncontainsSenderKeyDelegate OncontainsSenderKey; protected bool firecontainsSenderKey(int senderKeyId) { if (this.OncontainsSenderKey != null){ return this.OncontainsSenderKey(senderKeyId); } return false; } //event delegates public delegate void OnstoreSenderKeyDelegate(int senderKeyId, byte[] senderKeyRecord); public delegate byte[] OnloadSenderKeyDelegate(int senderKeyId); public delegate void OnremoveSenderKeyDelegate(int senderKeyId); public delegate bool OncontainsSenderKeyDelegate(int senderKeyId); #endregion #endregion #region TESTING IN MEMORY STORE /* private InMemoryPreKeyStore preKeyStore = new InMemoryPreKeyStore(); private InMemorySessionStore sessionStore = new InMemorySessionStore(); private InMemorySignedPreKeyStore signedPreKeyStore = new InMemorySignedPreKeyStore(); private InMemoryIdentityKeyStore identityKeyStore; public List<byte[]> LoadPreKeys() { return null; } public void RemoveAllPreKeys() { } public void StorePreKeys(IList<PreKeyRecord> keys) { } public void StoreLocalData(uint registrationId, byte[] publickey, byte[] privatekey) { } public void InMemoryTestSetup(IdentityKeyPair identityKeyPair, uint registrationId) { this.identityKeyStore = new InMemoryIdentityKeyStore(identityKeyPair, registrationId); } public IdentityKeyPair GetIdentityKeyPair() { return identityKeyStore.GetIdentityKeyPair(); } public uint GetLocalRegistrationId() { return identityKeyStore.GetLocalRegistrationId(); } public bool SaveIdentity(String name, IdentityKey identityKey) { identityKeyStore.SaveIdentity(name, identityKey); return true; } public bool IsTrustedIdentity(String name, IdentityKey identityKey) { return identityKeyStore.IsTrustedIdentity(name, identityKey); } public PreKeyRecord LoadPreKey(uint preKeyId) { return preKeyStore.LoadPreKey(preKeyId); } public void StorePreKey(uint preKeyId, PreKeyRecord record) { preKeyStore.StorePreKey(preKeyId, record); } public bool ContainsPreKey(uint preKeyId) { return preKeyStore.ContainsPreKey(preKeyId); } public void RemovePreKey(uint preKeyId) { preKeyStore.RemovePreKey(preKeyId); } public SessionRecord LoadSession(AxolotlAddress address) { return sessionStore.LoadSession(address); } public List<uint> GetSubDeviceSessions(String name) { return sessionStore.GetSubDeviceSessions(name); } public void StoreSession(AxolotlAddress address, SessionRecord record) { sessionStore.StoreSession(address, record); } public bool ContainsSession(AxolotlAddress address) { return sessionStore.ContainsSession(address); } public void DeleteSession(AxolotlAddress address) { sessionStore.DeleteSession(address); } public void DeleteAllSessions(String name) { sessionStore.DeleteAllSessions(name); } public SignedPreKeyRecord LoadSignedPreKey(uint signedPreKeyId) { return signedPreKeyStore.LoadSignedPreKey(signedPreKeyId); } public List<SignedPreKeyRecord> LoadSignedPreKeys() { return signedPreKeyStore.LoadSignedPreKeys(); } public void StoreSignedPreKey(uint signedPreKeyId, SignedPreKeyRecord record) { signedPreKeyStore.StoreSignedPreKey(signedPreKeyId, record); } public bool ContainsSignedPreKey(uint signedPreKeyId) { return signedPreKeyStore.ContainsSignedPreKey(signedPreKeyId); } public void RemoveSignedPreKey(uint signedPreKeyId) { signedPreKeyStore.RemoveSignedPreKey(signedPreKeyId); } */ #endregion } /// <summary> /// NOT USED YET /// </summary> public class ExtraFunctions { public static byte[] SerializeToBytes<T>(T item) { var formatter = new BinaryFormatter(); using (var stream = new MemoryStream()) { formatter.Serialize(stream, item); stream.Seek(0, SeekOrigin.Begin); return stream.ToArray(); } } public static object DeserializeFromBytes(byte[] bytes) { var formatter = new BinaryFormatter(); using (var stream = new MemoryStream(bytes)) { return formatter.Deserialize(stream); } } public static byte[] GetBigEndianBytes(UInt32 val, bool isLittleEndian) { UInt32 bigEndian = val; if (isLittleEndian) { bigEndian = (val & 0x000000FFU) << 24 | (val & 0x0000FF00U) << 8 | (val & 0x00FF0000U) >> 8 | (val & 0xFF000000U) >> 24; } return BitConverter.GetBytes(bigEndian); } public static byte[] intToByteArray(int value) { byte[] b = new byte[4]; // for (int i = 0; i >> offset) & 0xFF); return b; } public static void writetofile(string pathtofile, string data) { using (StreamWriter writer = new StreamWriter(pathtofile, true)) { writer.WriteLine(data); } } } }
using System; using System.Collections.Generic; using System.Linq; using ContentPatcher.Framework.Conditions; using ContentPatcher.Framework.Lexing; using Pathoschild.Stardew.Common.Utilities; namespace ContentPatcher.Framework.Tokens { /// <summary>The parsed input arguments for a token.</summary> internal class InputArguments : IInputArguments { /********* ** Fields *********/ /**** ** Constants ****/ /// <summary>The 'contains' argument key.</summary> internal const string ContainsKey = "contains"; /// <summary>The 'valueAt' argument key.</summary> internal const string ValueAtKey = "valueAt"; /// <summary>The 'inputSeparator' argument key.</summary> internal const string InputSeparatorKey = "inputSeparator"; /// <summary>The argument names handled by Content Patcher.</summary> private static readonly ISet<string> ReservedArgKeys = new InvariantHashSet { InputArguments.ContainsKey, InputArguments.ValueAtKey, InputArguments.InputSeparatorKey }; /**** ** State ****/ /// <summary>The last raw value that was parsed.</summary> private string LastRawValue; /// <summary>The last tokenizable value that was parsed.</summary> private string LastParsedValue; /// <summary>The raw input argument segment containing positional arguments, after parsing tokens but before splitting into individual arguments.</summary> private string PositionalSegment; /// <summary>The backing field for <see cref="PositionalArgs"/>.</summary> private string[] PositionalArgsImpl = Array.Empty<string>(); /// <summary>The backing field for <see cref="NamedArgs"/>.</summary> private IDictionary<string, IInputArgumentValue> NamedArgsImpl = new InvariantDictionary<IInputArgumentValue>(); /// <summary>The backing field for <see cref="ReservedArgs"/>.</summary> private IDictionary<string, IInputArgumentValue> ReservedArgsImpl = new InvariantDictionary<IInputArgumentValue>(); /// <summary>The backing field for <see cref="ReservedArgsList"/>.</summary> private KeyValuePair<string, IInputArgumentValue>[] ReservedArgsListImpl = Array.Empty<KeyValuePair<string, IInputArgumentValue>>(); /********* ** Accessors *********/ /// <summary>A singleton instance representing zero input arguments.</summary> public static IInputArguments Empty { get; } = new InputArguments(new LiteralString(string.Empty, new LogPathBuilder())); /**** ** Values ****/ /// <inheritdoc /> public ITokenString TokenString { get; } /// <inheritdoc /> public string[] PositionalArgs => this.ParseIfNeeded().PositionalArgsImpl; /// <inheritdoc /> public IDictionary<string, IInputArgumentValue> NamedArgs => this.ParseIfNeeded().NamedArgsImpl; /// <inheritdoc /> public IDictionary<string, IInputArgumentValue> ReservedArgs => this.ParseIfNeeded().ReservedArgsImpl; /// <inheritdoc /> public KeyValuePair<string, IInputArgumentValue>[] ReservedArgsList => this.ParseIfNeeded().ReservedArgsListImpl; /**** ** Metadata ****/ /// <inheritdoc /> public bool HasNamedArgs => this.NamedArgs.Any(); /// <inheritdoc /> public bool HasPositionalArgs => this.PositionalArgs.Any(); /// <inheritdoc /> public bool IsMutable => this.TokenString?.IsMutable ?? false; /// <inheritdoc /> public bool IsReady => this.TokenString?.IsReady ?? false; /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="tokenString">The underlying tokenized string.</param> public InputArguments(ITokenString tokenString) { this.TokenString = tokenString; } /// <inheritdoc /> public string GetFirstPositionalArg() { return this.PositionalArgs.FirstOrDefault(); } /// <summary>Get the raw value for a named argument, if any.</summary> /// <param name="key">The argument name.</param> public string GetRawArgumentValue(string key) { return this.NamedArgs.TryGetValue(key, out IInputArgumentValue value) ? value.Raw : null; } /// <inheritdoc /> public string GetPositionalSegment() { return this.PositionalSegment; } /********* ** Private methods *********/ /// <summary>Parse the underlying token string if it's not already parsed.</summary> private InputArguments ParseIfNeeded() { if (this.LastParsedValue != this.TokenString?.Value || this.LastRawValue != this.TokenString?.Raw) { InputArguments.Parse(this.TokenString, out this.PositionalSegment, out this.PositionalArgsImpl, out this.NamedArgsImpl, out this.ReservedArgsImpl, out var reservedArgsList); this.ReservedArgsListImpl = reservedArgsList.ToArray(); this.LastParsedValue = this.TokenString?.Value; this.LastRawValue = this.TokenString?.Raw; } return this; } /// <summary>Parse arguments from a tokenized string.</summary> /// <param name="input">The tokenized string to parse.</param> /// <param name="positionalSegment">The raw input argument segment containing positional arguments, after parsing tokens but before splitting into individual arguments.</param> /// <param name="positionalArgs">The positional arguments.</param> /// <param name="namedArgs">The named arguments.</param> /// <param name="reservedArgs">The named arguments handled by Content Patcher.</param> /// <param name="reservedArgsList">An ordered list of the <paramref name="reservedArgs"/>, including duplicate args.</param> private static void Parse(ITokenString input, out string positionalSegment, out string[] positionalArgs, out IDictionary<string, IInputArgumentValue> namedArgs, out IDictionary<string, IInputArgumentValue> reservedArgs, out IList<KeyValuePair<string, IInputArgumentValue>> reservedArgsList) { Lexer lexer = Lexer.Instance; InputArguments.GetRawArguments(input, lexer, out positionalSegment, out InvariantDictionary<string> rawNamedArgs); // get value separator if (!rawNamedArgs.TryGetValue(InputArguments.InputSeparatorKey, out string inputSeparator) || string.IsNullOrWhiteSpace(inputSeparator)) inputSeparator = ","; // parse args positionalArgs = lexer.SplitLexically(positionalSegment, delimiter: inputSeparator).ToArray(); namedArgs = new InvariantDictionary<IInputArgumentValue>(); reservedArgs = new InvariantDictionary<IInputArgumentValue>(); reservedArgsList = new List<KeyValuePair<string, IInputArgumentValue>>(); foreach (var arg in rawNamedArgs) { var values = new InputArgumentValue(arg.Value, lexer.SplitLexically(arg.Value, delimiter: inputSeparator).ToArray()); if (InputArguments.ReservedArgKeys.Contains(arg.Key)) { reservedArgs[arg.Key] = values; reservedArgsList.Add(new KeyValuePair<string, IInputArgumentValue>(arg.Key, values)); } else namedArgs[arg.Key] = values; } } /// <summary>Get the raw positional and named argument strings.</summary> /// <param name="input">The tokenized string to parse.</param> /// <param name="lexer">The lexer with which to tokenize the string.</param> /// <param name="rawPositional">The positional arguments string.</param> /// <param name="rawNamed">The named argument string.</param> private static void GetRawArguments(ITokenString input, Lexer lexer, out string rawPositional, out InvariantDictionary<string> rawNamed) { // get token text string raw = input?.IsReady == true ? input.Value : input?.Raw; raw = raw?.Trim() ?? string.Empty; // split into positional and named segments string positionalSegment; string[] namedSegments; { string[] parts = lexer.SplitLexically(raw, delimiter: "|", ignoreEmpty: false, trim: false).ToArray(); positionalSegment = parts[0].Trim(); namedSegments = parts.Skip(1).Select(p => p.Trim()).Where(p => !string.IsNullOrWhiteSpace(p)).ToArray(); } // extract raw arguments rawPositional = positionalSegment; rawNamed = new InvariantDictionary<string>(); foreach (string arg in namedSegments) { string[] parts = lexer.SplitLexically(arg, delimiter: "=", ignoreEmpty: true, trim: false).ToArray(); if (parts.Length == 1) rawNamed[arg] = string.Empty; else { string key = parts[0].Trim(); string value = string.Join("=", parts.Skip(1)).Trim(); rawNamed[key] = value; } } } } }
/* * 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.Threading; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime; using System.Text; using System.Text.RegularExpressions; using System.Timers; using log4net; using NDesk.Options; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Servers; using OpenSim.Framework.Monitoring; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; namespace OpenSim { /// <summary> /// Interactive OpenSim region server /// </summary> public class OpenSim : OpenSimBase { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected string m_startupCommandsFile; protected string m_shutdownCommandsFile; protected bool m_gui = false; protected string m_consoleType = "local"; protected uint m_consolePort = 0; /// <summary> /// Prompt to use for simulator command line. /// </summary> private string m_consolePrompt; /// <summary> /// Regex for parsing out special characters in the prompt. /// </summary> private Regex m_consolePromptRegex = new Regex(@"([^\\])\\(\w)", RegexOptions.Compiled); private string m_timedScript = "disabled"; private int m_timeInterval = 1200; private System.Timers.Timer m_scriptTimer; public OpenSim(IConfigSource configSource) : base(configSource) { } protected override void ReadExtraConfigSettings() { base.ReadExtraConfigSettings(); IConfig startupConfig = Config.Configs["Startup"]; IConfig networkConfig = Config.Configs["Network"]; int stpMinThreads = 2; int stpMaxThreads = 15; if (startupConfig != null) { m_startupCommandsFile = startupConfig.GetString("startup_console_commands_file", "startup_commands.txt"); m_shutdownCommandsFile = startupConfig.GetString("shutdown_console_commands_file", "shutdown_commands.txt"); if (startupConfig.GetString("console", String.Empty) == String.Empty) m_gui = startupConfig.GetBoolean("gui", false); else m_consoleType= startupConfig.GetString("console", String.Empty); if (networkConfig != null) m_consolePort = (uint)networkConfig.GetInt("console_port", 0); m_timedScript = startupConfig.GetString("timer_Script", "disabled"); if (m_timedScript != "disabled") { m_timeInterval = startupConfig.GetInt("timer_Interval", 1200); } string asyncCallMethodStr = startupConfig.GetString("async_call_method", String.Empty); FireAndForgetMethod asyncCallMethod; if (!String.IsNullOrEmpty(asyncCallMethodStr) && Utils.EnumTryParse<FireAndForgetMethod>(asyncCallMethodStr, out asyncCallMethod)) Util.FireAndForgetMethod = asyncCallMethod; stpMinThreads = startupConfig.GetInt("MinPoolThreads", 2 ); stpMaxThreads = startupConfig.GetInt("MaxPoolThreads", 25); m_consolePrompt = startupConfig.GetString("ConsolePrompt", @"Region (\R) "); } if (Util.FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool) Util.InitThreadPool(stpMinThreads, stpMaxThreads); m_log.Info("[OPENSIM MAIN]: Using async_call_method " + Util.FireAndForgetMethod); m_log.InfoFormat("[OPENSIM MAIN] Running GC in {0} mode", GCSettings.IsServerGC ? "server":"workstation"); } #if (_MONO) private static Mono.Unix.UnixSignal[] signals; private Thread signal_thread = new Thread (delegate () { while (true) { // Wait for a signal to be delivered int index = Mono.Unix.UnixSignal.WaitAny (signals, -1); //Mono.Unix.Native.Signum signal = signals [index].Signum; MainConsole.Instance.RunCommand("shutdown"); } }); #endif /// <summary> /// Performs initialisation of the scene, such as loading configuration from disk. /// </summary> protected override void StartupSpecific() { m_log.Info("===================================================================="); m_log.Info("========================= STARTING OPENSIM ========================="); m_log.Info("===================================================================="); #if (_MONO) if(!Util.IsWindows()) { try { // linux mac os specifics signals = new Mono.Unix.UnixSignal[] { new Mono.Unix.UnixSignal(Mono.Unix.Native.Signum.SIGTERM) }; signal_thread.IsBackground = true; signal_thread.Start(); } catch (Exception e) { m_log.Info("Could not set up UNIX signal handlers. SIGTERM will not"); m_log.InfoFormat("shut down gracefully: {0}", e.Message); m_log.Debug("Exception was: ", e); } } #endif //m_log.InfoFormat("[OPENSIM MAIN]: GC Is Server GC: {0}", GCSettings.IsServerGC.ToString()); // http://msdn.microsoft.com/en-us/library/bb384202.aspx //GCSettings.LatencyMode = GCLatencyMode.Batch; //m_log.InfoFormat("[OPENSIM MAIN]: GC Latency Mode: {0}", GCSettings.LatencyMode.ToString()); if (m_gui) // Driven by external GUI { m_console = new CommandConsole("Region"); } else { switch (m_consoleType) { case "basic": m_console = new CommandConsole("Region"); break; case "rest": m_console = new RemoteConsole("Region"); ((RemoteConsole)m_console).ReadConfig(Config); break; default: m_console = new LocalConsole("Region", Config.Configs["Startup"]); break; } } MainConsole.Instance = m_console; LogEnvironmentInformation(); RegisterCommonAppenders(Config.Configs["Startup"]); RegisterConsoleCommands(); base.StartupSpecific(); MainServer.Instance.AddStreamHandler(new OpenSim.SimStatusHandler()); MainServer.Instance.AddStreamHandler(new OpenSim.XSimStatusHandler(this)); if (userStatsURI != String.Empty) MainServer.Instance.AddStreamHandler(new OpenSim.UXSimStatusHandler(this)); MainServer.Instance.AddStreamHandler(new OpenSim.SimRobotsHandler()); if (managedStatsURI != String.Empty) { string urlBase = String.Format("/{0}/", managedStatsURI); StatsManager.StatsPassword = managedStatsPassword; MainServer.Instance.AddHTTPHandler(urlBase, StatsManager.HandleStatsRequest); m_log.InfoFormat("[OPENSIM] Enabling remote managed stats fetch. URL = {0}", urlBase); } if (m_console is RemoteConsole) { if (m_consolePort == 0) { ((RemoteConsole)m_console).SetServer(m_httpServer); } else { ((RemoteConsole)m_console).SetServer(MainServer.GetHttpServer(m_consolePort)); } } // Hook up to the watchdog timer Watchdog.OnWatchdogTimeout += WatchdogTimeoutHandler; PrintFileToConsole("startuplogo.txt"); // For now, start at the 'root' level by default if (SceneManager.Scenes.Count == 1) // If there is only one region, select it ChangeSelectedRegion("region", new string[] {"change", "region", SceneManager.Scenes[0].RegionInfo.RegionName}); else ChangeSelectedRegion("region", new string[] {"change", "region", "root"}); //Run Startup Commands if (String.IsNullOrEmpty(m_startupCommandsFile)) { m_log.Info("[STARTUP]: No startup command script specified. Moving on..."); } else { RunCommandScript(m_startupCommandsFile); } // Start timer script (run a script every xx seconds) if (m_timedScript != "disabled") { m_scriptTimer = new System.Timers.Timer(); m_scriptTimer.Enabled = true; m_scriptTimer.Interval = m_timeInterval*1000; m_scriptTimer.Elapsed += RunAutoTimerScript; } } /// <summary> /// Register standard set of region console commands /// </summary> private void RegisterConsoleCommands() { MainServer.RegisterHttpConsoleCommands(m_console); m_console.Commands.AddCommand("Objects", false, "force update", "force update", "Force the update of all objects on clients", HandleForceUpdate); m_console.Commands.AddCommand("General", false, "change region", "change region <region name>", "Change current console region", ChangeSelectedRegion); m_console.Commands.AddCommand("Archiving", false, "save xml", "save xml [<file name>]", "Save a region's data in XML format", SaveXml); m_console.Commands.AddCommand("Archiving", false, "save xml2", "save xml2 [<file name>]", "Save a region's data in XML2 format", SaveXml2); m_console.Commands.AddCommand("Archiving", false, "load xml", "load xml [<file name> [-newUID [<x> <y> <z>]]]", "Load a region's data from XML format", LoadXml); m_console.Commands.AddCommand("Archiving", false, "load xml2", "load xml2 [<file name>]", "Load a region's data from XML2 format", LoadXml2); m_console.Commands.AddCommand("Archiving", false, "save prims xml2", "save prims xml2 [<prim name> <file name>]", "Save named prim to XML2", SavePrimsXml2); m_console.Commands.AddCommand("Archiving", false, "load oar", "load oar [-m|--merge] [-s|--skip-assets]" + " [--default-user \"User Name\"]" + " [--force-terrain] [--force-parcels]" + " [--no-objects]" + " [--rotation degrees]" + " [--bounding-origin \"<x,y,z>\"]" + " [--bounding-size \"<x,y,z>\"]" + " [--displacement \"<x,y,z>\"]" + " [-d|--debug]" + " [<OAR path>]", "Load a region's data from an OAR archive.", "--merge will merge the OAR with the existing scene (suppresses terrain and parcel info loading).\n" + "--skip-assets will load the OAR but ignore the assets it contains.\n" + "--default-user will use this user for any objects with an owner whose UUID is not found in the grid.\n" + "--force-terrain forces the loading of terrain from the oar (undoes suppression done by --merge).\n" + "--force-parcels forces the loading of parcels from the oar (undoes suppression done by --merge).\n" + "--no-objects suppresses the addition of any objects (good for loading only the terrain).\n" + "--rotation specified rotation to be applied to the oar. Specified in degrees.\n" + "--bounding-origin will only place objects that after displacement and rotation fall within the bounding cube who's position starts at <x,y,z>. Defaults to <0,0,0>.\n" + "--bounding-size specifies the size of the bounding cube. The default is the size of the destination region and cannot be larger than this.\n" + "--displacement will add this value to the position of every object loaded.\n" + "--debug forces the archiver to display messages about where each object is being placed.\n\n" + "The path can be either a filesystem location or a URI.\n" + " If this is not given then the command looks for an OAR named region.oar in the current directory." + " [--rotation-center \"<x,y,z>\"] used to be an option, now it does nothing and will be removed soon." + "When an OAR is being loaded, operations are applied in this order:\n" + "1: Rotation (around the incoming OARs region center)\n" + "2: Cropping (a bounding cube with origin and size)\n" + "3: Displacement (setting offset coordinates within the destination region)", LoadOar); ; m_console.Commands.AddCommand("Archiving", false, "save oar", //"save oar [-v|--version=<N>] [-p|--profile=<url>] [<OAR path>]", "save oar [-h|--home=<url>] [--noassets] [--publish] [--perm=<permissions>] [--all] [<OAR path>]", "Save a region's data to an OAR archive.", // "-v|--version=<N> generates scene objects as per older versions of the serialization (e.g. -v=0)" + Environment.NewLine "-h|--home=<url> adds the url of the profile service to the saved user information.\n" + "--noassets stops assets being saved to the OAR.\n" + "--publish saves an OAR stripped of owner and last owner information.\n" + " on reload, the estate owner will be the owner of all objects\n" + " this is useful if you're making oars generally available that might be reloaded to the same grid from which you published\n" + "--perm=<permissions> stops objects with insufficient permissions from being saved to the OAR.\n" + " <permissions> can contain one or more of these characters: \"C\" = Copy, \"T\" = Transfer\n" + "--all saves all the regions in the simulator, instead of just the current region.\n" + "The OAR path must be a filesystem path." + " If this is not given then the oar is saved to region.oar in the current directory.", SaveOar); m_console.Commands.AddCommand("Objects", false, "edit scale", "edit scale <name> <x> <y> <z>", "Change the scale of a named prim", HandleEditScale); m_console.Commands.AddCommand("Objects", false, "rotate scene", "rotate scene <degrees> [centerX, centerY]", "Rotates all scene objects around centerX, centerY (default 128, 128) (please back up your region before using)", HandleRotateScene); m_console.Commands.AddCommand("Objects", false, "scale scene", "scale scene <factor>", "Scales the scene objects (please back up your region before using)", HandleScaleScene); m_console.Commands.AddCommand("Objects", false, "translate scene", "translate scene xOffset yOffset zOffset", "translates the scene objects (please back up your region before using)", HandleTranslateScene); m_console.Commands.AddCommand("Users", false, "kick user", "kick user <first> <last> [--force] [message]", "Kick a user off the simulator", "The --force option will kick the user without any checks to see whether it's already in the process of closing\n" + "Only use this option if you are sure the avatar is inactive and a normal kick user operation does not removed them", KickUserCommand); m_console.Commands.AddCommand("Users", false, "show users", "show users [full]", "Show user data for users currently on the region", "Without the 'full' option, only users actually on the region are shown." + " With the 'full' option child agents of users in neighbouring regions are also shown.", HandleShow); m_console.Commands.AddCommand("Comms", false, "show connections", "show connections", "Show connection data", HandleShow); m_console.Commands.AddCommand("Comms", false, "show circuits", "show circuits", "Show agent circuit data", HandleShow); m_console.Commands.AddCommand("Comms", false, "show pending-objects", "show pending-objects", "Show # of objects on the pending queues of all scene viewers", HandleShow); m_console.Commands.AddCommand("General", false, "show modules", "show modules", "Show module data", HandleShow); m_console.Commands.AddCommand("Regions", false, "show regions", "show regions", "Show region data", HandleShow); m_console.Commands.AddCommand("Regions", false, "show ratings", "show ratings", "Show rating data", HandleShow); m_console.Commands.AddCommand("Objects", false, "backup", "backup", "Persist currently unsaved object changes immediately instead of waiting for the normal persistence call.", RunCommand); m_console.Commands.AddCommand("Regions", false, "create region", "create region [\"region name\"] <region_file.ini>", "Create a new region.", "The settings for \"region name\" are read from <region_file.ini>. Paths specified with <region_file.ini> are relative to your Regions directory, unless an absolute path is given." + " If \"region name\" does not exist in <region_file.ini>, it will be added." + Environment.NewLine + "Without \"region name\", the first region found in <region_file.ini> will be created." + Environment.NewLine + "If <region_file.ini> does not exist, it will be created.", HandleCreateRegion); m_console.Commands.AddCommand("Regions", false, "restart", "restart", "Restart the currently selected region(s) in this instance", RunCommand); m_console.Commands.AddCommand("General", false, "command-script", "command-script <script>", "Run a command script from file", RunCommand); m_console.Commands.AddCommand("Regions", false, "remove-region", "remove-region <name>", "Remove a region from this simulator", RunCommand); m_console.Commands.AddCommand("Regions", false, "delete-region", "delete-region <name>", "Delete a region from disk", RunCommand); m_console.Commands.AddCommand("Estates", false, "estate create", "estate create <owner UUID> <estate name>", "Creates a new estate with the specified name, owned by the specified user." + " Estate name must be unique.", CreateEstateCommand); m_console.Commands.AddCommand("Estates", false, "estate set owner", "estate set owner <estate-id>[ <UUID> | <Firstname> <Lastname> ]", "Sets the owner of the specified estate to the specified UUID or user. ", SetEstateOwnerCommand); m_console.Commands.AddCommand("Estates", false, "estate set name", "estate set name <estate-id> <new name>", "Sets the name of the specified estate to the specified value. New name must be unique.", SetEstateNameCommand); m_console.Commands.AddCommand("Estates", false, "estate link region", "estate link region <estate ID> <region ID>", "Attaches the specified region to the specified estate.", EstateLinkRegionCommand); } protected override void ShutdownSpecific() { if (m_shutdownCommandsFile != String.Empty) { RunCommandScript(m_shutdownCommandsFile); } if (m_timedScript != "disabled") { m_scriptTimer.Dispose(); m_timedScript = "disabled"; } base.ShutdownSpecific(); } /// <summary> /// Timer to run a specific text file as console commands. Configured in in the main ini file /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RunAutoTimerScript(object sender, EventArgs e) { if (m_timedScript != "disabled") { RunCommandScript(m_timedScript); } } private void WatchdogTimeoutHandler(Watchdog.ThreadWatchdogInfo twi) { int now = Environment.TickCount & Int32.MaxValue; m_log.ErrorFormat( "[WATCHDOG]: Timeout detected for thread \"{0}\". ThreadState={1}. Last tick was {2}ms ago. {3}", twi.Thread.Name, twi.Thread.ThreadState, now - twi.LastTick, twi.AlarmMethod != null ? string.Format("Data: {0}", twi.AlarmMethod()) : ""); } #region Console Commands /// <summary> /// Kicks users off the region /// </summary> /// <param name="module"></param> /// <param name="cmdparams">name of avatar to kick</param> private void KickUserCommand(string module, string[] cmdparams) { bool force = false; OptionSet options = new OptionSet().Add("f|force", delegate (string v) { force = v != null; }); List<string> mainParams = options.Parse(cmdparams); if (mainParams.Count < 4) return; string alert = null; if (mainParams.Count > 4) alert = String.Format("\n{0}\n", String.Join(" ", cmdparams, 4, cmdparams.Length - 4)); IList agents = SceneManager.GetCurrentSceneAvatars(); foreach (ScenePresence presence in agents) { RegionInfo regionInfo = presence.Scene.RegionInfo; if (presence.Firstname.ToLower().Equals(mainParams[2].ToLower()) && presence.Lastname.ToLower().Equals(mainParams[3].ToLower())) { MainConsole.Instance.Output( String.Format( "Kicking user: {0,-16} {1,-16} {2,-37} in region: {3,-16}", presence.Firstname, presence.Lastname, presence.UUID, regionInfo.RegionName)); // kick client... if (alert != null) presence.ControllingClient.Kick(alert); else presence.ControllingClient.Kick("\nYou have been logged out by an administrator.\n"); presence.Scene.CloseAgent(presence.UUID, force); break; } } MainConsole.Instance.Output(""); } /// <summary> /// Opens a file and uses it as input to the console command parser. /// </summary> /// <param name="fileName">name of file to use as input to the console</param> private static void PrintFileToConsole(string fileName) { if (File.Exists(fileName)) { StreamReader readFile = File.OpenText(fileName); string currentLine; while ((currentLine = readFile.ReadLine()) != null) { m_log.Info("[!]" + currentLine); } } } /// <summary> /// Force resending of all updates to all clients in active region(s) /// </summary> /// <param name="module"></param> /// <param name="args"></param> private void HandleForceUpdate(string module, string[] args) { MainConsole.Instance.Output("Updating all clients"); SceneManager.ForceCurrentSceneClientUpdate(); } /// <summary> /// Edits the scale of a primative with the name specified /// </summary> /// <param name="module"></param> /// <param name="args">0,1, name, x, y, z</param> private void HandleEditScale(string module, string[] args) { if (args.Length == 6) { SceneManager.HandleEditCommandOnCurrentScene(args); } else { MainConsole.Instance.Output("Argument error: edit scale <prim name> <x> <y> <z>"); } } private void HandleRotateScene(string module, string[] args) { string usage = "Usage: rotate scene <angle in degrees> [centerX centerY] (centerX and centerY are optional and default to Constants.RegionSize / 2"; float centerX = Constants.RegionSize * 0.5f; float centerY = Constants.RegionSize * 0.5f; if (args.Length < 3 || args.Length == 4) { MainConsole.Instance.Output(usage); return; } float angle = (float)(Convert.ToSingle(args[2]) / 180.0 * Math.PI); OpenMetaverse.Quaternion rot = OpenMetaverse.Quaternion.CreateFromAxisAngle(0, 0, 1, angle); if (args.Length > 4) { centerX = Convert.ToSingle(args[3]); centerY = Convert.ToSingle(args[4]); } Vector3 center = new Vector3(centerX, centerY, 0.0f); SceneManager.ForEachSelectedScene(delegate(Scene scene) { scene.ForEachSOG(delegate(SceneObjectGroup sog) { if (!sog.IsAttachment) { sog.RootPart.UpdateRotation(rot * sog.GroupRotation); Vector3 offset = sog.AbsolutePosition - center; offset *= rot; sog.UpdateGroupPosition(center + offset); } }); }); } private void HandleScaleScene(string module, string[] args) { string usage = "Usage: scale scene <factor>"; if (args.Length < 3) { MainConsole.Instance.Output(usage); return; } float factor = (float)(Convert.ToSingle(args[2])); float minZ = float.MaxValue; SceneManager.ForEachSelectedScene(delegate(Scene scene) { scene.ForEachSOG(delegate(SceneObjectGroup sog) { if (!sog.IsAttachment) { if (sog.RootPart.AbsolutePosition.Z < minZ) minZ = sog.RootPart.AbsolutePosition.Z; } }); }); SceneManager.ForEachSelectedScene(delegate(Scene scene) { scene.ForEachSOG(delegate(SceneObjectGroup sog) { if (!sog.IsAttachment) { Vector3 tmpRootPos = sog.RootPart.AbsolutePosition; tmpRootPos.Z -= minZ; tmpRootPos *= factor; tmpRootPos.Z += minZ; foreach (SceneObjectPart sop in sog.Parts) { if (sop.ParentID != 0) sop.OffsetPosition *= factor; sop.Scale *= factor; } sog.UpdateGroupPosition(tmpRootPos); } }); }); } private void HandleTranslateScene(string module, string[] args) { string usage = "Usage: translate scene <xOffset, yOffset, zOffset>"; if (args.Length < 5) { MainConsole.Instance.Output(usage); return; } float xOFfset = (float)Convert.ToSingle(args[2]); float yOffset = (float)Convert.ToSingle(args[3]); float zOffset = (float)Convert.ToSingle(args[4]); Vector3 offset = new Vector3(xOFfset, yOffset, zOffset); SceneManager.ForEachSelectedScene(delegate(Scene scene) { scene.ForEachSOG(delegate(SceneObjectGroup sog) { if (!sog.IsAttachment) sog.UpdateGroupPosition(sog.AbsolutePosition + offset); }); }); } /// <summary> /// Creates a new region based on the parameters specified. This will ask the user questions on the console /// </summary> /// <param name="module"></param> /// <param name="cmd">0,1,region name, region ini or XML file</param> private void HandleCreateRegion(string module, string[] cmd) { string regionName = string.Empty; string regionFile = string.Empty; if (cmd.Length == 3) { regionFile = cmd[2]; } else if (cmd.Length > 3) { regionName = cmd[2]; regionFile = cmd[3]; } string extension = Path.GetExtension(regionFile).ToLower(); bool isXml = extension.Equals(".xml"); bool isIni = extension.Equals(".ini"); if (!isXml && !isIni) { MainConsole.Instance.Output("Usage: create region [\"region name\"] <region_file.ini>"); return; } if (!Path.IsPathRooted(regionFile)) { string regionsDir = ConfigSource.Source.Configs["Startup"].GetString("regionload_regionsdir", "Regions").Trim(); regionFile = Path.Combine(regionsDir, regionFile); } RegionInfo regInfo; if (isXml) { regInfo = new RegionInfo(regionName, regionFile, false, ConfigSource.Source); } else { regInfo = new RegionInfo(regionName, regionFile, false, ConfigSource.Source, regionName); } Scene existingScene; if (SceneManager.TryGetScene(regInfo.RegionID, out existingScene)) { MainConsole.Instance.OutputFormat( "ERROR: Cannot create region {0} with ID {1}, this ID is already assigned to region {2}", regInfo.RegionName, regInfo.RegionID, existingScene.RegionInfo.RegionName); return; } bool changed = PopulateRegionEstateInfo(regInfo); IScene scene; CreateRegion(regInfo, true, out scene); if (changed) m_estateDataService.StoreEstateSettings(regInfo.EstateSettings); scene.Start(); } /// <summary> /// Runs commands issued by the server console from the operator /// </summary> /// <param name="command">The first argument of the parameter (the command)</param> /// <param name="cmdparams">Additional arguments passed to the command</param> public void RunCommand(string module, string[] cmdparams) { List<string> args = new List<string>(cmdparams); if (args.Count < 1) return; string command = args[0]; args.RemoveAt(0); cmdparams = args.ToArray(); switch (command) { case "backup": MainConsole.Instance.Output("Triggering save of pending object updates to persistent store"); SceneManager.BackupCurrentScene(); break; case "remove-region": string regRemoveName = CombineParams(cmdparams, 0); Scene removeScene; if (SceneManager.TryGetScene(regRemoveName, out removeScene)) RemoveRegion(removeScene, false); else MainConsole.Instance.Output("No region with that name"); break; case "delete-region": string regDeleteName = CombineParams(cmdparams, 0); Scene killScene; if (SceneManager.TryGetScene(regDeleteName, out killScene)) RemoveRegion(killScene, true); else MainConsole.Instance.Output("no region with that name"); break; case "restart": SceneManager.RestartCurrentScene(); break; } } /// <summary> /// Change the currently selected region. The selected region is that operated upon by single region commands. /// </summary> /// <param name="cmdParams"></param> protected void ChangeSelectedRegion(string module, string[] cmdparams) { if (cmdparams.Length > 2) { string newRegionName = CombineParams(cmdparams, 2); if (!SceneManager.TrySetCurrentScene(newRegionName)) MainConsole.Instance.Output(String.Format("Couldn't select region {0}", newRegionName)); else RefreshPrompt(); } else { MainConsole.Instance.Output("Usage: change region <region name>"); } } /// <summary> /// Refreshs prompt with the current selection details. /// </summary> private void RefreshPrompt() { string regionName = (SceneManager.CurrentScene == null ? "root" : SceneManager.CurrentScene.RegionInfo.RegionName); MainConsole.Instance.Output(String.Format("Currently selected region is {0}", regionName)); // m_log.DebugFormat("Original prompt is {0}", m_consolePrompt); string prompt = m_consolePrompt; // Replace "\R" with the region name // Replace "\\" with "\" prompt = m_consolePromptRegex.Replace(prompt, m => { // m_log.DebugFormat("Matched {0}", m.Groups[2].Value); if (m.Groups[2].Value == "R") return m.Groups[1].Value + regionName; else return m.Groups[0].Value; }); m_console.DefaultPrompt = prompt; m_console.ConsoleScene = SceneManager.CurrentScene; } protected override void HandleRestartRegion(RegionInfo whichRegion) { base.HandleRestartRegion(whichRegion); // Where we are restarting multiple scenes at once, a previous call to RefreshPrompt may have set the // m_console.ConsoleScene to null (indicating all scenes). if (m_console.ConsoleScene != null && whichRegion.RegionName == ((Scene)m_console.ConsoleScene).Name) SceneManager.TrySetCurrentScene(whichRegion.RegionName); RefreshPrompt(); } // see BaseOpenSimServer /// <summary> /// Many commands list objects for debugging. Some of the types are listed here /// </summary> /// <param name="mod"></param> /// <param name="cmd"></param> public override void HandleShow(string mod, string[] cmd) { base.HandleShow(mod, cmd); List<string> args = new List<string>(cmd); args.RemoveAt(0); string[] showParams = args.ToArray(); switch (showParams[0]) { case "users": IList agents; if (showParams.Length > 1 && showParams[1] == "full") { agents = SceneManager.GetCurrentScenePresences(); } else { agents = SceneManager.GetCurrentSceneAvatars(); } MainConsole.Instance.Output(String.Format("\nAgents connected: {0}\n", agents.Count)); MainConsole.Instance.Output( String.Format("{0,-16} {1,-16} {2,-37} {3,-11} {4,-16} {5,-30}", "Firstname", "Lastname", "Agent ID", "Root/Child", "Region", "Position") ); foreach (ScenePresence presence in agents) { RegionInfo regionInfo = presence.Scene.RegionInfo; string regionName; if (regionInfo == null) { regionName = "Unresolvable"; } else { regionName = regionInfo.RegionName; } MainConsole.Instance.Output( String.Format( "{0,-16} {1,-16} {2,-37} {3,-11} {4,-16} {5,-30}", presence.Firstname, presence.Lastname, presence.UUID, presence.IsChildAgent ? "Child" : "Root", regionName, presence.AbsolutePosition.ToString()) ); } MainConsole.Instance.Output(String.Empty); break; case "connections": HandleShowConnections(); break; case "circuits": HandleShowCircuits(); break; case "modules": SceneManager.ForEachSelectedScene( scene => { MainConsole.Instance.OutputFormat("Loaded region modules in {0} are:", scene.Name); List<IRegionModuleBase> sharedModules = new List<IRegionModuleBase>(); List<IRegionModuleBase> nonSharedModules = new List<IRegionModuleBase>(); foreach (IRegionModuleBase module in scene.RegionModules.Values) { if (module.GetType().GetInterface("ISharedRegionModule") == null) nonSharedModules.Add(module); else sharedModules.Add(module); } foreach (IRegionModuleBase module in sharedModules.OrderBy(m => m.Name)) MainConsole.Instance.OutputFormat("New Region Module (Shared): {0}", module.Name); foreach (IRegionModuleBase module in nonSharedModules.OrderBy(m => m.Name)) MainConsole.Instance.OutputFormat("New Region Module (Non-Shared): {0}", module.Name); } ); MainConsole.Instance.Output(""); break; case "regions": ConsoleDisplayTable cdt = new ConsoleDisplayTable(); cdt.AddColumn("Name", ConsoleDisplayUtil.RegionNameSize); cdt.AddColumn("ID", ConsoleDisplayUtil.UuidSize); cdt.AddColumn("Position", ConsoleDisplayUtil.CoordTupleSize); cdt.AddColumn("Size", 11); cdt.AddColumn("Port", ConsoleDisplayUtil.PortSize); cdt.AddColumn("Ready?", 6); cdt.AddColumn("Estate", ConsoleDisplayUtil.EstateNameSize); SceneManager.ForEachScene( scene => { RegionInfo ri = scene.RegionInfo; cdt.AddRow( ri.RegionName, ri.RegionID, string.Format("{0},{1}", ri.RegionLocX, ri.RegionLocY), string.Format("{0}x{1}", ri.RegionSizeX, ri.RegionSizeY), ri.InternalEndPoint.Port, scene.Ready ? "Yes" : "No", ri.EstateSettings.EstateName); } ); MainConsole.Instance.Output(cdt.ToString()); break; case "ratings": SceneManager.ForEachScene( delegate(Scene scene) { string rating = ""; if (scene.RegionInfo.RegionSettings.Maturity == 1) { rating = "MATURE"; } else if (scene.RegionInfo.RegionSettings.Maturity == 2) { rating = "ADULT"; } else { rating = "PG"; } MainConsole.Instance.Output(String.Format( "Region Name: {0}, Region Rating {1}", scene.RegionInfo.RegionName, rating)); }); break; } } private void HandleShowCircuits() { ConsoleDisplayTable cdt = new ConsoleDisplayTable(); cdt.AddColumn("Region", 20); cdt.AddColumn("Avatar name", 24); cdt.AddColumn("Type", 5); cdt.AddColumn("Code", 10); cdt.AddColumn("IP", 16); cdt.AddColumn("Viewer Name", 24); SceneManager.ForEachScene( s => { foreach (AgentCircuitData aCircuit in s.AuthenticateHandler.GetAgentCircuits().Values) cdt.AddRow( s.Name, aCircuit.Name, aCircuit.child ? "child" : "root", aCircuit.circuitcode.ToString(), aCircuit.IPAddress != null ? aCircuit.IPAddress.ToString() : "not set", Util.GetViewerName(aCircuit)); }); MainConsole.Instance.Output(cdt.ToString()); } private void HandleShowConnections() { ConsoleDisplayTable cdt = new ConsoleDisplayTable(); cdt.AddColumn("Region", 20); cdt.AddColumn("Avatar name", 24); cdt.AddColumn("Circuit code", 12); cdt.AddColumn("Endpoint", 23); cdt.AddColumn("Active?", 7); cdt.AddColumn("ChildAgent?", 7); cdt.AddColumn("ping(ms)", 8); SceneManager.ForEachScene( s => s.ForEachClient( c => { bool child = false; if(c.SceneAgent != null && c.SceneAgent.IsChildAgent) child = true; cdt.AddRow( s.Name, c.Name, c.CircuitCode.ToString(), c.RemoteEndPoint.ToString(), c.IsActive.ToString(), child.ToString(), c.PingTimeMS); })); MainConsole.Instance.Output(cdt.ToString()); } /// <summary> /// Use XML2 format to serialize data to a file /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void SavePrimsXml2(string module, string[] cmdparams) { if (cmdparams.Length > 4) { SceneManager.SaveNamedPrimsToXml2(cmdparams[3], cmdparams[4]); } else { SceneManager.SaveNamedPrimsToXml2("Primitive", DEFAULT_PRIM_BACKUP_FILENAME); } } /// <summary> /// Use XML format to serialize data to a file /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void SaveXml(string module, string[] cmdparams) { MainConsole.Instance.Output("PLEASE NOTE, save-xml is DEPRECATED and may be REMOVED soon. If you are using this and there is some reason you can't use save-xml2, please file a mantis detailing the reason."); if (cmdparams.Length > 2) { SceneManager.SaveCurrentSceneToXml(cmdparams[2]); } else { SceneManager.SaveCurrentSceneToXml(DEFAULT_PRIM_BACKUP_FILENAME); } } /// <summary> /// Loads data and region objects from XML format. /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void LoadXml(string module, string[] cmdparams) { MainConsole.Instance.Output("PLEASE NOTE, load-xml is DEPRECATED and may be REMOVED soon. If you are using this and there is some reason you can't use load-xml2, please file a mantis detailing the reason."); Vector3 loadOffset = new Vector3(0, 0, 0); if (cmdparams.Length > 2) { bool generateNewIDS = false; if (cmdparams.Length > 3) { if (cmdparams[3] == "-newUID") { generateNewIDS = true; } if (cmdparams.Length > 4) { loadOffset.X = (float)Convert.ToDecimal(cmdparams[4], Culture.NumberFormatInfo); if (cmdparams.Length > 5) { loadOffset.Y = (float)Convert.ToDecimal(cmdparams[5], Culture.NumberFormatInfo); } if (cmdparams.Length > 6) { loadOffset.Z = (float)Convert.ToDecimal(cmdparams[6], Culture.NumberFormatInfo); } MainConsole.Instance.Output(String.Format("loadOffsets <X,Y,Z> = <{0},{1},{2}>",loadOffset.X,loadOffset.Y,loadOffset.Z)); } } SceneManager.LoadCurrentSceneFromXml(cmdparams[2], generateNewIDS, loadOffset); } else { try { SceneManager.LoadCurrentSceneFromXml(DEFAULT_PRIM_BACKUP_FILENAME, false, loadOffset); } catch (FileNotFoundException) { MainConsole.Instance.Output("Default xml not found. Usage: load-xml <filename>"); } } } /// <summary> /// Serialize region data to XML2Format /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void SaveXml2(string module, string[] cmdparams) { if (cmdparams.Length > 2) { SceneManager.SaveCurrentSceneToXml2(cmdparams[2]); } else { SceneManager.SaveCurrentSceneToXml2(DEFAULT_PRIM_BACKUP_FILENAME); } } /// <summary> /// Load region data from Xml2Format /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void LoadXml2(string module, string[] cmdparams) { if (cmdparams.Length > 2) { try { SceneManager.LoadCurrentSceneFromXml2(cmdparams[2]); } catch (FileNotFoundException) { MainConsole.Instance.Output("Specified xml not found. Usage: load xml2 <filename>"); } } else { try { SceneManager.LoadCurrentSceneFromXml2(DEFAULT_PRIM_BACKUP_FILENAME); } catch (FileNotFoundException) { MainConsole.Instance.Output("Default xml not found. Usage: load xml2 <filename>"); } } } /// <summary> /// Load a whole region from an opensimulator archive. /// </summary> /// <param name="cmdparams"></param> protected void LoadOar(string module, string[] cmdparams) { try { SceneManager.LoadArchiveToCurrentScene(cmdparams); } catch (Exception e) { MainConsole.Instance.Output(e.Message); } } /// <summary> /// Save a region to a file, including all the assets needed to restore it. /// </summary> /// <param name="cmdparams"></param> protected void SaveOar(string module, string[] cmdparams) { SceneManager.SaveCurrentSceneToArchive(cmdparams); } protected void CreateEstateCommand(string module, string[] args) { string response = null; UUID userID; if (args.Length == 2) { response = "No user specified."; } else if (!UUID.TryParse(args[2], out userID)) { response = String.Format("{0} is not a valid UUID", args[2]); } else if (args.Length == 3) { response = "No estate name specified."; } else { Scene scene = SceneManager.CurrentOrFirstScene; // TODO: Is there a better choice here? UUID scopeID = UUID.Zero; UserAccount account = scene.UserAccountService.GetUserAccount(scopeID, userID); if (account == null) { response = String.Format("Could not find user {0}", userID); } else { // concatenate it all to "name" StringBuilder sb = new StringBuilder(args[3]); for (int i = 4; i < args.Length; i++) sb.Append (" " + args[i]); string estateName = sb.ToString().Trim(); // send it off for processing. IEstateModule estateModule = scene.RequestModuleInterface<IEstateModule>(); response = estateModule.CreateEstate(estateName, userID); if (response == String.Empty) { List<int> estates = scene.EstateDataService.GetEstates(estateName); response = String.Format("Estate {0} created as \"{1}\"", estates.ElementAt(0), estateName); } } } // give the user some feedback if (response != null) MainConsole.Instance.Output(response); } protected void SetEstateOwnerCommand(string module, string[] args) { string response = null; Scene scene = SceneManager.CurrentOrFirstScene; IEstateModule estateModule = scene.RequestModuleInterface<IEstateModule>(); if (args.Length == 3) { response = "No estate specified."; } else { int estateId; if (!int.TryParse(args[3], out estateId)) { response = String.Format("\"{0}\" is not a valid ID for an Estate", args[3]); } else { if (args.Length == 4) { response = "No user specified."; } else { UserAccount account = null; // TODO: Is there a better choice here? UUID scopeID = UUID.Zero; string s1 = args[4]; if (args.Length == 5) { // attempt to get account by UUID UUID u; if (UUID.TryParse(s1, out u)) { account = scene.UserAccountService.GetUserAccount(scopeID, u); if (account == null) response = String.Format("Could not find user {0}", s1); } else { response = String.Format("Invalid UUID {0}", s1); } } else { // attempt to get account by Firstname, Lastname string s2 = args[5]; account = scene.UserAccountService.GetUserAccount(scopeID, s1, s2); if (account == null) response = String.Format("Could not find user {0} {1}", s1, s2); } // If it's valid, send it off for processing. if (account != null) response = estateModule.SetEstateOwner(estateId, account); if (response == String.Empty) { response = String.Format("Estate owner changed to {0} ({1} {2})", account.PrincipalID, account.FirstName, account.LastName); } } } } // give the user some feedback if (response != null) MainConsole.Instance.Output(response); } protected void SetEstateNameCommand(string module, string[] args) { string response = null; Scene scene = SceneManager.CurrentOrFirstScene; IEstateModule estateModule = scene.RequestModuleInterface<IEstateModule>(); if (args.Length == 3) { response = "No estate specified."; } else { int estateId; if (!int.TryParse(args[3], out estateId)) { response = String.Format("\"{0}\" is not a valid ID for an Estate", args[3]); } else { if (args.Length == 4) { response = "No name specified."; } else { // everything after the estate ID is "name" StringBuilder sb = new StringBuilder(args[4]); for (int i = 5; i < args.Length; i++) sb.Append (" " + args[i]); string estateName = sb.ToString(); // send it off for processing. response = estateModule.SetEstateName(estateId, estateName); if (response == String.Empty) { response = String.Format("Estate {0} renamed to \"{1}\"", estateId, estateName); } } } } // give the user some feedback if (response != null) MainConsole.Instance.Output(response); } private void EstateLinkRegionCommand(string module, string[] args) { int estateId =-1; UUID regionId = UUID.Zero; Scene scene = null; string response = null; if (args.Length == 3) { response = "No estate specified."; } else if (!int.TryParse(args [3], out estateId)) { response = String.Format("\"{0}\" is not a valid ID for an Estate", args [3]); } else if (args.Length == 4) { response = "No region specified."; } else if (!UUID.TryParse(args[4], out regionId)) { response = String.Format("\"{0}\" is not a valid UUID for a Region", args [4]); } else if (!SceneManager.TryGetScene(regionId, out scene)) { // region may exist, but on a different sim. response = String.Format("No access to Region \"{0}\"", args [4]); } if (response != null) { MainConsole.Instance.Output(response); return; } // send it off for processing. IEstateModule estateModule = scene.RequestModuleInterface<IEstateModule>(); response = estateModule.SetRegionEstate(scene.RegionInfo, estateId); if (response == String.Empty) { estateModule.TriggerRegionInfoChange(); estateModule.sendRegionHandshakeToAll(); response = String.Format ("Region {0} is now attached to estate {1}", regionId, estateId); } // give the user some feedback if (response != null) MainConsole.Instance.Output (response); } #endregion private static string CombineParams(string[] commandParams, int pos) { string result = String.Empty; for (int i = pos; i < commandParams.Length; i++) { result += commandParams[i] + " "; } result = result.TrimEnd(' '); return result; } } }
// Copyright (c) .NET Foundation. 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.Data; using System.Data.Common; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata.Internal; using Pomelo.EntityFrameworkCore.MySql.Internal; using Pomelo.EntityFrameworkCore.MySql.Storage.Internal; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.TestUtilities; using Xunit; // ReSharper disable InconsistentNaming namespace Microsoft.EntityFrameworkCore { public class MySqlTypeMapperTest : RelationalTypeMapperTestBase { [Fact] public void Does_simple_SQL_Server_mappings_to_DDL_types() { Assert.Equal("int", GetTypeMapping(typeof(int)).StoreType); Assert.Equal("datetime2", GetTypeMapping(typeof(DateTime)).StoreType); Assert.Equal("uniqueidentifier", GetTypeMapping(typeof(Guid)).StoreType); Assert.Equal("tinyint", GetTypeMapping(typeof(byte)).StoreType); Assert.Equal("float", GetTypeMapping(typeof(double)).StoreType); Assert.Equal("bit", GetTypeMapping(typeof(bool)).StoreType); Assert.Equal("smallint", GetTypeMapping(typeof(short)).StoreType); Assert.Equal("bigint", GetTypeMapping(typeof(long)).StoreType); Assert.Equal("real", GetTypeMapping(typeof(float)).StoreType); Assert.Equal("datetimeoffset", GetTypeMapping(typeof(DateTimeOffset)).StoreType); } [Fact] public void Does_simple_SQL_Server_mappings_for_nullable_CLR_types_to_DDL_types() { Assert.Equal("int", GetTypeMapping(typeof(int?)).StoreType); Assert.Equal("datetime2", GetTypeMapping(typeof(DateTime?)).StoreType); Assert.Equal("uniqueidentifier", GetTypeMapping(typeof(Guid?)).StoreType); Assert.Equal("tinyint", GetTypeMapping(typeof(byte?)).StoreType); Assert.Equal("float", GetTypeMapping(typeof(double?)).StoreType); Assert.Equal("bit", GetTypeMapping(typeof(bool?)).StoreType); Assert.Equal("smallint", GetTypeMapping(typeof(short?)).StoreType); Assert.Equal("bigint", GetTypeMapping(typeof(long?)).StoreType); Assert.Equal("real", GetTypeMapping(typeof(float?)).StoreType); Assert.Equal("datetimeoffset", GetTypeMapping(typeof(DateTimeOffset?)).StoreType); } [Fact] public void Does_simple_SQL_Server_mappings_for_enums_to_DDL_types() { Assert.Equal("int", GetTypeMapping(typeof(IntEnum)).StoreType); Assert.Equal("tinyint", GetTypeMapping(typeof(ByteEnum)).StoreType); Assert.Equal("smallint", GetTypeMapping(typeof(ShortEnum)).StoreType); Assert.Equal("bigint", GetTypeMapping(typeof(LongEnum)).StoreType); Assert.Equal("int", GetTypeMapping(typeof(IntEnum?)).StoreType); Assert.Equal("tinyint", GetTypeMapping(typeof(ByteEnum?)).StoreType); Assert.Equal("smallint", GetTypeMapping(typeof(ShortEnum?)).StoreType); Assert.Equal("bigint", GetTypeMapping(typeof(LongEnum?)).StoreType); } [Fact] public void Does_simple_SQL_Server_mappings_to_DbTypes() { Assert.Equal(DbType.Int32, GetTypeMapping(typeof(int)).DbType); Assert.Null(GetTypeMapping(typeof(string)).DbType); Assert.Equal(DbType.Binary, GetTypeMapping(typeof(byte[])).DbType); Assert.Null(GetTypeMapping(typeof(TimeSpan)).DbType); Assert.Equal(DbType.Guid, GetTypeMapping(typeof(Guid)).DbType); Assert.Equal(DbType.Byte, GetTypeMapping(typeof(byte)).DbType); Assert.Null(GetTypeMapping(typeof(double)).DbType); Assert.Null(GetTypeMapping(typeof(bool)).DbType); Assert.Equal(DbType.Int16, GetTypeMapping(typeof(short)).DbType); Assert.Equal(DbType.Int64, GetTypeMapping(typeof(long)).DbType); Assert.Null(GetTypeMapping(typeof(float)).DbType); Assert.Equal(DbType.DateTimeOffset, GetTypeMapping(typeof(DateTimeOffset)).DbType); } [Fact] public void Does_simple_SQL_Server_mappings_for_nullable_CLR_types_to_DbTypes() { Assert.Equal(DbType.Int32, GetTypeMapping(typeof(int?)).DbType); Assert.Null(GetTypeMapping(typeof(string)).DbType); Assert.Equal(DbType.Binary, GetTypeMapping(typeof(byte[])).DbType); Assert.Null(GetTypeMapping(typeof(TimeSpan?)).DbType); Assert.Equal(DbType.Guid, GetTypeMapping(typeof(Guid?)).DbType); Assert.Equal(DbType.Byte, GetTypeMapping(typeof(byte?)).DbType); Assert.Null(GetTypeMapping(typeof(double?)).DbType); Assert.Null(GetTypeMapping(typeof(bool?)).DbType); Assert.Equal(DbType.Int16, GetTypeMapping(typeof(short?)).DbType); Assert.Equal(DbType.Int64, GetTypeMapping(typeof(long?)).DbType); Assert.Null(GetTypeMapping(typeof(float?)).DbType); Assert.Equal(DbType.DateTimeOffset, GetTypeMapping(typeof(DateTimeOffset?)).DbType); } [Fact] public void Does_simple_SQL_Server_mappings_for_enums_to_DbTypes() { Assert.Equal(DbType.Int32, GetTypeMapping(typeof(IntEnum)).DbType); Assert.Equal(DbType.Byte, GetTypeMapping(typeof(ByteEnum)).DbType); Assert.Equal(DbType.Int16, GetTypeMapping(typeof(ShortEnum)).DbType); Assert.Equal(DbType.Int64, GetTypeMapping(typeof(LongEnum)).DbType); Assert.Equal(DbType.Int32, GetTypeMapping(typeof(IntEnum?)).DbType); Assert.Equal(DbType.Byte, GetTypeMapping(typeof(ByteEnum?)).DbType); Assert.Equal(DbType.Int16, GetTypeMapping(typeof(ShortEnum?)).DbType); Assert.Equal(DbType.Int64, GetTypeMapping(typeof(LongEnum?)).DbType); } [Fact] public void Does_decimal_mapping() { var typeMapping = GetTypeMapping(typeof(decimal)); Assert.Null(typeMapping.DbType); Assert.Equal("decimal(18,2)", typeMapping.StoreType); } [Fact] public void Does_decimal_mapping_for_nullable_CLR_types() { var typeMapping = GetTypeMapping(typeof(decimal?)); Assert.Null(typeMapping.DbType); Assert.Equal("decimal(18,2)", typeMapping.StoreType); } [Theory] [InlineData(true)] [InlineData(null)] public void Does_non_key_SQL_Server_string_mapping(bool? unicode) { var typeMapping = GetTypeMapping(typeof(string), unicode: unicode); Assert.Null(typeMapping.DbType); Assert.Equal("nvarchar(max)", typeMapping.StoreType); Assert.Null(typeMapping.Size); Assert.True(typeMapping.IsUnicode); Assert.Equal(4000, typeMapping.CreateParameter(new TestCommand(), "Name", "Value").Size); } [Theory] [InlineData(true)] [InlineData(null)] public void Does_non_key_SQL_Server_string_mapping_with_max_length(bool? unicode) { var typeMapping = GetTypeMapping(typeof(string), null, 3, unicode: unicode); Assert.Null(typeMapping.DbType); Assert.Equal("nvarchar(3)", typeMapping.StoreType); Assert.Equal(3, typeMapping.Size); Assert.True(typeMapping.IsUnicode); Assert.Equal(-1, typeMapping.CreateParameter(new TestCommand(), "Name", "Value").Size); } [Theory] [InlineData(true)] [InlineData(null)] public void Does_non_key_SQL_Server_string_mapping_with_long_string(bool? unicode) { var typeMapping = GetTypeMapping(typeof(string), unicode: unicode); Assert.Null(typeMapping.DbType); Assert.Equal("nvarchar(max)", typeMapping.StoreType); Assert.Null(typeMapping.Size); Assert.True(typeMapping.IsUnicode); Assert.Equal(-1, typeMapping.CreateParameter(new TestCommand(), "Name", new string('X', 4001)).Size); } [Theory] [InlineData(true)] [InlineData(null)] public void Does_non_key_SQL_Server_string_mapping_with_max_length_with_long_string(bool? unicode) { var typeMapping = GetTypeMapping(typeof(string), null, 3, unicode: unicode); Assert.Null(typeMapping.DbType); Assert.Equal("nvarchar(3)", typeMapping.StoreType); Assert.Equal(3, typeMapping.Size); Assert.True(typeMapping.IsUnicode); Assert.Equal(-1, typeMapping.CreateParameter(new TestCommand(), "Name", new string('X', 4001)).Size); } [Theory] [InlineData(true)] [InlineData(null)] public void Does_non_key_SQL_Server_required_string_mapping(bool? unicode) { var typeMapping = GetTypeMapping(typeof(string), nullable: false, unicode: unicode); Assert.Null(typeMapping.DbType); Assert.Equal("nvarchar(max)", typeMapping.StoreType); Assert.Null(typeMapping.Size); Assert.True(typeMapping.IsUnicode); Assert.Equal(4000, typeMapping.CreateParameter(new TestCommand(), "Name", "Value").Size); } [Theory] [InlineData(true)] [InlineData(null)] public void Does_key_SQL_Server_string_mapping(bool? unicode) { var property = CreateEntityType().AddProperty("MyProp", typeof(string)); property.IsNullable = false; property.IsUnicode(unicode); property.DeclaringEntityType.SetPrimaryKey(property); var typeMapping = CreateTypeMapper().GetMapping(property); Assert.Null(typeMapping.DbType); Assert.Equal("nvarchar(450)", typeMapping.StoreType); Assert.Equal(450, typeMapping.Size); Assert.True(typeMapping.IsUnicode); Assert.Equal(450, typeMapping.CreateParameter(new TestCommand(), "Name", "Value").Size); } private static IRelationalTypeMappingSource CreateTypeMapper() => new MySqlTypeMappingSource( TestServiceFactory.Instance.Create<TypeMappingSourceDependencies>(), TestServiceFactory.Instance.Create<RelationalTypeMappingSourceDependencies>()); [Theory] [InlineData(true)] [InlineData(null)] public void Does_foreign_key_SQL_Server_string_mapping(bool? unicode) { var property = CreateEntityType().AddProperty("MyProp", typeof(string)); property.IsNullable = false; property.IsUnicode(unicode); var fkProperty = property.DeclaringEntityType.AddProperty("FK", typeof(string)); var pk = property.DeclaringEntityType.SetPrimaryKey(property); property.DeclaringEntityType.AddForeignKey(fkProperty, pk, property.DeclaringEntityType); var typeMapping = CreateTypeMapper().GetMapping(fkProperty); Assert.Null(typeMapping.DbType); Assert.Equal("nvarchar(450)", typeMapping.StoreType); Assert.Equal(450, typeMapping.Size); Assert.True(typeMapping.IsUnicode); Assert.Equal(450, typeMapping.CreateParameter(new TestCommand(), "Name", "Value").Size); } [Theory] [InlineData(true)] [InlineData(null)] public void Does_required_foreign_key_SQL_Server_string_mapping(bool? unicode) { var property = CreateEntityType().AddProperty("MyProp", typeof(string)); property.IsNullable = false; property.IsUnicode(unicode); var fkProperty = property.DeclaringEntityType.AddProperty("FK", typeof(string)); var pk = property.DeclaringEntityType.SetPrimaryKey(property); property.DeclaringEntityType.AddForeignKey(fkProperty, pk, property.DeclaringEntityType); fkProperty.IsNullable = false; var typeMapping = CreateTypeMapper().GetMapping(fkProperty); Assert.Null(typeMapping.DbType); Assert.Equal("nvarchar(450)", typeMapping.StoreType); Assert.Equal(450, typeMapping.Size); Assert.True(typeMapping.IsUnicode); Assert.Equal(450, typeMapping.CreateParameter(new TestCommand(), "Name", "Value").Size); } [Theory] [InlineData(true)] [InlineData(null)] public void Does_indexed_column_SQL_Server_string_mapping(bool? unicode) { var entityType = CreateEntityType(); var property = entityType.AddProperty("MyProp", typeof(string)); property.IsUnicode(unicode); entityType.AddIndex(property); var typeMapping = CreateTypeMapper().GetMapping(property); Assert.Null(typeMapping.DbType); Assert.Equal("nvarchar(450)", typeMapping.StoreType); Assert.Equal(450, typeMapping.Size); Assert.True(typeMapping.IsUnicode); Assert.Equal(450, typeMapping.CreateParameter(new TestCommand(), "Name", "Value").Size); } [Fact] public void Does_non_key_SQL_Server_string_mapping_ansi() { var typeMapping = GetTypeMapping(typeof(string), unicode: false); Assert.Equal(DbType.AnsiString, typeMapping.DbType); Assert.Equal("varchar(max)", typeMapping.StoreType); Assert.Null(typeMapping.Size); Assert.False(typeMapping.IsUnicode); Assert.Equal(8000, typeMapping.CreateParameter(new TestCommand(), "Name", "Value").Size); } [Fact] public void Does_non_key_SQL_Server_string_mapping_with_max_length_ansi() { var typeMapping = GetTypeMapping(typeof(string), null, 3, unicode: false); Assert.Equal(DbType.AnsiString, typeMapping.DbType); Assert.Equal("varchar(3)", typeMapping.StoreType); Assert.Equal(3, typeMapping.Size); Assert.False(typeMapping.IsUnicode); Assert.Equal(-1, typeMapping.CreateParameter(new TestCommand(), "Name", "Value").Size); } [Fact] public void Does_non_key_SQL_Server_string_mapping_with_long_string_ansi() { var typeMapping = GetTypeMapping(typeof(string), unicode: false); Assert.Equal(DbType.AnsiString, typeMapping.DbType); Assert.Equal("varchar(max)", typeMapping.StoreType); Assert.Null(typeMapping.Size); Assert.False(typeMapping.IsUnicode); Assert.Equal(-1, typeMapping.CreateParameter(new TestCommand(), "Name", new string('X', 8001)).Size); } [Fact] public void Does_non_key_SQL_Server_string_mapping_with_max_length_with_long_string_ansi() { var typeMapping = GetTypeMapping(typeof(string), null, 3, unicode: false); Assert.Equal(DbType.AnsiString, typeMapping.DbType); Assert.Equal("varchar(3)", typeMapping.StoreType); Assert.Equal(3, typeMapping.Size); Assert.False(typeMapping.IsUnicode); Assert.Equal(-1, typeMapping.CreateParameter(new TestCommand(), "Name", new string('X', 8001)).Size); } [Fact] public void Does_non_key_SQL_Server_required_string_mapping_ansi() { var typeMapping = GetTypeMapping(typeof(string), nullable: false, unicode: false); Assert.Equal(DbType.AnsiString, typeMapping.DbType); Assert.Equal("varchar(max)", typeMapping.StoreType); Assert.Null(typeMapping.Size); Assert.False(typeMapping.IsUnicode); Assert.Equal(8000, typeMapping.CreateParameter(new TestCommand(), "Name", "Value").Size); } [Fact] public void Does_key_SQL_Server_string_mapping_ansi() { var property = CreateEntityType().AddProperty("MyProp", typeof(string)); property.IsNullable = false; property.IsUnicode(false); property.DeclaringEntityType.SetPrimaryKey(property); var typeMapping = CreateTypeMapper().GetMapping(property); Assert.Equal(DbType.AnsiString, typeMapping.DbType); Assert.Equal("varchar(900)", typeMapping.StoreType); Assert.Equal(900, typeMapping.Size); Assert.False(typeMapping.IsUnicode); Assert.Equal(900, typeMapping.CreateParameter(new TestCommand(), "Name", "Value").Size); } [Fact] public void Does_foreign_key_SQL_Server_string_mapping_ansi() { var property = CreateEntityType().AddProperty("MyProp", typeof(string)); property.IsUnicode(false); property.IsNullable = false; var fkProperty = property.DeclaringEntityType.AddProperty("FK", typeof(string)); var pk = property.DeclaringEntityType.SetPrimaryKey(property); property.DeclaringEntityType.AddForeignKey(fkProperty, pk, property.DeclaringEntityType); var typeMapping = CreateTypeMapper().GetMapping(fkProperty); Assert.Equal(DbType.AnsiString, typeMapping.DbType); Assert.Equal("varchar(900)", typeMapping.StoreType); Assert.Equal(900, typeMapping.Size); Assert.False(typeMapping.IsUnicode); Assert.Equal(900, typeMapping.CreateParameter(new TestCommand(), "Name", "Value").Size); } [Fact] public void Does_required_foreign_key_SQL_Server_string_mapping_ansi() { var property = CreateEntityType().AddProperty("MyProp", typeof(string)); property.IsUnicode(false); property.IsNullable = false; var fkProperty = property.DeclaringEntityType.AddProperty("FK", typeof(string)); var pk = property.DeclaringEntityType.SetPrimaryKey(property); property.DeclaringEntityType.AddForeignKey(fkProperty, pk, property.DeclaringEntityType); fkProperty.IsNullable = false; var typeMapping = CreateTypeMapper().GetMapping(fkProperty); Assert.Equal(DbType.AnsiString, typeMapping.DbType); Assert.Equal("varchar(900)", typeMapping.StoreType); Assert.Equal(900, typeMapping.Size); Assert.False(typeMapping.IsUnicode); Assert.Equal(900, typeMapping.CreateParameter(new TestCommand(), "Name", "Value").Size); } [Fact] public void Does_indexed_column_SQL_Server_string_mapping_ansi() { var entityType = CreateEntityType(); var property = entityType.AddProperty("MyProp", typeof(string)); property.IsUnicode(false); entityType.AddIndex(property); var typeMapping = CreateTypeMapper().GetMapping(property); Assert.Equal(DbType.AnsiString, typeMapping.DbType); Assert.Equal("varchar(900)", typeMapping.StoreType); Assert.Equal(900, typeMapping.Size); Assert.False(typeMapping.IsUnicode); Assert.Equal(900, typeMapping.CreateParameter(new TestCommand(), "Name", "Value").Size); } [Fact] public void Does_non_key_SQL_Server_binary_mapping() { var typeMapping = GetTypeMapping(typeof(byte[])); Assert.Equal(DbType.Binary, typeMapping.DbType); Assert.Equal("varbinary(max)", typeMapping.StoreType); Assert.Null(typeMapping.Size); Assert.Equal(8000, typeMapping.CreateParameter(new TestCommand(), "Name", new byte[3]).Size); } [Fact] public void Does_non_key_SQL_Server_binary_mapping_with_max_length() { var typeMapping = GetTypeMapping(typeof(byte[]), null, 3); Assert.Equal(DbType.Binary, typeMapping.DbType); Assert.Equal("varbinary(3)", typeMapping.StoreType); Assert.Equal(3, typeMapping.Size); Assert.Equal(3, typeMapping.CreateParameter(new TestCommand(), "Name", new byte[3]).Size); } [Fact] public void Does_non_key_SQL_Server_binary_mapping_with_long_array() { var typeMapping = GetTypeMapping(typeof(byte[])); Assert.Equal(DbType.Binary, typeMapping.DbType); Assert.Equal("varbinary(max)", typeMapping.StoreType); Assert.Null(typeMapping.Size); Assert.Equal(-1, typeMapping.CreateParameter(new TestCommand(), "Name", new byte[8001]).Size); } [Fact] public void Does_non_key_SQL_Server_binary_mapping_with_max_length_with_long_array() { var typeMapping = GetTypeMapping(typeof(byte[]), null, 3); Assert.Equal(DbType.Binary, typeMapping.DbType); Assert.Equal("varbinary(3)", typeMapping.StoreType); Assert.Equal(3, typeMapping.Size); Assert.Equal(-1, typeMapping.CreateParameter(new TestCommand(), "Name", new byte[8001]).Size); } [Fact] public void Does_non_key_SQL_Server_required_binary_mapping() { var typeMapping = GetTypeMapping(typeof(byte[]), nullable: false); Assert.Equal(DbType.Binary, typeMapping.DbType); Assert.Equal("varbinary(max)", typeMapping.StoreType); Assert.Null(typeMapping.Size); Assert.Equal(8000, typeMapping.CreateParameter(new TestCommand(), "Name", new byte[3]).Size); } [Fact] public void Does_non_key_SQL_Server_fixed_length_binary_mapping() { var property = CreateEntityType().AddProperty("MyBinaryProp", typeof(byte[])); property.Relational().ColumnType = "binary(100)"; var typeMapping = CreateTypeMapper().GetMapping(property); Assert.Equal(DbType.Binary, typeMapping.DbType); Assert.Equal("binary(100)", typeMapping.StoreType); } [Fact] public void Does_key_SQL_Server_binary_mapping() { var property = CreateEntityType().AddProperty("MyProp", typeof(byte[])); property.IsNullable = false; property.DeclaringEntityType.SetPrimaryKey(property); var typeMapping = CreateTypeMapper().GetMapping(property); Assert.Equal(DbType.Binary, typeMapping.DbType); Assert.Equal("varbinary(900)", typeMapping.StoreType); Assert.Equal(900, typeMapping.CreateParameter(new TestCommand(), "Name", new byte[3]).Size); } [Fact] public void Does_foreign_key_SQL_Server_binary_mapping() { var property = CreateEntityType().AddProperty("MyProp", typeof(byte[])); property.IsNullable = false; var fkProperty = property.DeclaringEntityType.AddProperty("FK", typeof(byte[])); var pk = property.DeclaringEntityType.SetPrimaryKey(property); property.DeclaringEntityType.AddForeignKey(fkProperty, pk, property.DeclaringEntityType); var typeMapping = CreateTypeMapper().GetMapping(fkProperty); Assert.Equal(DbType.Binary, typeMapping.DbType); Assert.Equal("varbinary(900)", typeMapping.StoreType); Assert.Equal(900, typeMapping.CreateParameter(new TestCommand(), "Name", new byte[3]).Size); } [Fact] public void Does_required_foreign_key_SQL_Server_binary_mapping() { var property = CreateEntityType().AddProperty("MyProp", typeof(byte[])); property.IsNullable = false; var fkProperty = property.DeclaringEntityType.AddProperty("FK", typeof(byte[])); var pk = property.DeclaringEntityType.SetPrimaryKey(property); property.DeclaringEntityType.AddForeignKey(fkProperty, pk, property.DeclaringEntityType); fkProperty.IsNullable = false; var typeMapping = CreateTypeMapper().GetMapping(fkProperty); Assert.Equal(DbType.Binary, typeMapping.DbType); Assert.Equal("varbinary(900)", typeMapping.StoreType); Assert.Equal(900, typeMapping.CreateParameter(new TestCommand(), "Name", new byte[3]).Size); } [Fact] public void Does_indexed_column_SQL_Server_binary_mapping() { var entityType = CreateEntityType(); var property = entityType.AddProperty("MyProp", typeof(byte[])); entityType.AddIndex(property); var typeMapping = CreateTypeMapper().GetMapping(property); Assert.Equal(DbType.Binary, typeMapping.DbType); Assert.Equal("varbinary(900)", typeMapping.StoreType); Assert.Equal(900, typeMapping.CreateParameter(new TestCommand(), "Name", new byte[] { 0, 1, 2, 3 }).Size); } [Fact] public void Does_non_key_SQL_Server_rowversion_mapping() { var property = CreateEntityType().AddProperty("MyProp", typeof(byte[])); property.IsConcurrencyToken = true; property.ValueGenerated = ValueGenerated.OnAddOrUpdate; var typeMapping = CreateTypeMapper().GetMapping(property); Assert.Equal(DbType.Binary, typeMapping.DbType); Assert.Equal("rowversion", typeMapping.StoreType); Assert.Equal(8, typeMapping.Size); Assert.Equal(8, typeMapping.CreateParameter(new TestCommand(), "Name", new byte[8]).Size); } [Fact] public void Does_non_key_SQL_Server_required_rowversion_mapping() { var property = CreateEntityType().AddProperty("MyProp", typeof(byte[])); property.IsConcurrencyToken = true; property.ValueGenerated = ValueGenerated.OnAddOrUpdate; property.IsNullable = false; var typeMapping = CreateTypeMapper().GetMapping(property); Assert.Equal(DbType.Binary, typeMapping.DbType); Assert.Equal("rowversion", typeMapping.StoreType); Assert.Equal(8, typeMapping.Size); Assert.Equal(8, typeMapping.CreateParameter(new TestCommand(), "Name", new byte[8]).Size); } [Fact] public void Does_not_do_rowversion_mapping_for_non_computed_concurrency_tokens() { var property = CreateEntityType().AddProperty("MyProp", typeof(byte[])); property.IsConcurrencyToken = true; var typeMapping = CreateTypeMapper().GetMapping(property); Assert.Equal(DbType.Binary, typeMapping.DbType); Assert.Equal("varbinary(max)", typeMapping.StoreType); } private RelationalTypeMapping GetTypeMapping( Type propertyType, bool? nullable = null, int? maxLength = null, bool? unicode = null) { var property = CreateEntityType().AddProperty("MyProp", propertyType); if (nullable.HasValue) { property.IsNullable = nullable.Value; } if (maxLength.HasValue) { property.SetMaxLength(maxLength); } if (unicode.HasValue) { property.IsUnicode(unicode); } return CreateTypeMapper().GetMapping(property); } [Fact] public void Does_default_mappings_for_sequence_types() { Assert.Equal("int", CreateTypeMapper().GetMapping(typeof(int)).StoreType); Assert.Equal("smallint", CreateTypeMapper().GetMapping(typeof(short)).StoreType); Assert.Equal("bigint", CreateTypeMapper().GetMapping(typeof(long)).StoreType); Assert.Equal("tinyint", CreateTypeMapper().GetMapping(typeof(byte)).StoreType); } [Fact] public void Does_default_mappings_for_strings_and_byte_arrays() { Assert.Equal("nvarchar(max)", CreateTypeMapper().GetMapping(typeof(string)).StoreType); Assert.Equal("varbinary(max)", CreateTypeMapper().GetMapping(typeof(byte[])).StoreType); } [Fact] public void Does_default_mappings_for_values() { Assert.Equal("nvarchar(max)", CreateTypeMapper().GetMappingForValue("Cheese").StoreType); Assert.Equal("varbinary(max)", CreateTypeMapper().GetMappingForValue(new byte[1]).StoreType); Assert.Equal("datetime2", CreateTypeMapper().GetMappingForValue(new DateTime()).StoreType); } [Fact] public void Does_default_mappings_for_null_values() { Assert.Equal("NULL", CreateTypeMapper().GetMappingForValue(null).StoreType); Assert.Equal("NULL", CreateTypeMapper().GetMappingForValue(DBNull.Value).StoreType); } [Fact] public void Throws_for_unrecognized_property_types() { var property = new Model().AddEntityType("Entity1").AddProperty("Strange", typeof(object)); var ex = Assert.Throws<InvalidOperationException>(() => CreateTypeMapper().GetMapping(property)); Assert.Equal(RelationalStrings.UnsupportedPropertyType("Entity1", "Strange", "object"), ex.Message); } [Theory] [InlineData("bigint", typeof(long), null, false)] [InlineData("binary varying(333)", typeof(byte[]), 333, false)] [InlineData("binary varying(max)", typeof(byte[]), null, false)] [InlineData("binary(333)", typeof(byte[]), 333, false)] [InlineData("bit", typeof(bool), null, false)] [InlineData("char varying(333)", typeof(string), 333, false)] [InlineData("char varying(max)", typeof(string), null, false)] [InlineData("char(333)", typeof(string), 333, false)] [InlineData("character varying(333)", typeof(string), 333, false)] [InlineData("character varying(max)", typeof(string), null, false)] [InlineData("character(333)", typeof(string), 333, false)] [InlineData("date", typeof(DateTime), null, false)] [InlineData("datetime", typeof(DateTime), null, false)] [InlineData("datetime2", typeof(DateTime), null, false)] [InlineData("datetimeoffset", typeof(DateTimeOffset), null, false)] [InlineData("dec", typeof(decimal), null, false, "dec(18,2)")] [InlineData("decimal", typeof(decimal), null, false, "decimal(18,2)")] [InlineData("float", typeof(double), null, false)] // This is correct. MySql 'float' type maps to C# double [InlineData("float(10,8)", typeof(double), null, false)] [InlineData("image", typeof(byte[]), null, false)] [InlineData("int", typeof(int), null, false)] [InlineData("money", typeof(decimal), null, false)] [InlineData("national char varying(333)", typeof(string), 333, true)] [InlineData("national char varying(max)", typeof(string), null, true)] [InlineData("national character varying(333)", typeof(string), 333, true)] [InlineData("national character varying(max)", typeof(string), null, true)] [InlineData("national character(333)", typeof(string), 333, true)] [InlineData("nchar(333)", typeof(string), 333, true)] [InlineData("ntext", typeof(string), null, true)] [InlineData("numeric", typeof(decimal), null, false, "numeric(18,2)")] [InlineData("nvarchar(333)", typeof(string), 333, true)] [InlineData("nvarchar(max)", typeof(string), null, true)] [InlineData("real", typeof(float), null, false)] [InlineData("rowversion", typeof(byte[]), 8, false)] [InlineData("smalldatetime", typeof(DateTime), null, false)] [InlineData("smallint", typeof(short), null, false)] [InlineData("smallmoney", typeof(decimal), null, false)] [InlineData("text", typeof(string), null, false)] [InlineData("time", typeof(TimeSpan), null, false)] [InlineData("timestamp", typeof(byte[]), 8, false)] // note: rowversion is a synonym but MySql stores the data type as 'timestamp' [InlineData("tinyint", typeof(byte), null, false)] [InlineData("uniqueidentifier", typeof(Guid), null, false)] [InlineData("varbinary(333)", typeof(byte[]), 333, false)] [InlineData("varbinary(max)", typeof(byte[]), null, false)] [InlineData("VarCHaR(333)", typeof(string), 333, false)] // case-insensitive [InlineData("varchar(333)", typeof(string), 333, false)] [InlineData("varchar(max)", typeof(string), null, false)] [InlineData("VARCHAR(max)", typeof(string), null, false, "varchar(max)")] public void Can_map_by_type_name(string typeName, Type clrType, int? size, bool unicode, string expectedType = null) { var mapping = CreateTypeMapper().FindMapping(typeName); Assert.Equal(clrType, mapping.ClrType); Assert.Equal(size, mapping.Size); Assert.Equal(unicode, mapping.IsUnicode); Assert.Equal(expectedType ?? typeName, mapping.StoreType); } [Theory] [InlineData("binary varying")] [InlineData("binary")] [InlineData("char varying")] [InlineData("char")] [InlineData("character varying")] [InlineData("character")] [InlineData("national char varying")] [InlineData("national character varying")] [InlineData("national character")] [InlineData("nchar")] [InlineData("nvarchar")] [InlineData("varbinary")] [InlineData("varchar")] [InlineData("VarCHaR")] // case-insensitive [InlineData("VARCHAR")] public void Throws_for_naked_type_name(string typeName) { var mapper = CreateTypeMapper(); Assert.Equal( MySqlStrings.UnqualifiedDataType(typeName), Assert.Throws<ArgumentException>(() => mapper.FindMapping(typeName)).Message, ignoreCase: true); } [Theory] [InlineData("binary varying")] [InlineData("binary")] [InlineData("char varying")] [InlineData("char")] [InlineData("character varying")] [InlineData("character")] [InlineData("national char varying")] [InlineData("national character varying")] [InlineData("national character")] [InlineData("nchar")] [InlineData("nvarchar")] [InlineData("varbinary")] [InlineData("varchar")] [InlineData("VarCHaR")] // case-insensitive [InlineData("VARCHAR")] public void Throws_for_naked_type_name_on_property(string typeName) { var builder = CreateModelBuilder(); var property = builder.Entity<StringCheese>() .Property(e => e.StringWithSize) .HasColumnType(typeName) .Metadata; var mapper = CreateTypeMapper(); Assert.Equal( MySqlStrings.UnqualifiedDataTypeOnProperty(typeName, nameof(StringCheese.StringWithSize)), Assert.Throws<ArgumentException>(() => mapper.FindMapping(property)).Message, ignoreCase: true); } [Theory] [InlineData("char varying")] [InlineData("char")] [InlineData("character varying")] [InlineData("character")] [InlineData("national char varying")] [InlineData("national character varying")] [InlineData("national character")] [InlineData("nchar")] [InlineData("nvarchar")] [InlineData("varchar")] [InlineData("VarCHaR")] [InlineData("VARCHAR")] public void Can_map_string_base_type_name_and_size(string typeName) { var builder = CreateModelBuilder(); var property = builder.Entity<StringCheese>() .Property(e => e.StringWithSize) .HasColumnType(typeName) .HasMaxLength(2018) .Metadata; var mapping = CreateTypeMapper().FindMapping(property); Assert.Same(typeof(string), mapping.ClrType); Assert.Equal(2018, mapping.Size); Assert.Equal(typeName.StartsWith("n", StringComparison.OrdinalIgnoreCase), mapping.IsUnicode); Assert.Equal(typeName + "(2018)", mapping.StoreType); } [Theory] [InlineData("binary varying")] [InlineData("binary")] [InlineData("varbinary")] public void Can_map_binary_base_type_name_and_size(string typeName) { var builder = CreateModelBuilder(); var property = builder.Entity<StringCheese>() .Property(e => e.BinaryWithSize) .HasColumnType(typeName) .HasMaxLength(2018) .Metadata; var mapping = CreateTypeMapper().FindMapping(property); Assert.Same(typeof(byte[]), mapping.ClrType); Assert.Equal(2018, mapping.Size); Assert.Equal(typeName + "(2018)", mapping.StoreType); } private class StringCheese { public int Id { get; set; } public string StringWithSize { get; set; } public byte[] BinaryWithSize { get; set; } } [Fact] public void Key_with_store_type_is_picked_up_by_FK() { var model = CreateModel(); var mapper = CreateTypeMapper(); Assert.Equal( "money", mapper.GetMapping(model.FindEntityType(typeof(MyType)).FindProperty("Id")).StoreType); Assert.Equal( "money", mapper.GetMapping(model.FindEntityType(typeof(MyRelatedType1)).FindProperty("Relationship1Id")).StoreType); } [Fact] public void String_key_with_max_length_is_picked_up_by_FK() { var model = CreateModel(); var mapper = CreateTypeMapper(); Assert.Equal( "nvarchar(200)", mapper.GetMapping(model.FindEntityType(typeof(MyRelatedType1)).FindProperty("Id")).StoreType); Assert.Equal( "nvarchar(200)", mapper.GetMapping(model.FindEntityType(typeof(MyRelatedType2)).FindProperty("Relationship1Id")).StoreType); } [Fact] public void Binary_key_with_max_length_is_picked_up_by_FK() { var model = CreateModel(); var mapper = CreateTypeMapper(); Assert.Equal( "varbinary(100)", mapper.GetMapping(model.FindEntityType(typeof(MyRelatedType2)).FindProperty("Id")).StoreType); Assert.Equal( "varbinary(100)", mapper.GetMapping(model.FindEntityType(typeof(MyRelatedType3)).FindProperty("Relationship1Id")).StoreType); } [Fact] public void String_key_with_unicode_is_picked_up_by_FK() { var model = CreateModel(); var mapper = CreateTypeMapper(); Assert.Equal( "varchar(900)", mapper.GetMapping(model.FindEntityType(typeof(MyRelatedType3)).FindProperty("Id")).StoreType); Assert.Equal( "varchar(900)", mapper.GetMapping(model.FindEntityType(typeof(MyRelatedType4)).FindProperty("Relationship1Id")).StoreType); } [Fact] public void Key_store_type_if_preferred_if_specified() { var model = CreateModel(); var mapper = CreateTypeMapper(); Assert.Equal( "money", mapper.GetMapping(model.FindEntityType(typeof(MyType)).FindProperty("Id")).StoreType); Assert.Equal( "dec(6,1)", mapper.GetMapping(model.FindEntityType(typeof(MyRelatedType1)).FindProperty("Relationship2Id")).StoreType); } [Fact] public void String_FK_max_length_is_preferred_if_specified() { var model = CreateModel(); var mapper = CreateTypeMapper(); Assert.Equal( "nvarchar(200)", mapper.GetMapping(model.FindEntityType(typeof(MyRelatedType1)).FindProperty("Id")).StoreType); Assert.Equal( "nvarchar(787)", mapper.GetMapping(model.FindEntityType(typeof(MyRelatedType2)).FindProperty("Relationship2Id")).StoreType); } [Fact] public void Binary_FK_max_length_is_preferred_if_specified() { var model = CreateModel(); var mapper = CreateTypeMapper(); Assert.Equal( "varbinary(100)", mapper.GetMapping(model.FindEntityType(typeof(MyRelatedType2)).FindProperty("Id")).StoreType); Assert.Equal( "varbinary(767)", mapper.GetMapping(model.FindEntityType(typeof(MyRelatedType3)).FindProperty("Relationship2Id")).StoreType); } [Fact] public void String_FK_unicode_is_preferred_if_specified() { var model = CreateModel(); var mapper = CreateTypeMapper(); Assert.Equal( "varchar(900)", mapper.GetMapping(model.FindEntityType(typeof(MyRelatedType3)).FindProperty("Id")).StoreType); Assert.Equal( "nvarchar(450)", mapper.GetMapping(model.FindEntityType(typeof(MyRelatedType4)).FindProperty("Relationship2Id")).StoreType); } private enum LongEnum : long { } private enum IntEnum { } private enum ShortEnum : short { } private enum ByteEnum : byte { } protected override ModelBuilder CreateModelBuilder() => MySqlTestHelpers.Instance.CreateConventionBuilder(); private class TestParameter : DbParameter { public override void ResetDbType() { } public override DbType DbType { get; set; } public override ParameterDirection Direction { get; set; } public override bool IsNullable { get; set; } public override string ParameterName { get; set; } public override string SourceColumn { get; set; } public override object Value { get; set; } public override bool SourceColumnNullMapping { get; set; } public override int Size { get; set; } } private class TestCommand : DbCommand { public override void Prepare() { } public override string CommandText { get; set; } public override int CommandTimeout { get; set; } public override CommandType CommandType { get; set; } public override UpdateRowSource UpdatedRowSource { get; set; } protected override DbConnection DbConnection { get; set; } protected override DbParameterCollection DbParameterCollection { get; } protected override DbTransaction DbTransaction { get; set; } public override bool DesignTimeVisible { get; set; } public override void Cancel() { } protected override DbParameter CreateDbParameter() { return new TestParameter(); } protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { throw new NotImplementedException(); } public override int ExecuteNonQuery() { throw new NotImplementedException(); } public override object ExecuteScalar() { throw new NotImplementedException(); } } } }
// 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 CompareScalarOrderedEqualBoolean() { var test = new BooleanBinaryOpTest__CompareScalarOrderedEqualBoolean(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class BooleanBinaryOpTest__CompareScalarOrderedEqualBoolean { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Single> _fld1; public Vector128<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(BooleanBinaryOpTest__CompareScalarOrderedEqualBoolean testClass) { var result = Sse.CompareScalarOrderedEqual(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } public void RunStructFldScenario_Load(BooleanBinaryOpTest__CompareScalarOrderedEqualBoolean testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse.CompareScalarOrderedEqual( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); testClass.ValidateResult(_fld1, _fld2, result); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private DataTable _dataTable; static BooleanBinaryOpTest__CompareScalarOrderedEqualBoolean() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public BooleanBinaryOpTest__CompareScalarOrderedEqualBoolean() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool IsSupported => Sse.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse.CompareScalarOrderedEqual( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse.CompareScalarOrderedEqual( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse.CompareScalarOrderedEqual( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarOrderedEqual), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarOrderedEqual), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarOrderedEqual), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse.CompareScalarOrderedEqual( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) fixed (Vector128<Single>* pClsVar2 = &_clsVar2) { var result = Sse.CompareScalarOrderedEqual( Sse.LoadVector128((Single*)(pClsVar1)), Sse.LoadVector128((Single*)(pClsVar2)) ); ValidateResult(_clsVar1, _clsVar2, result); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse.CompareScalarOrderedEqual(op1, op2); ValidateResult(op1, op2, result); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.CompareScalarOrderedEqual(op1, op2); ValidateResult(op1, op2, result); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.CompareScalarOrderedEqual(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new BooleanBinaryOpTest__CompareScalarOrderedEqualBoolean(); var result = Sse.CompareScalarOrderedEqual(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new BooleanBinaryOpTest__CompareScalarOrderedEqualBoolean(); fixed (Vector128<Single>* pFld1 = &test._fld1) fixed (Vector128<Single>* pFld2 = &test._fld2) { var result = Sse.CompareScalarOrderedEqual( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); ValidateResult(test._fld1, test._fld2, result); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse.CompareScalarOrderedEqual(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse.CompareScalarOrderedEqual( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); ValidateResult(_fld1, _fld2, result); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse.CompareScalarOrderedEqual(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse.CompareScalarOrderedEqual( Sse.LoadVector128((Single*)(&test._fld1)), Sse.LoadVector128((Single*)(&test._fld2)) ); ValidateResult(test._fld1, test._fld2, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Single> op1, Vector128<Single> op2, bool result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Single[] left, Single[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; if ((left[0] == right[0]) != result) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse)}.{nameof(Sse.CompareScalarOrderedEqual)}<Boolean>(Vector128<Single>, Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// 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.ServiceModel; namespace System.Collections.Generic { [System.Runtime.InteropServices.ComVisible(false)] public class SynchronizedReadOnlyCollection<T> : IList<T>, IList { private IList<T> _items; private object _sync; public SynchronizedReadOnlyCollection() { _items = new List<T>(); _sync = new Object(); } public SynchronizedReadOnlyCollection(object syncRoot) { if (syncRoot == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("syncRoot")); _items = new List<T>(); _sync = syncRoot; } public SynchronizedReadOnlyCollection(object syncRoot, IEnumerable<T> list) { if (syncRoot == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("syncRoot")); if (list == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("list")); _items = new List<T>(list); _sync = syncRoot; } public SynchronizedReadOnlyCollection(object syncRoot, params T[] list) { if (syncRoot == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("syncRoot")); if (list == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("list")); _items = new List<T>(list.Length); for (int i = 0; i < list.Length; i++) _items.Add(list[i]); _sync = syncRoot; } internal SynchronizedReadOnlyCollection(object syncRoot, List<T> list, bool makeCopy) { if (syncRoot == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("syncRoot")); if (list == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("list")); if (makeCopy) _items = new List<T>(list); else _items = list; _sync = syncRoot; } public int Count { get { lock (_sync) { return _items.Count; } } } protected IList<T> Items { get { return _items; } } public T this[int index] { get { lock (_sync) { return _items[index]; } } } public bool Contains(T value) { lock (_sync) { return _items.Contains(value); } } public void CopyTo(T[] array, int index) { lock (_sync) { _items.CopyTo(array, index); } } public IEnumerator<T> GetEnumerator() { lock (_sync) { return _items.GetEnumerator(); } } public int IndexOf(T value) { lock (_sync) { return _items.IndexOf(value); } } private void ThrowReadOnly() { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.SFxCollectionReadOnly)); } bool ICollection<T>.IsReadOnly { get { return true; } } T IList<T>.this[int index] { get { return this[index]; } set { this.ThrowReadOnly(); } } void ICollection<T>.Add(T value) { this.ThrowReadOnly(); } void ICollection<T>.Clear() { this.ThrowReadOnly(); } bool ICollection<T>.Remove(T value) { this.ThrowReadOnly(); return false; } void IList<T>.Insert(int index, T value) { this.ThrowReadOnly(); } void IList<T>.RemoveAt(int index) { this.ThrowReadOnly(); } bool ICollection.IsSynchronized { get { return true; } } object ICollection.SyncRoot { get { return _sync; } } void ICollection.CopyTo(Array array, int index) { ICollection asCollection = _items as ICollection; if (asCollection == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.SFxCopyToRequiresICollection)); lock (_sync) { asCollection.CopyTo(array, index); } } IEnumerator IEnumerable.GetEnumerator() { lock (_sync) { IEnumerable asEnumerable = _items as IEnumerable; if (asEnumerable != null) return asEnumerable.GetEnumerator(); else return new EnumeratorAdapter(_items); } } bool IList.IsFixedSize { get { return true; } } bool IList.IsReadOnly { get { return true; } } object IList.this[int index] { get { return this[index]; } set { this.ThrowReadOnly(); } } int IList.Add(object value) { this.ThrowReadOnly(); return 0; } void IList.Clear() { this.ThrowReadOnly(); } bool IList.Contains(object value) { VerifyValueType(value); return this.Contains((T)value); } int IList.IndexOf(object value) { VerifyValueType(value); return this.IndexOf((T)value); } void IList.Insert(int index, object value) { this.ThrowReadOnly(); } void IList.Remove(object value) { this.ThrowReadOnly(); } void IList.RemoveAt(int index) { this.ThrowReadOnly(); } private static void VerifyValueType(object value) { if ((value is T) || (value == null && !typeof(T).IsValueType())) return; Type type = (value == null) ? typeof(Object) : value.GetType(); string message = SR.Format(SR.SFxCollectionWrongType2, type.ToString(), typeof(T).ToString()); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(message)); } internal sealed class EnumeratorAdapter : IEnumerator, IDisposable { private IList<T> _list; private IEnumerator<T> _e; public EnumeratorAdapter(IList<T> list) { _list = list; _e = list.GetEnumerator(); } public object Current { get { return _e.Current; } } public bool MoveNext() { return _e.MoveNext(); } public void Dispose() { _e.Dispose(); } public void Reset() { _e = _list.GetEnumerator(); } } } }
#region Apache License // // 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. // #endregion using System; using System.Collections; using Ctrip.Log4.Appender; using Ctrip.Log4.Core; using Ctrip.Log4.Repository; using Ctrip.Log4.Util; namespace Ctrip.Log4.Repository.Hierarchy { #region LoggerCreationEvent /// <summary> /// Delegate used to handle logger creation event notifications. /// </summary> /// <param name="sender">The <see cref="Hierarchy"/> in which the <see cref="Logger"/> has been created.</param> /// <param name="e">The <see cref="LoggerCreationEventArgs"/> event args that hold the <see cref="Logger"/> instance that has been created.</param> /// <remarks> /// <para> /// Delegate used to handle logger creation event notifications. /// </para> /// </remarks> public delegate void LoggerCreationEventHandler(object sender, LoggerCreationEventArgs e); /// <summary> /// Provides data for the <see cref="Hierarchy.LoggerCreatedEvent"/> event. /// </summary> /// <remarks> /// <para> /// A <see cref="Hierarchy.LoggerCreatedEvent"/> event is raised every time a /// <see cref="Logger"/> is created. /// </para> /// </remarks> public class LoggerCreationEventArgs : EventArgs { /// <summary> /// The <see cref="Logger"/> created /// </summary> private Logger m_log; /// <summary> /// Constructor /// </summary> /// <param name="log">The <see cref="Logger"/> that has been created.</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="LoggerCreationEventArgs" /> event argument /// class,with the specified <see cref="Logger"/>. /// </para> /// </remarks> public LoggerCreationEventArgs(Logger log) { m_log = log; } /// <summary> /// Gets the <see cref="Logger"/> that has been created. /// </summary> /// <value> /// The <see cref="Logger"/> that has been created. /// </value> /// <remarks> /// <para> /// The <see cref="Logger"/> that has been created. /// </para> /// </remarks> public Logger Logger { get { return m_log; } } } #endregion LoggerCreationEvent /// <summary> /// Hierarchical organization of loggers /// </summary> /// <remarks> /// <para> /// <i>The casual user should not have to deal with this class /// directly.</i> /// </para> /// <para> /// This class is specialized in retrieving loggers by name and /// also maintaining the logger hierarchy. Implements the /// <see cref="ILoggerRepository"/> interface. /// </para> /// <para> /// The structure of the logger hierarchy is maintained by the /// <see cref="M:GetLogger(string)"/> method. The hierarchy is such that children /// link to their parent but parents do not have any references to their /// children. Moreover, loggers can be instantiated in any order, in /// particular descendant before ancestor. /// </para> /// <para> /// In case a descendant is created before a particular ancestor, /// then it creates a provision node for the ancestor and adds itself /// to the provision node. Other descendants of the same ancestor add /// themselves to the previously created provision node. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public class Hierarchy : LoggerRepositorySkeleton, IBasicRepositoryConfigurator, IXmlRepositoryConfigurator { #region Public Events /// <summary> /// Event used to notify that a logger has been created. /// </summary> /// <remarks> /// <para> /// Event raised when a logger is created. /// </para> /// </remarks> public event LoggerCreationEventHandler LoggerCreatedEvent { add { m_loggerCreatedEvent += value; } remove { m_loggerCreatedEvent -= value; } } #endregion Public Events #region Public Instance Constructors /// <summary> /// Default constructor /// </summary> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="Hierarchy" /> class. /// </para> /// </remarks> public Hierarchy() : this(new DefaultLoggerFactory()) { } /// <summary> /// Construct with properties /// </summary> /// <param name="properties">The properties to pass to this repository.</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="Hierarchy" /> class. /// </para> /// </remarks> public Hierarchy(PropertiesDictionary properties) : this(properties, new DefaultLoggerFactory()) { } /// <summary> /// Construct with a logger factory /// </summary> /// <param name="loggerFactory">The factory to use to create new logger instances.</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="Hierarchy" /> class with /// the specified <see cref="ILoggerFactory" />. /// </para> /// </remarks> public Hierarchy(ILoggerFactory loggerFactory) : this(new PropertiesDictionary(), loggerFactory) { } /// <summary> /// Construct with properties and a logger factory /// </summary> /// <param name="properties">The properties to pass to this repository.</param> /// <param name="loggerFactory">The factory to use to create new logger instances.</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="Hierarchy" /> class with /// the specified <see cref="ILoggerFactory" />. /// </para> /// </remarks> public Hierarchy(PropertiesDictionary properties, ILoggerFactory loggerFactory) : base(properties) { if (loggerFactory == null) { throw new ArgumentNullException("loggerFactory"); } m_defaultFactory = loggerFactory; m_ht = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); } #endregion Public Instance Constructors #region Public Instance Properties /// <summary> /// Has no appender warning been emitted /// </summary> /// <remarks> /// <para> /// Flag to indicate if we have already issued a warning /// about not having an appender warning. /// </para> /// </remarks> public bool EmittedNoAppenderWarning { get { return m_emittedNoAppenderWarning; } set { m_emittedNoAppenderWarning = value; } } /// <summary> /// Get the root of this hierarchy /// </summary> /// <remarks> /// <para> /// Get the root of this hierarchy. /// </para> /// </remarks> public Logger Root { get { if (m_root == null) { lock(this) { if (m_root == null) { // Create the root logger Logger root = m_defaultFactory.CreateLogger(this, null); root.Hierarchy = this; // Store root m_root = root; } } } return m_root; } } /// <summary> /// Gets or sets the default <see cref="ILoggerFactory" /> instance. /// </summary> /// <value>The default <see cref="ILoggerFactory" /></value> /// <remarks> /// <para> /// The logger factory is used to create logger instances. /// </para> /// </remarks> public ILoggerFactory LoggerFactory { get { return m_defaultFactory; } set { if (value == null) { throw new ArgumentNullException("value"); } m_defaultFactory = value; } } #endregion Public Instance Properties #region Override Implementation of LoggerRepositorySkeleton /// <summary> /// Test if a logger exists /// </summary> /// <param name="name">The name of the logger to lookup</param> /// <returns>The Logger object with the name specified</returns> /// <remarks> /// <para> /// Check if the named logger exists in the hierarchy. If so return /// its reference, otherwise returns <c>null</c>. /// </para> /// </remarks> override public ILogger Exists(string name) { if (name == null) { throw new ArgumentNullException("name"); } return m_ht[new LoggerKey(name)] as Logger; } /// <summary> /// Returns all the currently defined loggers in the hierarchy as an Array /// </summary> /// <returns>All the defined loggers</returns> /// <remarks> /// <para> /// Returns all the currently defined loggers in the hierarchy as an Array. /// The root logger is <b>not</b> included in the returned /// enumeration. /// </para> /// </remarks> override public ILogger[] GetCurrentLoggers() { // The accumulation in loggers is necessary because not all elements in // ht are Logger objects as there might be some ProvisionNodes // as well. System.Collections.ArrayList loggers = new System.Collections.ArrayList(m_ht.Count); // Iterate through m_ht values foreach(object node in m_ht.Values) { if (node is Logger) { loggers.Add(node); } } return (Logger[])loggers.ToArray(typeof(Logger)); } /// <summary> /// Return a new logger instance named as the first parameter using /// the default factory. /// </summary> /// <remarks> /// <para> /// Return a new logger instance named as the first parameter using /// the default factory. /// </para> /// <para> /// If a logger of that name already exists, then it will be /// returned. Otherwise, a new logger will be instantiated and /// then linked with its existing ancestors as well as children. /// </para> /// </remarks> /// <param name="name">The name of the logger to retrieve</param> /// <returns>The logger object with the name specified</returns> override public ILogger GetLogger(string name) { if (name == null) { throw new ArgumentNullException("name"); } return GetLogger(name, m_defaultFactory); } /// <summary> /// Shutting down a hierarchy will <i>safely</i> close and remove /// all appenders in all loggers including the root logger. /// </summary> /// <remarks> /// <para> /// Shutting down a hierarchy will <i>safely</i> close and remove /// all appenders in all loggers including the root logger. /// </para> /// <para> /// Some appenders need to be closed before the /// application exists. Otherwise, pending logging events might be /// lost. /// </para> /// <para> /// The <c>Shutdown</c> method is careful to close nested /// appenders before closing regular appenders. This is allows /// configurations where a regular appender is attached to a logger /// and again to a nested appender. /// </para> /// </remarks> override public void Shutdown() { LogLog.Debug(declaringType, "Shutdown called on Hierarchy ["+this.Name+"]"); // begin by closing nested appenders Root.CloseNestedAppenders(); lock(m_ht) { ILogger[] currentLoggers = this.GetCurrentLoggers(); foreach(Logger logger in currentLoggers) { logger.CloseNestedAppenders(); } // then, remove all appenders Root.RemoveAllAppenders(); foreach(Logger logger in currentLoggers) { logger.RemoveAllAppenders(); } } base.Shutdown(); } /// <summary> /// Reset all values contained in this hierarchy instance to their default. /// </summary> /// <remarks> /// <para> /// Reset all values contained in this hierarchy instance to their /// default. This removes all appenders from all loggers, sets /// the level of all non-root loggers to <c>null</c>, /// sets their additivity flag to <c>true</c> and sets the level /// of the root logger to <see cref="Level.Debug"/>. Moreover, /// message disabling is set its default "off" value. /// </para> /// <para> /// Existing loggers are not removed. They are just reset. /// </para> /// <para> /// This method should be used sparingly and with care as it will /// block all logging until it is completed. /// </para> /// </remarks> override public void ResetConfiguration() { Root.Level = LevelMap.LookupWithDefault(Level.Debug); Threshold = LevelMap.LookupWithDefault(Level.All); // the synchronization is needed to prevent hashtable surprises lock(m_ht) { Shutdown(); // nested locks are OK foreach(Logger l in this.GetCurrentLoggers()) { l.Level = null; l.Additivity = true; } } base.ResetConfiguration(); // Notify listeners OnConfigurationChanged(null); } /// <summary> /// Log the logEvent through this hierarchy. /// </summary> /// <param name="logEvent">the event to log</param> /// <remarks> /// <para> /// This method should not normally be used to log. /// The <see cref="ILog"/> interface should be used /// for routine logging. This interface can be obtained /// using the <see cref="M:Ctrip.LogManager.GetLogger(string)"/> method. /// </para> /// <para> /// The <c>logEvent</c> is delivered to the appropriate logger and /// that logger is then responsible for logging the event. /// </para> /// </remarks> override public void Log(LoggingEvent logEvent) { if (logEvent == null) { throw new ArgumentNullException("logEvent"); } this.GetLogger(logEvent.LoggerName, m_defaultFactory).Log(logEvent); } /// <summary> /// Returns all the Appenders that are currently configured /// </summary> /// <returns>An array containing all the currently configured appenders</returns> /// <remarks> /// <para> /// Returns all the <see cref="Ctrip.Log4.Appender.IAppender"/> instances that are currently configured. /// All the loggers are searched for appenders. The appenders may also be containers /// for appenders and these are also searched for additional loggers. /// </para> /// <para> /// The list returned is unordered but does not contain duplicates. /// </para> /// </remarks> override public Appender.IAppender[] GetAppenders() { System.Collections.ArrayList appenderList = new System.Collections.ArrayList(); CollectAppenders(appenderList, Root); foreach(Logger logger in GetCurrentLoggers()) { CollectAppenders(appenderList, logger); } return (Appender.IAppender[])appenderList.ToArray(typeof(Appender.IAppender)); } #endregion Override Implementation of LoggerRepositorySkeleton #region Private Static Methods /// <summary> /// Collect the appenders from an <see cref="IAppenderAttachable"/>. /// The appender may also be a container. /// </summary> /// <param name="appenderList"></param> /// <param name="appender"></param> private static void CollectAppender(System.Collections.ArrayList appenderList, Appender.IAppender appender) { if (!appenderList.Contains(appender)) { appenderList.Add(appender); IAppenderAttachable container = appender as IAppenderAttachable; if (container != null) { CollectAppenders(appenderList, container); } } } /// <summary> /// Collect the appenders from an <see cref="IAppenderAttachable"/> container /// </summary> /// <param name="appenderList"></param> /// <param name="container"></param> private static void CollectAppenders(System.Collections.ArrayList appenderList, IAppenderAttachable container) { foreach(Appender.IAppender appender in container.Appenders) { CollectAppender(appenderList, appender); } } #endregion #region Implementation of IBasicRepositoryConfigurator /// <summary> /// Initialize the Ctrip system using the specified appender /// </summary> /// <param name="appender">the appender to use to log all logging events</param> void IBasicRepositoryConfigurator.Configure(IAppender appender) { BasicRepositoryConfigure(appender); } /// <summary> /// Initialize the Ctrip system using the specified appenders /// </summary> /// <param name="appenders">the appenders to use to log all logging events</param> void IBasicRepositoryConfigurator.Configure(params IAppender[] appenders) { BasicRepositoryConfigure(appenders); } /// <summary> /// Initialize the Ctrip system using the specified appenders /// </summary> /// <param name="appenders">the appenders to use to log all logging events</param> /// <remarks> /// <para> /// This method provides the same functionality as the /// <see cref="M:IBasicRepositoryConfigurator.Configure(IAppender)"/> method implemented /// on this object, but it is protected and therefore can be called by subclasses. /// </para> /// </remarks> protected void BasicRepositoryConfigure(params IAppender[] appenders) { ArrayList configurationMessages = new ArrayList(); using (new LogLog.LogReceivedAdapter(configurationMessages)) { foreach (IAppender appender in appenders) { Root.AddAppender(appender); } } Configured = true; ConfigurationMessages = configurationMessages; // Notify listeners OnConfigurationChanged(new ConfigurationChangedEventArgs(configurationMessages)); } #endregion Implementation of IBasicRepositoryConfigurator #region Implementation of IXmlRepositoryConfigurator /// <summary> /// Initialize the Ctrip system using the specified config /// </summary> /// <param name="element">the element containing the root of the config</param> void IXmlRepositoryConfigurator.Configure(System.Xml.XmlElement element) { XmlRepositoryConfigure(element); } /// <summary> /// Initialize the Ctrip system using the specified config /// </summary> /// <param name="element">the element containing the root of the config</param> /// <remarks> /// <para> /// This method provides the same functionality as the /// <see cref="M:IBasicRepositoryConfigurator.Configure(IAppender)"/> method implemented /// on this object, but it is protected and therefore can be called by subclasses. /// </para> /// </remarks> protected void XmlRepositoryConfigure(System.Xml.XmlElement element) { ArrayList configurationMessages = new ArrayList(); using (new LogLog.LogReceivedAdapter(configurationMessages)) { XmlHierarchyConfigurator config = new XmlHierarchyConfigurator(this); config.Configure(element); } Configured = true; ConfigurationMessages = configurationMessages; // Notify listeners OnConfigurationChanged(new ConfigurationChangedEventArgs(configurationMessages)); } #endregion Implementation of IXmlRepositoryConfigurator #region Public Instance Methods /// <summary> /// Test if this hierarchy is disabled for the specified <see cref="Level"/>. /// </summary> /// <param name="level">The level to check against.</param> /// <returns> /// <c>true</c> if the repository is disabled for the level argument, <c>false</c> otherwise. /// </returns> /// <remarks> /// <para> /// If this hierarchy has not been configured then this method will /// always return <c>true</c>. /// </para> /// <para> /// This method will return <c>true</c> if this repository is /// disabled for <c>level</c> object passed as parameter and /// <c>false</c> otherwise. /// </para> /// <para> /// See also the <see cref="ILoggerRepository.Threshold"/> property. /// </para> /// </remarks> public bool IsDisabled(Level level) { // Cast level to object for performance if ((object)level == null) { throw new ArgumentNullException("level"); } if (Configured) { return Threshold > level; } else { // If not configured the hierarchy is effectively disabled return true; } } /// <summary> /// Clear all logger definitions from the internal hashtable /// </summary> /// <remarks> /// <para> /// This call will clear all logger definitions from the internal /// hashtable. Invoking this method will irrevocably mess up the /// logger hierarchy. /// </para> /// <para> /// You should <b>really</b> know what you are doing before /// invoking this method. /// </para> /// </remarks> public void Clear() { m_ht.Clear(); } /// <summary> /// Return a new logger instance named as the first parameter using /// <paramref name="factory"/>. /// </summary> /// <param name="name">The name of the logger to retrieve</param> /// <param name="factory">The factory that will make the new logger instance</param> /// <returns>The logger object with the name specified</returns> /// <remarks> /// <para> /// If a logger of that name already exists, then it will be /// returned. Otherwise, a new logger will be instantiated by the /// <paramref name="factory"/> parameter and linked with its existing /// ancestors as well as children. /// </para> /// </remarks> public Logger GetLogger(string name, ILoggerFactory factory) { if (name == null) { throw new ArgumentNullException("name"); } if (factory == null) { throw new ArgumentNullException("factory"); } LoggerKey key = new LoggerKey(name); // Synchronize to prevent write conflicts. Read conflicts (in // GetEffectiveLevel() method) are possible only if variable // assignments are non-atomic. lock(m_ht) { Logger logger = null; Object node = m_ht[key]; if (node == null) { logger = factory.CreateLogger(this, name); logger.Hierarchy = this; m_ht[key] = logger; UpdateParents(logger); OnLoggerCreationEvent(logger); return logger; } Logger nodeLogger = node as Logger; if (nodeLogger != null) { return nodeLogger; } ProvisionNode nodeProvisionNode = node as ProvisionNode; if (nodeProvisionNode != null) { logger = factory.CreateLogger(this, name); logger.Hierarchy = this; m_ht[key] = logger; UpdateChildren(nodeProvisionNode, logger); UpdateParents(logger); OnLoggerCreationEvent(logger); return logger; } // It should be impossible to arrive here but let's keep the compiler happy. return null; } } #endregion Public Instance Methods #region Protected Instance Methods /// <summary> /// Sends a logger creation event to all registered listeners /// </summary> /// <param name="logger">The newly created logger</param> /// <remarks> /// Raises the logger creation event. /// </remarks> protected virtual void OnLoggerCreationEvent(Logger logger) { LoggerCreationEventHandler handler = m_loggerCreatedEvent; if (handler != null) { handler(this, new LoggerCreationEventArgs(logger)); } } #endregion Protected Instance Methods #region Private Instance Methods /// <summary> /// Updates all the parents of the specified logger /// </summary> /// <param name="log">The logger to update the parents for</param> /// <remarks> /// <para> /// This method loops through all the <i>potential</i> parents of /// <paramref name="log"/>. There 3 possible cases: /// </para> /// <list type="number"> /// <item> /// <term>No entry for the potential parent of <paramref name="log"/> exists</term> /// <description> /// We create a ProvisionNode for this potential /// parent and insert <paramref name="log"/> in that provision node. /// </description> /// </item> /// <item> /// <term>The entry is of type Logger for the potential parent.</term> /// <description> /// The entry is <paramref name="log"/>'s nearest existing parent. We /// update <paramref name="log"/>'s parent field with this entry. We also break from /// he loop because updating our parent's parent is our parent's /// responsibility. /// </description> /// </item> /// <item> /// <term>The entry is of type ProvisionNode for this potential parent.</term> /// <description> /// We add <paramref name="log"/> to the list of children for this /// potential parent. /// </description> /// </item> /// </list> /// </remarks> private void UpdateParents(Logger log) { string name = log.Name; int length = name.Length; bool parentFound = false; // if name = "w.x.y.z", loop through "w.x.y", "w.x" and "w", but not "w.x.y.z" for(int i = name.LastIndexOf('.', length-1); i >= 0; i = name.LastIndexOf('.', i-1)) { string substr = name.Substring(0, i); LoggerKey key = new LoggerKey(substr); // simple constructor Object node = m_ht[key]; // Create a provision node for a future parent. if (node == null) { ProvisionNode pn = new ProvisionNode(log); m_ht[key] = pn; } else { Logger nodeLogger = node as Logger; if (nodeLogger != null) { parentFound = true; log.Parent = nodeLogger; break; // no need to update the ancestors of the closest ancestor } else { ProvisionNode nodeProvisionNode = node as ProvisionNode; if (nodeProvisionNode != null) { nodeProvisionNode.Add(log); } else { LogLog.Error(declaringType, "Unexpected object type ["+node.GetType()+"] in ht.", new LogException()); } } } if (i == 0) { // logger name starts with a dot // and we've hit the start break; } } // If we could not find any existing parents, then link with root. if (!parentFound) { log.Parent = this.Root; } } /// <summary> /// Replace a <see cref="ProvisionNode"/> with a <see cref="Logger"/> in the hierarchy. /// </summary> /// <param name="pn"></param> /// <param name="log"></param> /// <remarks> /// <para> /// We update the links for all the children that placed themselves /// in the provision node 'pn'. The second argument 'log' is a /// reference for the newly created Logger, parent of all the /// children in 'pn'. /// </para> /// <para> /// We loop on all the children 'c' in 'pn'. /// </para> /// <para> /// If the child 'c' has been already linked to a child of /// 'log' then there is no need to update 'c'. /// </para> /// <para> /// Otherwise, we set log's parent field to c's parent and set /// c's parent field to log. /// </para> /// </remarks> private static void UpdateChildren(ProvisionNode pn, Logger log) { for(int i = 0; i < pn.Count; i++) { Logger childLogger = (Logger)pn[i]; // Unless this child already points to a correct (lower) parent, // make log.Parent point to childLogger.Parent and childLogger.Parent to log. if (!childLogger.Parent.Name.StartsWith(log.Name)) { log.Parent = childLogger.Parent; childLogger.Parent = log; } } } /// <summary> /// Define or redefine a Level using the values in the <see cref="LevelEntry"/> argument /// </summary> /// <param name="levelEntry">the level values</param> /// <remarks> /// <para> /// Define or redefine a Level using the values in the <see cref="LevelEntry"/> argument /// </para> /// <para> /// Supports setting levels via the configuration file. /// </para> /// </remarks> internal void AddLevel(LevelEntry levelEntry) { if (levelEntry == null) throw new ArgumentNullException("levelEntry"); if (levelEntry.Name == null) throw new ArgumentNullException("levelEntry.Name"); // Lookup replacement value if (levelEntry.Value == -1) { Level previousLevel = LevelMap[levelEntry.Name]; if (previousLevel == null) { throw new InvalidOperationException("Cannot redefine level ["+levelEntry.Name+"] because it is not defined in the LevelMap. To define the level supply the level value."); } levelEntry.Value = previousLevel.Value; } LevelMap.Add(levelEntry.Name, levelEntry.Value, levelEntry.DisplayName); } /// <summary> /// A class to hold the value, name and display name for a level /// </summary> /// <remarks> /// <para> /// A class to hold the value, name and display name for a level /// </para> /// </remarks> internal class LevelEntry { private int m_levelValue = -1; private string m_levelName = null; private string m_levelDisplayName = null; /// <summary> /// Value of the level /// </summary> /// <remarks> /// <para> /// If the value is not set (defaults to -1) the value will be looked /// up for the current level with the same name. /// </para> /// </remarks> public int Value { get { return m_levelValue; } set { m_levelValue = value; } } /// <summary> /// Name of the level /// </summary> /// <value> /// The name of the level /// </value> /// <remarks> /// <para> /// The name of the level. /// </para> /// </remarks> public string Name { get { return m_levelName; } set { m_levelName = value; } } /// <summary> /// Display name for the level /// </summary> /// <value> /// The display name of the level /// </value> /// <remarks> /// <para> /// The display name of the level. /// </para> /// </remarks> public string DisplayName { get { return m_levelDisplayName; } set { m_levelDisplayName = value; } } /// <summary> /// Override <c>Object.ToString</c> to return sensible debug info /// </summary> /// <returns>string info about this object</returns> public override string ToString() { return "LevelEntry(Value="+m_levelValue+", Name="+m_levelName+", DisplayName="+m_levelDisplayName+")"; } } /// <summary> /// Set a Property using the values in the <see cref="LevelEntry"/> argument /// </summary> /// <param name="propertyEntry">the property value</param> /// <remarks> /// <para> /// Set a Property using the values in the <see cref="LevelEntry"/> argument. /// </para> /// <para> /// Supports setting property values via the configuration file. /// </para> /// </remarks> internal void AddProperty(PropertyEntry propertyEntry) { if (propertyEntry == null) throw new ArgumentNullException("propertyEntry"); if (propertyEntry.Key == null) throw new ArgumentNullException("propertyEntry.Key"); Properties[propertyEntry.Key] = propertyEntry.Value; } #endregion Private Instance Methods #region Private Instance Fields private ILoggerFactory m_defaultFactory; private System.Collections.Hashtable m_ht; private Logger m_root; private bool m_emittedNoAppenderWarning = false; private event LoggerCreationEventHandler m_loggerCreatedEvent; #endregion Private Instance Fields #region Private Static Fields /// <summary> /// The fully qualified type of the Hierarchy class. /// </summary> /// <remarks> /// Used by the internal logger to record the Type of the /// log message. /// </remarks> private readonly static Type declaringType = typeof(Hierarchy); #endregion Private Static Fields } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // THIS FILE IS NOT INTENDED TO BE EDITED. // // This file can be updated in-place using the Package Manager Console. To check for updates, run the following command: // // PM> Get-Package -Updates using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using Microsoft.CSharp.RuntimeBinder; namespace Pocket { /// <summary> /// Supports chaining of expressions when intermediate values may be null, to support a fluent API style using common .NET types. /// </summary> #if !RecipesProject [System.Diagnostics.DebuggerStepThrough] [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] #endif internal static class MaybeExtensions { /// <summary> /// Specifies a function that will be evaluated if the source <see cref="Pocket.Maybe{T}" /> has no value. /// </summary> /// <typeparam name="T"> /// The type held by the <see cref="Pocket.Maybe{T}" />. /// </typeparam> /// <param name="maybe">The source maybe.</param> /// <param name="otherValue">The value to be returned if the <see cref="Pocket.Maybe{T}" /> has no value.</param> /// <returns> /// The value of the Maybe if it has a value; otherwise, the value returned by <paramref name="otherValue" />. /// </returns> public static T Else<T>(this Maybe<T> maybe, Func<T> otherValue) { if (maybe.HasValue) { return maybe.Value; } return otherValue(); } /// <summary> /// Specifies a function that will be evaluated if the source <see cref="Pocket.Maybe{T}" /> has no value. /// </summary> /// <typeparam name="T"> /// The type held by the <see cref="Pocket.Maybe{T}" />. /// </typeparam> /// <param name="maybe">The source maybe.</param> /// <param name="other">The value to be returned if the <see cref="Pocket.Maybe{T}" /> has no value.</param> /// <returns> /// The value of the Maybe if it has a value; otherwise, the value returned by <paramref name="other" />. /// </returns> public static Maybe<T> Else<T>(this Maybe<T> maybe, Func<Maybe<T>> other) { return maybe.HasValue ? maybe : other(); } /// <summary> /// Specifies a function that will be evaluated if the source <see cref="Pocket.Maybe{T}" /> has no value. /// </summary> /// <typeparam name="T"> /// The type held by the <see cref="Pocket.Maybe{T}" />. /// </typeparam> /// <param name="maybe">The source maybe.</param> /// <param name="otherValue">The value to be returned if the <see cref="Pocket.Maybe{T}" /> has no value.</param> /// <returns> /// The value of the Maybe if it has a value; otherwise, the value returned by <paramref name="otherValue" />. /// </returns> public static T Else<T>(this Maybe<Maybe<T>> maybe, Func<T> otherValue) { if (maybe.HasValue) { return maybe.Value.Else(otherValue); } return otherValue(); } /// <summary> /// Specifies a function that will be evaluated if the source <see cref="Pocket.Maybe{T}" /> has no value. /// </summary> /// <typeparam name="T"> /// The type held by the <see cref="Pocket.Maybe{T}" />. /// </typeparam> /// <param name="maybe">The source maybe.</param> /// <param name="otherValue">The value to be returned if the <see cref="Pocket.Maybe{T}" /> has no value.</param> /// <returns> /// The value of the Maybe if it has a value; otherwise, the value returned by <paramref name="otherValue" />. /// </returns> public static T Else<T>(this Maybe<Maybe<Maybe<T>>> maybe, Func<T> otherValue) { if (maybe.HasValue) { return maybe.Value.Else(otherValue); } return otherValue(); } /// <summary> /// Specifies a function that will be evaluated if the source <see cref="Pocket.Maybe{T}" /> has no value. /// </summary> /// <typeparam name="T"> /// The type held by the <see cref="Pocket.Maybe{T}" />. /// </typeparam> /// <param name="maybe">The source maybe.</param> /// <param name="otherValue">The value to be returned if the <see cref="Pocket.Maybe{T}" /> has no value.</param> /// <returns> /// The value of the Maybe if it has a value; otherwise, the value returned by <paramref name="otherValue" />. /// </returns> public static T Else<T>(this Maybe<Maybe<Maybe<Maybe<T>>>> maybe, Func<T> otherValue) { if (maybe.HasValue) { return maybe.Value.Else(otherValue); } return otherValue(); } /// <summary> /// Returns the default value for <typeparamref name="T" /> if the <see cref="Pocket.Maybe{T}" /> has no value. /// </summary> /// <typeparam name="T"> /// The type held by the <see cref="Pocket.Maybe{T}" />. /// </typeparam> public static T ElseDefault<T>(this Maybe<T> maybe) { return maybe.Else(() => default(T)); } /// <summary> /// Returns the default value for <typeparamref name="T" /> if the <see cref="Pocket.Maybe{T}" /> has no value. /// </summary> /// <typeparam name="T"> /// The type held by the <see cref="Pocket.Maybe{T}" />. /// </typeparam> public static T ElseDefault<T>(this Maybe<Maybe<T>> maybe) { return maybe.Else(() => default(T)); } /// <summary> /// Returns the default value for <typeparamref name="T" /> if the <see cref="Pocket.Maybe{T}" /> has no value. /// </summary> /// <typeparam name="T"> /// The type held by the <see cref="Pocket.Maybe{T}" />. /// </typeparam> public static T ElseDefault<T>(this Maybe<Maybe<Maybe<T>>> maybe) { return maybe.Else(() => default(T)); } /// <summary> /// Returns the default value for <typeparamref name="T" /> if the <see cref="Pocket.Maybe{T}" /> has no value. /// </summary> /// <typeparam name="T"> /// The type held by the <see cref="Pocket.Maybe{T}" />. /// </typeparam> public static T ElseDefault<T>(this Maybe<Maybe<Maybe<Maybe<T>>>> maybe) { return maybe.Else(() => default(T)); } /// <summary> /// Returns null if the source has no value. /// </summary> /// <typeparam name="T">The type held by the <see cref="Pocket.Maybe{T}" />.</typeparam> public static T? ElseNull<T>(this Maybe<T> maybe) where T : struct { if (maybe.HasValue) { return maybe.Value; } return null; } /// <summary> /// Performs an action if the <see cref="Pocket.Maybe{T}" /> has no value. /// </summary> /// <typeparam name="T"> /// The type held by the <see cref="Pocket.Maybe{T}" />. /// </typeparam> public static void ElseDo<T>(this Maybe<T> maybe, Action action) { if (action == null) { throw new ArgumentNullException("action"); } if (!maybe.HasValue) { action(); } } /// <summary> /// Throws an exception if the <see cref="Pocket.Maybe{T}" /> has no value. /// </summary> /// <typeparam name="T">The type held by the <see cref="Pocket.Maybe{T}" />.</typeparam> /// <param name="maybe">The maybe.</param> /// <param name="exception">A function that returns the exception to be thrown.</param> /// <returns></returns> public static T ElseThrow<T>(this Maybe<T> maybe, Func<Exception> exception) { if (maybe.HasValue) { return maybe.Value; } throw exception(); } /// <summary> /// If the dictionary contains a value for a specified key, executes an action passing the corresponding value. /// </summary> /// <typeparam name="TKey"> The type of the key. </typeparam> /// <typeparam name="TValue"> The type of the value. </typeparam> /// <param name="dictionary"> The dictionary. </param> /// <param name="key"> The key. </param> /// <exception cref="ArgumentNullException">dictionary</exception> public static Maybe<TValue> IfContains<TKey, TValue>( this IDictionary<TKey, TValue> dictionary, TKey key) { TValue value; if (dictionary != null && dictionary.TryGetValue(key, out value)) { return Maybe<TValue>.Yes(value); } return Maybe<TValue>.No(); } /// <summary> /// Allows two maybes to be combined so that the resulting maybe has its value transformed by the second if and only if the first has a value. /// </summary> /// <typeparam name="T1">The type of the <see cref="Maybe{T}" />.</typeparam> /// <param name="first">The first maybe.</param> /// <returns></returns> public static T1 And<T1>( this Maybe<T1> first) { if (first.HasValue) { return first.Value; } return default(T1); } /// <summary> /// Attempts to retrieve a value dynamically. /// </summary> /// <typeparam name="T">The type of the value expected to be returned.</typeparam> /// <param name="source">The source object.</param> /// <param name="getValue">A delegate that attempts to return a value via a dynamic invocation on the source object.</param> /// <remarks>This method will not cast the result value to <typeparamref name="T" />. If the returned value is not of this type, then a negative <see cref="Pocket.Maybe{T}" /> will be returned.</remarks> public static Maybe<T> IfHas<T>( this object source, Func<dynamic, T> getValue) { try { var value = getValue(source); return value.IfTypeIs<T>(); } catch (RuntimeBinderException) { return Maybe<T>.No(); } } /// <summary> /// Creates a <see cref="Pocket.Maybe{T}" /> that has a value if <paramref name="source" /> is not null. /// </summary> /// <typeparam name="T">The type of the instance wrapped by the <see cref="Pocket.Maybe{T}" />.</typeparam> /// <param name="source">The source instance, which may be null.</param> public static Maybe<T> IfNotNull<T>(this T source) where T : class { if (source != null) { return Maybe<T>.Yes(source); } return Maybe<T>.No(); } /// <summary> /// Creates a <see cref="Pocket.Maybe{T}" /> that has a value if <paramref name="source" /> has a value. /// </summary> public static Maybe<T> IfNotNull<T>(this Maybe<T> source) where T : class { if (source.HasValue && source.Value != null) { return source; } return Maybe<T>.No(); } /// <summary> /// Creates a <see cref="Pocket.Maybe{T}" /> that has a value if <paramref name="source" /> is not null. /// </summary> /// <typeparam name="T">The type of the instance wrapped by the <see cref="Pocket.Maybe{T}" />.</typeparam> /// <param name="source">The source instance, which may be null.</param> public static Maybe<T> IfNotNull<T>(this T? source) where T : struct { if (source.HasValue) { return Maybe<T>.Yes(source.Value); } return Maybe<T>.No(); } /// <summary> /// Creates a <see cref="Pocket.Maybe{T}" /> that has a value if <paramref name="source" /> is not null, empty, or entirely whitespace. /// </summary> /// <param name="source">The string.</param> public static Maybe<string> IfNotNullOrEmptyOrWhitespace(this string source) { if (!string.IsNullOrWhiteSpace(source)) { return Maybe<string>.Yes(source); } return Maybe<string>.No(); } /// <summary> /// Creates a <see cref="Pocket.Maybe{T}" /> that has a value if <paramref name="source" /> is assignable to type <typeparamref name="T" />. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <returns></returns> public static Maybe<T> IfTypeIs<T>( this object source) { if (source is T) { return Maybe<T>.Yes((T) source); } return Maybe<T>.No(); } /// <summary> /// Returns either the <paramref name="source" /> or, if it is null, an empty <see cref="IEnumerable{T}" /> sequence. /// </summary> /// <typeparam name="T"> The type of the objects in the sequence. </typeparam> /// <param name="source"> The source sequence. </param> /// <returns> The source sequence or, if it is null, an empty sequence. </returns> public static IEnumerable<T> OrEmpty<T>(this IEnumerable<T> source) { return source ?? Enumerable.Empty<T>(); } /// <summary> /// Attempts to get the value of a Try* method with an out parameter, for example <see cref="Dictionary{TKey,TValue}.TryGetValue" /> or <see cref="ConcurrentQueue{T}.TryDequeue" />. /// </summary> /// <typeparam name="T">The type of the source object.</typeparam> /// <typeparam name="TOut">The type the out parameter.</typeparam> /// <param name="source">The source object exposing the Try* method.</param> /// <param name="tryTryGetValue">A delegate to call the Try* method.</param> /// <returns></returns> public static Maybe<TOut> Out<T, TOut>(this T source, TryGetOutParameter<T, TOut> tryTryGetValue) { TOut result; if (tryTryGetValue(source, out result)) { return Maybe<TOut>.Yes(result); } return Maybe<TOut>.No(); } /// <summary> /// Specifies the result of a <see cref="Pocket.Maybe{T}" /> if the <see cref="Pocket.Maybe{T}" /> has a value. /// </summary> /// <typeparam name="TIn">The type of source object.</typeparam> /// <typeparam name="TOut">The type of result.</typeparam> /// <param name="maybe">The maybe.</param> /// <param name="getValue">A delegate to get the value from the source object.</param> public static Maybe<TOut> Then<TIn, TOut>( this Maybe<TIn> maybe, Func<TIn, TOut> getValue) { TOut value; return maybe.HasValue && (value = getValue(maybe.Value)) != null ? Maybe<TOut>.Yes(value) : Maybe<TOut>.No(); } /// <summary> /// Performs an action if the <see cref="Pocket.Maybe{T}" /> has a value. /// </summary> /// <typeparam name="T"> /// The type held by the <see cref="Pocket.Maybe{T}" />. /// </typeparam> public static Maybe<Unit> ThenDo<T>(this Maybe<T> maybe, Action<T> action) { if (action == null) { throw new ArgumentNullException("action"); } if (maybe.HasValue) { action(maybe.Value); return Maybe<Unit>.Yes(Unit.Default); } return Maybe<Unit>.No(); } /// <summary> /// Tries to call the specified method and catches exceptions if they occur. /// </summary> /// <typeparam name="TIn">The type of source object.</typeparam> /// <typeparam name="TOut">The type of result.</typeparam> /// <param name="source">The source object.</param> /// <param name="getValue">A delegate to get the value from the source object.</param> /// <param name="ignore">A predicate to determine whether the exception should be ignored. If this is not specified, all exceptions are ignored. If it is specified and an exception is thrown that matches the predicate, the exception is ignored and a <see cref="Pocket.Maybe{TOut}" /> having no value is returned. If it is specified and an exception is thrown that does not match the predicate, the exception is allowed to propagate.</param> /// <returns></returns> public static Maybe<TOut> Try<TIn, TOut>( this TIn source, Func<TIn, TOut> getValue, Func<Exception, bool> ignore) { if (getValue == null) { throw new ArgumentNullException("getValue"); } if (ignore == null) { throw new ArgumentNullException("ignore"); } try { return Maybe<TOut>.Yes(getValue(source)); } catch (Exception ex) { if (!ignore(ex)) { throw; } } return Maybe<TOut>.No(); } } /// <summary> /// Represents an object that may or may not contain a value, allowing optional chained results to be specified for both possibilities. /// </summary> /// <typeparam name="T">The type of the possible value.</typeparam> #if !RecipesProject [System.Diagnostics.DebuggerStepThrough] [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] #endif internal struct Maybe<T> { private static readonly Maybe<T> no = new Maybe<T> { HasValue = false }; private T value; /// <summary> /// Returns a <see cref="Pocket.Maybe{T}" /> that contains a value. /// </summary> /// <param name="value">The value.</param> public static Maybe<T> Yes(T value) { return new Maybe<T> { HasValue = true, value = value }; } /// <summary> /// Returns a <see cref="Pocket.Maybe{T}" /> that does not contain a value. /// </summary> public static Maybe<T> No() { return no; } /// <summary> /// Gets the value contained by the <see cref="Pocket.Maybe{T}" />. /// </summary> /// <value> /// The value. /// </value> public T Value { get { if (!HasValue) { throw new InvalidOperationException("The Maybe does not contain a value."); } return value; } } /// <summary> /// Gets a value indicating whether this instance has a value. /// </summary> /// <value> /// <c>true</c> if this instance has value; otherwise, <c>false</c>. /// </value> public bool HasValue { get; private set; } } /// <summary> /// A delegate used to return an out parameter from a Try* method that indicates success via a boolean return value. /// </summary> /// <typeparam name="T">The type of the source object.</typeparam> /// <typeparam name="TOut">The type of the out parameter.</typeparam> /// <param name="source">The source.</param> /// <param name="outValue">The out parameter's value.</param> /// <returns>true if the out parameter was set; otherwise, false.</returns> internal delegate bool TryGetOutParameter<in T, TOut>(T source, out TOut outValue); /// <summary> /// A type representing a void return type. /// </summary> #if !RecipesProject [System.Diagnostics.DebuggerStepThrough] [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] #endif internal struct Unit { /// <summary> /// The default instance. /// </summary> public static readonly Unit Default = new Unit(); } }
// Copyright 2013 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System.Globalization; using System.Text; using NodaTime.Annotations; using NodaTime.Globalization; using NodaTime.Text.Patterns; using NodaTime.TimeZones; using NodaTime.Utility; using JetBrains.Annotations; namespace NodaTime.Text { /// <summary> /// Represents a pattern for parsing and formatting <see cref="ZonedDateTime"/> values. /// </summary> /// <threadsafety> /// When used with a read-only <see cref="CultureInfo" />, this type is immutable and instances /// may be shared freely between threads. We recommend only using read-only cultures for patterns, although this is /// not currently enforced. /// </threadsafety> [Immutable] // Well, assuming an immutable culture... public sealed class ZonedDateTimePattern : IPattern<ZonedDateTime> { internal static ZonedDateTime DefaultTemplateValue { get; } = new LocalDateTime(2000, 1, 1, 0, 0).InUtc(); /// <summary> /// Gets an zoned local date/time pattern based on ISO-8601 (down to the second) including offset from UTC and zone ID. /// It corresponds to a custom pattern of "uuuu'-'MM'-'dd'T'HH':'mm':'ss z '('o&lt;g&gt;')'" and is available /// as the 'G' standard pattern. /// </summary> /// <remarks> /// The calendar system is not formatted as part of this pattern, and it cannot be used for parsing as no time zone /// provider is included. Call <see cref="WithZoneProvider"/> on the value of this property to obtain a /// pattern which can be used for parsing. /// </remarks> /// <value>An zoned local date/time pattern based on ISO-8601 (down to the second) including offset from UTC and zone ID.</value> public static ZonedDateTimePattern GeneralFormatOnlyIsoPattern => Patterns.GeneralFormatOnlyPatternImpl; // TODO(2.0): Add tests for this and other patterns from properties. /// <summary> /// Returns an invariant zoned date/time pattern based on ISO-8601 (down to the nanosecond) including offset from UTC and zone ID. /// It corresponds to a custom pattern of "uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFF z '('o&lt;g&gt;')'" and is available /// as the 'F' standard pattern. /// </summary> /// <remarks> /// The calendar system is not formatted as part of this pattern, and it cannot be used for parsing as no time zone /// provider is included. Call <see cref="WithZoneProvider"/> on the value of this property to obtain a /// pattern which can be used for parsing. /// </remarks> /// <value>An invariant zoned date/time pattern based on ISO-8601 (down to the nanosecond) including offset from UTC and zone ID.</value> public static ZonedDateTimePattern ExtendedFormatOnlyIsoPattern => Patterns.ExtendedFormatOnlyPatternImpl; private readonly IPattern<ZonedDateTime> pattern; /// <summary> /// Class whose existence is solely to avoid type initialization order issues, most of which stem /// from needing NodaFormatInfo.InvariantInfo... /// </summary> internal static class Patterns { internal static readonly ZonedDateTimePattern GeneralFormatOnlyPatternImpl = CreateWithInvariantCulture("uuuu'-'MM'-'dd'T'HH':'mm':'ss z '('o<g>')'", null); internal static readonly ZonedDateTimePattern ExtendedFormatOnlyPatternImpl = CreateWithInvariantCulture("uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFF z '('o<g>')'", null); internal static readonly PatternBclSupport<ZonedDateTime> BclSupport = new PatternBclSupport<ZonedDateTime>("G", fi => fi.ZonedDateTimePatternParser); } /// <summary> /// Gets the pattern text for this pattern, as supplied on creation. /// </summary> /// <value>The pattern text for this pattern, as supplied on creation.</value> public string PatternText { get; } /// <summary> /// Gets the localization information used in this pattern. /// </summary> internal NodaFormatInfo FormatInfo { get; } /// <summary> /// Gets the value used as a template for parsing: any field values unspecified /// in the pattern are taken from the template. /// </summary> /// <value>The value used as a template for parsing.</value> public ZonedDateTime TemplateValue { get; } /// <summary> /// Gets the resolver which is used to map local date/times to zoned date/times, /// handling skipped and ambiguous times appropriately (where the offset isn't specified in the pattern). /// </summary> /// <value>The resolver which is used to map local date/times to zoned date/times.</value> public ZoneLocalMappingResolver Resolver { get; } /// <summary> /// Gets the provider which is used to look up time zones when parsing a pattern /// which contains a time zone identifier. This may be null, in which case the pattern can /// only be used for formatting (not parsing). /// </summary> /// <value>The provider which is used to look up time zones when parsing a pattern /// which contains a time zone identifier.</value> public IDateTimeZoneProvider ZoneProvider { get; } private ZonedDateTimePattern(string patternText, NodaFormatInfo formatInfo, ZonedDateTime templateValue, ZoneLocalMappingResolver resolver, IDateTimeZoneProvider zoneProvider, IPattern<ZonedDateTime> pattern) { this.PatternText = patternText; this.FormatInfo = formatInfo; this.TemplateValue = templateValue; this.Resolver = resolver; this.ZoneProvider = zoneProvider; this.pattern = pattern; } /// <summary> /// Parses the given text value according to the rules of this pattern. /// </summary> /// <remarks> /// This method never throws an exception (barring a bug in Noda Time itself). Even errors such as /// the argument being null are wrapped in a parse result. /// </remarks> /// <param name="text">The text value to parse.</param> /// <returns>The result of parsing, which may be successful or unsuccessful.</returns> public ParseResult<ZonedDateTime> Parse(string text) => pattern.Parse(text); /// <summary> /// Formats the given zoned date/time as text according to the rules of this pattern. /// </summary> /// <param name="value">The zoned date/time to format.</param> /// <returns>The zoned date/time formatted according to this pattern.</returns> public string Format(ZonedDateTime value) => pattern.Format(value); /// <summary> /// Formats the given value as text according to the rules of this pattern, /// appending to the given <see cref="StringBuilder"/>. /// </summary> /// <param name="value">The value to format.</param> /// <param name="builder">The <c>StringBuilder</c> to append to.</param> /// <returns>The builder passed in as <paramref name="builder"/>.</returns> public StringBuilder AppendFormat(ZonedDateTime value, [NotNull] StringBuilder builder) => pattern.AppendFormat(value, builder); /// <summary> /// Creates a pattern for the given pattern text, format info, template value, mapping resolver and time zone provider. /// </summary> /// <param name="patternText">Pattern text to create the pattern for</param> /// <param name="formatInfo">The format info to use in the pattern</param> /// <param name="templateValue">Template value to use for unspecified fields</param> /// <param name="resolver">Resolver to apply when mapping local date/time values into the zone.</param> /// <param name="zoneProvider">Time zone provider, used when parsing text which contains a time zone identifier.</param> /// <returns>A pattern for parsing and formatting zoned date/times.</returns> /// <exception cref="InvalidPatternException">The pattern text was invalid.</exception> private static ZonedDateTimePattern Create([NotNull] string patternText, [NotNull] NodaFormatInfo formatInfo, [NotNull] ZoneLocalMappingResolver resolver, IDateTimeZoneProvider zoneProvider, ZonedDateTime templateValue) { Preconditions.CheckNotNull(patternText, nameof(patternText)); Preconditions.CheckNotNull(formatInfo, nameof(formatInfo)); Preconditions.CheckNotNull(resolver, nameof(resolver)); var pattern = new ZonedDateTimePatternParser(templateValue, resolver, zoneProvider).ParsePattern(patternText, formatInfo); return new ZonedDateTimePattern(patternText, formatInfo, templateValue, resolver, zoneProvider, pattern); } /// <summary> /// Creates a pattern for the given pattern text, culture, resolver, time zone provider, and template value. /// </summary> /// <remarks> /// See the user guide for the available pattern text options. /// If <paramref name="zoneProvider"/> is null, the resulting pattern can be used for formatting /// but not parsing. /// </remarks> /// <param name="patternText">Pattern text to create the pattern for</param> /// <param name="cultureInfo">The culture to use in the pattern</param> /// <param name="resolver">Resolver to apply when mapping local date/time values into the zone.</param> /// <param name="zoneProvider">Time zone provider, used when parsing text which contains a time zone identifier.</param> /// <param name="templateValue">Template value to use for unspecified fields</param> /// <returns>A pattern for parsing and formatting zoned date/times.</returns> /// <exception cref="InvalidPatternException">The pattern text was invalid.</exception> public static ZonedDateTimePattern Create([NotNull] string patternText, [NotNull] CultureInfo cultureInfo, [NotNull] ZoneLocalMappingResolver resolver, IDateTimeZoneProvider zoneProvider, ZonedDateTime templateValue) => Create(patternText, NodaFormatInfo.GetFormatInfo(cultureInfo), resolver, zoneProvider, templateValue); /// <summary> /// Creates a pattern for the given pattern text and time zone provider, using a strict resolver, the invariant /// culture, and a default template value of midnight January 1st 2000 UTC. /// </summary> /// <remarks> /// The resolver is only used if the pattern text doesn't include an offset. /// If <paramref name="zoneProvider"/> is null, the resulting pattern can be used for formatting /// but not parsing. /// </remarks> /// <param name="patternText">Pattern text to create the pattern for</param> /// <param name="zoneProvider">Time zone provider, used when parsing text which contains a time zone identifier.</param> /// <returns>A pattern for parsing and formatting zoned date/times.</returns> public static ZonedDateTimePattern CreateWithInvariantCulture([NotNull] string patternText, IDateTimeZoneProvider zoneProvider) => Create(patternText, NodaFormatInfo.InvariantInfo, Resolvers.StrictResolver, zoneProvider, DefaultTemplateValue); /// <summary> /// Creates a pattern for the given pattern text and time zone provider, using a strict resolver, the current /// culture, and a default template value of midnight January 1st 2000 UTC. /// </summary> /// <remarks> /// The resolver is only used if the pattern text doesn't include an offset. /// If <paramref name="zoneProvider"/> is null, the resulting pattern can be used for formatting /// but not parsing. Note that the current culture is captured at the time this method is called /// - it is not captured at the point of parsing or formatting values. /// </remarks> /// <param name="patternText">Pattern text to create the pattern for</param> /// <param name="zoneProvider">Time zone provider, used when parsing text which contains a time zone identifier.</param> /// <returns>A pattern for parsing and formatting zoned date/times.</returns> public static ZonedDateTimePattern CreateWithCurrentCulture([NotNull] string patternText, IDateTimeZoneProvider zoneProvider) => Create(patternText, NodaFormatInfo.CurrentInfo, Resolvers.StrictResolver, zoneProvider, DefaultTemplateValue); /// <summary> /// Creates a pattern for the same original localization information as this pattern, but with the specified /// pattern text. /// </summary> /// <param name="patternText">The pattern text to use in the new pattern.</param> /// <returns>A new pattern with the given pattern text.</returns> public ZonedDateTimePattern WithPatternText([NotNull] string patternText) => Create(patternText, FormatInfo, Resolver, ZoneProvider, TemplateValue); /// <summary> /// Creates a pattern for the same original pattern text as this pattern, but with the specified /// localization information. /// </summary> /// <param name="formatInfo">The localization information to use in the new pattern.</param> /// <returns>A new pattern with the given localization information.</returns> private ZonedDateTimePattern WithFormatInfo([NotNull] NodaFormatInfo formatInfo) => Create(PatternText, formatInfo, Resolver, ZoneProvider, TemplateValue); /// <summary> /// Creates a pattern for the same original pattern text as this pattern, but with the specified /// culture. /// </summary> /// <param name="cultureInfo">The culture to use in the new pattern.</param> /// <returns>A new pattern with the given culture.</returns> public ZonedDateTimePattern WithCulture([NotNull] CultureInfo cultureInfo) => WithFormatInfo(NodaFormatInfo.GetFormatInfo(cultureInfo)); /// <summary> /// Creates a pattern for the same original pattern text as this pattern, but with the specified /// resolver. /// </summary> /// <param name="resolver">The new local mapping resolver to use.</param> /// <returns>A new pattern with the given resolver.</returns> public ZonedDateTimePattern WithResolver([NotNull] ZoneLocalMappingResolver resolver) => Resolver == resolver ? this : Create(PatternText, FormatInfo, resolver, ZoneProvider, TemplateValue); /// <summary> /// Creates a pattern for the same original pattern text as this pattern, but with the specified /// time zone provider. /// </summary> /// <remarks> /// If <paramref name="newZoneProvider"/> is null, the resulting pattern can be used for formatting /// but not parsing. /// </remarks> /// <param name="newZoneProvider">The new time zone provider to use.</param> /// <returns>A new pattern with the given time zone provider.</returns> public ZonedDateTimePattern WithZoneProvider(IDateTimeZoneProvider newZoneProvider) => newZoneProvider == ZoneProvider ? this : Create(PatternText, FormatInfo, Resolver, newZoneProvider, TemplateValue); /// <summary> /// Creates a pattern like this one, but with the specified template value. /// </summary> /// <param name="newTemplateValue">The template value for the new pattern, used to fill in unspecified fields.</param> /// <returns>A new pattern with the given template value.</returns> public ZonedDateTimePattern WithTemplateValue(ZonedDateTime newTemplateValue) => newTemplateValue == TemplateValue ? this : Create(PatternText, FormatInfo, Resolver, ZoneProvider, newTemplateValue); /// <summary> /// Creates a pattern like this one, but with the template value modified to use /// the specified calendar system. /// </summary> /// <remarks> /// <para> /// Care should be taken in two (relatively rare) scenarios. Although the default template value /// is supported by all Noda Time calendar systems, if a pattern is created with a different /// template value and then this method is called with a calendar system which doesn't support that /// date, an exception will be thrown. Additionally, if the pattern only specifies some date fields, /// it's possible that the new template value will not be suitable for all values. /// </para> /// </remarks> /// <param name="calendar">The calendar system to convert the template value into.</param> /// <returns>A new pattern with a template value in the specified calendar system.</returns> public ZonedDateTimePattern WithCalendar([NotNull] CalendarSystem calendar) => WithTemplateValue(TemplateValue.WithCalendar(calendar)); } }
// =========================================================== // Copyright (C) 2014-2015 Kendar.org // // 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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS // BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF // OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // =========================================================== using System; using System.Collections.Generic; using System.Web; using Node.Cs.Lib.Exceptions; using Node.Cs.Lib.Utils; using System.Text; namespace Node.Cs.Lib.Routing { //TODO: This must be optimized grouping definitions public class RoutingService : IRoutingService { public List<RouteDefinition> _routeDefinitions; private readonly List<string> _staticRoutes; public RoutingService() { _staticRoutes = new List<string>(); _routeDefinitions = new List<RouteDefinition>(); } public void AddStaticRoute(string route) { if (!route.StartsWith("~/")) { throw new NodeCsException("Invalid route '{0}' not starting with ~", route); } route = route.TrimStart('~'); if (route.StartsWith("/")) { route = route.TrimStart('/'); } _staticRoutes.Add(route.ToLowerInvariant()); } public RouteInstance Resolve(string route, HttpContextBase context) { if (route.StartsWith("~/")) { route = route.TrimStart('~'); } if (route.StartsWith("/")) { route = route.TrimStart('/'); } foreach (var staticRoute in _staticRoutes) { if (route.StartsWith(staticRoute, StringComparison.OrdinalIgnoreCase)) { return new RouteInstance(true); } } var splitted = route.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); foreach (var routeDefinition in _routeDefinitions) { var routeInstance = IsValid(splitted, routeDefinition); if (routeInstance != null) { return routeInstance; } } return null; } private RouteInstance IsValid(string[] route, RouteDefinition routeDefinition) { if (route.Length > routeDefinition.Url.Count) return null; var routeInstance = new RouteInstance(); var index = -1; while (index < (route.Length - 1)) { index++; var routeValue = route[index]; var block = routeDefinition.Url[index]; if (block.IsParameter) { routeInstance.Parameters.Add(block.Name, routeValue); } else { if (string.Compare(routeValue, block.Name, StringComparison.OrdinalIgnoreCase) != 0) return null; } } while (index < (routeDefinition.Url.Count - 1)) { index++; var block = routeDefinition.Url[index]; if (block.IsParameter) { if (routeDefinition.Parameters.ContainsKey(block.Name)) { var parameter = routeDefinition.Parameters[block.Name]; if (parameter.Optional) { if (parameter.Value != null && parameter.Value.GetType() != typeof(RoutingParameter)) { routeInstance.Parameters.Add(block.Name, parameter.Value); } } else if (parameter.Value != null) { routeInstance.Parameters.Add(block.Name, parameter.Value); } else { return null; } } else { return null; } } else { return null; } } foreach (var param in routeDefinition.Parameters) { if (!routeInstance.Parameters.ContainsKey(param.Key)) { var paramReal = param.Value; if (paramReal.Value != null && paramReal.Value.GetType() != typeof(RoutingParameter)) { routeInstance.Parameters.Add(param.Key, paramReal.Value); } } } return routeInstance; } private void CheckForConflicting(RouteDefinition routeDefinition) { } public void AddRoute(string route, dynamic parameters = null) { if (!route.StartsWith("~/")) { throw new NodeCsException("Invalid route '{0}' not starting with ~", route); } route = route.TrimStart('~'); if (route.StartsWith("/")) { route = route.TrimStart('/'); } var routeDefinition = new RouteDefinition(route, NodeCsAssembliesManager.ObjectToDictionary(parameters)); CheckForConflicting(routeDefinition); _routeDefinitions.Add(routeDefinition); } class MatchingRoute { public int Weight; public RouteDefinition Definition; public string Route; } public string ResolveFromParams(Dictionary<string, object> pars) { var mr = new List<MatchingRoute>(); var parKeys = new List<string>(pars.Keys); for (int i = 0; i < _routeDefinitions.Count; i++) { var routeDefinition = _routeDefinitions[i]; var weigth = IsMatching(routeDefinition, pars, parKeys); mr.Add(new MatchingRoute { Definition = routeDefinition, Weight = weigth }); } if (mr.Count == 0) return null; var max = int.MinValue; var maxRoute = -1; var hashRoute = new HashSet<string>(); var routeSplitted = new StringBuilder(); var routeMissing = new StringBuilder(); for (int index = 0; index < mr.Count; index++) { var match = mr[index]; if (match.Weight > max) { var route = CreateRoute(match, pars, parKeys, hashRoute, routeSplitted, routeMissing); if (route != null) { match.Route = route; maxRoute = index; max = match.Weight; } } } if (maxRoute != -1) { return mr[maxRoute].Route; } return null; } private int IsMatching(RouteDefinition routeDefinition, Dictionary<string, object> pars, List<string> keys) { int weight = 0; for (int i = 0; i < keys.Count; i++) { var key = keys[i]; if (!pars.ContainsKey(key)) { var pardef = routeDefinition.Parameters[key]; if (!pardef.Optional) { return 0; } if (pardef.Value != null) { weight++; } } else { weight++; } } return weight; } private string CreateRoute(MatchingRoute match, Dictionary<string, object> pars, List<string> parsKeys, HashSet<string> routeParamsUsed, StringBuilder routeSplitted, StringBuilder routeMissing) { routeMissing.Clear(); routeSplitted.Clear(); routeParamsUsed.Clear(); routeSplitted.Clear(); var routeDefinition = match.Definition; for (int i = 0; i < routeDefinition.Url.Count; i++) { var par = routeDefinition.Url[i]; var name = par.LowerRoute; if (!par.IsParameter) { routeSplitted.Append("/"); routeSplitted.Append(name); } else { if (pars.ContainsKey(name)) { routeSplitted.Append("/"); routeSplitted.Append(pars[par.Name].ToString()); routeParamsUsed.Add(name); } else { var pdesc = routeDefinition.Parameters[par.Name]; if (!pdesc.Optional) { return null; } } } } routeMissing.Clear(); var hasRoute = false; for (var i = 0; i < parsKeys.Count; i++) { var parKey = parsKeys[i]; if (!routeParamsUsed.Contains(parKey)) { if (hasRoute) routeMissing.Append("&"); routeMissing.Append(HttpUtility.UrlEncode(parKey)) .Append("=") .Append(HttpUtility.UrlEncode(pars[parKey].ToString())); hasRoute = true; } } //var url = "/" + string.Join("/", routeSplitted); if (routeMissing.Length > 0) { routeSplitted.Append("?"); routeSplitted.Append(routeMissing); } return routeSplitted.ToString(); } } }
// 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. // // This file was autogenerated by a tool. // Do not modify it. // namespace Microsoft.Azure.Batch { using Models = Microsoft.Azure.Batch.Protocol.Models; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// A inbound NAT pool that can be used to address specific ports on compute nodes in a Batch pool externally. /// </summary> public partial class InboundNatPool : ITransportObjectProvider<Models.InboundNATPool>, IPropertyMetadata { private readonly int backendPort; private readonly int frontendPortRangeEnd; private readonly int frontendPortRangeStart; private readonly string name; private readonly IReadOnlyList<NetworkSecurityGroupRule> networkSecurityGroupRules; private readonly Common.InboundEndpointProtocol protocol; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="InboundNatPool"/> class. /// </summary> /// <param name='name'>The name of the endpoint.</param> /// <param name='protocol'>The protocol of the endpoint.</param> /// <param name='backendPort'>The port number on the compute node.</param> /// <param name='frontendPortRangeStart'>The first port number in the range of external ports that will be used to provide inbound access to the backendPort /// on individual compute nodes.</param> /// <param name='frontendPortRangeEnd'>The last port number in the range of external ports that will be used to provide inbound access to the backendPort /// on individual compute nodes.</param> /// <param name='networkSecurityGroupRules'>A list of network security group rules that will be applied to the endpoint.</param> public InboundNatPool( string name, Common.InboundEndpointProtocol protocol, int backendPort, int frontendPortRangeStart, int frontendPortRangeEnd, IReadOnlyList<NetworkSecurityGroupRule> networkSecurityGroupRules = default(IReadOnlyList<NetworkSecurityGroupRule>)) { this.name = name; this.protocol = protocol; this.backendPort = backendPort; this.frontendPortRangeStart = frontendPortRangeStart; this.frontendPortRangeEnd = frontendPortRangeEnd; this.networkSecurityGroupRules = networkSecurityGroupRules; } internal InboundNatPool(Models.InboundNATPool protocolObject) { this.backendPort = protocolObject.BackendPort; this.frontendPortRangeEnd = protocolObject.FrontendPortRangeEnd; this.frontendPortRangeStart = protocolObject.FrontendPortRangeStart; this.name = protocolObject.Name; this.networkSecurityGroupRules = NetworkSecurityGroupRule.ConvertFromProtocolCollectionReadOnly(protocolObject.NetworkSecurityGroupRules); this.protocol = UtilitiesInternal.MapEnum<Models.InboundEndpointProtocol, Common.InboundEndpointProtocol>(protocolObject.Protocol); } #endregion Constructors #region InboundNatPool /// <summary> /// Gets the port number on the compute node. /// </summary> /// <remarks> /// This must be unique within a Batch pool. Acceptable values are between 1 and 65535 except for 22, 3389, 29876 /// and 29877 as these are reserved. /// </remarks> public int BackendPort { get { return this.backendPort; } } /// <summary> /// Gets the last port number in the range of external ports that will be used to provide inbound access to the backendPort /// on individual compute nodes. /// </summary> /// <remarks> /// Acceptable values range between 1 and 65534 except ports from 50000 to 55000 which are reserved by the Batch /// service. All ranges within a pool must be distinct and cannot overlap. /// </remarks> public int FrontendPortRangeEnd { get { return this.frontendPortRangeEnd; } } /// <summary> /// Gets the first port number in the range of external ports that will be used to provide inbound access to the /// backendPort on individual compute nodes. /// </summary> /// <remarks> /// Acceptable values range between 1 and 65534 except ports from 50000 to 55000 which are reserved. All ranges within /// a pool must be distinct and cannot overlap. /// </remarks> public int FrontendPortRangeStart { get { return this.frontendPortRangeStart; } } /// <summary> /// Gets the name of the endpoint. /// </summary> /// <remarks> /// The name must be unique within a Batch pool, can contain letters, numbers, underscores, periods, and hyphens. /// Names must start with a letter or number, must end with a letter, number, or underscore, and cannot exceed 77 /// characters. /// </remarks> public string Name { get { return this.name; } } /// <summary> /// Gets a list of network security group rules that will be applied to the endpoint. /// </summary> /// <remarks> /// The maximum number of rules that can be specified across all the endpoints on a pool is 25. If no network security /// group rules are specified, a default rule will be created to allow inbound access to the specified backendPort. /// </remarks> public IReadOnlyList<NetworkSecurityGroupRule> NetworkSecurityGroupRules { get { return this.networkSecurityGroupRules; } } /// <summary> /// Gets the protocol of the endpoint. /// </summary> public Common.InboundEndpointProtocol Protocol { get { return this.protocol; } } #endregion // InboundNatPool #region IPropertyMetadata bool IModifiable.HasBeenModified { //This class is compile time readonly so it cannot have been modified get { return false; } } bool IReadOnly.IsReadOnly { get { return true; } set { // This class is compile time readonly already } } #endregion // IPropertyMetadata #region Internal/private methods /// <summary> /// Return a protocol object of the requested type. /// </summary> /// <returns>The protocol object of the requested type.</returns> Models.InboundNATPool ITransportObjectProvider<Models.InboundNATPool>.GetTransportObject() { Models.InboundNATPool result = new Models.InboundNATPool() { BackendPort = this.BackendPort, FrontendPortRangeEnd = this.FrontendPortRangeEnd, FrontendPortRangeStart = this.FrontendPortRangeStart, Name = this.Name, NetworkSecurityGroupRules = UtilitiesInternal.ConvertToProtocolCollection(this.NetworkSecurityGroupRules), Protocol = UtilitiesInternal.MapEnum<Common.InboundEndpointProtocol, Models.InboundEndpointProtocol>(this.Protocol), }; return result; } /// <summary> /// Converts a collection of protocol layer objects to object layer collection objects. /// </summary> internal static IList<InboundNatPool> ConvertFromProtocolCollection(IEnumerable<Models.InboundNATPool> protoCollection) { ConcurrentChangeTrackedModifiableList<InboundNatPool> converted = UtilitiesInternal.CollectionToThreadSafeCollectionIModifiable( items: protoCollection, objectCreationFunc: o => new InboundNatPool(o)); return converted; } /// <summary> /// Converts a collection of protocol layer objects to object layer collection objects, in a frozen state. /// </summary> internal static IList<InboundNatPool> ConvertFromProtocolCollectionAndFreeze(IEnumerable<Models.InboundNATPool> protoCollection) { ConcurrentChangeTrackedModifiableList<InboundNatPool> converted = UtilitiesInternal.CollectionToThreadSafeCollectionIModifiable( items: protoCollection, objectCreationFunc: o => new InboundNatPool(o).Freeze()); converted = UtilitiesInternal.CreateObjectWithNullCheck(converted, o => o.Freeze()); return converted; } /// <summary> /// Converts a collection of protocol layer objects to object layer collection objects, with each object marked readonly /// and returned as a readonly collection. /// </summary> internal static IReadOnlyList<InboundNatPool> ConvertFromProtocolCollectionReadOnly(IEnumerable<Models.InboundNATPool> protoCollection) { IReadOnlyList<InboundNatPool> converted = UtilitiesInternal.CreateObjectWithNullCheck( UtilitiesInternal.CollectionToNonThreadSafeCollection( items: protoCollection, objectCreationFunc: o => new InboundNatPool(o).Freeze()), o => o.AsReadOnly()); return converted; } #endregion // Internal/private methods } }
using System.Collections.Generic; using UnityEngine; [AddComponentMenu("Mesh/Mesh Exploder")] public class MeshExploder : MonoBehaviour { public enum ExplosionType { Visual, Physics }; public ExplosionType type = ExplosionType.Visual; public float minSpeed = 1; public float maxSpeed = 5; public float minRotationSpeed = 90; public float maxRotationSpeed = 360; public float fadeWaitTime = 0.5f; public float fadeTime = 2; public bool useGravity = false; public float colliderThickness = 0.125f; public bool useNormals = false; public bool useMeshBoundsCenter = false; public bool allowShadows = false; public bool shadersAlreadyHandleTransparency = false; public struct MeshExplosionPreparation { public Mesh startMesh; public Vector3[] triangleNormals; public Vector3[] triangleCentroids; public int totalFrontTriangles; public Mesh[] physicsMeshes; public Quaternion[] rotations; public int[] frontMeshTrianglesPerSubMesh; } MeshExplosionPreparation preparation; static Dictionary<Mesh, MeshExplosionPreparation> cache = new Dictionary<Mesh, MeshExplosionPreparation>(); string ComponentName { get { return this.GetType().Name; } } void Start() { var meshFilter = GetComponent<MeshFilter>(); if (meshFilter == null) { #if UNITY_4_0 var skinnedMeshRenderer = GetComponent<SkinnedMeshRenderer>(); if (skinnedMeshRenderer != null) { // In this case there isn't anything we can do ahead of time to prepare since we // need to bake the mesh at the point of explosion. return; } Debug.LogError(ComponentName + " must be on a GameObject with a MeshFilter or SkinnedMeshRenderer component."); return; #else Debug.LogError(ComponentName + " must be on a GameObject with a MeshFilter component."); return; #endif } var oldMesh = meshFilter.sharedMesh; if (oldMesh == null) { Debug.LogError("The MeshFilter does not reference a mesh."); return; } Prepare(oldMesh); } void PrepareWithoutCaching(Mesh oldMesh) { Prepare(oldMesh, false); } void Prepare(Mesh oldMesh, bool cachePreparation = true) { #if UNITY_4_0 if (!oldMesh.isReadable) { Debug.LogError("The mesh is not readable. Switch on the \"Read/Write Enabled\"" + " option on the mesh's import settings."); return; } #endif var usePhysics = type == ExplosionType.Physics; MeshExplosionPreparation prep; if (cache.TryGetValue(oldMesh, out prep)) { // The caching is different for physics explosions and non-physics explosions, so make // sure that we have the correct stuff: if ((usePhysics && prep.physicsMeshes != null) || (!usePhysics && prep.startMesh != null)) { preparation = prep; return; } } // Make a copy of the mesh but with every triangle made discrete so that it doesn't share // any vertices with any other triangle. var oldVertices = oldMesh.vertices; var oldNormals = oldMesh.normals; var oldTangents = oldMesh.tangents; var oldUV = oldMesh.uv; var oldUV2 = oldMesh.uv2; var oldColors = oldMesh.colors; var subMeshCount = oldMesh.subMeshCount; var oldMeshTriangles = new int[subMeshCount][]; var frontMeshTrianglesPerSubMesh = usePhysics ? prep.frontMeshTrianglesPerSubMesh = new int[subMeshCount] : null; int frontTriangles = 0; for (var subMesh = 0; subMesh < subMeshCount; ++subMesh) { int[] triangles; oldMeshTriangles[subMesh] = triangles = oldMesh.GetTriangles(subMesh); var frontMeshTrianglesInThisSubMesh = triangles.Length / 3; if (usePhysics) frontMeshTrianglesPerSubMesh[subMesh] = frontMeshTrianglesInThisSubMesh; frontTriangles += frontMeshTrianglesInThisSubMesh; } prep.totalFrontTriangles = frontTriangles; var totalTriangles = frontTriangles * 2; // back faces var newTotalVertices = usePhysics ? 3 * 2 : // one triangle, both sides totalTriangles * 3; const int vertexLimit = 65534; if (newTotalVertices > vertexLimit) { Debug.LogError("The mesh has too many triangles to explode. It must have" + " " + ((vertexLimit / 3) / 2) + " or fewer triangles."); return; } var newVertices = new Vector3[newTotalVertices]; var newNormals = oldNormals == null || oldNormals.Length == 0 ? null : new Vector3[newTotalVertices]; var newTangents = oldTangents == null || oldTangents.Length == 0 ? null : new Vector4[newTotalVertices]; var newUV = oldUV == null || oldUV.Length == 0 ? null : new Vector2[newTotalVertices]; var newUV2 = oldUV2 == null || oldUV2.Length == 0 ? null : new Vector2[newTotalVertices]; var newColors = oldColors == null || oldColors.Length == 0 ? null : new Color[newTotalVertices]; var triangleCentroids = prep.triangleCentroids = new Vector3[frontTriangles]; var physicsMeshes = prep.physicsMeshes = usePhysics ? new Mesh[frontTriangles] : null; var rotations = prep.rotations = usePhysics ? new Quaternion[frontTriangles] : null; var physicsMeshTriangles = usePhysics ? new int[] { 0, 1, 2, 3, 4, 5 } : null; var newVertexNumber = 0; var wholeMeshTriangleIndex = 0; var invRotation = Quaternion.identity; for (var subMesh = 0; subMesh < subMeshCount; ++subMesh) { var triangles = oldMeshTriangles[subMesh]; var n = triangles.Length; int i = 0; while (i < n) { var triangleStartI = i; var centroid = Vector3.zero; for (int repeat = 0; repeat < 2; ++repeat) { i = triangleStartI; var back = repeat == 1; while (i < n) { var oldVertexNumber = triangles[back ? (triangleStartI + (3 - 1 - (i - triangleStartI))) : i]; if (usePhysics && (newVertexNumber % 6) == 0) { // Start of a triangle var a = oldVertices[oldVertexNumber]; var b = oldVertices[triangles[i + 1]]; var c = oldVertices[triangles[i + 2]]; var triangleRealNormal = Vector3.Cross(b - a, c - a); // We want to rotate the triangle so that it is flat on the x-z plane. // The reason for that is so that we can use an axis-aligned box // collider to be its physics proxy. rotations[wholeMeshTriangleIndex] = Quaternion.FromToRotation(Vector3.up, triangleRealNormal); invRotation = Quaternion.FromToRotation(triangleRealNormal, Vector3.up); triangleCentroids[wholeMeshTriangleIndex] = centroid = (a + b + c) / 3; } if (!back) { newVertices[newVertexNumber] = invRotation * (oldVertices[oldVertexNumber] - centroid); if (newNormals != null) { newNormals[newVertexNumber] = invRotation * oldNormals[oldVertexNumber]; } if (newTangents != null) { newTangents[newVertexNumber] = invRotation * oldTangents[oldVertexNumber]; } } else { // This stuff is handled by MeshExplosion.SetBackTriangleVertices(). } if (newUV != null) { newUV[newVertexNumber] = oldUV[oldVertexNumber]; } if (newUV2 != null) { newUV2[newVertexNumber] = oldUV2[oldVertexNumber]; } if (newColors != null) { newColors[newVertexNumber] = oldColors[oldVertexNumber]; } // It's important that these are here rather than in a for statement so // that they get executed even if we break. ++i; ++newVertexNumber; if ((newVertexNumber % 6) == 0) { // End of a triangle if (usePhysics) { MeshExplosion.SetBackTriangleVertices( newVertices, newNormals, newTangents, 1); var mesh = new Mesh(); mesh.vertices = newVertices; if (newNormals != null) mesh.normals = newNormals; if (newTangents != null) { mesh.tangents = newTangents; } if (newUV != null) mesh.uv = newUV; if (newUV2 != null) mesh.uv2 = newUV2; if (newColors != null) mesh.colors = newColors; mesh.triangles = physicsMeshTriangles; physicsMeshes[wholeMeshTriangleIndex] = mesh; newVertexNumber = 0; } break; } else if ((newVertexNumber % 3) == 0 && !back) { break; } } } ++wholeMeshTriangleIndex; } } var newMeshCenter = Vector3.zero; if (!usePhysics) { var newMesh = prep.startMesh = new Mesh(); #if UNITY_4_0 newMesh.MarkDynamic(); #endif newMesh.vertices = newVertices; if (newNormals != null) newMesh.normals = newNormals; if (newTangents != null) newMesh.tangents = newTangents; if (newUV != null) newMesh.uv = newUV; if (newUV2 != null) newMesh.uv2 = newUV2; if (newColors != null) newMesh.colors = newColors; newMesh.subMeshCount = subMeshCount; newVertexNumber = 0; for (var subMesh = 0; subMesh < subMeshCount; ++subMesh) { var n = oldMeshTriangles[subMesh].Length * 2; var newTriangles = new int[n]; for (var i = 0; i < n; ++i, ++newVertexNumber) { newTriangles[i] = newVertexNumber; } newMesh.SetTriangles(newTriangles, subMesh); } if (useMeshBoundsCenter) newMeshCenter = newMesh.bounds.center; } var triangleNormals = prep.triangleNormals = new Vector3[frontTriangles]; var firstVertexIndex = 0; for (var triangleNumber = 0; triangleNumber < frontTriangles; ++triangleNumber, firstVertexIndex += 6) { Vector3 centroid; if (usePhysics) { centroid = triangleCentroids[triangleNumber]; } else { centroid = (newVertices[firstVertexIndex] + newVertices[firstVertexIndex + 1] + newVertices[firstVertexIndex + 2]) / 3; triangleCentroids[triangleNumber] = centroid; } Vector3 normal; if (useNormals && newNormals != null) { if (usePhysics) { newNormals = physicsMeshes[triangleNumber].normals; firstVertexIndex = 0; } normal = ((newNormals[firstVertexIndex] + newNormals[firstVertexIndex + 1] + newNormals[firstVertexIndex + 2]) / 3).normalized; } else { normal = centroid; if (useMeshBoundsCenter) { normal -= newMeshCenter; } normal.Normalize(); } triangleNormals[triangleNumber] = normal; } preparation = prep; if (cachePreparation) cache[oldMesh] = prep; if (fadeTime != 0 && !shadersAlreadyHandleTransparency) { // Preload any replacement shaders that will be needed: foreach (var i in renderer.sharedMaterials) { var shader = i.shader; var replacement = Fade.GetReplacementFor(shader); if (replacement == null || !replacement.name.StartsWith("Transparent/")) { Debug.LogWarning("Couldn't find an explicitly transparent version of shader" + " '" + shader.name + "' so fading may not work. If the shader does" + " support transparency then this warning can be avoided by enabling" + " the 'Shaders Already Handle Transparency' option."); } } } } public GameObject Explode() { if (preparation.startMesh == null && preparation.physicsMeshes == null) { #if UNITY_4_0 var skinnedMeshRenderer = GetComponent<SkinnedMeshRenderer>(); if (skinnedMeshRenderer == null) { return null; // Initialization failed. } if (skinnedMeshRenderer.sharedMesh == null) { Debug.LogError("The SkinnedMeshRenderer does not reference a mesh."); return null; } var mesh = new Mesh(); skinnedMeshRenderer.BakeMesh(mesh); // Since the mesh we just baked is a one-off, it doesn't make any sense to cache it: PrepareWithoutCaching(mesh); #else return null; // Initialization failed. #endif } var explosionPieceName = gameObject.name + " (Mesh Explosion)"; if (type == ExplosionType.Physics) { var physicsMeshes = preparation.physicsMeshes; var rotations = preparation.rotations; var deltaSpeed = maxSpeed - minSpeed; var deltaRotationSpeed = maxRotationSpeed - minRotationSpeed; var fixedSpeed = minSpeed == maxSpeed; var fixedRotationSpeed = minRotationSpeed == maxRotationSpeed; var triangleCentroids = preparation.triangleCentroids; var triangleNormals = preparation.triangleNormals; var thisTransform = this.transform; var thisRotation = thisTransform.rotation; var thisPosition = thisTransform.position; var n = physicsMeshes.Length; var currentSubMesh = 0; var materials = GetComponent<Renderer>().materials; var frontMeshTrianglesPerSubMesh = preparation.frontMeshTrianglesPerSubMesh; var trianglesInCurrentSubMesh = frontMeshTrianglesPerSubMesh[0]; Material currentMaterial = null; var totalFadeTime = fadeWaitTime + fadeTime; for (int i = 0, triangleInCurrentSubMesh = 0; i < n; ++i, ++triangleInCurrentSubMesh) { if (triangleInCurrentSubMesh == trianglesInCurrentSubMesh) { triangleInCurrentSubMesh = 0; ++currentSubMesh; trianglesInCurrentSubMesh = frontMeshTrianglesPerSubMesh[currentSubMesh]; currentMaterial = null; } var explosionPiece = SetUpExplosionPiece(explosionPieceName, currentMaterial == null); if (currentMaterial == null) { currentMaterial = materials[currentSubMesh]; if (fadeTime != 0) { // Set the material explicitly because otherwise when Fade fetches it from // the renderer it will make another copy. explosionPiece.GetComponent<Fade>().materials = new Material[] { currentMaterial }; } } else { if (fadeTime != 0) { explosionPiece.AddComponent<DestroyAfterTime>().waitTime = totalFadeTime; } } explosionPiece.GetComponent<MeshRenderer>().sharedMaterials = new Material[] { currentMaterial }; var position = triangleCentroids[i]; var rotation = rotations[i]; // Transform them to where this GameObject is: position = thisRotation * position + thisPosition; rotation = thisRotation * rotation; var t = explosionPiece.transform; t.localPosition = position; t.localRotation = rotation; var mesh = preparation.physicsMeshes[i]; explosionPiece.GetComponent<MeshFilter>().mesh = mesh; var rb = explosionPiece.AddComponent<Rigidbody>(); rb.angularVelocity = Quaternion.AngleAxis(fixedRotationSpeed ? minRotationSpeed : minRotationSpeed + Random.value * deltaRotationSpeed, Random.onUnitSphere).eulerAngles; rb.velocity = (fixedSpeed ? minSpeed : minSpeed + Random.value * deltaSpeed) * triangleNormals[i]; var boxCollider = explosionPiece.AddComponent<BoxCollider>(); var size = mesh.bounds.size; size.y = colliderThickness; boxCollider.size = size; const float fragmentDensity = 1; rb.SetDensity(fragmentDensity); } return null; } else { var explosion = SetUpExplosionPiece(explosionPieceName); explosion.AddComponent<MeshExplosion>().Go( preparation, minSpeed, maxSpeed, minRotationSpeed, maxRotationSpeed, useGravity); return explosion; } } GameObject SetUpExplosionPiece(string name, bool addFade = true) { var explosion = new GameObject(name); { var thisTransform = transform; var explosionTransform = explosion.transform; explosionTransform.localPosition = thisTransform.position; explosionTransform.localRotation = thisTransform.rotation; } explosion.AddComponent<MeshFilter>(); var explosionRenderer = explosion.AddComponent<MeshRenderer>(); { var thisRenderer = renderer; explosionRenderer.castShadows = thisRenderer.castShadows; explosionRenderer.receiveShadows = thisRenderer.receiveShadows; explosionRenderer.sharedMaterials = thisRenderer.sharedMaterials; explosionRenderer.useLightProbes = thisRenderer.useLightProbes; } if (fadeTime != 0) { if (addFade) { var fade = explosion.AddComponent<Fade>(); fade.waitTime = fadeWaitTime; fade.fadeTime = fadeTime; fade.replaceShaders = !shadersAlreadyHandleTransparency; explosion.AddComponent<DestroyOnFadeCompletion>(); } if (!allowShadows) { explosionRenderer.castShadows = false; explosionRenderer.receiveShadows = false; } } return explosion; } }
namespace FakeItEasy.Specs { using System; using System.Diagnostics.CodeAnalysis; using FakeItEasy.Creation; using FakeItEasy.Tests.TestHelpers; using FluentAssertions; using Xbehave; using Xunit; public class UserCallbackExceptionSpecs { public interface IFoo { int Bar(int x); void OutAndRef(ref int x, out string s); } [SuppressMessage("Microsoft.Design", "CA1040:AvoidEmptyInterfaces", Justification = "Required for testing.")] public interface IHasFakeOptionsBuilder { } [Scenario] public void ExceptionInArgumentConstraintExpression(IFoo fake, Exception exception) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And an argument constraint factory that throws an exception" .See(ThrowingConstraintFactory); "When a call to the fake is configured using that constraint factory" .x(() => exception = Record.Exception(() => A.CallTo(() => fake.Bar(ThrowingConstraintFactory())).Returns(42))); "Then a UserCallbackException should be thrown" .x(() => exception.Should().BeAnExceptionOfType<UserCallbackException>()); "And its message should describe where the exception was thrown from" .x(() => exception.Message.Should().Be("Argument constraint expression <ThrowingConstraintFactory()> threw an exception. See inner exception for details.")); "And the inner exception should be the original exception" .x(() => exception.InnerException.Should().BeAnExceptionOfType<MyException>().Which.Message.Should().Be("Oops")); } [Scenario] public void ExceptionInArgumentMatcher(IFoo fake, Exception exception) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And a call to the fake is configured with a custom argument matcher that throws an exception" .x(() => A.CallTo(() => fake.Bar(A<int>.That.Matches(i => ThrowException()))).Returns(42)); "When the configured method is called" .x(() => exception = Record.Exception(() => fake.Bar(0))); "Then a UserCallbackException should be thrown" .x(() => exception.Should().BeAnExceptionOfType<UserCallbackException>()); "And its message should describe where the exception was thrown from" .x(() => exception.Message.Should().Be("Argument matcher <i => ThrowException()> threw an exception. See inner exception for details.")); "And the inner exception should be the original exception" .x(() => exception.InnerException.Should().BeAnExceptionOfType<MyException>().Which.Message.Should().Be("Oops")); } [Scenario] public void ExceptionInArgumentMatcherDescription(IFoo fake, Exception exception) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And no call to the fake is made" .x(() => { }); "When an assertion is made with a custom argument matcher whose description throws an exception" .x(() => exception = Record.Exception(() => A.CallTo(() => fake.Bar(A<int>.That.Matches(i => i % 2 == 0, o => o.Write(ThrowException())))).MustHaveHappened())); "Then a UserCallbackException should be thrown" .x(() => exception.Should().BeAnExceptionOfType<UserCallbackException>()); "And its message should describe where the exception was thrown from" .x(() => exception.Message.Should().Be("Argument matcher description threw an exception. See inner exception for details.")); "And the inner exception should be the original exception" .x(() => exception.InnerException.Should().BeAnExceptionOfType<MyException>().Which.Message.Should().Be("Oops")); } [Scenario] public void ExceptionInArgumentMatcherAndInDescription(IFoo fake, Exception exception) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And a call to the fake is configured with a custom argument matcher that throws an exception and whose description also throws an exception" .x(() => A.CallTo(() => fake.Bar(A<int>.That.Matches(i => ThrowException(), o => o.Write(ThrowException())))).Returns(42)); "When the configured method is called" .x(() => exception = Record.Exception(() => fake.Bar(0))); "Then a UserCallbackException should be thrown" .x(() => exception.Should().BeAnExceptionOfType<UserCallbackException>()); "And its message should describe where the exception was thrown from" .x(() => exception.Message.Should().Be("Argument matcher description threw an exception. See inner exception for details.")); "And the inner exception should be the original exception" .x(() => exception.InnerException.Should().BeAnExceptionOfType<MyException>().Which.Message.Should().Be("Oops")); } [Scenario] public void ExceptionInCallCountSpecification(IFoo fake, Exception exception) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And no call to the fake is made" .x(() => { }); "When an assertion is made with a call count constraint that throws an exception" .x(() => exception = Record.Exception(() => A.CallTo(() => fake.Bar(0)).MustHaveHappenedANumberOfTimesMatching(n => ThrowException()))); "Then a UserCallbackException should be thrown" .x(() => exception.Should().BeAnExceptionOfType<UserCallbackException>()); "And its message should describe where the exception was thrown from" .x(() => exception.Message.Should().Be("Call count constraint <a number of times matching the predicate 'n => ThrowException()'> threw an exception. See inner exception for details.")); "And the inner exception should be the original exception" .x(() => exception.InnerException.Should().BeAnExceptionOfType<MyException>().Which.Message.Should().Be("Oops")); } [Scenario] public void ExceptionInDummyFactory(MyDummy dummy, Exception exception) { "Given a type" .See<MyDummy>(); "And a dummy factory for this type that throws" .See<MyDummyFactory>(); "When I try to create a dummy for this type" .x(() => exception = Record.Exception(() => dummy = A.Dummy<MyDummy>())); "Then a UserCallbackException should be thrown" .x(() => exception.Should().BeAnExceptionOfType<UserCallbackException>()); "And its message should describe where the exception was thrown from" .x(() => exception.Message.Should().Be("Dummy factory 'FakeItEasy.Specs.UserCallbackExceptionSpecs+MyDummyFactory' threw an exception. See inner exception for details.")); "And the inner exception should be the original exception" .x(() => exception.InnerException.Should().BeAnExceptionOfType<MyException>().Which.Message.Should().Be("Oops")); } [Scenario] public void ExceptionInFakeOptionsBuilder(IHasFakeOptionsBuilder fake, Exception exception) { "Given a type" .See<IHasFakeOptionsBuilder>(); "And an option builder for this type that throws" .See<BadOptionsBuilder>(); "When I try to create a fake of this type" .x(() => exception = Record.Exception(() => fake = A.Fake<IHasFakeOptionsBuilder>())); "Then a UserCallbackException should be thrown" .x(() => exception.Should().BeAnExceptionOfType<UserCallbackException>()); "And its message should describe where the exception was thrown from" .x(() => exception.Message.Should().Be("Fake options builder 'FakeItEasy.Specs.UserCallbackExceptionSpecs+BadOptionsBuilder' threw an exception. See inner exception for details.")); "And the inner exception should be the original exception" .x(() => exception.InnerException.Should().BeAnExceptionOfType<MyException>().Which.Message.Should().Be("Oops")); } [Scenario] public void ExceptionInWhenArgumentsMatchPredicateForExpressionCallSpec(IFoo fake, Exception exception) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And a method configured on this fake with a WhenArgumentsMatch predicate that throws an exception" .x(() => A.CallTo(() => fake.Bar(0)).WhenArgumentsMatch(args => ThrowException()).Returns(0)); "When a call to the configured method is made" .x(() => exception = Record.Exception(() => fake.Bar(0))); "Then a UserCallbackException should be thrown" .x(() => exception.Should().BeAnExceptionOfType<UserCallbackException>()); "And its message should describe where the exception was thrown from" .x(() => exception.Message.Should().Be("Arguments predicate threw an exception. See inner exception for details.")); "And the inner exception should be the original exception" .x(() => exception.InnerException.Should().BeAnExceptionOfType<MyException>().Which.Message.Should().Be("Oops")); } [Scenario] public void ExceptionInWhenArgumentsMatchPredicateForAnyCallSpec(IFoo fake, Exception exception) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And calls configured on this fake with a WhenArgumentsMatch predicate that throws an exception" .x(() => A.CallTo(fake).WhenArgumentsMatch(args => ThrowException()).DoesNothing()); "When a call to any method of the fake is made" .x(() => exception = Record.Exception(() => fake.Bar(0))); "Then a UserCallbackException should be thrown" .x(() => exception.Should().BeAnExceptionOfType<UserCallbackException>()); "And its message should describe where the exception was thrown from" .x(() => exception.Message.Should().Be("Arguments predicate threw an exception. See inner exception for details.")); "And the inner exception should be the original exception" .x(() => exception.InnerException.Should().BeAnExceptionOfType<MyException>().Which.Message.Should().Be("Oops")); } [Scenario] public void ExceptionInWherePredicate(IFoo fake, Exception exception) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And calls configured on this fake with a call filter predicate that throws an exception" .x(() => A.CallTo(fake).Where(call => ThrowException()).DoesNothing()); "When a call to any method of the fake is made" .x(() => exception = Record.Exception(() => fake.Bar(0))); "Then a UserCallbackException should be thrown" .x(() => exception.Should().BeAnExceptionOfType<UserCallbackException>()); "And its message should describe where the exception was thrown from" .x(() => exception.Message.Should().Be("Call filter <call => ThrowException()> threw an exception. See inner exception for details.")); "And the inner exception should be the original exception" .x(() => exception.InnerException.Should().BeAnExceptionOfType<MyException>().Which.Message.Should().Be("Oops")); } [Scenario] public void ExceptionInWhereDescription(IFoo fake, Exception exception) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And no call to the fake is made" .x(() => { }); "When an assertion is made with a call filter whose description throws an exception" .x(() => exception = Record.Exception(() => A.CallTo(fake).Where(call => true, o => o.Write(ThrowException())).MustHaveHappened())); "Then a UserCallbackException should be thrown" .x(() => exception.Should().BeAnExceptionOfType<UserCallbackException>()); "And its message should describe where the exception was thrown from" .x(() => exception.Message.Should().Be("Call filter description threw an exception. See inner exception for details.")); "And the inner exception should be the original exception" .x(() => exception.InnerException.Should().BeAnExceptionOfType<MyException>().Which.Message.Should().Be("Oops")); } [Scenario] public void ExceptionInWherePredicateAndInDescription(IFoo fake, Exception exception) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And calls configured on this fake with a call filter predicate that throws an exception and whose description also throws an exception" .x(() => A.CallTo(fake).Where(call => ThrowException(), o => o.Write(ThrowException())).DoesNothing()); "When a call to any method of the fake is made" .x(() => exception = Record.Exception(() => fake.Bar(0))); "Then a UserCallbackException should be thrown" .x(() => exception.Should().BeAnExceptionOfType<UserCallbackException>()); "And its message should describe where the exception was thrown from" .x(() => exception.Message.Should().Be("Call filter description threw an exception. See inner exception for details.")); "And the inner exception should be the original exception" .x(() => exception.InnerException.Should().BeAnExceptionOfType<MyException>().Which.Message.Should().Be("Oops")); } [Scenario] public void ExceptionInReturnValueProducerIsNotWrapped(IFoo fake, Exception exception) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And a call to the fake is configured with a return value producer that throws an exception" .x(() => A.CallTo(() => fake.Bar(0)).ReturnsLazily(() => ThrowException().GetHashCode())); "When the configured method is called" .x(() => exception = Record.Exception(() => fake.Bar(0))); "Then the original exception should be thrown" .x(() => exception.Should().BeAnExceptionOfType<MyException>().Which.Message.Should().Be("Oops")); } [Scenario] public void ExceptionInOutAndRefValueProducerIsNotWrapped(IFoo fake, Exception exception, int x, string s) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And a call to the fake is configured with an out and ref value producer that throws an exception" .x(() => A.CallTo(() => fake.OutAndRef(ref x, out s)).AssignsOutAndRefParametersLazily(call => new object[] { ThrowException() })); "When the configured method is called" .x(() => exception = Record.Exception(() => fake.OutAndRef(ref x, out s))); "Then the original exception should be thrown" .x(() => exception.Should().BeAnExceptionOfType<MyException>().Which.Message.Should().Be("Oops")); } [Scenario] public void ExceptionInExceptionFactoryIsNotWrapped(IFoo fake, Exception exception) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And a call to the fake is configured with an exception factory that throws an exception" .x(() => A.CallTo(() => fake.Bar(0)).Throws(call => { ThrowException(); return new Exception("test"); })); "When the configured method is called" .x(() => exception = Record.Exception(() => fake.Bar(0))); "Then the original exception should be thrown" .x(() => exception.Should().BeAnExceptionOfType<MyException>().Which.Message.Should().Be("Oops")); } [Scenario] public void ExceptionInCallbackIsNotWrapped(IFoo fake, Exception exception) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And a call to the fake is configured with a callback that throws an exception" .x(() => A.CallTo(() => fake.Bar(0)).Invokes(() => ThrowException())); "When the configured method is called" .x(() => exception = Record.Exception(() => fake.Bar(0))); "Then the original exception should be thrown" .x(() => exception.Should().BeAnExceptionOfType<MyException>().Which.Message.Should().Be("Oops")); } private static bool ThrowException() { throw new MyException("Oops"); } private static int ThrowingConstraintFactory() { ThrowException(); return 42; } public class MyException : Exception { public MyException(string message) : base(message) { } } public class MyDummy { } public class MyDummyFactory : DummyFactory<MyDummy?> { protected override MyDummy? Create() { ThrowException(); return default; } } public class BadOptionsBuilder : FakeOptionsBuilder<IHasFakeOptionsBuilder> { protected override void BuildOptions(IFakeOptions<IHasFakeOptionsBuilder> options) { ThrowException(); } } } }
// 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.Dynamic.Utils; using System.Reflection; using System.Reflection.Emit; namespace System.Linq.Expressions.Compiler { internal partial class LambdaCompiler { private void EmitAddress(Expression node, Type type) { EmitAddress(node, type, CompilationFlags.EmitExpressionStart); } // We don't want "ref" parameters to modify values of expressions // except where it would in IL: locals, args, fields, and array elements // (Unbox is an exception, it's intended to emit a ref to the original // boxed value) private void EmitAddress(Expression node, Type type, CompilationFlags flags) { Debug.Assert(node != null); bool emitStart = (flags & CompilationFlags.EmitExpressionStartMask) == CompilationFlags.EmitExpressionStart; CompilationFlags startEmitted = emitStart ? EmitExpressionStart(node) : CompilationFlags.EmitNoExpressionStart; switch (node.NodeType) { default: EmitExpressionAddress(node, type); break; case ExpressionType.ArrayIndex: AddressOf((BinaryExpression)node, type); break; case ExpressionType.Parameter: AddressOf((ParameterExpression)node, type); break; case ExpressionType.MemberAccess: AddressOf((MemberExpression)node, type); break; case ExpressionType.Unbox: AddressOf((UnaryExpression)node, type); break; case ExpressionType.Call: AddressOf((MethodCallExpression)node, type); break; case ExpressionType.Index: AddressOf((IndexExpression)node, type); break; } if (emitStart) { EmitExpressionEnd(startEmitted); } } private void AddressOf(BinaryExpression node, Type type) { Debug.Assert(node.NodeType == ExpressionType.ArrayIndex && node.Method == null); if (TypeUtils.AreEquivalent(type, node.Type)) { EmitExpression(node.Left); EmitExpression(node.Right); Type rightType = node.Right.Type; if (TypeUtils.IsNullableType(rightType)) { LocalBuilder loc = GetLocal(rightType); _ilg.Emit(OpCodes.Stloc, loc); _ilg.Emit(OpCodes.Ldloca, loc); _ilg.EmitGetValue(rightType); FreeLocal(loc); } Type indexType = TypeUtils.GetNonNullableType(rightType); if (indexType != typeof(int)) { _ilg.EmitConvertToType(indexType, typeof(int), true); } _ilg.Emit(OpCodes.Ldelema, node.Type); } else { EmitExpressionAddress(node, type); } } private void AddressOf(ParameterExpression node, Type type) { if (TypeUtils.AreEquivalent(type, node.Type)) { if (node.IsByRef) { _scope.EmitGet(node); } else { _scope.EmitAddressOf(node); } } else { EmitExpressionAddress(node, type); } } private void AddressOf(MemberExpression node, Type type) { if (TypeUtils.AreEquivalent(type, node.Type)) { // emit "this", if any Type objectType = null; if (node.Expression != null) { EmitInstance(node.Expression, objectType = node.Expression.Type); } EmitMemberAddress(node.Member, objectType); } else { EmitExpressionAddress(node, type); } } // assumes the instance is already on the stack private void EmitMemberAddress(MemberInfo member, Type objectType) { FieldInfo field = member as FieldInfo; if ((object)field != null) { // Verifiable code may not take the address of an init-only field. // If we are asked to do so then get the value out of the field, stuff it // into a local of the same type, and then take the address of the local. // Typically this is what we want to do anyway; if we are saying // Foo.bar.ToString() for a static value-typed field bar then we don't need // the address of field bar to do the call. The address of a local which // has the same value as bar is sufficient. // The C# compiler will not compile a lambda expression tree // which writes to the address of an init-only field. But one could // probably use the expression tree API to build such an expression. // (When compiled, such an expression would fail silently.) It might // be worth it to add checking to the expression tree API to ensure // that it is illegal to attempt to write to an init-only field, // the same way that it is illegal to write to a read-only property. // The same goes for literal fields. if (!field.IsLiteral && !field.IsInitOnly) { _ilg.EmitFieldAddress(field); return; } } EmitMemberGet(member, objectType); LocalBuilder temp = GetLocal(GetMemberType(member)); _ilg.Emit(OpCodes.Stloc, temp); _ilg.Emit(OpCodes.Ldloca, temp); } private void AddressOf(MethodCallExpression node, Type type) { // An array index of a multi-dimensional array is represented by a call to Array.Get, // rather than having its own array-access node. This means that when we are trying to // get the address of a member of a multi-dimensional array, we'll be trying to // get the address of a Get method, and it will fail to do so. Instead, detect // this situation and replace it with a call to the Address method. if (!node.Method.IsStatic && node.Object.Type.IsArray && node.Method == node.Object.Type.GetMethod("Get", BindingFlags.Public | BindingFlags.Instance)) { MethodInfo mi = node.Object.Type.GetMethod("Address", BindingFlags.Public | BindingFlags.Instance); EmitMethodCall(node.Object, mi, node); } else { EmitExpressionAddress(node, type); } } private void AddressOf(IndexExpression node, Type type) { if (!TypeUtils.AreEquivalent(type, node.Type) || node.Indexer != null) { EmitExpressionAddress(node, type); return; } if (node.ArgumentCount == 1) { EmitExpression(node.Object); EmitExpression(node.GetArgument(0)); _ilg.Emit(OpCodes.Ldelema, node.Type); } else { var address = node.Object.Type.GetMethod("Address", BindingFlags.Public | BindingFlags.Instance); EmitMethodCall(node.Object, address, node); } } private void AddressOf(UnaryExpression node, Type type) { Debug.Assert(node.NodeType == ExpressionType.Unbox); Debug.Assert(type.GetTypeInfo().IsValueType); // Unbox leaves a pointer to the boxed value on the stack EmitExpression(node.Operand); _ilg.Emit(OpCodes.Unbox, type); } private void EmitExpressionAddress(Expression node, Type type) { Debug.Assert(TypeUtils.AreReferenceAssignable(type, node.Type)); EmitExpression(node, CompilationFlags.EmitAsNoTail | CompilationFlags.EmitNoExpressionStart); LocalBuilder tmp = GetLocal(type); _ilg.Emit(OpCodes.Stloc, tmp); _ilg.Emit(OpCodes.Ldloca, tmp); } // Emits the address of the expression, returning the write back if necessary // // For properties, we want to write back into the property if it's // passed byref. private WriteBack EmitAddressWriteBack(Expression node, Type type) { CompilationFlags startEmitted = EmitExpressionStart(node); WriteBack result = null; if (TypeUtils.AreEquivalent(type, node.Type)) { switch (node.NodeType) { case ExpressionType.MemberAccess: result = AddressOfWriteBack((MemberExpression)node); break; case ExpressionType.Index: result = AddressOfWriteBack((IndexExpression)node); break; } } if (result == null) { EmitAddress(node, type, CompilationFlags.EmitAsNoTail | CompilationFlags.EmitNoExpressionStart); } EmitExpressionEnd(startEmitted); return result; } private WriteBack AddressOfWriteBack(MemberExpression node) { var property = node.Member as PropertyInfo; if ((object)property == null || !property.CanWrite) { return null; } return AddressOfWriteBackCore(node); // avoids closure allocation } private WriteBack AddressOfWriteBackCore(MemberExpression node) { // emit instance, if any LocalBuilder instanceLocal = null; Type instanceType = null; if (node.Expression != null) { EmitInstance(node.Expression, instanceType = node.Expression.Type); // store in local _ilg.Emit(OpCodes.Dup); _ilg.Emit(OpCodes.Stloc, instanceLocal = GetInstanceLocal(instanceType)); } PropertyInfo pi = (PropertyInfo)node.Member; // emit the get EmitCall(instanceType, pi.GetGetMethod(true)); // emit the address of the value var valueLocal = GetLocal(node.Type); _ilg.Emit(OpCodes.Stloc, valueLocal); _ilg.Emit(OpCodes.Ldloca, valueLocal); // Set the property after the method call // don't re-evaluate anything return @this => { if (instanceLocal != null) { @this._ilg.Emit(OpCodes.Ldloc, instanceLocal); @this.FreeLocal(instanceLocal); } @this._ilg.Emit(OpCodes.Ldloc, valueLocal); @this.FreeLocal(valueLocal); @this.EmitCall(instanceLocal?.LocalType, pi.GetSetMethod(true)); }; } private WriteBack AddressOfWriteBack(IndexExpression node) { if (node.Indexer == null || !node.Indexer.CanWrite) { return null; } return AddressOfWriteBackCore(node); // avoids closure allocation } private WriteBack AddressOfWriteBackCore(IndexExpression node) { // emit instance, if any LocalBuilder instanceLocal = null; Type instanceType = null; if (node.Object != null) { EmitInstance(node.Object, instanceType = node.Object.Type); // store in local _ilg.Emit(OpCodes.Dup); _ilg.Emit(OpCodes.Stloc, instanceLocal = GetInstanceLocal(instanceType)); } // Emit indexes. We don't allow byref args, so no need to worry // about write-backs or EmitAddress var n = node.ArgumentCount; List<LocalBuilder> args = new List<LocalBuilder>(n); for (var i = 0; i < n; i++) { var arg = node.GetArgument(i); EmitExpression(arg); var argLocal = GetLocal(arg.Type); _ilg.Emit(OpCodes.Dup); _ilg.Emit(OpCodes.Stloc, argLocal); args.Add(argLocal); } // emit the get EmitGetIndexCall(node, instanceType); // emit the address of the value var valueLocal = GetLocal(node.Type); _ilg.Emit(OpCodes.Stloc, valueLocal); _ilg.Emit(OpCodes.Ldloca, valueLocal); // Set the property after the method call // don't re-evaluate anything return @this => { if (instanceLocal != null) { @this._ilg.Emit(OpCodes.Ldloc, instanceLocal); @this.FreeLocal(instanceLocal); } foreach (var arg in args) { @this._ilg.Emit(OpCodes.Ldloc, arg); @this.FreeLocal(arg); } @this._ilg.Emit(OpCodes.Ldloc, valueLocal); @this.FreeLocal(valueLocal); @this.EmitSetIndexCall(node, instanceLocal?.LocalType); }; } private LocalBuilder GetInstanceLocal(Type type) { var instanceLocalType = type.GetTypeInfo().IsValueType ? type.MakeByRefType() : type; return GetLocal(instanceLocalType); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.ComponentModel; using System.Diagnostics; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; namespace System.Net.NetworkInformation { public partial class Ping : IDisposable { private const int DefaultSendBufferSize = 32; // Same as ping.exe on Windows. private const int DefaultTimeout = 5000; // 5 seconds: same as ping.exe on Windows. private const int MaxBufferSize = 65500; // Artificial constraint due to win32 api limitations. private const int MaxUdpPacket = 0xFFFF + 256; // Marshal.SizeOf(typeof(Icmp6EchoReply)) * 2 + ip header info; private bool _disposeRequested = false; private byte[] _defaultSendBuffer = null; private AsyncOperation _asyncOp = null; private SendOrPostCallback _onPingCompletedDelegate; public event PingCompletedEventHandler PingCompleted; // Thread safety: private const int Free = 0; private const int InProgress = 1; private const int Disposed = 2; private int _status = Free; private void CheckStart() { if (_disposeRequested) { throw new ObjectDisposedException(GetType().FullName); } int currentStatus = Interlocked.CompareExchange(ref _status, InProgress, Free); if (currentStatus == InProgress) { throw new InvalidOperationException(SR.net_inasync); } else if (currentStatus == Disposed) { throw new ObjectDisposedException(GetType().FullName); } } private void Finish() { Debug.Assert(_status == InProgress, "Invalid status: " + _status); _status = Free; if (_disposeRequested) { InternalDispose(); } } protected void OnPingCompleted(PingCompletedEventArgs e) { PingCompletedEventHandler handler = PingCompleted; if (handler != null) { handler(this, e); } } public Ping() { _onPingCompletedDelegate = s => OnPingCompleted((PingCompletedEventArgs)s); } // Cancels pending async requests, closes the handles. private void InternalDispose() { _disposeRequested = true; if (Interlocked.CompareExchange(ref _status, Disposed, Free) != Free) { // Already disposed, or Finish will call Dispose again once Free. return; } InternalDisposeCore(); } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { // Only on explicit dispose. Otherwise, the GC can cleanup everything else. InternalDispose(); } } private void SendAsync(string hostNameOrAddress, object userToken) { SendAsync(hostNameOrAddress, DefaultTimeout, DefaultSendBuffer, userToken); } public void SendAsync(string hostNameOrAddress, int timeout, object userToken) { SendAsync(hostNameOrAddress, timeout, DefaultSendBuffer, userToken); } private void SendAsync(IPAddress address, object userToken) { SendAsync(address, DefaultTimeout, DefaultSendBuffer, userToken); } private void SendAsync(IPAddress address, int timeout, object userToken) { SendAsync(address, timeout, DefaultSendBuffer, userToken); } private void SendAsync(string hostNameOrAddress, int timeout, byte[] buffer, object userToken) { SendAsync(hostNameOrAddress, timeout, buffer, null, userToken); } private void SendAsync(IPAddress address, int timeout, byte[] buffer, object userToken) { SendAsync(address, timeout, buffer, null, userToken); } private void SendAsync(string hostNameOrAddress, int timeout, byte[] buffer, PingOptions options, object userToken) { if (string.IsNullOrEmpty(hostNameOrAddress)) { throw new ArgumentNullException("hostNameOrAddress"); } if (buffer == null) { throw new ArgumentNullException("buffer"); } if (buffer.Length > MaxBufferSize) { throw new ArgumentException(SR.net_invalidPingBufferSize, "buffer"); } if (timeout < 0) { throw new ArgumentOutOfRangeException("timeout"); } IPAddress address; if (IPAddress.TryParse(hostNameOrAddress, out address)) { SendAsync(address, timeout, buffer, options, userToken); return; } CheckStart(); try { _asyncOp = AsyncOperationManager.CreateOperation(userToken); AsyncStateObject state = new AsyncStateObject(hostNameOrAddress, buffer, timeout, options, userToken); ThreadPool.QueueUserWorkItem(new WaitCallback(ContinueAsyncSend), state); } catch (Exception e) { Finish(); throw new PingException(SR.net_ping, e); } } private void SendAsync(IPAddress address, int timeout, byte[] buffer, PingOptions options, object userToken) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (buffer.Length > MaxBufferSize) { throw new ArgumentException(SR.net_invalidPingBufferSize, "buffer"); } if (timeout < 0) { throw new ArgumentOutOfRangeException("timeout"); } if (address == null) { throw new ArgumentNullException("address"); } // Check if address family is installed. TestIsIpSupported(address); if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any)) { throw new ArgumentException(SR.net_invalid_ip_addr, "address"); } // Need to snapshot the address here, so we're sure that it's not changed between now // and the operation, and to be sure that IPAddress.ToString() is called and not some override. IPAddress addressSnapshot = (address.AddressFamily == AddressFamily.InterNetwork) ? new IPAddress(address.GetAddressBytes()) : new IPAddress(address.GetAddressBytes(), address.ScopeId); CheckStart(); try { _asyncOp = AsyncOperationManager.CreateOperation(userToken); InternalSendAsync(addressSnapshot, buffer, timeout, options); } catch (Exception e) { Finish(); throw new PingException(SR.net_ping, e); } } public Task<PingReply> SendPingAsync(IPAddress address) { return SendPingAsyncCore(tcs => SendAsync(address, tcs)); } public Task<PingReply> SendPingAsync(string hostNameOrAddress) { return SendPingAsyncCore(tcs => SendAsync(hostNameOrAddress, tcs)); } public Task<PingReply> SendPingAsync(IPAddress address, int timeout) { return SendPingAsyncCore(tcs => SendAsync(address, timeout, tcs)); } public Task<PingReply> SendPingAsync(string hostNameOrAddress, int timeout) { return SendPingAsyncCore(tcs => SendAsync(hostNameOrAddress, timeout, tcs)); } public Task<PingReply> SendPingAsync(IPAddress address, int timeout, byte[] buffer) { return SendPingAsyncCore(tcs => SendAsync(address, timeout, buffer, tcs)); } public Task<PingReply> SendPingAsync(string hostNameOrAddress, int timeout, byte[] buffer) { return SendPingAsyncCore(tcs => SendAsync(hostNameOrAddress, timeout, buffer, tcs)); } public Task<PingReply> SendPingAsync(IPAddress address, int timeout, byte[] buffer, PingOptions options) { return SendPingAsyncCore(tcs => SendAsync(address, timeout, buffer, options, tcs)); } public Task<PingReply> SendPingAsync(string hostNameOrAddress, int timeout, byte[] buffer, PingOptions options) { return SendPingAsyncCore(tcs => SendAsync(hostNameOrAddress, timeout, buffer, options, tcs)); } private Task<PingReply> SendPingAsyncCore(Action<TaskCompletionSource<PingReply>> sendAsync) { // Create a TaskCompletionSource to represent the operation. var tcs = new TaskCompletionSource<PingReply>(); // Register a handler that will transfer completion results to the TCS Task. PingCompletedEventHandler handler = null; handler = (sender, e) => HandleCompletion(tcs, e, handler); PingCompleted += handler; // Start the async operation. try { sendAsync(tcs); } catch { PingCompleted -= handler; throw; } // Return the task to represent the asynchronous operation. return tcs.Task; } private void HandleCompletion(TaskCompletionSource<PingReply> tcs, PingCompletedEventArgs e, PingCompletedEventHandler handler) { if (e.UserState == tcs) { try { PingCompleted -= handler; } finally { if (e.Error != null) tcs.TrySetException(e.Error); else if (e.Cancelled) tcs.TrySetCanceled(); else tcs.TrySetResult(e.Reply); } } } internal sealed class AsyncStateObject { internal AsyncStateObject(string hostName, byte[] buffer, int timeout, PingOptions options, object userToken) { HostName = hostName; Buffer = buffer; Timeout = timeout; Options = options; UserToken = userToken; } internal readonly byte[] Buffer; internal readonly string HostName; internal readonly int Timeout; internal readonly PingOptions Options; internal readonly object UserToken; } private void ContinueAsyncSend(object state) { Debug.Assert(_asyncOp != null, "Null AsyncOp?"); AsyncStateObject stateObject = (AsyncStateObject)state; try { IPAddress address = Dns.GetHostAddressesAsync(stateObject.HostName).GetAwaiter().GetResult()[0]; InternalSendAsync(address, stateObject.Buffer, stateObject.Timeout, stateObject.Options); } catch (Exception e) { PingException pe = new PingException(SR.net_ping, e); PingCompletedEventArgs eventArgs = new PingCompletedEventArgs(null, pe, false, _asyncOp.UserSuppliedState); Finish(); _asyncOp.PostOperationCompleted(_onPingCompletedDelegate, eventArgs); } } // Tests if the current machine supports the given ip protocol family. private void TestIsIpSupported(IPAddress ip) { InitializeSockets(); if (ip.AddressFamily == AddressFamily.InterNetwork && !SocketProtocolSupportPal.OSSupportsIPv4) { throw new NotSupportedException(SR.net_ipv4_not_installed); } else if ((ip.AddressFamily == AddressFamily.InterNetworkV6 && !SocketProtocolSupportPal.OSSupportsIPv6)) { throw new NotSupportedException(SR.net_ipv6_not_installed); } } static partial void InitializeSockets(); // Creates a default send buffer if a buffer wasn't specified. This follows the // ping.exe model. private byte[] DefaultSendBuffer { get { if (_defaultSendBuffer == null) { _defaultSendBuffer = new byte[DefaultSendBufferSize]; for (int i = 0; i < DefaultSendBufferSize; i++) _defaultSendBuffer[i] = (byte)((int)'a' + i % 23); } return _defaultSendBuffer; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using Xunit; using SortedList_SortedListUtils; namespace SortedListContains { public class Driver<K, V> where K : IComparableValue { private Test m_test; public Driver(Test test) { m_test = test; } /*public void BasicContains(K[] keys, V[] values) { SortedList<K,V> tbl = new SortedList<K,V>(new ValueKeyComparer<K>()); for (int i=0; i<keys.Length; i++) { tbl.Add(keys[i],values[i]); } m_test.Eval(tbl.Count==keys.Length); for (int i=0; i<keys.Length; i++) { m_test.Eval(tbl.Contains(keys[i])); } } public void ContainsNegative(K[] keys, V[] values, K[] missingkeys) { SortedList<K,V> tbl = new SortedList<K,V>(new ValueKeyComparer<K>()); for (int i=0; i<keys.Length; i++) { tbl.Add(keys[i],values[i]); } m_test.Eval(tbl.Count==keys.Length); for (int i=0; i<missingkeys.Length; i++) { m_test.Eval(false==tbl.Contains(missingkeys[i])); } } public void AddRemoveKeyContains(K[] keys, V[] values, int index) { SortedList<K,V> tbl = new SortedList<K,V>(new ValueKeyComparer<K>()); for (int i=0; i<keys.Length; i++) { tbl.Add(keys[i],values[i]); } tbl.Remove(keys[index]); m_test.Eval(false==tbl.Contains(keys[index])); } public void AddRemoveAddKeyContains(K[] keys, V[] values, int index, int repeat) { SortedList<K,V> tbl = new SortedList<K,V>(new ValueKeyComparer<K>()); for (int i=0; i<keys.Length; i++) { tbl.Add(keys[i],values[i]); } for (int i=0; i<repeat; i++) { tbl.Remove(keys[index]); tbl.Add(keys[index],values[index]); m_test.Eval(tbl.Contains(keys[index])); } } public void ContainsValidations(K[] keys, V[] values) { SortedList<K,V> tbl = new SortedList<K,V>(new ValueKeyComparer<K>()); for (int i=0; i<keys.Length; i++) { tbl.Add(keys[i],values[i]); } // //try null key // if(!typeof(K).IsSubclassOf(typeof(System.ValueType))) { try { tbl.Contains((K)(object)null); m_test.Eval(false); } catch(ArgumentException) { m_test.Eval(true); } } }*/ public void NonGenericIDictionaryBasicContains(K[] keys, V[] values) { SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>()); IDictionary _idic = tbl; for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } m_test.Eval(tbl.Count == keys.Length); for (int i = 0; i < keys.Length; i++) { m_test.Eval(_idic.Contains(keys[i])); } } public void NonGenericIDictionaryContainsNegative(K[] keys, V[] values, K[] missingkeys) { SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>()); IDictionary _idic = tbl; for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } m_test.Eval(tbl.Count == keys.Length); for (int i = 0; i < missingkeys.Length; i++) { m_test.Eval(false == _idic.Contains(missingkeys[i])); } } public void NonGenericIDictionaryAddRemoveKeyContains(K[] keys, V[] values, int index) { SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>()); IDictionary _idic = tbl; for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } tbl.Remove(keys[index]); m_test.Eval(false == _idic.Contains(keys[index])); } public void NonGenericIDictionaryAddRemoveAddKeyContains(K[] keys, V[] values, int index, int repeat) { SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>()); IDictionary _idic = tbl; for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } for (int i = 0; i < repeat; i++) { tbl.Remove(keys[index]); tbl.Add(keys[index], values[index]); m_test.Eval(_idic.Contains(keys[index])); } } public void NonGenericIDictionaryContainsValidations(K[] keys, V[] values) { SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>()); IDictionary _idic = tbl; for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } // //try null key // try { _idic.Contains(null); m_test.Eval(false); } catch (ArgumentException) { m_test.Eval(true); } m_test.Eval(!_idic.Contains(new Random(-55)), "Err_298282haiued Expected Contains to return false with an invalid type for the key"); } } public class Contains { [Fact] public static void ContainsMain() { Test test = new Test(); Driver<RefX1<int>, ValX1<string>> IntDriver = new Driver<RefX1<int>, ValX1<string>>(test); RefX1<int>[] intArr1 = new RefX1<int>[100]; for (int i = 0; i < 100; i++) { intArr1[i] = new RefX1<int>(i); } RefX1<int>[] intArr2 = new RefX1<int>[10]; for (int i = 0; i < 10; i++) { intArr2[i] = new RefX1<int>(i + 100); } Driver<ValX1<string>, RefX1<int>> StringDriver = new Driver<ValX1<string>, RefX1<int>>(test); ValX1<string>[] stringArr1 = new ValX1<string>[100]; for (int i = 0; i < 100; i++) { stringArr1[i] = new ValX1<string>("SomeTestString" + i.ToString()); } ValX1<string>[] stringArr2 = new ValX1<string>[10]; for (int i = 0; i < 10; i++) { stringArr2[i] = new ValX1<string>("SomeTestString" + (i + 100).ToString()); } //Ref<val>,Val<Ref> /* IntDriver.BasicContains(intArr1,stringArr1); IntDriver.ContainsNegative(intArr1,stringArr1,intArr2); IntDriver.ContainsNegative(new RefX1<int>[]{},new ValX1<string>[]{},intArr2); IntDriver.AddRemoveKeyContains(intArr1,stringArr1,0); IntDriver.AddRemoveKeyContains(intArr1,stringArr1,50); IntDriver.AddRemoveKeyContains(intArr1,stringArr1,99); IntDriver.AddRemoveAddKeyContains(intArr1,stringArr1,0,1); IntDriver.AddRemoveAddKeyContains(intArr1,stringArr1,50,2); IntDriver.AddRemoveAddKeyContains(intArr1,stringArr1,99,3); IntDriver.ContainsValidations(intArr1,stringArr1); IntDriver.ContainsValidations(new RefX1<int>[]{},new ValX1<string>[]{});*/ IntDriver.NonGenericIDictionaryBasicContains(intArr1, stringArr1); IntDriver.NonGenericIDictionaryContainsNegative(intArr1, stringArr1, intArr2); IntDriver.NonGenericIDictionaryContainsNegative(new RefX1<int>[] { }, new ValX1<string>[] { }, intArr2); IntDriver.NonGenericIDictionaryAddRemoveKeyContains(intArr1, stringArr1, 0); IntDriver.NonGenericIDictionaryAddRemoveKeyContains(intArr1, stringArr1, 50); IntDriver.NonGenericIDictionaryAddRemoveKeyContains(intArr1, stringArr1, 99); IntDriver.NonGenericIDictionaryAddRemoveAddKeyContains(intArr1, stringArr1, 0, 1); IntDriver.NonGenericIDictionaryAddRemoveAddKeyContains(intArr1, stringArr1, 50, 2); IntDriver.NonGenericIDictionaryAddRemoveAddKeyContains(intArr1, stringArr1, 99, 3); IntDriver.NonGenericIDictionaryContainsValidations(intArr1, stringArr1); IntDriver.NonGenericIDictionaryContainsValidations(new RefX1<int>[] { }, new ValX1<string>[] { }); //Val<Ref>,Ref<Val> /* StringDriver.BasicContains(stringArr1,intArr1); StringDriver.ContainsNegative(stringArr1,intArr1,stringArr2); StringDriver.ContainsNegative(new ValX1<string>[]{},new RefX1<int>[]{},stringArr2); StringDriver.AddRemoveKeyContains(stringArr1,intArr1,0); StringDriver.AddRemoveKeyContains(stringArr1,intArr1,50); StringDriver.AddRemoveKeyContains(stringArr1,intArr1,99); StringDriver.AddRemoveAddKeyContains(stringArr1,intArr1,0,1); StringDriver.AddRemoveAddKeyContains(stringArr1,intArr1,50,2); StringDriver.AddRemoveAddKeyContains(stringArr1,intArr1,99,3); StringDriver.ContainsValidations(stringArr1,intArr1); StringDriver.ContainsValidations(new ValX1<string>[]{},new RefX1<int>[]{});*/ StringDriver.NonGenericIDictionaryBasicContains(stringArr1, intArr1); StringDriver.NonGenericIDictionaryContainsNegative(stringArr1, intArr1, stringArr2); StringDriver.NonGenericIDictionaryContainsNegative(new ValX1<string>[] { }, new RefX1<int>[] { }, stringArr2); StringDriver.NonGenericIDictionaryAddRemoveKeyContains(stringArr1, intArr1, 0); StringDriver.NonGenericIDictionaryAddRemoveKeyContains(stringArr1, intArr1, 50); StringDriver.NonGenericIDictionaryAddRemoveKeyContains(stringArr1, intArr1, 99); StringDriver.NonGenericIDictionaryAddRemoveAddKeyContains(stringArr1, intArr1, 0, 1); StringDriver.NonGenericIDictionaryAddRemoveAddKeyContains(stringArr1, intArr1, 50, 2); StringDriver.NonGenericIDictionaryAddRemoveAddKeyContains(stringArr1, intArr1, 99, 3); StringDriver.NonGenericIDictionaryContainsValidations(stringArr1, intArr1); StringDriver.NonGenericIDictionaryContainsValidations(new ValX1<string>[] { }, new RefX1<int>[] { }); Assert.True(test.result); } } }
/* * Copyright (c) 2009, Stefan Simek * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ using System; using System.Collections.Generic; using System.Text; using System.Reflection; using System.Reflection.Emit; namespace TriAxis.RunSharp { public sealed class PropertyGen : Operand, IMemberInfo, IDelayedCompletion { TypeGen owner; MethodAttributes attrs; Type type; string name; ParameterGenCollection indexParameters = new ParameterGenCollection(); PropertyBuilder pb; Type interfaceType; List<AttributeGen> customAttributes; MethodGen getter, setter; internal PropertyGen(TypeGen owner, MethodAttributes attrs, Type type, string name) { this.owner = owner; this.attrs = attrs; this.type = type; this.name = name; } void LockSignature() { if (pb == null) { indexParameters.Lock(); pb = owner.TypeBuilder.DefineProperty(interfaceType == null ? name : interfaceType.FullName + "." + name, PropertyAttributes.None, type, indexParameters.TypeArray); owner.RegisterForCompletion(this); } } internal Type ImplementedInterface { get { return interfaceType; } set { interfaceType = value; } } public MethodGen Getter() { if (getter == null) { LockSignature(); getter = new MethodGen(owner, "get_" + name, attrs | MethodAttributes.SpecialName, type, 0); getter.ImplementedInterface = interfaceType; getter.CopyParameters(indexParameters); pb.SetGetMethod(getter.GetMethodBuilder()); } return getter; } public MethodGen Setter() { if (setter == null) { LockSignature(); setter = new MethodGen(owner, "set_" + name, attrs | MethodAttributes.SpecialName, typeof(void), 0); setter.ImplementedInterface = interfaceType; setter.CopyParameters(indexParameters); setter.UncheckedParameter(type, "value"); pb.SetSetMethod(setter.GetMethodBuilder()); } return setter; } #region Custom Attributes public PropertyGen Attribute<AT>() where AT : Attribute { return Attribute(typeof(AT)); } public PropertyGen Attribute(AttributeType type) { BeginAttribute(type); return this; } public PropertyGen Attribute<AT>(params object[] args) where AT : Attribute { return Attribute(typeof(AT), args); } public PropertyGen Attribute(AttributeType type, params object[] args) { BeginAttribute(type, args); return this; } public AttributeGen<PropertyGen> BeginAttribute<AT>() where AT : Attribute { return BeginAttribute(typeof(AT)); } public AttributeGen<PropertyGen> BeginAttribute(AttributeType type) { return BeginAttribute(type, EmptyArray<object>.Instance); } public AttributeGen<PropertyGen> BeginAttribute<AT>(params object[] args) where AT : Attribute { return BeginAttribute(typeof(AT), args); } public AttributeGen<PropertyGen> BeginAttribute(AttributeType type, params object[] args) { return AttributeGen<PropertyGen>.CreateAndAdd(this, ref customAttributes, AttributeTargets.Property, type, args); } #endregion #region Index parameter definition public ParameterGen BeginIndex(Type type, string name) { ParameterGen pgen = new ParameterGen(indexParameters, indexParameters.Count + 1, type, 0, name, false); indexParameters.Add(pgen); return pgen; } public PropertyGen Index<T>(string name) { return Index(typeof(T), name); } public PropertyGen Index(Type type, string name) { BeginIndex(type, name); return this; } #endregion public bool IsAbstract { get { return (attrs & MethodAttributes.Abstract) != 0; } } public bool IsOverride { get { return Utils.IsOverride(attrs); } } public bool IsStatic { get { return (attrs & MethodAttributes.Static) != 0; } } public string Name { get { return name; } } internal override void EmitGet(CodeGen g) { if (getter == null) base.EmitGet(g); if (indexParameters.Count != 0) throw new InvalidOperationException(Properties.Messages.ErrMissingPropertyIndex); if (!IsStatic && (g.Context.IsStatic || g.Context.OwnerType != owner.TypeBuilder)) throw new InvalidOperationException(Properties.Messages.ErrInvalidPropertyContext); g.IL.Emit(OpCodes.Ldarg_0); g.EmitCallHelper(getter.GetMethodBuilder(), null); } internal override void EmitSet(CodeGen g, Operand value, bool allowExplicitConversion) { if (setter == null) base.EmitSet(g, value, allowExplicitConversion); if (indexParameters.Count != 0) throw new InvalidOperationException(Properties.Messages.ErrMissingPropertyIndex); if (!IsStatic && (g.Context.IsStatic || g.Context.OwnerType != owner.TypeBuilder)) throw new InvalidOperationException(Properties.Messages.ErrInvalidPropertyContext); g.IL.Emit(OpCodes.Ldarg_0); g.EmitGetHelper(value, Type, allowExplicitConversion); g.EmitCallHelper(setter.GetMethodBuilder(), null); } public override Type Type { get { return type; } } #region IMethodInfo Members MemberInfo IMemberInfo.Member { get { return pb; } } Type IMemberInfo.ReturnType { get { return type; } } Type[] IMemberInfo.ParameterTypes { get { return indexParameters.TypeArray; } } bool IMemberInfo.IsParameterArray { get { return indexParameters.Count > 0 && indexParameters[indexParameters.Count - 1].IsParameterArray; } } #endregion #region IDelayedCompletion Members void IDelayedCompletion.Complete() { AttributeGen.ApplyList(ref customAttributes, pb.SetCustomAttribute); } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyInteger { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; public static partial class IntModelExtensions { /// <summary> /// Get null Int value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static int? GetNull(this IIntModel operations) { return Task.Factory.StartNew(s => ((IIntModel)s).GetNullAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get null Int value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<int?> GetNullAsync( this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<int?> result = await operations.GetNullWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Get invalid Int value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static int? GetInvalid(this IIntModel operations) { return Task.Factory.StartNew(s => ((IIntModel)s).GetInvalidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get invalid Int value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<int?> GetInvalidAsync( this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<int?> result = await operations.GetInvalidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Get overflow Int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static int? GetOverflowInt32(this IIntModel operations) { return Task.Factory.StartNew(s => ((IIntModel)s).GetOverflowInt32Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get overflow Int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<int?> GetOverflowInt32Async( this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<int?> result = await operations.GetOverflowInt32WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Get underflow Int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static int? GetUnderflowInt32(this IIntModel operations) { return Task.Factory.StartNew(s => ((IIntModel)s).GetUnderflowInt32Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get underflow Int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<int?> GetUnderflowInt32Async( this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<int?> result = await operations.GetUnderflowInt32WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Get overflow Int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static long? GetOverflowInt64(this IIntModel operations) { return Task.Factory.StartNew(s => ((IIntModel)s).GetOverflowInt64Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get overflow Int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<long?> GetOverflowInt64Async( this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<long?> result = await operations.GetOverflowInt64WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Get underflow Int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static long? GetUnderflowInt64(this IIntModel operations) { return Task.Factory.StartNew(s => ((IIntModel)s).GetUnderflowInt64Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get underflow Int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<long?> GetUnderflowInt64Async( this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<long?> result = await operations.GetUnderflowInt64WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Put max int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> public static void PutMax32(this IIntModel operations, int? intBody) { Task.Factory.StartNew(s => ((IIntModel)s).PutMax32Async(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put max int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutMax32Async( this IIntModel operations, int? intBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutMax32WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Put max int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> public static void PutMax64(this IIntModel operations, long? intBody) { Task.Factory.StartNew(s => ((IIntModel)s).PutMax64Async(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put max int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutMax64Async( this IIntModel operations, long? intBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutMax64WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Put min int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> public static void PutMin32(this IIntModel operations, int? intBody) { Task.Factory.StartNew(s => ((IIntModel)s).PutMin32Async(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put min int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutMin32Async( this IIntModel operations, int? intBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutMin32WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Put min int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> public static void PutMin64(this IIntModel operations, long? intBody) { Task.Factory.StartNew(s => ((IIntModel)s).PutMin64Async(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put min int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutMin64Async( this IIntModel operations, long? intBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutMin64WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace CloudFoundryWeb.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// <copyright file="FormChunk.cs" company=""> // TODO: Update copyright text. // </copyright> using DjvuNet.DataChunks.Enums; namespace DjvuNet.DataChunks { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; /// <summary> /// TODO: Update summary. /// </summary> public class FormChunk : IFFChunk { #region Public Properties #region ChunkType public override ChunkTypes ChunkType { get { return ChunkTypes.Form; } } #endregion ChunkType #region Children private IFFChunk[] _children = new IFFChunk[0]; /// <summary> /// Gets the children chunks for this chunk /// </summary> public IFFChunk[] Children { get { return _children; } private set { if (Children != value) { _children = value; } } } #endregion Children #region Data private DjvuReader _data; /// <summary> /// Gets the raw chunk data /// </summary> public DjvuReader Data { get { if (_data == null) { _data = ExtractRawData(); } return _data; } } #endregion Data #region DirmData private DirmChunk _dirmData; /// <summary> /// Gets the DIRM chunk for the form /// </summary> public DirmChunk DirmData { get { if (_dirmData == null && Children != null) { _dirmData = (DirmChunk)Children.FirstOrDefault(x => x.ChunkType == ChunkTypes.Dirm); } return _dirmData; } } #endregion DirmData #region NavmData private NavmChunk _NavmData; /// <summary> /// Gets the Navm chunk for the form /// </summary> public NavmChunk NavmData { get { if (_NavmData == null && Children != null) { _NavmData = (NavmChunk)Children.FirstOrDefault(x => x.ChunkType == ChunkTypes.Navm); } return _NavmData; } } #endregion NavmData #region IncludedItems /// <summary> /// Gets the included items for the form /// </summary> public InclChunk[] IncludedItems { get { return Children.Where(x => x is InclChunk).Cast<InclChunk>().ToArray(); } } #endregion IncludedItems #endregion Public Properties #region Constructors public FormChunk(DjvuReader reader, IFFChunk parent, DjvuDocument document) : base(reader, parent, document) { // Nothing } #endregion Constructors #region Public Methods /// <summary> /// Gets the string representation of the item /// </summary> /// <returns></returns> public override string ToString() { return string.Format("N:{0}; L:{1}; O:{2}; C:{3}", Name, Length, Offset, Children.Length); } #endregion Public Methods #region Protected Methods protected override void ReadChunkData(DjvuReader reader) { if (Length > 0) { ReadChildren(reader); } } #endregion Protected Methods #region Private Methods /// <summary> /// Decodes the children of this chunk /// </summary> /// <param name="reader"></param> private void ReadChildren(DjvuReader reader) { List<IFFChunk> children = new List<IFFChunk>(); // Read in all the chunks while (reader.Position < Offset + Length + 8) { if (reader.Position % 2 == 1) { reader.Position++; } // Read the chunk ID string id = reader.ReadUTF8String(4); ChunkTypes type = IFFChunk.GetChunkType(id); // Reset the stream position reader.Position -= 4; var chunk = IFFChunk.BuildIFFChunk(reader, Document, this, type); if (chunk != null) { children.Add(chunk); } } Children = children.ToArray(); } /// <summary> /// Extracts the raw data from the chunk /// </summary> /// <returns></returns> private DjvuReader ExtractRawData() { // Read the data in return Reader.CloneReader(Offset + 4 + 4, Length); } #endregion Private Methods } }
// 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 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.EventHub { using Azure; using Management; using Rest; using Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// NamespacesOperations operations. /// </summary> public partial interface INamespacesOperations { /// <summary> /// Check the give Namespace name availability. /// </summary> /// <param name='parameters'> /// Parameters to check availability of the given Namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<CheckNameAvailabilityResult>> CheckNameAvailabilityWithHttpMessagesAsync(CheckNameAvailabilityParameter parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all the available Namespaces within a subscription, /// irrespective of the resource groups. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<NamespaceResource>>> ListBySubscriptionWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the available Namespaces within a resource group. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<NamespaceResource>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a namespace. Once created, this namespace's /// resource manifest is immutable. This operation is idempotent. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='parameters'> /// Parameters for creating a namespace resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<NamespaceResource>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes an existing namespace. This operation also removes all /// associated resources under the namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the description of the specified namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<NamespaceResource>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a namespace. Once created, this namespace's /// resource manifest is immutable. This operation is idempotent. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='parameters'> /// Parameters for updating a namespace resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<NamespaceResource>> UpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, NamespaceUpdateParameter parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a list of authorization rules for a Namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SharedAccessAuthorizationRuleResource>>> ListAuthorizationRulesWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates an AuthorizationRule for a Namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='parameters'> /// The shared access AuthorizationRule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SharedAccessAuthorizationRuleResource>> CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes an AuthorizationRule for a Namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets an AuthorizationRule for a Namespace by rule name. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SharedAccessAuthorizationRuleResource>> GetAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the primary and secondary connection strings for the /// Namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ResourceListKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Regenerates the primary or secondary connection strings for the /// specified Namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='parameters'> /// Parameters required to regenerate the connection string. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ResourceListKeys>> RegenerateKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, RegenerateKeysParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a namespace. Once created, this namespace's /// resource manifest is immutable. This operation is idempotent. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='parameters'> /// Parameters for creating a namespace resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<NamespaceResource>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes an existing namespace. This operation also removes all /// associated resources under the namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all the available Namespaces within a subscription, /// irrespective of the resource groups. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<NamespaceResource>>> ListBySubscriptionNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the available Namespaces within a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<NamespaceResource>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a list of authorization rules for a Namespace. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SharedAccessAuthorizationRuleResource>>> ListAuthorizationRulesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// Copyright 2004-2009 Castle Project - http://www.castleproject.org/ // // 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 Castle.ActiveRecord.Generator.Components.Database { using System; using System.IO; using System.Collections; using System.Runtime.Serialization.Formatters.Binary; /// <summary> /// Represents a Property to be generated. /// </summary> [Serializable] public abstract class ActiveRecordPropertyDescriptor : ICloneable { private bool _generate = true; private String _columnName; private String _columnTypeName = "VARCHAR"; private String _propertyName; protected Type _propertyType; private bool _insert = true; private bool _update = true; public ActiveRecordPropertyDescriptor( String columnName, String columnTypeName, String propertyName, Type propertyType) : this(columnName, columnTypeName,propertyName) { if (propertyType == null) throw new ArgumentNullException("propertyType can't be null"); _propertyType = propertyType; } public ActiveRecordPropertyDescriptor(String columnName, String columnTypeName, String propertyName) { if (columnName == null) throw new ArgumentNullException("columnName can't be null"); if (columnTypeName == null) throw new ArgumentNullException("columnTypeName can't be null"); if (propertyName == null) throw new ArgumentNullException("propertyName can't be null"); _columnName = columnName; _columnTypeName = columnTypeName; _propertyName = propertyName; } public String ColumnName { get { return _columnName; } } public String ColumnTypeName { get { return _columnTypeName; } } public String PropertyName { get { return _propertyName; } set { _propertyName = value; } } public Type PropertyType { get { return _propertyType; } } public bool Generate { get { return _generate; } set { _generate = value; } } public bool Insert { get { return _insert; } set { _insert = value; } } public bool Update { get { return _update; } set { _update = value; } } public override String ToString() { return _columnName; } public override bool Equals(object obj) { ActiveRecordPropertyDescriptor other = obj as ActiveRecordPropertyDescriptor; if (other == null) return false; return _columnName.Equals(other._columnName); } public override int GetHashCode() { return _columnName.GetHashCode(); } #region ICloneable Members public virtual object Clone() { // Using serialization is the best // way to keep things synchronized. // Otherwise we might forget to include a new field // and terrible/unexplained bugs might raise MemoryStream stream = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, this); stream.Position = 0; return formatter.Deserialize(stream); } #endregion } [Serializable] public class ActiveRecordPrimaryKeyDescriptor : ActiveRecordFieldDescriptor { private String _generatorType; public ActiveRecordPrimaryKeyDescriptor( String columnName, String columnTypeName, String propertyName, Type propertyType, String generatorType) : base(columnName, columnTypeName, propertyName, propertyType, false) { _generatorType = generatorType; } } [Serializable] public class ActiveRecordFieldDescriptor : ActiveRecordPropertyDescriptor { private bool _nullable = false; public ActiveRecordFieldDescriptor( String columnName, String columnTypeName, String propertyName, Type propertyType, bool _nullable) : base(columnName, columnTypeName, propertyName, propertyType) { this._nullable = _nullable; } } [Serializable] public abstract class ActiveRecordPropertyRelationDescriptor : ActiveRecordPropertyDescriptor { private ActiveRecordDescriptor _targetType; private String _relationType; private String _where; private String _orderBy; private String _cascade; private String _outerJoin; private bool _lazy; private bool _proxy; private bool _inverse; public ActiveRecordPropertyRelationDescriptor(String columnName, String columnTypeName, String propertyName, String relationType, ActiveRecordDescriptor targetType) : base(columnName, columnTypeName, propertyName) { _relationType = relationType; _targetType = targetType; } public String RelationType { get { return _relationType; } } public ActiveRecordDescriptor TargetType { get { return _targetType; } } public String Where { get { return _where; } set { _where = value; } } public String OrderBy { get { return _orderBy; } set { _orderBy = value; } } public String Cascade { get { return _cascade; } set { _cascade = value; } } public String OuterJoin { get { return _outerJoin; } set { _outerJoin = value; } } public bool Proxy { get { return _proxy; } set { _proxy = value; } } public bool Lazy { get { return _lazy; } set { _lazy = value; } } public bool Inverse { get { return _inverse; } set { _inverse = value; } } } /// <summary> /// Represents a many to one association /// /// Order has OrderItem /// -> OrderItem.ParentOrderId /// /// OrderItem.ParentOrder /// /// </summary> [Serializable] public class ActiveRecordBelongsToDescriptor : ActiveRecordPropertyRelationDescriptor { public ActiveRecordBelongsToDescriptor(String columnName, String propertyName, ActiveRecordDescriptor targetType) : base(columnName, String.Empty, propertyName, "BelongsTo", targetType) { } } /// <summary> /// Represents a one to many association with a key on the foreign table: /// /// Order has OrderItem /// -> OrderItem.ParentOrderId /// /// Order.Items /// /// </summary> [Serializable] public class ActiveRecordHasManyDescriptor : ActiveRecordPropertyRelationDescriptor { public ActiveRecordHasManyDescriptor(String columnName, String propertyName, ActiveRecordDescriptor targetType) : base(columnName, String.Empty, propertyName, "HasMany", targetType) { _propertyType = typeof(IList); } } /// <summary> /// Represents an one to one association /// </summary> [Serializable] public class ActiveRecordHasOneDescriptor : ActiveRecordPropertyRelationDescriptor { public ActiveRecordHasOneDescriptor(String _columnName, String _propertyName, ActiveRecordDescriptor _targetType) : base(_columnName, String.Empty, _propertyName, "HasOne", _targetType) { } } /// <summary> /// Represents a Many to many association using an /// association table /// </summary> [Serializable] public class ActiveRecordHasAndBelongsToManyDescriptor : ActiveRecordPropertyRelationDescriptor { private String _columnKey; private String _associationtable; public ActiveRecordHasAndBelongsToManyDescriptor(String columnName, String associationtable, String propertyName, ActiveRecordDescriptor targetType, String columnKey) : base(columnName, String.Empty, propertyName, "HasAndBelongsToMany", targetType) { _associationtable = associationtable; _columnKey = columnKey; _propertyType = typeof(IList); } public String ColumnKey { get { return _columnKey; } set { _columnKey = value; } } public String AssociationTable { get { return _associationtable; } set { _associationtable = value; } } } }
//----------------------------------------------------------------------- // <copyright file="TestSubscriber.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using Akka.Actor; using Akka.TestKit; using Reactive.Streams; namespace Akka.Streams.TestKit { public static class TestSubscriber { #region messages public interface ISubscriberEvent : INoSerializationVerificationNeeded { } public struct OnSubscribe : ISubscriberEvent { public readonly ISubscription Subscription; public OnSubscribe(ISubscription subscription) { Subscription = subscription; } } public struct OnNext<T> : ISubscriberEvent { public readonly T Element; public OnNext(T element) { Element = element; } } public sealed class OnComplete: ISubscriberEvent { public static readonly OnComplete Instance = new OnComplete(); private OnComplete() { } } public struct OnError : ISubscriberEvent { public readonly Exception Cause; public OnError(Exception cause) { Cause = cause; } } #endregion /// <summary> /// Implementation of <see cref="ISubscriber{T}"/> that allows various assertions. All timeouts are dilated automatically, /// for more details about time dilation refer to <see cref="TestKit"/>. /// </summary> public class ManualProbe<T> : ISubscriber<T> { private readonly TestProbe _probe; internal ManualProbe(TestKitBase testKit) { _probe = testKit.CreateTestProbe(); } private volatile ISubscription _subscription; public void OnSubscribe(ISubscription subscription) { _probe.Ref.Tell(new OnSubscribe(subscription)); } public void OnError(Exception cause) { _probe.Ref.Tell(new OnError(cause)); } public void OnComplete() { _probe.Ref.Tell(TestSubscriber.OnComplete.Instance); } public void OnNext(T element) { _probe.Ref.Tell(new OnNext<T>(element)); } /// <summary> /// Expects and returns <see cref="ISubscription"/>. /// </summary> public ISubscription ExpectSubscription() { _subscription = _probe.ExpectMsg<OnSubscribe>().Subscription; return _subscription; } /// <summary> /// Expect and return <see cref="ISubscriberEvent"/> (any of: <see cref="OnSubscribe"/>, <see cref="OnNext"/>, <see cref="OnError"/> or <see cref="OnComplete"/>). /// </summary> public ISubscriberEvent ExpectEvent() { return _probe.ExpectMsg<ISubscriberEvent>(); } /// <summary> /// Expect and return <see cref="ISubscriberEvent"/> (any of: <see cref="OnSubscribe"/>, <see cref="OnNext"/>, <see cref="OnError"/> or <see cref="OnComplete"/>). /// </summary> public ISubscriberEvent ExpectEvent(TimeSpan max) { return _probe.ExpectMsg<ISubscriberEvent>(max); } /// <summary> /// Fluent DSL. Expect and return <see cref="ISubscriberEvent"/> (any of: <see cref="OnSubscribe"/>, <see cref="OnNext"/>, <see cref="OnError"/> or <see cref="OnComplete"/>). /// </summary> public ManualProbe<T> ExpectEvent(ISubscriberEvent e) { _probe.ExpectMsg(e); return this; } /// <summary> /// Expect and return a stream element. /// </summary> public T ExpectNext() { var t = _probe.RemainingOrDilated(null); var message = _probe.ReceiveOne(t); if (message is OnNext<T>) return ((OnNext<T>) message).Element; else throw new Exception("expected OnNext, found " + message); } /// <summary> /// Fluent DSL. Expect a stream element. /// </summary> public ManualProbe<T> ExpectNext(T element) { _probe.ExpectMsg<OnNext<T>>(x => Equals(x.Element, element)); return this; } /// <summary> /// Fluent DSL. Expect a stream element during specified timeout. /// </summary> public ManualProbe<T> ExpectNext(T element, TimeSpan timeout) { _probe.ExpectMsg<OnNext<T>>(x => Equals(x.Element, element), timeout); return this; } /// <summary> /// Fluent DSL. Expect multiple stream elements. /// </summary> public ManualProbe<T> ExpectNext(T e1, T e2, params T[] elems) { var len = elems.Length + 2; var e = ExpectNextN(len).ToArray(); AssertEquals(e.Length, len, "expected to get {0} events, but got {1}", len, e.Length); AssertEquals(e[0], e1, "expected [0] element to be {0} but found {1}", e1, e[0]); AssertEquals(e[1], e2, "expected [1] element to be {0} but found {1}", e2, e[1]); for (var i = 0; i < elems.Length; i++) { var j = i + 2; AssertEquals(e[j], elems[i], "expected [{2}] element to be {0} but found {1}", elems[i], e[j], j); } return this; } /// <summary> /// FluentDSL. Expect multiple stream elements in arbitrary order. /// </summary> public ManualProbe<T> ExpectNextUnordered(T e1, T e2, params T[] elems) { var len = elems.Length + 2; var e = ExpectNextN(len).ToArray(); AssertEquals(e.Length, len, "expected to get {0} events, but got {1}", len, e.Length); var expectedSet = new HashSet<T>(elems) {e1, e2}; expectedSet.ExceptWith(e); Assert(expectedSet.Count == 0, "unexpected elemenents [{0}] found in the result", string.Join(", ", expectedSet)); return this; } /// <summary> /// Expect and return the next <paramref name="n"/> stream elements. /// </summary> public IEnumerable<T> ExpectNextN(long n) { var i = 0; while (i < n) { var next = _probe.ExpectMsg<OnNext<T>>(); yield return next.Element; i++; } } /// <summary> /// Fluent DSL. Expect the given elements to be signalled in order. /// </summary> public ManualProbe<T> ExpectNextN(IEnumerable<T> all) { foreach (var x in all) _probe.ExpectMsg<OnNext<T>>(y => Equals(y.Element, x)); return this; } /// <summary> /// Fluent DSL. Expect the given elements to be signalled in any order. /// </summary> public ManualProbe<T> ExpectNextUnorderedN(IEnumerable<T> all) { var collection = new HashSet<T>(all); while (collection.Count > 0) { var next = ExpectNext(); Assert(collection.Contains(next), $"expected one of (${string.Join(", ", collection)}), but received {next}"); collection.Remove(next); } return this; } /// <summary> /// Fluent DSL. Expect completion. /// </summary> public ManualProbe<T> ExpectComplete() { _probe.ExpectMsg<OnComplete>(); return this; } /// <summary> /// Expect and return the signalled <see cref="Exception"/>. /// </summary> public Exception ExpectError() { return _probe.ExpectMsg<OnError>().Cause; } /// <summary> /// Expect subscription to be followed immediatly by an error signal. By default single demand will be signalled in order to wake up a possibly lazy upstream. /// <seealso cref="ExpectSubscriptionAndError(bool)"/> /// </summary> public Exception ExpectSubscriptionAndError() { return ExpectSubscriptionAndError(true); } /// <summary> /// Expect subscription to be followed immediatly by an error signal. Depending on the `signalDemand` parameter demand may be signalled /// immediatly after obtaining the subscription in order to wake up a possibly lazy upstream.You can disable this by setting the `signalDemand` parameter to `false`. /// <seealso cref="ExpectSubscriptionAndError()"/> /// </summary> public Exception ExpectSubscriptionAndError(bool signalDemand) { var sub = ExpectSubscription(); if(signalDemand) sub.Request(1); return ExpectError(); } /// <summary> /// Fluent DSL. Expect subscription followed by immediate stream completion. By default single demand will be signalled in order to wake up a possibly lazy upstream /// </summary> /// <seealso cref="ExpectSubscriptionAndComplete(bool)"/> public ManualProbe<T> ExpectSubscriptionAndComplete() { return ExpectSubscriptionAndComplete(true); } /// <summary> /// Fluent DSL. Expect subscription followed by immediate stream completion. Depending on the `signalDemand` parameter /// demand may be signalled immediatly after obtaining the subscription in order to wake up a possibly lazy upstream. /// You can disable this by setting the `signalDemand` parameter to `false`. /// </summary> /// <seealso cref="ExpectSubscriptionAndComplete()"/> public ManualProbe<T> ExpectSubscriptionAndComplete(bool signalDemand) { var sub = ExpectSubscription(); if (signalDemand) sub.Request(1); ExpectComplete(); return this; } /// <summary> /// Expect given next element or error signal, returning whichever was signalled. /// </summary> public object ExpectNextOrError() { var message = _probe.FishForMessage(m => m is OnNext<T> || m is OnError, hint: "OnNext(_) or error"); if (message is OnNext<T>) return ((OnNext<T>) message).Element; return ((OnError) message).Cause; } /// <summary> /// Fluent DSL. Expect given next element or error signal. /// </summary> public ManualProbe<T> ExpectNextOrError(T element, Exception cause) { _probe.FishForMessage( m => (m is OnNext<T> && ((OnNext<T>) m).Element.Equals(element)) || (m is OnError && ((OnError) m).Cause.Equals(cause)), hint: $"OnNext({element}) or {cause.GetType().Name}"); return this; } /// <summary> /// Expect given next element or stream completion, returning whichever was signalled. /// </summary> public object ExpectNextOrComplete() { var message = _probe.FishForMessage(m => m is OnNext<T> || m is OnComplete, hint: "OnNext(_) or OnComplete"); if (message is OnNext<T>) return ((OnNext<T>) message).Element; return message; } /// <summary> /// Fluent DSL. Expect given next element or stream completion. /// </summary> public ManualProbe<T> ExpectNextOrComplete(T element) { _probe.FishForMessage( m => (m is OnNext<T> && ((OnNext<T>) m).Element.Equals(element)) || m is OnComplete, hint: $"OnNext({element}) or OnComplete"); return this; } /// <summary> /// Fluent DSL. Same as <see cref="ExpectNoMsg(TimeSpan)"/>, but correctly treating the timeFactor. /// </summary> public ManualProbe<T> ExpectNoMsg() { _probe.ExpectNoMsg(); return this; } /// <summary> /// Fluent DSL. Assert that no message is received for the specified time. /// </summary> public ManualProbe<T> ExpectNoMsg(TimeSpan remaining) { _probe.ExpectNoMsg(remaining); return this; } public TOther ExpectNext<TOther>(Predicate<TOther> predicate) { return _probe.ExpectMsg<OnNext<TOther>>(x => predicate(x.Element)).Element; } public TOther ExpectEvent<TOther>(Func<ISubscriberEvent, TOther> func) { return func(_probe.ExpectMsg<ISubscriberEvent>()); } /// <summary> /// Receive messages for a given duration or until one does not match a given partial function. /// </summary> public IEnumerable<TOther> ReceiveWhile<TOther>(TimeSpan? max = null, TimeSpan? idle = null, Func<object, TOther> filter = null, int msgs = int.MaxValue) where TOther : class { return _probe.ReceiveWhile(max, idle, filter, msgs); } public TOther Within<TOther>(TimeSpan max, Func<TOther> func) { return _probe.Within(TimeSpan.Zero, max, func); } /// <summary> /// Attempt to drain the stream into a strict collection (by requesting <see cref="long.MaxValue"/> elements). /// </summary> /// <remarks> /// Use with caution: Be warned that this may not be a good idea if the stream is infinite or its elements are very large! /// </remarks> public IList<T> ToStrict(TimeSpan atMost) { var deadline = DateTime.UtcNow + atMost; // if no subscription was obtained yet, we expect it if (_subscription == null) ExpectSubscription(); _subscription.Request(long.MaxValue); var result = new List<T>(); while (true) { var e = ExpectEvent(TimeSpan.FromTicks(Math.Max(deadline.Ticks - DateTime.UtcNow.Ticks, 0))); if (e is OnError) throw new ArgumentException( $"ToStrict received OnError while draining stream! Accumulated elements: ${string.Join(", ", result)}", ((OnError) e).Cause); if (e is OnComplete) break; if (e is OnNext<T>) result.Add(((OnNext<T>) e).Element); } return result; } private void Assert(bool predicate, string format, params object[] args) { if (!predicate) throw new Exception(string.Format(format, args)); } private void AssertEquals<T1, T2>(T1 x, T2 y, string format, params object[] args) { if (!Equals(x, y)) throw new Exception(string.Format(format, args)); } } /// <summary> /// Single subscription tracking for <see cref="ManualProbe{T}"/>. /// </summary> public class Probe<T> : ManualProbe<T> { private readonly Lazy<ISubscription> _subscription; internal Probe(TestKitBase testKit) : base(testKit) { _subscription = new Lazy<ISubscription>(ExpectSubscription); } /// <summary> /// Asserts that a subscription has been received or will be received /// </summary> public Probe<T> EnsureSubscription() { var _ = _subscription.Value; // initializes lazy val return this; } public Probe<T> Request(long n) { _subscription.Value.Request(n); return this; } public Probe<T> RequestNext(T element) { _subscription.Value.Request(1); ExpectNext(element); return this; } public Probe<T> Cancel() { _subscription.Value.Cancel(); return this; } public T RequestNext() { _subscription.Value.Request(1); return ExpectNext(); } } public static ManualProbe<T> CreateManualProbe<T>(this TestKitBase testKit) { return new ManualProbe<T>(testKit); } public static Probe<T> CreateProbe<T>(this TestKitBase testKit) { return new Probe<T>(testKit); } } }
#region License, Terms and Author(s) // // NCrontab - Crontab for .NET // Copyright (c) 2008 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion namespace NCrontab { #region Imports using System; using System.Collections.Generic; using System.Globalization; using System.IO; using Debug = System.Diagnostics.Debug; #endregion /// <summary> /// Represents a schedule initialized from the crontab expression. /// </summary> [ Serializable ] public sealed class CrontabSchedule { private readonly CrontabField _minutes; private readonly CrontabField _hours; private readonly CrontabField _days; private readonly CrontabField _months; private readonly CrontabField _daysOfWeek; private static readonly char[] _separators = new[] {' '}; // // Crontab expression format: // // * * * * * // - - - - - // | | | | | // | | | | +----- day of week (0 - 6) (Sunday=0) // | | | +------- month (1 - 12) // | | +--------- day of month (1 - 31) // | +----------- hour (0 - 23) // +------------- min (0 - 59) // // Star (*) in the value field above means all legal values as in // braces for that column. The value column can have a * or a list // of elements separated by commas. An element is either a number in // the ranges shown above or two numbers in the range separated by a // hyphen (meaning an inclusive range). // // Source: http://www.adminschoice.com/docs/crontab.htm // public static CrontabSchedule Parse(string expression) { return TryParse(expression, ErrorHandling.Throw).Value; } public static ValueOrError<CrontabSchedule> TryParse(string expression) { return TryParse(expression, null); } private static ValueOrError<CrontabSchedule> TryParse(string expression, ExceptionHandler onError) { if (expression == null) throw new ArgumentNullException("expression"); var tokens = expression.Split(_separators, StringSplitOptions.RemoveEmptyEntries); if (tokens.Length != 5) { return ErrorHandling.OnError(() => new CrontabException(string.Format( "'{0}' is not a valid crontab expression. It must contain at least 5 components of a schedule " + "(in the sequence of minutes, hours, days, months, days of week).", expression)), onError); } var fields = new CrontabField[5]; for (var i = 0; i < fields.Length; i++) { var field = CrontabField.TryParse((CrontabFieldKind) i, tokens[i], onError); if (field.IsError) return field.ErrorProvider; fields[i] = field.Value; } return new CrontabSchedule(fields[0], fields[1], fields[2], fields[3], fields[4]); } private CrontabSchedule( CrontabField minutes, CrontabField hours, CrontabField days, CrontabField months, CrontabField daysOfWeek) { Debug.Assert(minutes != null); Debug.Assert(hours != null); Debug.Assert(days != null); Debug.Assert(months != null); Debug.Assert(daysOfWeek != null); _minutes = minutes; _hours = hours; _days = days; _months = months; _daysOfWeek = daysOfWeek; } /// <summary> /// Enumerates all the occurrences of this schedule starting with a /// base time and up to an end time limit. This method uses deferred /// execution such that the occurrences are only calculated as they /// are enumerated. /// </summary> /// <remarks> /// This method does not return the value of <paramref name="baseTime"/> /// itself if it falls on the schedule. For example, if <paramref name="baseTime" /> /// is midnight and the schedule was created from the expression <c>* * * * *</c> /// (meaning every minute) then the next occurrence of the schedule /// will be at one minute past midnight and not midnight itself. /// The method returns the <em>next</em> occurrence <em>after</em> /// <paramref name="baseTime"/>. Also, <param name="endTime" /> is /// exclusive. /// </remarks> public IEnumerable<DateTime> GetNextOccurrences(DateTime baseTime, DateTime endTime) { for (var occurrence = GetNextOccurrence(baseTime, endTime); occurrence < endTime; occurrence = GetNextOccurrence(occurrence, endTime)) { yield return occurrence; } } /// <summary> /// Gets the next occurrence of this schedule starting with a base time. /// </summary> public DateTime GetNextOccurrence(DateTime baseTime) { return GetNextOccurrence(baseTime, DateTime.MaxValue); } /// <summary> /// Gets the next occurrence of this schedule starting with a base /// time and up to an end time limit. /// </summary> /// <remarks> /// This method does not return the value of <paramref name="baseTime"/> /// itself if it falls on the schedule. For example, if <paramref name="baseTime" /> /// is midnight and the schedule was created from the expression <c>* * * * *</c> /// (meaning every minute) then the next occurrence of the schedule /// will be at one minute past midnight and not midnight itself. /// The method returns the <em>next</em> occurrence <em>after</em> /// <paramref name="baseTime"/>. Also, <param name="endTime" /> is /// exclusive. /// </remarks> public DateTime GetNextOccurrence(DateTime baseTime, DateTime endTime) { const int nil = -1; var baseYear = baseTime.Year; var baseMonth = baseTime.Month; var baseDay = baseTime.Day; var baseHour = baseTime.Hour; var baseMinute = baseTime.Minute; var endYear = endTime.Year; var endMonth = endTime.Month; var endDay = endTime.Day; var year = baseYear; var month = baseMonth; var day = baseDay; var hour = baseHour; var minute = baseMinute + 1; // // Minute // minute = _minutes.Next(minute); if (minute == nil) { minute = _minutes.GetFirst(); hour++; } // // Hour // hour = _hours.Next(hour); if (hour == nil) { minute = _minutes.GetFirst(); hour = _hours.GetFirst(); day++; } else if (hour > baseHour) { minute = _minutes.GetFirst(); } // // Day // day = _days.Next(day); RetryDayMonth: if (day == nil) { minute = _minutes.GetFirst(); hour = _hours.GetFirst(); day = _days.GetFirst(); month++; } else if (day > baseDay) { minute = _minutes.GetFirst(); hour = _hours.GetFirst(); } // // Month // month = _months.Next(month); if (month == nil) { minute = _minutes.GetFirst(); hour = _hours.GetFirst(); day = _days.GetFirst(); month = _months.GetFirst(); year++; } else if (month > baseMonth) { minute = _minutes.GetFirst(); hour = _hours.GetFirst(); day = _days.GetFirst(); } // // The day field in a cron expression spans the entire range of days // in a month, which is from 1 to 31. However, the number of days in // a month tend to be variable depending on the month (and the year // in case of February). So a check is needed here to see if the // date is a border case. If the day happens to be beyond 28 // (meaning that we're dealing with the suspicious range of 29-31) // and the date part has changed then we need to determine whether // the day still makes sense for the given year and month. If the // day is beyond the last possible value, then the day/month part // for the schedule is re-evaluated. So an expression like "0 0 // 15,31 * *" will yield the following sequence starting on midnight // of Jan 1, 2000: // // Jan 15, Jan 31, Feb 15, Mar 15, Apr 15, Apr 31, ... // var dateChanged = day != baseDay || month != baseMonth || year != baseYear; if (day > 28 && dateChanged && day > Calendar.GetDaysInMonth(year, month)) { if (year >= endYear && month >= endMonth && day >= endDay) return endTime; day = nil; goto RetryDayMonth; } var nextTime = new DateTime(year, month, day, hour, minute, 0, 0, baseTime.Kind); if (nextTime >= endTime) return endTime; // // Day of week // if (_daysOfWeek.Contains((int) nextTime.DayOfWeek)) return nextTime; return GetNextOccurrence(new DateTime(year, month, day, 23, 59, 0, 0, baseTime.Kind), endTime); } /// <summary> /// Returns a string in crontab expression (expanded) that represents /// this schedule. /// </summary> public override string ToString() { var writer = new StringWriter(CultureInfo.InvariantCulture); _minutes.Format(writer, true); writer.Write(' '); _hours.Format(writer, true); writer.Write(' '); _days.Format(writer, true); writer.Write(' '); _months.Format(writer, true); writer.Write(' '); _daysOfWeek.Format(writer, true); return writer.ToString(); } private static Calendar Calendar { get { return CultureInfo.InvariantCulture.Calendar; } } } }
#region CopyrightHeader // // Copyright by Contributors // // 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.txt // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System.Web.Services; using System.ComponentModel; using gov.va.medora.mdws.dto; using System.ServiceModel; namespace gov.va.medora.mdws { /// <summary> /// Summary description for EmrSvc /// </summary> [ServiceContract(Namespace = "http://mdws.medora.va.gov/EmrSvc")] [WebService(Namespace = "http://mdws.medora.va.gov/EmrSvc")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ToolboxItem(false)] public partial class EmrSvc : BaseService { /// <summary> /// This version should be incremented accordingly (minor for bugfixes, major for API changes, version for contract changes) as the facade is changed /// </summary> public const string VERSION = "2.0.0"; [OperationContract] [WebMethod(EnableSession = true, Description = "Get lab test description text")] public TaggedTextArray getLabTestDescription(string identifierString) { return (TaggedTextArray)MySession.execute("LabsLib", "getTestDescription", new object[] { identifierString }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get a list of lab tests for subsequent call to get test description")] public TaggedLabTestArrays getLabTests(string target) { return (TaggedLabTestArrays)MySession.execute("LabsLib", "getLabTests", new object[] { target }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get patient associates (NOK, caregiver, etc.)")] public TaggedPatientAssociateArrays getPatientAssociates() { return (TaggedPatientAssociateArrays)MySession.execute("PatientLib", "getPatientAssociatesMS", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get patient's adhoc health summary by display name from all connected VistAs.")] public TaggedTextArray getAdhocHealthSummaryByDisplayName(string displayName) { return (TaggedTextArray)MySession.execute("ClinicalLib", "getAdHocHealthSummaryByDisplayName", new object[] { displayName }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get patient's IDs from the session's base connection (i.e. from your local site/authenticated site)")] public TaggedTextArray getCorrespondingIds(string sitecode, string patientId, string idType) { return (TaggedTextArray)MySession.execute("PatientLib", "getCorrespondingIds", new object[] { sitecode, patientId, idType }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get all VHA sites")] public RegionArray getVHA() { return (RegionArray)MySession.execute("SitesLib", "getVHA", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get all VHA sites in a VISN")] public RegionTO getVISN(string regionId) { return (RegionTO)MySession.execute("SitesLib", "getVISN", new object[] { regionId }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Connect to a single VistA system.")] public DataSourceArray connect(string sitelist) { return (DataSourceArray)MySession.execute("ConnectionLib", "connectToLoginSite", new object[] { sitelist }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Log onto a single VistA system.")] public UserTO login(string username, string pwd, string context) { return (UserTO)MySession.execute("AccountLib", "login", new object[] { username, pwd, context }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Disconnect from single Vista system.")] public TaggedTextArray disconnect() { return (TaggedTextArray)MySession.execute("ConnectionLib", "disconnectAll", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Disconnect from remote Vista systems.")] public TaggedTextArray disconnectRemoteSites() { return (TaggedTextArray)MySession.execute("ConnectionLib", "disconnectRemoteSites", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Use when switching patient lookup sites.")] public TaggedTextArray visit(string pwd, string sitelist, string userSitecode, string userName, string DUZ, string SSN, string context) { return (TaggedTextArray)MySession.execute("AccountLib", "visitSites", new object[] { pwd, sitelist, userSitecode, userName, DUZ, SSN, context }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Call when launching from CPRS Tools menu: connects, authenticates, selects patient.")] public PersonsTO cprsLaunch(string pwd, string sitecode, string DUZ, string DFN) { return (PersonsTO)MySession.execute("AccountLib", "cprsLaunch", new object[] { pwd, sitecode, DUZ, DFN }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Lookup a CPRS-enabled user")] public UserArray cprsUserLookup(string target) { return (UserArray)MySession.execute("UserLib", "cprsUserLookup", new object[] { target }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Match patients at logged in site. Accepts: SSN, 'LAST,FIRST', A1234 (Last name initial + last four SSN)")] public TaggedPatientArrays match(string target) { return (TaggedPatientArrays)MySession.execute("PatientLib", "match", new object[] { target }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Select a patient at logged in site. DFN is the IEN of the patient")] public PatientTO select(string DFN) { return (PatientTO)MySession.execute("PatientLib", "select", new object[] { DFN }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Setup patient's remote sites for querying.")] public SiteArray setupMultiSiteQuery(string appPwd) { return (SiteArray)MySession.execute("AccountLib", "setupMultiSourcePatientQuery", new object[] { appPwd, "" }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get patient confidentiality from all connected sites.")] public TaggedTextArray getConfidentiality() { return (TaggedTextArray)MySession.execute("PatientLib", "getConfidentiality", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Issue patient confidentiality bulletin to all connected sites.")] public TaggedTextArray issueConfidentialityBulletin() { return (TaggedTextArray)MySession.execute("PatientLib", "issueConfidentialityBulletin", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get latest vitals from all connected VistAs")] public TaggedVitalSignArrays getLatestVitalSigns() { return (TaggedVitalSignArrays)MySession.execute("VitalsLib", "getLatestVitalSigns", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get patient's vital signs.")] public TaggedVitalSignSetArrays getVitalSigns() { return (TaggedVitalSignSetArrays)MySession.execute("VitalsLib", "getVitalSigns", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get allergies from all connected VistAs")] public TaggedAllergyArrays getAllergies() { return (TaggedAllergyArrays)MySession.execute("ClinicalLib", "getAllergies", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get radiology reports from all connected VistAs")] public TaggedRadiologyReportArrays getRadiologyReports(string fromDate, string toDate, int nrpts) { return (TaggedRadiologyReportArrays)MySession.execute("ClinicalLib", "getRadiologyReports", new object[] { fromDate, toDate, nrpts }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get surgery reports from all connected VistAs")] public TaggedSurgeryReportArrays getSurgeryReports() { return (TaggedSurgeryReportArrays)MySession.execute("ClinicalLib", "getSurgeryReports", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get text for a certain surgery report")] public TextTO getSurgeryReportText(string siteId, string rptId) { return (TextTO)MySession.execute("ClinicalLib", "getSurgeryReportText", new object[] { siteId, rptId }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get surgery reports from all connected VistAs")] public TaggedSurgeryReportArrays getSurgeryReportsWithText() { return (TaggedSurgeryReportArrays)MySession.execute("ClinicalLib", "getSurgeryReports", new object[] { true }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get problem list from all connected VistAs")] public TaggedProblemArrays getProblemList(string type) { return (TaggedProblemArrays)MySession.execute("ClinicalLib", "getProblemList", new object[] { type }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get outpatient medications from all connected VistAs")] public TaggedMedicationArrays getOutpatientMeds() { return (TaggedMedicationArrays)MySession.execute("MedsLib", "getOutpatientMeds", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get IV medications from all connected VistAs")] public TaggedMedicationArrays getIvMeds() { return (TaggedMedicationArrays)MySession.execute("MedsLib", "getIvMeds", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get Inpatient for Outpatient medications from all connected VistAs")] public TaggedMedicationArrays getImoMeds() { return (TaggedMedicationArrays)MySession.execute("MedsLib", "getImoMeds", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get unit dose medications from all connected VistAs")] public TaggedMedicationArrays getUnitDoseMeds() { return (TaggedMedicationArrays)MySession.execute("MedsLib", "getUnitDoseMeds", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get non-VA medications from all connected VistAs")] public TaggedMedicationArrays getOtherMeds() { return (TaggedMedicationArrays)MySession.execute("MedsLib", "getOtherMeds", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get all medications from all connected VistAs")] public TaggedMedicationArrays getAllMeds() { return (TaggedMedicationArrays)MySession.execute("MedsLib", "getAllMeds", new object[] { }); } //[WebMethod(EnableSession = true, Description = "Get VA medications from all connected VistAs")] //public TaggedMedicationArrays getVaMeds() //{ // return (TaggedMedicationArrays)MySession.execute("MedsLib", "getVaMeds", new object[] { }); //} [OperationContract] [WebMethod(EnableSession = true, Description = "Get medication detail from a single connected VistA.")] public TextTO getMedicationDetail(string siteId, string medId) { return (TextTO)MySession.execute("MedsLib", "getMedicationDetail", new object[] { siteId, medId }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get signed note metadata from all connected VistAs")] public TaggedNoteArrays getSignedNotes(string fromDate, string toDate, int nNotes) { return (TaggedNoteArrays)MySession.execute("NoteLib", "getSignedNotes", new object[] { fromDate, toDate, nNotes }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get unsigned note metadata from all connected VistAs")] public TaggedNoteArrays getUnsignedNotes(string fromDate, string toDate, int nNotes) { return (TaggedNoteArrays)MySession.execute("NoteLib", "getUnsignedNotes", new object[] { fromDate, toDate, nNotes }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get uncosigned note metadata from all connected VistAs")] public TaggedNoteArrays getUncosignedNotes(string fromDate, string toDate, int nNotes) { return (TaggedNoteArrays)MySession.execute("NoteLib", "getUncosignedNotes", new object[] { fromDate, toDate, nNotes }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get a note from a single connected VistA.")] public TextTO getNote(string siteId, string noteId) { return (TextTO)MySession.execute("NoteLib", "getNote", new object[] { siteId, noteId }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get notes with text from all connected VistAs.")] public TaggedNoteArrays getNotesWithText(string fromDate, string toDate, int nNotes) { return (TaggedNoteArrays)MySession.execute("NoteLib", "getNotesWithText", new object[] { fromDate, toDate, nNotes }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get discharge summaries from all connected VistAs.")] public TaggedNoteArrays getDischargeSummaries(string fromDate, string toDate, int nNotes) { return (TaggedNoteArrays)MySession.execute("NoteLib", "getDischargeSummaries", new object[] { fromDate, toDate, nNotes }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get patient's current consults.")] public TaggedConsultArrays getConsultsForPatient() { return (TaggedConsultArrays)MySession.execute("OrdersLib", "getConsultsForPatient", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get patient's appointments.")] public TaggedAppointmentArrays getAppointments() { return (TaggedAppointmentArrays)MySession.execute("EncounterLib", "getAppointments", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get note for appointment.")] public TextTO getAppointmentText(string siteId, string apptId) { return (TextTO)MySession.execute("EncounterLib", "getAppointmentText", new object[] { siteId, apptId }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get patient's clinical warnings.")] public TaggedTextArray getClinicalWarnings(string fromDate, string toDate, int nrpts) { return (TaggedTextArray)MySession.execute("NoteLib", "getClinicalWarnings", new object[] { fromDate, toDate, nrpts }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get patient's advance directives.")] public TaggedTextArray getAdvanceDirectives(string fromDate, string toDate, int nrpts) { return (TaggedTextArray)MySession.execute("NoteLib", "getAdvanceDirectives", new object[] { fromDate, toDate, nrpts }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get patient's crisis notes.")] public TaggedTextArray getCrisisNotes(string fromDate, string toDate, int nrpts) { return (TaggedTextArray)MySession.execute("NoteLib", "getCrisisNotes", new object[] { fromDate, toDate, nrpts }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get patient's immunizations.")] public TaggedTextArray getImmunizations(string fromDate, string toDate, int nrpts) { return (TaggedTextArray)MySession.execute("MedsLib", "getImmunizations", new object[] { fromDate, toDate, nrpts }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get patient's outpatient prescription profile.")] public TaggedTextArray getOutpatientRxProfile() { return (TaggedTextArray)MySession.execute("MedsLib", "getOutpatientRxProfile", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get patient's meds administation history.")] public TaggedTextArray getMedsAdminHx(string fromDate, string toDate, int nrpts) { return (TaggedTextArray)MySession.execute("MedsLib", "getMedsAdminHx", new object[] { fromDate, toDate, nrpts }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get patient's meds administation log.")] public TaggedTextArray getMedsAdminLog(string fromDate, string toDate, int nrpts) { return (TaggedTextArray)MySession.execute("MedsLib", "getMedsAdminLog", new object[] { fromDate, toDate, nrpts }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get patient's chem/hem lab results.")] public TaggedChemHemRptArrays getChemHemReports(string fromDate, string toDate, int nrpts) { return (TaggedChemHemRptArrays)MySession.execute("LabsLib", "getChemHemReports", new object[] { fromDate, toDate }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get patient's chem/hem lab results. Use 0 for number of results to retrieve all results for the time period.")] public TaggedChemHemRptArrays getChemHemReportsSimple(string fromDate, string toDate, int nrpts) { return (TaggedChemHemRptArrays)MySession.execute("LabsLib", "getChemHemReportsRdv", new object[] { fromDate, toDate, nrpts }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get patient's Cytology lab results.")] public TaggedCytologyRptArrays getCytologyReports(string fromDate, string toDate, int nrpts) { return (TaggedCytologyRptArrays)MySession.execute("LabsLib", "getCytologyReports", new object[] { fromDate, toDate, nrpts }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get patient's microbiology lab results.")] public TaggedMicrobiologyRptArrays getMicrobiologyReports(string fromDate, string toDate, int nrpts) { return (TaggedMicrobiologyRptArrays)MySession.execute("LabsLib", "getMicrobiologyReports", new object[] { fromDate, toDate, nrpts }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get patient's surgical pathology lab results.")] public TaggedSurgicalPathologyRptArrays getSurgicalPathologyReports(string fromDate, string toDate, int nrpts) { return (TaggedSurgicalPathologyRptArrays)MySession.execute("LabsLib", "getSurgicalPathologyReports", new object[] { fromDate, toDate, nrpts }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get patient's blood availability reports.")] public TaggedTextArray getBloodAvailabilityReports(string fromDate, string toDate, int nrpts) { return (TaggedTextArray)MySession.execute("LabsLib", "getBloodAvailabilityReports", new object[] { fromDate, toDate, nrpts }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get patient's blood transfusion reports.")] public TaggedTextArray getBloodTransfusionReports(string fromDate, string toDate, int nrpts) { return (TaggedTextArray)MySession.execute("LabsLib", "getBloodTransfusionReports", new object[] { fromDate, toDate, nrpts }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get patient's blood bank reports.")] public TaggedTextArray getBloodBankReports() { return (TaggedTextArray)MySession.execute("LabsLib", "getBloodBankReports", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get patient's electron microscopy reports.")] public TaggedTextArray getElectronMicroscopyReports(string fromDate, string toDate, int nrpts) { return (TaggedTextArray)MySession.execute("LabsLib", "getElectronMicroscopyReports", new object[] { fromDate, toDate, nrpts }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get patient's cytopathology reports.")] public TaggedTextArray getCytopathologyReports() { return (TaggedTextArray)MySession.execute("LabsLib", "getCytopathologyReports", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get patient's autopsy reports.")] public TaggedTextArray getAutopsyReports() { return (TaggedTextArray)MySession.execute("LabsLib", "getAutopsyReports", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get outpatient encounters from all connected VistAs.")] public TaggedTextArray getOutpatientEncounterReports(string fromDate, string toDate, int nrpts) { return (TaggedTextArray)MySession.execute("EncounterLib", "getOutpatientEncounterReports", new object[] { fromDate, toDate, nrpts }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get admission summaries from all connected VistAs.")] public TaggedTextArray getAdmissionsReports(string fromDate, string toDate, int nrpts) { return (TaggedTextArray)MySession.execute("EncounterLib", "getAdmissionsReports", new object[] { fromDate, toDate, nrpts }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get ADT reports from all connected VistAs.")] public TaggedTextArray getExpandedAdtReports(string fromDate, string toDate, int nrpts) { return (TaggedTextArray)MySession.execute("EncounterLib", "getExpandedAdtReports", new object[] { fromDate, toDate, nrpts }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get discharge diagnosis from all connected VistAs.")] public TaggedTextArray getDischargeDiagnosisReports(string fromDate, string toDate, int nrpts) { return (TaggedTextArray)MySession.execute("EncounterLib", "getDischargeDiagnosisReports", new object[] { fromDate, toDate, nrpts }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get discharge reports from all connected VistAs.")] public TaggedTextArray getDischargesReports(string fromDate, string toDate, int nrpts) { return (TaggedTextArray)MySession.execute("EncounterLib", "getDischargesReports", new object[] { fromDate, toDate, nrpts }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get transfer reports from all connected VistAs.")] public TaggedTextArray getTransfersReports(string fromDate, string toDate, int nrpts) { return (TaggedTextArray)MySession.execute("EncounterLib", "getTransfersReports", new object[] { fromDate, toDate, nrpts }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get future clinic visits from all connected VistAs.")] public TaggedTextArray getFutureClinicVisitsReports(string fromDate, string toDate, int nrpts) { return (TaggedTextArray)MySession.execute("EncounterLib", "getFutureClinicVisitsReports", new object[] { fromDate, toDate, nrpts }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get past clinic visits from all connected VistAs.")] public TaggedTextArray getPastClinicVisitsReports(string fromDate, string toDate, int nrpts) { return (TaggedTextArray)MySession.execute("EncounterLib", "getPastClinicVisitsReports", new object[] { fromDate, toDate, nrpts }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get treating specialty from all connected VistAs.")] public TaggedTextArray getTreatingSpecialtyReports(string fromDate, string toDate, int nrpts) { return (TaggedTextArray)MySession.execute("EncounterLib", "getTreatingSpecialtyReports", new object[] { fromDate, toDate, nrpts }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get C&P reports from all connected VistAs.")] public TaggedTextArray getCompAndPenReports(string fromDate, string toDate, int nrpts) { return (TaggedTextArray)MySession.execute("EncounterLib", "getCompAndPenReports", new object[] { fromDate, toDate, nrpts }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get care team from all connected VistAs.")] public TaggedTextArray getCareTeamReports() { return (TaggedTextArray)MySession.execute("EncounterLib", "getCareTeamReports", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get ICD procedure reports from all connected VistAs.")] public TaggedIcdRptArrays getIcdProceduresReports(string fromDate, string toDate, int nrpts) { return (TaggedIcdRptArrays)MySession.execute("EncounterLib", "getIcdProceduresReports", new object[] { fromDate, toDate, nrpts }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get ICD surgery reports from all connected VistAs.")] public TaggedIcdRptArrays getIcdSurgeryReports(string fromDate, string toDate, int nrpts) { return (TaggedIcdRptArrays)MySession.execute("EncounterLib", "getIcdSurgeryReports", new object[] { fromDate, toDate, nrpts }); } [OperationContract] [WebMethod(EnableSession = true)] public TaggedTextArray getNoteTitles(string target, string direction) { return (TaggedTextArray)MySession.execute("NoteLib", "getNoteTitles", new object[] { target, direction }); } [OperationContract] [WebMethod(EnableSession = true)] public TaggedHospitalLocationArray getHospitalLocations(string target, string direction) { return (TaggedHospitalLocationArray)MySession.execute("EncounterLib", "getLocations", new object[] { target, direction }); } [OperationContract] [WebMethod(EnableSession = true)] public RadiologyReportTO getImagingReport(string SSN, string accessionNumber) { return (RadiologyReportTO)MySession.execute("ClinicalLib", "getImagingReport", new object[] { SSN, accessionNumber }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Write a simple, by policy order to a single VistA")] public OrderTO writeSimpleOrderByPolicy(string providerDUZ, string esig, string locationIEN, string orderIEN, string startDate) { return (OrderTO)MySession.execute("OrdersLib", "writeSimpleOrderByPolicy", new object[] { providerDUZ, esig, locationIEN, orderIEN, startDate }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Validate electronic signature")] public TextTO isValidEsig(string esig) { return (TextTO)MySession.execute("UserLib", "isValidEsig", new object[] { esig }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Make a patient inquiry call (address, contact numbers, NOK, etc. information)")] public TextTO patientInquiry() { return (TextTO)MySession.execute("PatientLib", "patientInquiry", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get a list of hospital wards")] public TaggedHospitalLocationArray getWards() { return (TaggedHospitalLocationArray)MySession.execute("EncounterLib", "getWards", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get a list of patients by ward")] public TaggedPatientArray getPatientsByWard(string wardId) { return (TaggedPatientArray)MySession.execute("PatientLib", "getPatientsByWard", new object[] { wardId }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get a list of hospital clinics")] public TaggedHospitalLocationArray getClinics(string target) { return (TaggedHospitalLocationArray)MySession.execute("EncounterLib", "getClinics", new object[] { target }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get a list of patients by clinic")] public TaggedPatientArray getPatientsByClinic(string clinicId) { return (TaggedPatientArray)MySession.execute("PatientLib", "getPatientsByClinic", new object[] { clinicId }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get the list of specialties")] public TaggedText getSpecialties() { return (TaggedText)MySession.execute("EncounterLib", "getSpecialties", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get a list of patients by specialty")] public TaggedPatientArray getPatientsBySpecialty(string specialtyId) { return (TaggedPatientArray)MySession.execute("PatientLib", "getPatientsBySpecialty", new object[] { specialtyId }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get the list of teams")] public TaggedText getTeams() { return (TaggedText)MySession.execute("EncounterLib", "getTeams", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get a list of patients by team")] public TaggedPatientArray getPatientsByTeam(string teamId) { return (TaggedPatientArray)MySession.execute("PatientLib", "getPatientsByTeam", new object[] { teamId }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get a list of patients by provider")] public TaggedPatientArray getPatientsByProvider(string duz) { return (TaggedPatientArray)MySession.execute("PatientLib", "getPatientsByProvider", new object[] { duz }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get selected patient's admissions")] public TaggedInpatientStayArray getAdmissions() { return (TaggedInpatientStayArray)MySession.execute("EncounterLib", "getAdmissions", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get a VistA's hospital locations (clinics, etc.).")] public TaggedHospitalLocationArray getLocations(string target, string direction) { return (TaggedHospitalLocationArray)MySession.execute("EncounterLib", "getLocations", new object[] { target, direction }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get patient record flag actions.")] public PatientRecordFlagArray getPrfNoteActions(string noteDefinitionIEN) { return (PatientRecordFlagArray)MySession.execute("NoteLib", "getPrfNoteActions", new object[] { noteDefinitionIEN }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get selected patient's visits")] public TaggedVisitArray getVisits(string fromDate, string toDate) { return (TaggedVisitArray)MySession.execute("EncounterLib", "getVisits", new object[] { fromDate, toDate }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Is given note a consult note?")] public TextTO isConsultNote(string noteDefinitionIEN) { return (TextTO)MySession.execute("NoteLib", "isConsultNote", new object[] { noteDefinitionIEN }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Is cosigner required for this user/author pair?")] public TextTO isCosignerRequired(string noteDefinitionIEN, string authorDUZ) { return (TextTO)MySession.execute("NoteLib", "isCosignerRequired", new object[] { noteDefinitionIEN, authorDUZ }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Is given note a surgery note?")] public TaggedText isOneVisitNote(string noteDefinitionIEN, string noteTitle, string visitString) { return (TaggedText)MySession.execute("NoteLib", "isOneVisitNote", new object[] { noteDefinitionIEN, noteTitle, visitString }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Is given note a PRF note?")] public TextTO isPrfNote(string noteDefinitionIEN) { return (TextTO)MySession.execute("NoteLib", "isPrfNote", new object[] { noteDefinitionIEN }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Is given note a surgery note?")] public TaggedText isSurgeryNote(string noteDefinitionIEN) { return (TaggedText)MySession.execute("NoteLib", "isSurgeryNote", new object[] { noteDefinitionIEN }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Write a note.")] public NoteResultTO writeNote( string titleIEN, string encounterString, string text, string authorDUZ, string cosignerDUZ, string consultIEN, string prfIEN) { NoteLib lib = new NoteLib(MySession); return lib.writeNote(titleIEN, encounterString, text, authorDUZ, cosignerDUZ, consultIEN, prfIEN); } [OperationContract] [WebMethod(EnableSession = true, Description = "Sign a note.")] public TextTO signNote(string noteIEN, string userDUZ, string esig) { NoteLib lib = new NoteLib(MySession); return lib.signNote(noteIEN, userDUZ, esig); } [OperationContract] [WebMethod(EnableSession = true, Description = "Close a note.")] public TextTO closeNote(string noteIEN, string consultIEN) { NoteLib lib = new NoteLib(MySession); return lib.closeNote(noteIEN, consultIEN); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get a patient's demographics")] public PatientTO getDemographics() { PatientLib lib = new PatientLib(MySession); return lib.getDemographics(); } [OperationContract] [WebMethod(EnableSession = true, Description = "Find a patient in the MPI")] public PatientArray mpiLookup(string SSN) { return (PatientArray)MySession.execute("PatientLib", "mpiLookup", new object[] { SSN, "", "", "", "", "", "" }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Find a patient in the NPT")] public PatientArray nptLookup(string SSN) { return (PatientArray)MySession.execute("PatientLib", "nptLookup", new object[] { SSN, "", "", "", "", "", "" }); } [OperationContract] [WebMethod(EnableSession = true, Description = "Get a patient's orders")] public TaggedOrderArrays getAllOrders() { return (TaggedOrderArrays)MySession.execute("OrdersLib", "getOrdersForPatient", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "")] public TextArray getReminderReportTemplates() { return (TextArray)MySession.execute("ClinicalRemindersLib", "getReminderReportTemplates", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "")] public TaggedTextArray getActiveReminderReports() { return (TaggedTextArray)MySession.execute("ClinicalRemindersLib", "getActiveReminderReports", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "")] public ReminderReportPatientListTO getPatientListForReminderReport(string rptId) { return (ReminderReportPatientListTO)MySession.execute("ClinicalRemindersLib", "getPatientListForReminderReport", new object[] { rptId }); } [OperationContract] [WebMethod(EnableSession = true, Description = "")] public TaggedText getPcpForPatient(string pid) { return (TaggedText)MySession.execute("PatientLib", "getPcpForPatient", new object[] { pid }); } [OperationContract] [WebMethod(EnableSession = true, Description = "")] public TaggedTextArray getSitesForStation() { return (TaggedTextArray)MySession.execute("LocationLib", "getSitesForStation", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "")] public TaggedTextArray getClinicsByName(string name) { return (TaggedTextArray)MySession.execute("LocationLib", "getClinicsByName", new object[] { name }); } [OperationContract] [WebMethod(EnableSession = true, Description = "")] public TaggedTextArray getOrderableItemsByName(string name) { return (TaggedTextArray)MySession.execute("OrdersLib", "getOrderableItemsByName", new object[] { name }); } [OperationContract] [WebMethod(EnableSession = true, Description = "")] public TextTO getOrderStatusForPatient(string pid, string orderableItemId) { return (TextTO)MySession.execute("OrdersLib", "getOrderStatusForPatient", new object[] { pid, orderableItemId }); } [OperationContract] [WebMethod(EnableSession = true, Description = "")] public TaggedTextArray getOrderDialogsForDisplayGroup(string displayGroupId) { return (TaggedTextArray)MySession.execute("OrdersLib", "getOrderDialogsForDisplayGroup", new object[] { displayGroupId }); } [OperationContract] [WebMethod(EnableSession = true, Description = "")] public OrderDialogItemArray getOrderDialogItems(string dialogId) { return (OrderDialogItemArray)MySession.execute("OrdersLib", "getOrderDialogItems", new object[] { dialogId }); } [OperationContract] [WebMethod(EnableSession = true, Description = "")] public TaggedTextArray getUsersWithOption(string optionName) { return (TaggedTextArray)MySession.execute("UserLib", "getUsersWithOption", new object[] { optionName }); } [OperationContract] [WebMethod(EnableSession = true, Description = "")] public BoolTO userHasPermission(string uid, string permissionName) { return (BoolTO)MySession.execute("UserLib", "hasPermission", new object[] { uid, permissionName }); } [OperationContract] [WebMethod(EnableSession = true, Description = "")] public UserSecurityKeyArray getUserSecurityKeys(string uid) { return (UserSecurityKeyArray)MySession.execute("UserLib", "getUserSecurityKeys", new object[] { uid }); } [OperationContract] [WebMethod(EnableSession = true, Description = "")] public TaggedMentalHealthInstrumentAdministrationArrays getMentalHealthInstrumentsForPatient() { return (TaggedMentalHealthInstrumentAdministrationArrays)MySession.execute("ClinicalLib", "getMentalHealthInstrumentsForPatient", new object[] { }); } [OperationContract] [WebMethod(EnableSession = true, Description = "")] public MentalHealthInstrumentResultSetTO getMentalHealthInstrumentResultSet(string sitecode, string administrationId) { return (MentalHealthInstrumentResultSetTO)MySession.execute("ClinicalLib", "getMentalHealthInstrumentResultSet", new object[] { sitecode, administrationId }); } [OperationContract] [WebMethod(EnableSession = true, Description = "")] public TaggedTextArray getNhinData(string types) { return (TaggedTextArray)MySession.execute("ClinicalLib", "getNhinData", new object[] { types }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel.Composition; using System.ComponentModel.Composition.AttributedModel; using System.ComponentModel.Composition.Primitives; using System.Globalization; using System.Linq; using System.Reflection; using Microsoft.Internal; using Microsoft.Internal.Collections; using System.Collections.ObjectModel; using System.ComponentModel.Composition.ReflectionModel; namespace System.ComponentModel.Composition.Hosting { internal static class CompositionServices { internal static readonly Type InheritedExportAttributeType = typeof(InheritedExportAttribute); internal static readonly Type ExportAttributeType = typeof(ExportAttribute); internal static readonly Type AttributeType = typeof(Attribute); internal static readonly Type ObjectType = typeof(object); private static readonly string[] reservedMetadataNames = new string[] { CompositionConstants.PartCreationPolicyMetadataName }; internal static Type GetDefaultTypeFromMember(this MemberInfo member) { Assumes.NotNull(member); switch (member.MemberType) { case MemberTypes.Property: return ((PropertyInfo)member).PropertyType; case MemberTypes.NestedType: case MemberTypes.TypeInfo: return ((Type)member); case MemberTypes.Field: default: Assumes.IsTrue(member.MemberType == MemberTypes.Field); return ((FieldInfo)member).FieldType; } } internal static Type AdjustSpecifiedTypeIdentityType(this Type specifiedContractType, MemberInfo member) { if (member.MemberType == MemberTypes.Method) { return specifiedContractType; } else { return specifiedContractType.AdjustSpecifiedTypeIdentityType(member.GetDefaultTypeFromMember()); } } internal static Type AdjustSpecifiedTypeIdentityType(this Type specifiedContractType, Type memberType) { Assumes.NotNull(specifiedContractType); if ((memberType != null) && memberType.IsGenericType && specifiedContractType.IsGenericType) { // if the memeber type is closed and the specified contract type is open and they have exatly the same number of parameters // we will close the specfied contract type if (specifiedContractType.ContainsGenericParameters && !memberType.ContainsGenericParameters) { var typeGenericArguments = memberType.GetGenericArguments(); var metadataTypeGenericArguments = specifiedContractType.GetGenericArguments(); if (typeGenericArguments.Length == metadataTypeGenericArguments.Length) { return specifiedContractType.MakeGenericType(typeGenericArguments); } } // if both member type and the contract type are open generic types, make sure that their parameters are ordered the same way else if(specifiedContractType.ContainsGenericParameters && memberType.ContainsGenericParameters) { var memberGenericParameters = memberType.GetPureGenericParameters(); if (specifiedContractType.GetPureGenericArity() == memberGenericParameters.Count) { return specifiedContractType.GetGenericTypeDefinition().MakeGenericType(memberGenericParameters.ToArray()); } } } return specifiedContractType; } private static string AdjustTypeIdentity(string originalTypeIdentity, Type typeIdentityType) { return GenericServices.GetGenericName(originalTypeIdentity, GenericServices.GetGenericParametersOrder(typeIdentityType), GenericServices.GetPureGenericArity(typeIdentityType)); } internal static void GetContractInfoFromExport(this MemberInfo member, ExportAttribute export, out Type typeIdentityType, out string contractName) { typeIdentityType = member.GetTypeIdentityTypeFromExport(export); if (!string.IsNullOrEmpty(export.ContractName)) { contractName = export.ContractName; } else { contractName = member.GetTypeIdentityFromExport(typeIdentityType); } } internal static string GetTypeIdentityFromExport(this MemberInfo member, Type typeIdentityType) { if (typeIdentityType != null) { string typeIdentity = AttributedModelServices.GetTypeIdentity(typeIdentityType); if (typeIdentityType.ContainsGenericParameters) { typeIdentity = AdjustTypeIdentity(typeIdentity, typeIdentityType); } return typeIdentity; } else { MethodInfo method = member as MethodInfo; Assumes.NotNull(method); return AttributedModelServices.GetTypeIdentity(method); } } private static Type GetTypeIdentityTypeFromExport(this MemberInfo member, ExportAttribute export) { if (export.ContractType != null) { return export.ContractType.AdjustSpecifiedTypeIdentityType(member); } else { return (member.MemberType != MemberTypes.Method) ? member.GetDefaultTypeFromMember() : null; } } internal static bool IsContractNameSameAsTypeIdentity(this ExportAttribute export) { return string.IsNullOrEmpty(export.ContractName); } internal static Type GetContractTypeFromImport(this IAttributedImport import, ImportType importType) { if (import.ContractType != null) { return import.ContractType.AdjustSpecifiedTypeIdentityType(importType.ContractType); } return importType.ContractType; } internal static string GetContractNameFromImport(this IAttributedImport import, ImportType importType) { if (!string.IsNullOrEmpty(import.ContractName)) { return import.ContractName; } Type contractType = import.GetContractTypeFromImport(importType); return AttributedModelServices.GetContractName(contractType); } internal static string GetTypeIdentityFromImport(this IAttributedImport import, ImportType importType) { Type contractType = import.GetContractTypeFromImport(importType); // For our importers we treat object as not having a type identity if (contractType == CompositionServices.ObjectType) { return null; } return AttributedModelServices.GetTypeIdentity(contractType); } internal static IDictionary<string, object> GetPartMetadataForType(this Type type, CreationPolicy creationPolicy) { IDictionary<string, object> dictionary = new Dictionary<string, object>(StringComparers.MetadataKeyNames); if (creationPolicy != CreationPolicy.Any) { dictionary.Add(CompositionConstants.PartCreationPolicyMetadataName, creationPolicy); } foreach (PartMetadataAttribute partMetadata in type.GetAttributes<PartMetadataAttribute>()) { if (reservedMetadataNames.Contains(partMetadata.Name, StringComparers.MetadataKeyNames) || dictionary.ContainsKey(partMetadata.Name)) { // Perhaps we should log an error here so that people know this value is being ignored. continue; } dictionary.Add(partMetadata.Name, partMetadata.Value); } // metadata for generic types if (type.ContainsGenericParameters) { // Register the part as generic dictionary.Add(CompositionConstants.IsGenericPartMetadataName, true); // Add arity Type[] genericArguments = type.GetGenericArguments(); dictionary.Add(CompositionConstants.GenericPartArityMetadataName, genericArguments.Length); // add constraints bool hasConstraints = false; object[] genericParameterConstraints = new object[genericArguments.Length]; GenericParameterAttributes[] genericParameterAttributes = new GenericParameterAttributes[genericArguments.Length]; for (int i=0; i< genericArguments.Length ; i++) { Type genericArgument = genericArguments[i]; Type[] constraints = genericArgument.GetGenericParameterConstraints(); if (constraints.Length == 0) { constraints = null; } GenericParameterAttributes attributes = genericArgument.GenericParameterAttributes; if ((constraints != null) || (attributes != GenericParameterAttributes.None)) { genericParameterConstraints[i] = constraints; genericParameterAttributes[i] = attributes; hasConstraints = true; } } if (hasConstraints) { dictionary.Add(CompositionConstants.GenericParameterConstraintsMetadataName, genericParameterConstraints); dictionary.Add(CompositionConstants.GenericParameterAttributesMetadataName, genericParameterAttributes); } } if (dictionary.Count == 0) { return MetadataServices.EmptyMetadata; } else { return dictionary; } } internal static void TryExportMetadataForMember(this MemberInfo member, out IDictionary<string, object> dictionary) { dictionary = new Dictionary<string, object>(); foreach (var attr in member.GetAttributes<Attribute>()) { var provider = attr as ExportMetadataAttribute; if (provider != null) { if (reservedMetadataNames.Contains(provider.Name, StringComparers.MetadataKeyNames)) { throw ExceptionBuilder.CreateDiscoveryException(SR.Discovery_ReservedMetadataNameUsed, member.GetDisplayName(), provider.Name); } // we pass "null" for valueType which would make it inferred. We don;t have additional type information when metadata // goes through the ExportMetadataAttribute path if (!dictionary.TryContributeMetadataValue(provider.Name, provider.Value, null, provider.IsMultiple)) { throw ExceptionBuilder.CreateDiscoveryException(SR.Discovery_DuplicateMetadataNameValues, member.GetDisplayName(), provider.Name); } } else { Type attrType = attr.GetType(); // Perf optimization, relies on short circuit evaluation, often a property attribute is an ExportAttribute if ((attrType != CompositionServices.ExportAttributeType) && attrType.IsAttributeDefined<MetadataAttributeAttribute>(true)) { bool allowsMultiple = false; AttributeUsageAttribute usage = attrType.GetFirstAttribute<AttributeUsageAttribute>(true); if (usage != null) { allowsMultiple = usage.AllowMultiple; } foreach (PropertyInfo pi in attrType.GetProperties()) { if (pi.DeclaringType == CompositionServices.ExportAttributeType || pi.DeclaringType == CompositionServices.AttributeType) { // Don't contribute metadata properies from the base attribute types. continue; } if (reservedMetadataNames.Contains(pi.Name, StringComparers.MetadataKeyNames)) { throw ExceptionBuilder.CreateDiscoveryException(SR.Discovery_ReservedMetadataNameUsed, member.GetDisplayName(), provider.Name); } object value = pi.GetValue(attr, null); if (value != null && !IsValidAttributeType(value.GetType())) { throw ExceptionBuilder.CreateDiscoveryException(SR.Discovery_MetadataContainsValueWithInvalidType, pi.GetDisplayName(), value.GetType().GetDisplayName()); } if (!dictionary.TryContributeMetadataValue(pi.Name, value, pi.PropertyType, allowsMultiple)) { throw ExceptionBuilder.CreateDiscoveryException(SR.Discovery_DuplicateMetadataNameValues, member.GetDisplayName(), pi.Name); } } } } } // Need Keys.ToArray because we alter the dictionary in the loop foreach (var key in dictionary.Keys.ToArray()) { var list = dictionary[key] as MetadataList; if (list != null) { dictionary[key] = list.ToArray(); } } return; } private static bool TryContributeMetadataValue(this IDictionary<string, object> dictionary, string name, object value, Type valueType, bool allowsMultiple) { object metadataValue; if (!dictionary.TryGetValue(name, out metadataValue)) { if (allowsMultiple) { var list = new MetadataList(); list.Add(value, valueType); value = list; } dictionary.Add(name, value); } else { var list = metadataValue as MetadataList; if (!allowsMultiple || list == null) { // Either single value already found when should be multiple // or a duplicate name already exists dictionary.Remove(name); return false; } list.Add(value, valueType); } return true; } private class MetadataList { private Type _arrayType = null; private bool _containsNulls = false; private static readonly Type ObjectType = typeof(object); private static readonly Type TypeType = typeof(Type); private Collection<object> _innerList = new Collection<object>(); public void Add(object item, Type itemType) { _containsNulls |= (item == null); // if we've been passed typeof(object), we basically have no type inmformation if (itemType == ObjectType) { itemType = null; } // if we have no type information, get it from the item, if we can if ((itemType == null) && (item != null)) { itemType = item.GetType(); } // Types are special, because the are abstract classes, so if the item casts to Type, we assume System.Type if (item is Type) { itemType = TypeType; } // only try to call this if we got a meaningful type if (itemType != null) { InferArrayType(itemType); } _innerList.Add(item); } private void InferArrayType(Type itemType) { Assumes.NotNull(itemType); if (_arrayType == null) { // this is the first typed element we've been given, it sets the type of the array _arrayType = itemType; } else { // if there's a disagreement on the array type, we flip to Object // NOTE : we can try to do better in the future to find common base class, but given that we support very limited set of types // in metadata right now, it's a moot point if (_arrayType != itemType) { _arrayType = ObjectType; } } } public Array ToArray() { if (_arrayType == null) { // if the array type has not been set, assume Object _arrayType = ObjectType; } else if (_containsNulls && _arrayType.IsValueType) { // if the array type is a value type and we have seen nulls, then assume Object _arrayType = ObjectType; } Array array = Array.CreateInstance(_arrayType, _innerList.Count); for(int i = 0; i < array.Length; i++) { array.SetValue(_innerList[i], i); } return array; } } //UNDONE: Need to add these warnings somewhere...Dev10:472538 should address //internal static CompositionResult MatchRequiredMetadata(this IDictionary<string, object> metadata, IEnumerable<string> requiredMetadata, string contractName) //{ // Assumes.IsTrue(metadata != null); // var result = CompositionResult.SucceededResult; // var missingMetadata = (requiredMetadata == null) ? null : requiredMetadata.Except<string>(metadata.Keys); // if (missingMetadata != null && missingMetadata.Any()) // { // result = result.MergeIssue( // CompositionError.CreateIssueAsWarning(CompositionErrorId.RequiredMetadataNotFound, // SR.RequiredMetadataNotFound, // contractName, // string.Join(", ", missingMetadata.ToArray()))); // return new CompositionResult(false, result.Issues); // } // return result; //} internal static IEnumerable<KeyValuePair<string, Type>> GetRequiredMetadata(Type metadataViewType) { if ((metadataViewType == null) || ExportServices.IsDefaultMetadataViewType(metadataViewType) || ExportServices.IsDictionaryConstructorViewType(metadataViewType) || !metadataViewType.IsInterface) { return Enumerable.Empty<KeyValuePair<string, Type>>(); } // A metadata view is required to be an Intrerface, and therefore only properties are allowed List<PropertyInfo> properties = metadataViewType.GetAllProperties(). Where(property => property.GetFirstAttribute<DefaultValueAttribute>() == null). ToList(); // NOTE : this is a carefully found balance between eager and delay-evaluation - the properties are filtered once and upfront // whereas the key/Type pairs are created every time. The latter is fine as KVPs are structs and as such copied on access regardless. // This also allows us to avoid creation of List<KVP> which - at least according to FxCop - leads to isues with NGEN return properties.Select(property => new KeyValuePair<string, Type>(property.Name, property.PropertyType)); } internal static IDictionary<string, object> GetImportMetadata(ImportType importType, IAttributedImport attributedImport) { return GetImportMetadata(importType.ContractType, attributedImport); } internal static IDictionary<string, object> GetImportMetadata(Type type, IAttributedImport attributedImport) { Dictionary<string, object> metadata = null; //Prior to V4.5 MEF did not support ImportMetadata if (type.IsGenericType) { metadata = new Dictionary<string, object>(); if (type.ContainsGenericParameters) { metadata[CompositionConstants.GenericImportParametersOrderMetadataName] = GenericServices.GetGenericParametersOrder(type); } else { metadata[CompositionConstants.GenericContractMetadataName] = ContractNameServices.GetTypeIdentity(type.GetGenericTypeDefinition()); metadata[CompositionConstants.GenericParametersMetadataName] = type.GetGenericArguments(); } } // Default value is ImportSource.Any if (attributedImport != null && attributedImport.Source != ImportSource.Any) { if (metadata == null) { metadata = new Dictionary<string, object>(); } metadata[CompositionConstants.ImportSourceMetadataName] = attributedImport.Source; } if (metadata != null) { return metadata.AsReadOnly(); } else { return MetadataServices.EmptyMetadata; } } internal static object GetExportedValueFromComposedPart(ImportEngine engine, ComposablePart part, ExportDefinition definition) { if (engine != null) { try { engine.SatisfyImports(part); } catch (CompositionException ex) { throw ExceptionBuilder.CreateCannotGetExportedValue(part, definition, ex); } } try { return part.GetExportedValue(definition); } catch (ComposablePartException ex) { throw ExceptionBuilder.CreateCannotGetExportedValue(part, definition, ex); } } internal static bool IsRecomposable(this ComposablePart part) { return part.ImportDefinitions.Any(import => import.IsRecomposable); } internal static CompositionResult TryInvoke(Action action) { try { action(); return CompositionResult.SucceededResult; } catch (CompositionException ex) { return new CompositionResult(ex.Errors); } } internal static CompositionResult TryFire<TEventArgs>(EventHandler<TEventArgs> _delegate, object sender, TEventArgs e) where TEventArgs : EventArgs { CompositionResult result = CompositionResult.SucceededResult; foreach (EventHandler<TEventArgs> _subscriber in _delegate.GetInvocationList()) { try { _subscriber.Invoke(sender, e); } catch (CompositionException ex) { result = result.MergeErrors(ex.Errors); } } return result; } internal static CreationPolicy GetRequiredCreationPolicy(this ImportDefinition definition) { ContractBasedImportDefinition contractDefinition = definition as ContractBasedImportDefinition; if (contractDefinition != null) { return contractDefinition.RequiredCreationPolicy; } return CreationPolicy.Any; } /// <summary> /// Returns a value indicating whether cardinality is /// <see cref="ImportCardinality.ZeroOrOne"/> or /// <see cref="ImportCardinality.ExactlyOne"/>. /// </summary> internal static bool IsAtMostOne(this ImportCardinality cardinality) { return cardinality == ImportCardinality.ZeroOrOne || cardinality == ImportCardinality.ExactlyOne; } private static bool IsValidAttributeType(Type type) { return IsValidAttributeType(type, true); } private static bool IsValidAttributeType(Type type, bool arrayAllowed) { Assumes.NotNull(type); // Definitions of valid attribute type taken from C# 3.0 Specification section 17.1.3. // One of the following types: bool, byte, char, double, float, int, long, sbyte, short, string, uint, ulong, ushort. if (type.IsPrimitive) { return true; } if (type == typeof(string)) { return true; } // An enum type, provided it has public accessibility and the types in which it is nested (if any) also have public accessibility if (type.IsEnum && type.IsVisible) { return true; } if (typeof(Type).IsAssignableFrom(type)) { return true; } // Single-dimensional arrays of the above types. if (arrayAllowed && type.IsArray && type.GetArrayRank() == 1 && IsValidAttributeType(type.GetElementType(), false)) { return true; } return false; } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.Versioning; using System.Xml.Linq; using NuGet.Packages; using NuGet.Resources; namespace NuGet { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] public class ProjectManager : IProjectManager { public event EventHandler<PackageOperationEventArgs> PackageReferenceAdding; public event EventHandler<PackageOperationEventArgs> PackageReferenceAdded; public event EventHandler<PackageOperationEventArgs> PackageReferenceRemoving; public event EventHandler<PackageOperationEventArgs> PackageReferenceRemoved; private ILogger _logger; private IPackageConstraintProvider _constraintProvider; private readonly IPackageReferenceRepository _packageReferenceRepository; private readonly IDictionary<FileTransformExtensions, IPackageFileTransformer> _fileTransformers = new Dictionary<FileTransformExtensions, IPackageFileTransformer>() { { new FileTransformExtensions(".transform", ".transform"), new XmlTransformer(GetConfigMappings()) }, { new FileTransformExtensions(".pp", ".pp"), new Preprocessor() }, { new FileTransformExtensions(".install.xdt", ".uninstall.xdt"), new XdtTransformer() } }; public ProjectManager(IPackageRepository sourceRepository, IPackagePathResolver pathResolver, IProjectSystem project, IPackageRepository localRepository) { if (sourceRepository == null) { throw new ArgumentNullException("sourceRepository"); } if (pathResolver == null) { throw new ArgumentNullException("pathResolver"); } if (project == null) { throw new ArgumentNullException("project"); } if (localRepository == null) { throw new ArgumentNullException("localRepository"); } SourceRepository = sourceRepository; Project = project; PathResolver = pathResolver; LocalRepository = localRepository; _packageReferenceRepository = LocalRepository as IPackageReferenceRepository; DependencyVersion = DependencyVersion.Lowest; } public IPackagePathResolver PathResolver { get; private set; } public IPackageRepository LocalRepository { get; private set; } public IPackageRepository SourceRepository { get; private set; } public IPackageConstraintProvider ConstraintProvider { get { return _constraintProvider ?? NullConstraintProvider.Instance; } set { _constraintProvider = value; } } public IProjectSystem Project { get; private set; } public ILogger Logger { get { return _logger ?? NullLogger.Instance; } set { _logger = value; } } public DependencyVersion DependencyVersion { get; set; } public bool WhatIf { get; set; } public bool AllowDowngradeFromPrerelease { get; set; } /// <summary> /// Seems to be used by unit tests only. Perhaps, consumers of NuGet.Core may be using this overload /// </summary> public virtual void AddPackageReference(string packageId) { AddPackageReference(packageId, version: null, ignoreDependencies: false, allowPrereleaseVersions: false); } public virtual void AddPackageReference(string packageId, SemanticVersion version) { AddPackageReference(packageId, version: version, ignoreDependencies: false, allowPrereleaseVersions: false); } public virtual void AddPackageReference(string packageId, SemanticVersion version, bool ignoreDependencies, bool allowPrereleaseVersions) { IPackage package = PackageRepositoryHelper.ResolvePackage(SourceRepository, LocalRepository, NullConstraintProvider.Instance, packageId, version, allowPrereleaseVersions); AddPackageReference(package, ignoreDependencies, allowPrereleaseVersions); } public virtual void AddPackageReference(IPackage package, bool ignoreDependencies, bool allowPrereleaseVersions) { // In case of a scenario like UpdateAll, the graph has already been walked once for all the packages as a bulk operation // But, we walk here again, just for a single package, since, we need to use UpdateWalker for project installs // unlike simple package installs for which InstallWalker is used // Also, it is noteworthy that the DependentsWalker has the same TargetFramework as the package in PackageReferenceRepository // unlike the UpdateWalker whose TargetFramework is the same as that of the Project // This makes it harder to perform a bulk operation for AddPackageReference and we have to go package by package var dependentsWalker = new DependentsWalker(LocalRepository, GetPackageTargetFramework(package.Id)) { DependencyVersion = DependencyVersion }; Execute(package, new UpdateWalker(LocalRepository, SourceRepository, dependentsWalker, ConstraintProvider, Project.TargetFramework, NullLogger.Instance, !ignoreDependencies, allowPrereleaseVersions) { DisableWalkInfo = WhatIf, AcceptedTargets = PackageTargets.Project, DependencyVersion = DependencyVersion, AllowDowngradeFromPrerelease = AllowDowngradeFromPrerelease }); } private void Execute(IPackage package, IPackageOperationResolver resolver) { IEnumerable<PackageOperation> operations = resolver.ResolveOperations(package); if (operations.Any()) { HashSet<string> fullyRemoved=new HashSet<string>(); if (resolver is UpdateWalker) //in update we will disable package removal (same behaviour as Nuget 3.0) foreach (PackageOperation operation in operations) { if (operation.Action == PackageAction.Uninstall) { fullyRemoved.Add(operation.Package.Id); } else //install { fullyRemoved.Remove(operation.Package.Id); } } foreach (PackageOperation operation in operations) { if (fullyRemoved.Contains(operation.Package.Id)) { Logger.Log(MessageLevel.Warning,"Package {0} is trying to fully remove package {1} without replacement (probably due to change in dependencies). Disabling removal.",package,operation.Package); continue; } Execute(operation); } } else if (LocalRepository.Exists(package)) { Logger.Log(MessageLevel.Info, NuGetResources.Log_ProjectAlreadyReferencesPackage, Project.ProjectName, package.GetFullName()); } } protected void Execute(PackageOperation operation) { bool packageExists = LocalRepository.Exists(operation.Package); if (operation.Action == PackageAction.Install) { // If the package is already installed, then skip it if (packageExists) { Logger.Log(MessageLevel.Info, NuGetResources.Log_ProjectAlreadyReferencesPackage, Project.ProjectName, operation.Package.GetFullName()); } else { if (WhatIf) { Logger.Log( MessageLevel.Info, NuGetResources.Log_InstallPackageIntoProject, operation.Package, Project.ProjectName); PackageOperationEventArgs args = CreateOperation(operation.Package); OnPackageReferenceAdding(args); } else { AddPackageReferenceToProject(operation.Package); } } } else { if (packageExists) { if (WhatIf) { Logger.Log( MessageLevel.Info, NuGetResources.Log_UninstallPackageFromProject, operation.Package, Project.ProjectName); PackageOperationEventArgs args = CreateOperation(operation.Package); OnPackageReferenceRemoved(args); } else { RemovePackageReferenceFromProject(operation.Package); } } } } protected void AddPackageReferenceToProject(IPackage package) { string packageFullName = package.GetFullName(); Console.WriteLine(NuGetResources.Log_BeginAddPackageReference, packageFullName, Project.ProjectName); IPackagePhysicalPathInfo physicalPath=package as IPackagePhysicalPathInfo; if (physicalPath!=null) Console.WriteLine("\tUsing package source {0}",physicalPath.PhysicalFilePath); PackageOperationEventArgs args = CreateOperation(package); OnPackageReferenceAdding(args); if (args.Cancel) { return; } ExtractPackageFilesToProject(package); Logger.Log(MessageLevel.Info, NuGetResources.Log_SuccessfullyAddedPackageReference, packageFullName, Project.ProjectName); OnPackageReferenceAdded(args); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] protected virtual void ExtractPackageFilesToProject(IPackage package) { // BUG 491: Installing a package with incompatible binaries still does a partial install. // Resolve assembly references and content files first so that if this fails we never do anything to the project List<IPackageAssemblyReference> assemblyReferences = Project.GetCompatibleItemsCore(package.AssemblyReferences).ToList(); List<FrameworkAssemblyReference> frameworkReferences = Project.GetCompatibleItemsCore(package.FrameworkAssemblies).ToList(); List<IPackageFile> contentFiles = Project.GetCompatibleItemsCore(package.GetContentFiles()).ToList(); List<IPackageFile> buildFiles = Project.GetCompatibleItemsCore(package.GetBuildFiles()).ToList(); // If the package doesn't have any compatible assembly references or content files, // throw, unless it's a meta package. if (assemblyReferences.Count == 0 && frameworkReferences.Count == 0 && contentFiles.Count == 0 && buildFiles.Count == 0 && (package.FrameworkAssemblies.Any() || package.AssemblyReferences.Any() || package.GetContentFiles().Any() || package.GetBuildFiles().Any())) { // for portable framework, we want to show the friendly short form (e.g. portable-win8+net45+wp8) instead of ".NETPortable, Profile=Profile104". FrameworkName targetFramework = Project.TargetFramework; string targetFrameworkString = targetFramework.IsPortableFramework() ? VersionUtility.GetShortFrameworkName(targetFramework) : targetFramework != null ? targetFramework.ToString() : null; throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, NuGetResources.UnableToFindCompatibleItems, package.GetFullName(), targetFrameworkString)); } // IMPORTANT: this filtering has to be done AFTER the 'if' statement above, // so that we don't throw the exception in case the <References> filters out all assemblies. FilterAssemblyReferences(assemblyReferences, package.PackageAssemblyReferences); try { // Log target framework info for debugging LogTargetFrameworkInfo(package, assemblyReferences, contentFiles, buildFiles); // Add content files Project.AddFiles(contentFiles, _fileTransformers); // Add the references to the reference path foreach (IPackageAssemblyReference assemblyReference in assemblyReferences) { if (assemblyReference.IsEmptyFolder()) { continue; } // Get the physical path of the assembly reference string referencePath = Path.Combine(PathResolver.GetInstallPath(package), assemblyReference.Path); string relativeReferencePath = PathUtility.GetRelativePath(Project.Root, referencePath); if (Project.ReferenceExists(assemblyReference.Name)) { Project.RemoveReference(assemblyReference.Name); } // The current implementation of all ProjectSystem does not use the Stream parameter at all. // We can't change the API now, so just pass in a null stream. Project.AddReference(relativeReferencePath, Stream.Null); } // Add GAC/Framework references foreach (FrameworkAssemblyReference frameworkReference in frameworkReferences) { if (!Project.ReferenceExists(frameworkReference.AssemblyName)) { Project.AddFrameworkReference(frameworkReference.AssemblyName); } } foreach (var importFile in buildFiles) { string fullImportFilePath = Path.Combine(PathResolver.GetInstallPath(package), importFile.Path); Project.AddImport( fullImportFilePath, importFile.Path.EndsWith(".props", StringComparison.OrdinalIgnoreCase) ? ProjectImportLocation.Top : ProjectImportLocation.Bottom); } } finally { if (_packageReferenceRepository != null) { // save the used project's framework if the repository supports it. _packageReferenceRepository.AddPackage(package.Id, package.Version, package.DevelopmentDependency, Project.TargetFramework); } else { // Add package to local repository in the finally so that the user can uninstall it // if any exception occurs. This is easier than rolling back since the user can just // manually uninstall things that may have failed. // If this fails then the user is out of luck. LocalRepository.AddPackage(package); } } } private void LogTargetFrameworkInfo(IPackage package, List<IPackageAssemblyReference> assemblyReferences, List<IPackageFile> contentFiles, List<IPackageFile> buildFiles) { if (assemblyReferences.Count > 0 || contentFiles.Count > 0 || buildFiles.Count > 0) { // targetFramework can be null for unknown project types string shortFramework = Project.TargetFramework == null ? string.Empty : VersionUtility.GetShortFrameworkName(Project.TargetFramework); Logger.Log(MessageLevel.Debug, NuGetResources.Debug_TargetFrameworkInfoPrefix, package.GetFullName(), Project.ProjectName, shortFramework); if (assemblyReferences.Count > 0) { Logger.Log(MessageLevel.Debug, NuGetResources.Debug_TargetFrameworkInfo, NuGetResources.Debug_TargetFrameworkInfo_AssemblyReferences, Path.GetDirectoryName(assemblyReferences[0].Path), VersionUtility.GetTargetFrameworkLogString(assemblyReferences[0].TargetFramework)); } if (contentFiles.Count > 0) { Logger.Log(MessageLevel.Debug, NuGetResources.Debug_TargetFrameworkInfo, NuGetResources.Debug_TargetFrameworkInfo_ContentFiles, Path.GetDirectoryName(contentFiles[0].Path), VersionUtility.GetTargetFrameworkLogString(contentFiles[0].TargetFramework)); } if (buildFiles.Count > 0) { Logger.Log(MessageLevel.Debug, NuGetResources.Debug_TargetFrameworkInfo, NuGetResources.Debug_TargetFrameworkInfo_BuildFiles, Path.GetDirectoryName(buildFiles[0].Path), VersionUtility.GetTargetFrameworkLogString(buildFiles[0].TargetFramework)); } } } private void FilterAssemblyReferences(List<IPackageAssemblyReference> assemblyReferences, ICollection<PackageReferenceSet> packageAssemblyReferences) { if (packageAssemblyReferences != null && packageAssemblyReferences.Count > 0) { var packageReferences = Project.GetCompatibleItemsCore(packageAssemblyReferences).FirstOrDefault(); if (packageReferences != null) { // remove all assemblies of which names do not appear in the References list assemblyReferences.RemoveAll(assembly => !packageReferences.References.Contains(assembly.Name, StringComparer.OrdinalIgnoreCase)); } } } public bool IsInstalled(IPackage package) { return LocalRepository.Exists(package); } public void RemovePackageReference(string packageId) { RemovePackageReference(packageId, forceRemove: false, removeDependencies: false); } public void RemovePackageReference(string packageId, bool forceRemove) { RemovePackageReference(packageId, forceRemove: forceRemove, removeDependencies: false); } public virtual void RemovePackageReference(string packageId, bool forceRemove, bool removeDependencies) { if (String.IsNullOrEmpty(packageId)) { throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId"); } IPackage package = LocalRepository.FindPackage(packageId); if (package == null) { throw new InvalidOperationException(String.Format( CultureInfo.CurrentCulture, NuGetResources.UnknownPackage, packageId)); } RemovePackageReference(package, forceRemove, removeDependencies); } public virtual void RemovePackageReference(IPackage package, bool forceRemove, bool removeDependencies) { FrameworkName targetFramework = GetPackageTargetFramework(package.Id); Execute(package, new UninstallWalker(LocalRepository, new DependentsWalker(LocalRepository, targetFramework), targetFramework, NullLogger.Instance, removeDependencies, forceRemove)); } [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] private void RemovePackageReferenceFromProject(IPackage package) { string packageFullName = package.GetFullName(); Logger.Log(MessageLevel.Info, NuGetResources.Log_BeginRemovePackageReference, packageFullName, Project.ProjectName); PackageOperationEventArgs args = CreateOperation(package); OnPackageReferenceRemoving(args); if (args.Cancel) { return; } // Get other packages IEnumerable<IPackage> otherPackages = from p in LocalRepository.GetPackages() where p.Id != package.Id select p; // Get other references var otherAssemblyReferences = from p in otherPackages let assemblyReferences = GetFilteredAssembliesToDelete(p) from assemblyReference in assemblyReferences ?? Enumerable.Empty<IPackageAssemblyReference>() // This can happen if package installed left the project in a bad state select assemblyReference; // Get content files from other packages // Exclude transform files since they are treated specially var otherContentFiles = from p in otherPackages from file in GetCompatibleInstalledItemsForPackage(p.Id, p.GetContentFiles()) where !IsTransformFile(file.Path) select file; // Get the files and references for this package, that aren't in use by any other packages so we don't have to do reference counting var assemblyReferencesToDelete = GetFilteredAssembliesToDelete(package) .Except(otherAssemblyReferences, PackageFileComparer.Default); var contentFilesToDelete = GetCompatibleInstalledItemsForPackage(package.Id, package.GetContentFiles()) .Except(otherContentFiles, PackageFileComparer.Default); var buildFilesToDelete = GetCompatibleInstalledItemsForPackage(package.Id, package.GetBuildFiles()); // Delete the content files Project.DeleteFiles(contentFilesToDelete, otherPackages, _fileTransformers); // Remove references foreach (IPackageAssemblyReference assemblyReference in assemblyReferencesToDelete) { Project.RemoveReference(assemblyReference.Name); } // remove the <Import> statement from projects for the .targets and .props files foreach (var importFile in buildFilesToDelete) { string fullImportFilePath = Path.Combine(PathResolver.GetInstallPath(package), importFile.Path); Project.RemoveImport(fullImportFilePath); Project.RemoveImport(package.Id+"*"+importFile.Path); } // Remove package to the repository LocalRepository.RemovePackage(package); Logger.Log(MessageLevel.Info, NuGetResources.Log_SuccessfullyRemovedPackageReference, packageFullName, Project.ProjectName); OnPackageReferenceRemoved(args); } private bool IsTransformFile(string path) { return _fileTransformers.Keys.Any( file => path.EndsWith(file.InstallExtension, StringComparison.OrdinalIgnoreCase) || path.EndsWith(file.UninstallExtension, StringComparison.OrdinalIgnoreCase)); } private IList<IPackageAssemblyReference> GetFilteredAssembliesToDelete(IPackage package) { List<IPackageAssemblyReference> assemblyReferences = GetCompatibleInstalledItemsForPackage(package.Id, package.AssemblyReferences).ToList(); if (assemblyReferences.Count == 0) { return assemblyReferences; } var packageReferences = GetCompatibleInstalledItemsForPackage(package.Id, package.PackageAssemblyReferences).FirstOrDefault(); if (packageReferences != null) { assemblyReferences.RemoveAll(p => !packageReferences.References.Contains(p.Name, StringComparer.OrdinalIgnoreCase)); } return assemblyReferences; } /// <summary> /// Seems to be used by unit tests only. Perhaps, consumers of NuGet.Core may be using this overload /// </summary> internal void UpdatePackageReference(string packageId) { UpdatePackageReference(packageId, version: null, updateDependencies: true, allowPrereleaseVersions: false); } /// <summary> /// Seems to be used by unit tests only. Perhaps, consumers of NuGet.Core may be using this overload /// </summary> internal void UpdatePackageReference(string packageId, SemanticVersion version) { UpdatePackageReference(packageId, version: version, updateDependencies: true, allowPrereleaseVersions: false); } public void UpdatePackageReference(string packageId, IVersionSpec versionSpec, bool updateDependencies, bool allowPrereleaseVersions) { UpdatePackageReference( packageId, () => SourceRepository.FindPackage(packageId, versionSpec, ConstraintProvider, allowPrereleaseVersions, allowUnlisted: false), updateDependencies, allowPrereleaseVersions, targetVersionSetExplicitly: versionSpec != null); } /// <summary> /// If the remote package is already determined, consider using the overload which directly takes in the remote package /// Can avoid calls FindPackage calls to source repository. However, it should also be remembered that SourceRepository of ProjectManager /// is an aggregate of "SharedPackageRepository" and the selected repository. So, if the package is present on the repository path (by default, the packages folder) /// It would not result in a call to the server /// </summary> public virtual void UpdatePackageReference(string packageId, SemanticVersion version, bool updateDependencies, bool allowPrereleaseVersions) { UpdatePackageReference(packageId, () => SourceRepository.FindPackage(packageId, version, ConstraintProvider, allowPrereleaseVersions, allowUnlisted: false), updateDependencies, allowPrereleaseVersions, targetVersionSetExplicitly: version != null); } private void UpdatePackageReference(string packageId, Func<IPackage> resolvePackage, bool updateDependencies, bool allowPrereleaseVersions, bool targetVersionSetExplicitly) { if (String.IsNullOrEmpty(packageId)) { throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId"); } IPackage oldPackage = LocalRepository.FindPackage(packageId); // Check to see if this package is installed if (oldPackage == null) { throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, NuGetResources.ProjectDoesNotHaveReference, Project.ProjectName, packageId)); } Logger.Log(MessageLevel.Debug, NuGetResources.Debug_LookingForUpdates, packageId); IPackage package = resolvePackage(); // the condition (allowPrereleaseVersions || targetVersionSetExplicitly || oldPackage.IsReleaseVersion() || !package.IsReleaseVersion() || oldPackage.Version < package.Version) // is to fix bug 1574. We want to do nothing if, let's say, you have package 2.0alpha installed, and you do: // update-package // without specifying a version explicitly, and the feed only has version 1.0 as the latest stable version. if (package != null && oldPackage.Version != package.Version && (allowPrereleaseVersions || targetVersionSetExplicitly || AllowDowngradeFromPrerelease || oldPackage.IsReleaseVersion() || !package.IsReleaseVersion() || oldPackage.Version < package.Version)) { Logger.Log(MessageLevel.Info, NuGetResources.Log_UpdatingPackages, package.Id, oldPackage.Version, package.Version, Project.ProjectName); UpdatePackageReferenceCore(package, updateDependencies, allowPrereleaseVersions); } else { IVersionSpec constraint = ConstraintProvider.GetConstraint(packageId); if (constraint != null) { Logger.Log(MessageLevel.Info, NuGetResources.Log_ApplyingConstraints, packageId, VersionUtility.PrettyPrint(constraint), ConstraintProvider.Source); } Logger.Log(MessageLevel.Info, NuGetResources.Log_NoUpdatesAvailableForProject, packageId, Project.ProjectName); } } public virtual void UpdatePackageReference(IPackage remotePackage, bool updateDependencies, bool allowPrereleaseVersions) { Logger.Log(MessageLevel.Info, NuGetResources.Log_UpdatingPackagesWithoutOldVersion, remotePackage.Id, remotePackage.Version, Project.ProjectName); UpdatePackageReferenceCore(remotePackage, updateDependencies, allowPrereleaseVersions); } protected void UpdatePackageReference(IPackage package) { UpdatePackageReferenceCore(package, updateDependencies: true, allowPrereleaseVersions: false); } private void UpdatePackageReferenceCore(IPackage package, bool updateDependencies, bool allowPrereleaseVersions) { AddPackageReference(package, !updateDependencies, allowPrereleaseVersions); } private void OnPackageReferenceAdding(PackageOperationEventArgs e) { if (PackageReferenceAdding != null) { PackageReferenceAdding(this, e); } } private void OnPackageReferenceAdded(PackageOperationEventArgs e) { if (PackageReferenceAdded != null) { PackageReferenceAdded(this, e); } } private void OnPackageReferenceRemoved(PackageOperationEventArgs e) { if (PackageReferenceRemoved != null) { PackageReferenceRemoved(this, e); } } private void OnPackageReferenceRemoving(PackageOperationEventArgs e) { if (PackageReferenceRemoving != null) { PackageReferenceRemoving(this, e); } } private FrameworkName GetPackageTargetFramework(string packageId) { if (_packageReferenceRepository != null) { return _packageReferenceRepository.GetPackageTargetFramework(packageId) ?? Project.TargetFramework; } return Project.TargetFramework; } /// <summary> /// This method uses the 'targetFramework' attribute in the packages.config to determine compatible items. /// Hence, it's only good for uninstall operations. /// </summary> private IEnumerable<T> GetCompatibleInstalledItemsForPackage<T>(string packageId, IEnumerable<T> items) where T : IFrameworkTargetable { FrameworkName packageFramework = GetPackageTargetFramework(packageId); if (packageFramework == null) { return items; } IEnumerable<T> compatibleItems; if (VersionUtility.TryGetCompatibleItems(packageFramework, items, out compatibleItems)) { return compatibleItems; } return Enumerable.Empty<T>(); } private PackageOperationEventArgs CreateOperation(IPackage package) { return new PackageOperationEventArgs(package, Project, PathResolver.GetInstallPath(package)); } private static IDictionary<XName, Action<XElement, XElement>> GetConfigMappings() { // REVIEW: This might be an edge case, but we're setting this rule for all xml files. // If someone happens to do a transform where the xml file has a configSections node // we will add it first. This is probably fine, but this is a config specific scenario return new Dictionary<XName, Action<XElement, XElement>>() { { "configSections" , (parent, element) => parent.AddFirst(element) } }; } private class PackageFileComparer : IEqualityComparer<IPackageFile> { internal readonly static PackageFileComparer Default = new PackageFileComparer(); private PackageFileComparer() { } public bool Equals(IPackageFile x, IPackageFile y) { // technically, this check will fail if, for example, 'x' is a content file and 'y' is a lib file. // However, because we only use this comparer to compare files within the same folder type, // this check is sufficient. return x.TargetFramework == y.TargetFramework && x.EffectivePath.Equals(y.EffectivePath, StringComparison.OrdinalIgnoreCase); } public int GetHashCode(IPackageFile obj) { return obj.Path.GetHashCode(); } } } }
/* * REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application * * The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or other piece of equipment they want to hire out to the transportation ministry for day labour and emergency projects. The Hired Equipment Program distributes available work to local equipment owners. The program is based on seniority and is designed to deliver work to registered users fairly and efficiently through the development of local area call-out lists. * * OpenAPI spec version: v1 * * */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; using HETSAPI.Models; namespace HETSAPI.ViewModels { /// <summary> /// /// </summary> [DataContract] public partial class UserFavouriteViewModel : IEquatable<UserFavouriteViewModel> { /// <summary> /// Default constructor, required by entity framework /// </summary> public UserFavouriteViewModel() { } /// <summary> /// Initializes a new instance of the <see cref="UserFavouriteViewModel" /> class. /// </summary> /// <param name="Id">Id.</param> /// <param name="Name">Context Name.</param> /// <param name="Value">Saved search.</param> /// <param name="IsDefault">IsDefault.</param> /// <param name="Type">Type of favourite.</param> public UserFavouriteViewModel(int? Id = null, string Name = null, string Value = null, bool? IsDefault = null, string Type = null) { this.Id = Id; this.Name = Name; this.Value = Value; this.IsDefault = IsDefault; this.Type = Type; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id")] public int? Id { get; set; } /// <summary> /// Context Name /// </summary> /// <value>Context Name</value> [DataMember(Name="name")] [MetaDataExtension (Description = "Context Name")] public string Name { get; set; } /// <summary> /// Saved search /// </summary> /// <value>Saved search</value> [DataMember(Name="value")] [MetaDataExtension (Description = "Saved search")] public string Value { get; set; } /// <summary> /// Gets or Sets IsDefault /// </summary> [DataMember(Name="isDefault")] public bool? IsDefault { get; set; } /// <summary> /// Type of favourite /// </summary> /// <value>Type of favourite</value> [DataMember(Name="type")] [MetaDataExtension (Description = "Type of favourite")] public string Type { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class UserFavouriteViewModel {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Value: ").Append(Value).Append("\n"); sb.Append(" IsDefault: ").Append(IsDefault).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((UserFavouriteViewModel)obj); } /// <summary> /// Returns true if UserFavouriteViewModel instances are equal /// </summary> /// <param name="other">Instance of UserFavouriteViewModel to be compared</param> /// <returns>Boolean</returns> public bool Equals(UserFavouriteViewModel other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.Value == other.Value || this.Value != null && this.Value.Equals(other.Value) ) && ( this.IsDefault == other.IsDefault || this.IsDefault != null && this.IsDefault.Equals(other.IsDefault) ) && ( this.Type == other.Type || this.Type != null && this.Type.Equals(other.Type) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks if (this.Id != null) { hash = hash * 59 + this.Id.GetHashCode(); } if (this.Name != null) { hash = hash * 59 + this.Name.GetHashCode(); } if (this.Value != null) { hash = hash * 59 + this.Value.GetHashCode(); } if (this.IsDefault != null) { hash = hash * 59 + this.IsDefault.GetHashCode(); } if (this.Type != null) { hash = hash * 59 + this.Type.GetHashCode(); } return hash; } } #region Operators /// <summary> /// Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator ==(UserFavouriteViewModel left, UserFavouriteViewModel right) { return Equals(left, right); } /// <summary> /// Not Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator !=(UserFavouriteViewModel left, UserFavouriteViewModel right) { return !Equals(left, right); } #endregion Operators } }
// 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: Pointer Type to a EEType in the runtime. ** ** ===========================================================*/ using System.Runtime; using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using EEType = Internal.Runtime.EEType; using EETypeRef = Internal.Runtime.EETypeRef; namespace System { [StructLayout(LayoutKind.Sequential)] internal unsafe struct EETypePtr : IEquatable<EETypePtr> { private EEType* _value; public EETypePtr(IntPtr value) { _value = (EEType*)value; } internal EEType* ToPointer() { return _value; } public override bool Equals(Object obj) { if (obj is EETypePtr) { return this == (EETypePtr)obj; } return false; } public bool Equals(EETypePtr p) { return this == p; } public static bool operator ==(EETypePtr value1, EETypePtr value2) { if (value1.IsNull) return value2.IsNull; else if (value2.IsNull) return false; else return RuntimeImports.AreTypesEquivalent(value1, value2); } public static bool operator !=(EETypePtr value1, EETypePtr value2) { return !(value1 == value2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() { return (int)_value->HashCode; } // // Faster version of Equals for use on EETypes that are known not to be null and where the "match" case is the hot path. // public bool FastEquals(EETypePtr other) { Debug.Assert(!this.IsNull); Debug.Assert(!other.IsNull); // Fast check for raw equality before making call to helper. if (this.RawValue == other.RawValue) return true; return RuntimeImports.AreTypesEquivalent(this, other); } // Caution: You cannot safely compare RawValue's as RH does NOT unify EETypes. Use the == or Equals() methods exposed by EETypePtr itself. internal IntPtr RawValue { get { return (IntPtr)_value; } } internal bool IsNull { get { return _value == null; } } internal bool IsArray { get { return _value->IsArray; } } internal bool IsSzArray { get { return _value->IsSzArray; } } internal bool IsPointer { get { return _value->IsPointerType; } } internal bool IsByRef { get { return _value->IsByRefType; } } internal bool IsValueType { get { return _value->IsValueType; } } internal bool IsString { get { // String is currently the only non-array type with a non-zero component size. return (_value->ComponentSize == sizeof(char)) && !_value->IsArray && !_value->IsGenericTypeDefinition; } } internal bool IsPrimitive { get { RuntimeImports.RhCorElementType et = CorElementType; return ((et >= RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN) && (et <= RuntimeImports.RhCorElementType.ELEMENT_TYPE_R8)) || (et == RuntimeImports.RhCorElementType.ELEMENT_TYPE_I) || (et == RuntimeImports.RhCorElementType.ELEMENT_TYPE_U); } } internal bool IsEnum { get { // Q: When is an enum type a constructed generic type? // A: When it's nested inside a generic type. if (!(IsDefType)) return false; EETypePtr baseType = this.BaseType; return baseType == EETypePtr.EETypePtrOf<Enum>(); } } /// <summary> /// Gets a value indicating whether this is a generic type definition (an uninstantiated generic type). /// </summary> internal bool IsGenericTypeDefinition { get { return _value->IsGenericTypeDefinition; } } /// <summary> /// Gets a value indicating whether this is an instantiated generic type. /// </summary> internal bool IsGeneric { get { return _value->IsGeneric; } } internal GenericArgumentCollection Instantiation { get { return new GenericArgumentCollection(_value->GenericArity, _value->GenericArguments); } } internal EETypePtr GenericDefinition { get { return new EETypePtr((IntPtr)_value->GenericDefinition); } } /// <summary> /// Gets a value indicating whether this is a class, a struct, an enum, or an interface. /// </summary> internal bool IsDefType { get { return !_value->IsParameterizedType; } } internal bool IsDynamicType { get { return _value->IsDynamicType; } } internal bool IsInterface { get { return _value->IsInterface; } } internal bool IsAbstract { get { return _value->IsAbstract; } } internal bool IsNullable { get { return _value->IsNullable; } } internal bool HasCctor { get { return _value->HasCctor; } } internal EETypePtr NullableType { get { return new EETypePtr((IntPtr)_value->NullableType); } } internal EETypePtr ArrayElementType { get { return new EETypePtr((IntPtr)_value->RelatedParameterType); } } internal int ArrayRank { get { return _value->ArrayRank; } } internal InterfaceCollection Interfaces { get { return new InterfaceCollection(_value); } } internal EETypePtr BaseType { get { if (IsArray) return EETypePtr.EETypePtrOf<Array>(); if (IsPointer || IsByRef) return new EETypePtr(default(IntPtr)); EETypePtr baseEEType = new EETypePtr((IntPtr)_value->NonArrayBaseType); return baseEEType; } } internal ushort ComponentSize { get { return _value->ComponentSize; } } internal uint BaseSize { get { return _value->BaseSize; } } // Has internal gc pointers. internal bool HasPointers { get { return _value->HasGCPointers; } } internal uint ValueTypeSize { get { return _value->ValueTypeSize; } } internal RuntimeImports.RhCorElementType CorElementType { get { Debug.Assert((int)Internal.Runtime.CorElementType.ELEMENT_TYPE_I1 == (int)RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1); Debug.Assert((int)Internal.Runtime.CorElementType.ELEMENT_TYPE_R8 == (int)RuntimeImports.RhCorElementType.ELEMENT_TYPE_R8); return (RuntimeImports.RhCorElementType)_value->CorElementType; } } internal RuntimeImports.RhCorElementTypeInfo CorElementTypeInfo { get { RuntimeImports.RhCorElementType corElementType = this.CorElementType; return RuntimeImports.GetRhCorElementTypeInfo(corElementType); } } [Intrinsic] internal static EETypePtr EETypePtrOf<T>() { // Compilers are required to provide a low level implementation of this method. // This can be achieved by optimizing away the reflection part of this implementation // by optimizing typeof(!!0).TypeHandle into "ldtoken !!0", or by // completely replacing the body of this method. return typeof(T).TypeHandle.ToEETypePtr(); } public struct InterfaceCollection { private EEType* _value; internal InterfaceCollection(EEType* value) { _value = value; } public int Count { get { return _value->NumInterfaces; } } public EETypePtr this[int index] { get { Debug.Assert((uint)index < _value->NumInterfaces); EEType* interfaceType = _value->InterfaceMap[index].InterfaceType; return new EETypePtr((IntPtr)interfaceType); } } } public struct GenericArgumentCollection { private EETypeRef* _arguments; private uint _argumentCount; internal GenericArgumentCollection(uint argumentCount, EETypeRef* arguments) { _argumentCount = argumentCount; _arguments = arguments; } public int Length { get { return (int)_argumentCount; } } public EETypePtr this[int index] { get { Debug.Assert((uint)index < _argumentCount); return new EETypePtr((IntPtr)_arguments[index].Value); } } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Xml.Serialization; namespace Wyam.Feeds.Syndication.Atom { /// <summary> /// http://tools.ietf.org/html/rfc4287#section-4.1.2 /// </summary> /// <remarks> /// atomEntry : atomBase /// atomContent? /// atomPublished? /// atomSource? /// atomSummary? /// </remarks> [Serializable] public class AtomEntry : AtomBase, IFeedItem { private AtomContent _content = null; private AtomDate _published; private AtomSource _source = null; private AtomText _summary = null; private int? _threadTotal = null; public AtomEntry() { } public AtomEntry(IFeedItem source) { // ** IFeedMetadata // ID Id = source.ID.ToString(); // Title string title = source.Title; if (!string.IsNullOrWhiteSpace(title)) { Title = title; } // Description string description = source.Description; if (!string.IsNullOrEmpty(description)) { Summary = description; } // Author string author = source.Author; if (!string.IsNullOrEmpty(author)) { Authors.Add(new AtomPerson { Name = author }); } // Published DateTime? published = source.Published; if (published.HasValue) { Updated = published.Value; } // Updated DateTime? updated = source.Updated; if (updated.HasValue) { Updated = updated.Value; } // Link Uri link = source.Link; if (link != null) { Links.Add(new AtomLink(link.ToString())); } // ImageLink Uri imageLink = source.ImageLink; if (imageLink != null) { Links.Add(new AtomLink { Type = "image", Href = imageLink.ToString(), Relation = AtomLinkRelation.Enclosure }); } // ** IFeedItem // Content string content = source.Content; if (!string.IsNullOrEmpty(content)) { Content = new AtomContent(content); } // ThreadLink Uri threadLink = source.ThreadLink; AtomLink replies = null; if (threadLink != null) { replies = new AtomLink { Href = threadLink.ToString(), Relation = AtomLinkRelation.Replies }; Links.Add(replies); } // ThreadCount int? threadCount = source.ThreadCount; if (threadCount.HasValue && replies != null) { replies.ThreadCount = threadCount.Value; } // ThreadUpdated DateTime? threadUpdated = source.ThreadUpdated; if (threadUpdated.HasValue && replies != null) { replies.ThreadUpdated = threadUpdated.Value; } } [DefaultValue(null)] [XmlElement("content")] public AtomContent Content { get { return _content; } set { _content = value; } } [DefaultValue(null)] [XmlElement("published")] public virtual AtomDate Published { get { return _published; } set { _published = value; } } [XmlIgnore] public virtual bool PublishedSpecified { get { return _published.HasValue; } set { } } [DefaultValue(null)] [XmlElement("source")] public AtomSource Source { get { return _source; } set { _source = value; } } [DefaultValue(null)] [XmlElement("summary")] public AtomText Summary { get { return _summary; } set { _summary = value; } } [XmlElement("in-reply-to", Namespace=ThreadingNamespace)] public readonly List<AtomInReplyTo> InReplyToReferences = new List<AtomInReplyTo>(); [XmlIgnore] public bool InReplyToReferencesSpecified { get { return (InReplyToReferences.Count > 0); } set { } } /// <summary> /// http://tools.ietf.org/html/rfc4685#section-5 /// </summary> [XmlElement(ElementName="total", Namespace=ThreadingNamespace)] public int ThreadTotal { get { if (!_threadTotal.HasValue) { return 0; } return _threadTotal.Value; } set { if (value < 0) { _threadTotal = null; } else { _threadTotal = value; } } } [XmlIgnore] public bool ThreadTotalSpecified { get { return _threadTotal.HasValue; } set { } } Uri IFeedMetadata.ID => ((IUriProvider)this).Uri; string IFeedMetadata.Title { get { if (Title == null) { return null; } return Title.StringValue; } } string IFeedMetadata.Description => _summary == null ? _content?.StringValue : _summary.StringValue; string IFeedMetadata.Author { get { if (!AuthorsSpecified) { if (!ContributorsSpecified) { return null; } foreach (AtomPerson person in Contributors) { if (!string.IsNullOrEmpty(person.Name)) { return person.Name; } if (!string.IsNullOrEmpty(person.Email)) { return person.Name; } } } foreach (AtomPerson person in Authors) { if (!string.IsNullOrEmpty(person.Name)) { return person.Name; } if (!string.IsNullOrEmpty(person.Email)) { return person.Name; } } return null; } } DateTime? IFeedMetadata.Published { get { if (!Published.HasValue) { return ((IFeedMetadata)this).Updated; } return Published.Value; } } DateTime? IFeedMetadata.Updated { get { if (!Updated.HasValue) { return null; } return Updated.Value; } } Uri IFeedMetadata.Link { get { if (!LinksSpecified) { return null; } Uri alternate = null; foreach (AtomLink link in Links) { switch (link.Relation) { case AtomLinkRelation.Alternate: { return ((IUriProvider)link).Uri; } case AtomLinkRelation.Related: case AtomLinkRelation.Enclosure: { if (alternate == null) { alternate = ((IUriProvider)link).Uri; } break; } default: { continue; } } } if (alternate == null && _content != null) { alternate = ((IUriProvider)_content).Uri; } return alternate; } } Uri IFeedMetadata.ImageLink { get { if (!LinksSpecified) { return null; } foreach (AtomLink link in Links) { if (link.Relation == AtomLinkRelation.Enclosure) { string type = link.Type; if (!string.IsNullOrEmpty(type) && type.StartsWith("image", StringComparison.InvariantCultureIgnoreCase)) { return ((IUriProvider)link).Uri; } } } return null; } } string IFeedItem.Content => _content?.StringValue; Uri IFeedItem.ThreadLink { get { if (!LinksSpecified) { return null; } foreach (AtomLink link in Links) { if (link.Relation == AtomLinkRelation.Replies) { return ((IUriProvider)link).Uri; } } return null; } } int? IFeedItem.ThreadCount { get { if (LinksSpecified) { foreach (AtomLink link in Links) { if (link.Relation == AtomLinkRelation.Replies && link.ThreadCountSpecified) { return link.ThreadCount; } } } return _threadTotal; } } DateTime? IFeedItem.ThreadUpdated { get { if (LinksSpecified) { foreach (AtomLink link in Links) { if (link.Relation == AtomLinkRelation.Replies && link.ThreadUpdatedSpecified) { return link.ThreadUpdated.Value; } } } return null; } } public override void AddNamespaces(XmlSerializerNamespaces namespaces) { if (ThreadTotal > 0) { namespaces.Add(ThreadingPrefix, ThreadingNamespace); } if (InReplyToReferencesSpecified) { foreach (AtomInReplyTo inReplyTo in InReplyToReferences) { inReplyTo.AddNamespaces(namespaces); } } base.AddNamespaces(namespaces); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Rest.Generator.Azure.Python.Properties; using Microsoft.Rest.Generator.Azure.Python.Templates; using Microsoft.Rest.Generator.ClientModel; using Microsoft.Rest.Generator.Python; using Microsoft.Rest.Generator.Python.Templates; using Microsoft.Rest.Generator.Python.TemplateModels; using Microsoft.Rest.Generator.Utilities; using Microsoft.Rest.Generator.Logging; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Threading.Tasks; namespace Microsoft.Rest.Generator.Azure.Python { public class AzurePythonCodeGenerator : PythonCodeGenerator { private const string ClientRuntimePackage = "msrestazure version 0.4.0"; // page extensions class dictionary. private IList<PageTemplateModel> pageModels; private IDictionary<string, IDictionary<int, string>> pageClasses; public AzurePythonCodeGenerator(Settings settings) : base(settings) { pageModels = new List<PageTemplateModel>(); pageClasses = new Dictionary<string, IDictionary<int, string>>(); Namer = new AzurePythonCodeNamer(); } public override string Name { get { return "Azure.Python"; } } public override string Description { // TODO resource string. get { return "Azure specific Python code generator."; } } public override string UsageInstructions { get { return string.Format(CultureInfo.InvariantCulture, Resources.UsageInformation, ClientRuntimePackage); } } /// <summary> /// Normalizes client model by updating names and types to be language specific. /// </summary> /// <param name="serviceClient"></param> public override void NormalizeClientModel(ServiceClient serviceClient) { // Don't add pagable/longrunning method since we already handle ourself. Settings.AddCredentials = true; AzureExtensions.ProcessClientRequestIdExtension(serviceClient); AzureExtensions.UpdateHeadMethods(serviceClient); AzureExtensions.ParseODataExtension(serviceClient); Extensions.FlattenModels(serviceClient); ParameterGroupExtensionHelper.AddParameterGroups(serviceClient); AzureExtensions.AddAzureProperties(serviceClient); AzureExtensions.SetDefaultResponses(serviceClient); CorrectFilterParameters(serviceClient); base.NormalizeClientModel(serviceClient); NormalizeApiVersion(serviceClient); NormalizePaginatedMethods(serviceClient); } private static void NormalizeApiVersion(ServiceClient serviceClient) { serviceClient.Properties.Where( p => p.SerializedName.Equals(AzureExtensions.ApiVersion, StringComparison.OrdinalIgnoreCase)) .ForEach(p => p.DefaultValue = p.DefaultValue.Replace("\"", "'")); serviceClient.Properties.Where( p => p.SerializedName.Equals(AzureExtensions.AcceptLanguage, StringComparison.OrdinalIgnoreCase)) .ForEach(p => p.DefaultValue = p.DefaultValue.Replace("\"", "'")); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "nextLink")] private string GetPagingSetting(CompositeType body, Dictionary<string, object> extensions, string valueTypeName, IDictionary<int, string> typePageClasses) { var ext = extensions[AzureExtensions.PageableExtension] as Newtonsoft.Json.Linq.JContainer; string nextLinkName = (string)ext["nextLinkName"] ?? "nextLink"; string itemName = (string)ext["itemName"] ?? "value"; nextLinkName = nextLinkName.Replace(".", "\\\\."); itemName = itemName.Replace(".", "\\\\."); bool findNextLink = false; bool findItem = false; foreach (var property in body.ComposedProperties) { if (property.SerializedName == nextLinkName) { findNextLink = true; } else if (property.SerializedName == itemName) { findItem = true; } } if (!findNextLink) { throw new KeyNotFoundException("Couldn't find the nextLink property specified by extension"); } if (!findItem) { throw new KeyNotFoundException("Couldn't find the item property specified by extension"); } string className; var hash = (nextLinkName + "#" + itemName).GetHashCode(); if (!typePageClasses.ContainsKey(hash)) { className = (string)ext["className"]; if (string.IsNullOrEmpty(className)) { if (typePageClasses.Count > 0) { className = valueTypeName + String.Format(CultureInfo.InvariantCulture, "Paged{0}", typePageClasses.Count); } else { className = valueTypeName + "Paged"; } } typePageClasses.Add(hash, className); } className = typePageClasses[hash]; ext["className"] = className; var pageModel = new PageTemplateModel(className, nextLinkName, itemName, valueTypeName); if (!pageModels.Contains(pageModel)) { pageModels.Add(pageModel); } return className; } /// <summary> /// Changes paginated method signatures to return Page type. /// </summary> /// <param name="serviceClient"></param> private void NormalizePaginatedMethods(ServiceClient serviceClient) { if (serviceClient == null) { throw new ArgumentNullException("serviceClient"); } var convertedTypes = new Dictionary<IType, Response>(); foreach (var method in serviceClient.Methods.Where(m => m.Extensions.ContainsKey(AzureExtensions.PageableExtension))) { foreach (var responseStatus in method.Responses.Where(r => r.Value.Body is CompositeType).Select(s => s.Key)) { var compositType = (CompositeType)method.Responses[responseStatus].Body; var sequenceType = compositType.Properties.Select(p => p.Type).FirstOrDefault(t => t is SequenceType) as SequenceType; // if the type is a wrapper over page-able response if (sequenceType != null) { string valueType = sequenceType.ElementType.Name; if (!pageClasses.ContainsKey(valueType)) { pageClasses.Add(valueType, new Dictionary<int, string>()); } string pagableTypeName = GetPagingSetting(compositType, method.Extensions, valueType, pageClasses[valueType]); CompositeType pagedResult = new CompositeType { Name = pagableTypeName }; convertedTypes[compositType] = new Response(pagedResult, null); method.Responses[responseStatus] = convertedTypes[compositType]; break; } } if (convertedTypes.ContainsKey(method.ReturnType.Body)) { method.ReturnType = convertedTypes[method.ReturnType.Body]; } } Extensions.RemoveUnreferencedTypes(serviceClient, new HashSet<string>(convertedTypes.Keys.Cast<CompositeType>().Select(t => t.Name))); } /// <summary> /// Corrects type of the filter parameter. Currently typization of filters isn't /// supported and therefore we provide to user an opportunity to pass it in form /// of raw string. /// </summary> /// <param name="serviceClient">The service client.</param> public static void CorrectFilterParameters(ServiceClient serviceClient) { if (serviceClient == null) { throw new ArgumentNullException("serviceClient"); } foreach (var method in serviceClient.Methods.Where(m => m.Extensions.ContainsKey(AzureExtensions.ODataExtension))) { var filterParameter = method.Parameters.FirstOrDefault(p => p.SerializedName.Equals("$filter", StringComparison.OrdinalIgnoreCase) && p.Location == ParameterLocation.Query && p.Type is CompositeType); if (filterParameter != null) { filterParameter.Type = new PrimaryType(KnownPrimaryType.String); } } } /// <summary> /// Generate Python client code for given ServiceClient. /// </summary> /// <param name="serviceClient"></param> /// <returns></returns> public override async Task Generate(ServiceClient serviceClient) { var serviceClientTemplateModel = new AzureServiceClientTemplateModel(serviceClient); if (!string.IsNullOrWhiteSpace(this.PackageVersion)) { serviceClientTemplateModel.Version = this.PackageVersion; } // Service client var setupTemplate = new SetupTemplate { Model = serviceClientTemplateModel }; await Write(setupTemplate, "setup.py"); var serviceClientInitTemplate = new ServiceClientInitTemplate { Model = serviceClientTemplateModel }; await Write(serviceClientInitTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "__init__.py")); var serviceClientTemplate = new AzureServiceClientTemplate { Model = serviceClientTemplateModel, }; await Write(serviceClientTemplate, Path.Combine(serviceClientTemplateModel.PackageName, serviceClientTemplateModel.Name.ToPythonCase() + ".py")); var versionTemplate = new VersionTemplate { Model = serviceClientTemplateModel, }; await Write(versionTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "version.py")); var exceptionTemplate = new ExceptionTemplate { Model = serviceClientTemplateModel, }; await Write(exceptionTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "exceptions.py")); var credentialTemplate = new CredentialTemplate { Model = serviceClientTemplateModel, }; await Write(credentialTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "credentials.py")); //Models if (serviceClientTemplateModel.ModelTemplateModels.Any()) { var modelInitTemplate = new AzureModelInitTemplate { Model = new AzureModelInitTemplateModel(serviceClient, pageModels.Select(t => t.TypeDefinitionName)) }; await Write(modelInitTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "models", "__init__.py")); foreach (var modelType in serviceClientTemplateModel.ModelTemplateModels) { var modelTemplate = new ModelTemplate { Model = modelType }; await Write(modelTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "models", modelType.Name.ToPythonCase() + ".py")); } } //MethodGroups if (serviceClientTemplateModel.MethodGroupModels.Any()) { var methodGroupIndexTemplate = new MethodGroupInitTemplate { Model = serviceClientTemplateModel }; await Write(methodGroupIndexTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "operations", "__init__.py")); foreach (var methodGroupModel in serviceClientTemplateModel.MethodGroupModels) { var methodGroupTemplate = new AzureMethodGroupTemplate { Model = methodGroupModel as AzureMethodGroupTemplateModel }; await Write(methodGroupTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "operations", methodGroupModel.MethodGroupType.ToPythonCase() + ".py")); } } // Enums if (serviceClient.EnumTypes.Any()) { var enumTemplate = new EnumTemplate { Model = new EnumTemplateModel(serviceClient.EnumTypes), }; await Write(enumTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "models", serviceClientTemplateModel.Name.ToPythonCase() + "_enums.py")); } // Page class foreach (var pageModel in pageModels) { var pageTemplate = new PageTemplate { Model = pageModel }; await Write(pageTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "models", pageModel.TypeDefinitionName.ToPythonCase() + ".py")); } } } }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections; using System.Collections.Generic; namespace System.IO { public sealed class Directory { private Directory() { } //--// public static DirectoryInfo CreateDirectory(string path) { // path validation in Path.GetFullPath() path = Path.GetFullPath(path); /// According to MSDN, Directory.CreateDirectory on an existing /// directory is no-op. NativeIO.CreateDirectory(path); return new DirectoryInfo(path); } public static bool Exists(string path) { // path validation in Path.GetFullPath() path = Path.GetFullPath(path); /// Is this the absolute root? this always exists. if (path == NativeIO.FSRoot) { return true; } else { try { uint attributes = NativeIO.GetAttributes(path); /// This is essentially file not found. if (attributes == 0xFFFFFFFF) return false; /// Need to make sure these are not FAT16 or FAT32 specific. if ((((FileAttributes)attributes) & FileAttributes.Directory) == FileAttributes.Directory) { /// It is a directory. return true; } } catch (Exception) { return false; } } return false; } public static IEnumerable EnumerateFiles(string path) { if (!Directory.Exists(path)) #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.DirectoryNotFound); #else throw new IOException(); #endif return new FileEnumerator(path, FileEnumFlags.Files); } public static IEnumerable EnumerateDirectories(string path) { if (!Directory.Exists(path)) #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.DirectoryNotFound); #else throw new IOException(); #endif return new FileEnumerator(path, FileEnumFlags.Directories); } public static IEnumerable EnumerateFileSystemEntries(string path) { if (!Directory.Exists(path)) #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.DirectoryNotFound); #else throw new IOException(); #endif return new FileEnumerator(path, FileEnumFlags.FilesAndDirectories); } public static string[] GetFiles(string path) { return GetChildren(path, "*", false); } public static string[] GetDirectories(string path) { return GetChildren(path, "*", true); } public static string GetCurrentDirectory() { return FileSystemManager.CurrentDirectory; } public static void SetCurrentDirectory(string path) { // path validation in Path.GetFullPath() path = Path.GetFullPath(path); // We lock the directory for read-access first, to ensure path won't get deleted Object record = FileSystemManager.AddToOpenListForRead(path); try { if (!Directory.Exists(path)) { #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.DirectoryNotFound); #else throw new IOException(); #endif } // This will put the actual lock on path. (also read-access) FileSystemManager.SetCurrentDirectory(path); } finally { // We take our lock off. FileSystemManager.RemoveFromOpenList(record); } } public static void Move(string sourceDirName, string destDirName) { // sourceDirName and destDirName validation in Path.GetFullPath() sourceDirName = Path.GetFullPath(sourceDirName); destDirName = Path.GetFullPath(destDirName); bool tryCopyAndDelete = false; Object srcRecord = FileSystemManager.AddToOpenList(sourceDirName); try { // Make sure sourceDir is actually a directory if (!Exists(sourceDirName)) { #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.DirectoryNotFound); #else throw new IOException(); #endif } if (Exists( destDirName )) { #if EXCEPTION_STRINGS throw new IOException( "", (int)IOExceptionErrorCode.PathAlreadyExists ); #else throw new IOException(); #endif } // If Move() returns false, we'll try doing copy and delete to accomplish the move // ZeligBUG - the following fails to set tryCopyAndDelete //tryCopyAndDelete = !NativeIO.Move(sourceDirName, destDirName); if(false == NativeIO.Move( sourceDirName, destDirName )) { tryCopyAndDelete = true; } } finally { FileSystemManager.RemoveFromOpenList(srcRecord); } if (tryCopyAndDelete) { RecursiveCopyAndDelete(sourceDirName, destDirName); } } private static void RecursiveCopyAndDelete(String sourceDirName, String destDirName) { String[] files; int filesCount, i; int relativePathIndex = sourceDirName.Length + 1; // relative path starts after the sourceDirName and a path seperator // We have to make sure no one else can modify it (for example, delete the directory and // create a file of the same name) while we're moving Object recordSrc = FileSystemManager.AddToOpenList(sourceDirName); try { // Make sure sourceDir is actually a directory if (!Exists(sourceDirName)) { #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.DirectoryNotFound); #else throw new IOException(); #endif } // Make sure destDir does not yet exist if (Exists(destDirName)) { #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.PathAlreadyExists); #else throw new IOException(); #endif } NativeIO.CreateDirectory(destDirName); files = Directory.GetFiles(sourceDirName); filesCount = files.Length; for (i = 0; i < filesCount; i++) { File.Copy(files[i], Path.Combine(destDirName, files[i].Substring(relativePathIndex)), false, true); } files = Directory.GetDirectories(sourceDirName); filesCount = files.Length; for (i = 0; i < filesCount; i++) { RecursiveCopyAndDelete(files[i], Path.Combine(destDirName, files[i].Substring(relativePathIndex))); } NativeIO.Delete(sourceDirName); } finally { FileSystemManager.RemoveFromOpenList(recordSrc); } } public static void Delete(string path) { Delete(path, false); } public static void Delete(string path, bool recursive) { path = Path.GetFullPath(path); Object record = FileSystemManager.LockDirectory(path); try { uint attributes = NativeIO.GetAttributes(path); if (attributes == 0xFFFFFFFF) { #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.DirectoryNotFound); #else throw new IOException(); #endif } if (((attributes & (uint)(FileAttributes.Directory)) == 0) || ((attributes & (uint)(FileAttributes.ReadOnly)) != 0)) { /// it's readonly or not a directory #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.UnauthorizedAccess); #else throw new IOException(); #endif } if (!Exists(path)) // make sure it is indeed a directory (and not a file) { #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.DirectoryNotFound); #else throw new IOException(); #endif } if (!recursive) { NativeFindFile ff = new NativeFindFile(path, "*"); try { if (ff.GetNext() != null) { #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.DirectoryNotEmpty); #else throw new IOException(); #endif } } finally { ff.Close(); } } NativeIO.Delete(path); } finally { // regardless of what happened, we need to release the directory when we're done FileSystemManager.UnlockDirectory(record); } } private static string[] GetChildren(string path, string searchPattern, bool isDirectory) { // path and searchPattern validation in Path.GetFullPath() and Path.NormalizePath() path = Path.GetFullPath(path); if (!Directory.Exists(path)) #if EXCEPTION_STRINGS throw new IOException("", (int)IOExceptionErrorCode.DirectoryNotFound); #else throw new IOException(); #endif Path.NormalizePath(searchPattern, true); List<string> fileNames = new List<string>(); string root = Path.GetPathRoot(path); if (String.Equals(root, path)) { /// This is special case. Return all the volumes. /// Note this will not work, once we start having \\server\share like paths. if (isDirectory) { VolumeInfo[] volumes = VolumeInfo.GetVolumes(); int count = volumes.Length; for (int i = 0; i < count; i++) { fileNames.Add(volumes[i].RootDirectory); } } } else { Object record = FileSystemManager.AddToOpenListForRead(path); NativeFindFile ff = new NativeFindFile( path, searchPattern ); try { uint targetAttribute = (isDirectory ? (uint)FileAttributes.Directory : 0); NativeFileInfo fileinfo = ff.GetNext(); while (fileinfo != null) { if ((fileinfo.Attributes & (uint)FileAttributes.Directory) == targetAttribute) { fileNames.Add( Path.Combine(path, fileinfo.FileName) ); } fileinfo = ff.GetNext(); } } finally { if (ff != null) ff.Close(); FileSystemManager.RemoveFromOpenList(record); } } return fileNames.ToArray(); } } }
// Copyright 2016 Applied Geographics, 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 DotSpatial.Projections; using DotSpatial.Projections.Transforms; using GeoAPI.Geometries; using NetTopologySuite.Geometries; public class CoordinateSystem { private ProjectionInfo _geodetic = KnownCoordinateSystems.Geographic.World.WGS1984; protected ProjectionInfo Projection; protected CoordinateSystem() { } public CoordinateSystem(string proj4String) { Projection = ProjectionInfo.FromProj4String(proj4String); } public bool IsWebMercator { get { Spheroid spheroid = Projection.GeographicInfo.Datum.Spheroid; return Projection.Transform.Proj4Name == "merc" && Projection.Unit.Name == "Meter" && spheroid.EquatorialRadius == 6378137 && spheroid.PolarRadius == 6378137; } } public string MapUnits { get { if (Projection.Unit.Name == "Meter") { return "meters"; } else if (Projection.Unit.Name == "Foot_US" || Projection.Unit.Name == "Foot") { return "feet"; } return "unknown"; } } public override bool Equals(object obj) { CoordinateSystem other = obj as CoordinateSystem; if (other == null) { return false; } return Projection.Equals(other.Projection); } public override int GetHashCode() { return base.GetHashCode(); } public Coordinate ToGeodetic(Coordinate c) { double[] p = new double[] { c.X, c.Y }; double[] z = new double[] { 0 }; Reproject.ReprojectPoints(p, z, Projection, _geodetic, 0, 1); return new Coordinate(p[0], p[1]); } public Envelope ToGeodetic(Envelope extent) { Coordinate min = ToGeodetic(new Coordinate(extent.MinX, extent.MinY)); Coordinate max = ToGeodetic(new Coordinate(extent.MaxX, extent.MaxY)); return new Envelope(min, max); } public IGeometry ToGeodetic(IGeometry geometry) { Coordinate[] points; switch (geometry.OgcGeometryType) { case OgcGeometryType.Point: return new Point(ToGeodetic(geometry.Coordinate)); case OgcGeometryType.LineString: ILineString lineString = (ILineString)geometry; points = new Coordinate[lineString.Coordinates.Length]; for (int i = 0; i < lineString.Coordinates.Length; ++i) { points[i] = ToGeodetic(lineString.Coordinates[i]); } return new LineString(points); case OgcGeometryType.Polygon: IPolygon polygon = (IPolygon)geometry; points = new Coordinate[polygon.ExteriorRing.Coordinates.Length]; for (int i = 0; i < polygon.ExteriorRing.Coordinates.Length; ++i) { points[i] = ToGeodetic(polygon.ExteriorRing.Coordinates[i]); } return new Polygon(new LinearRing(points)); } return null; } public ILineString ToGeodetic(ILineString lineString) { return (ILineString)ToGeodetic((IGeometry)lineString); } public IPolygon ToGeodetic(IPolygon polygon) { return (IPolygon)ToGeodetic((IGeometry)polygon); } public Coordinate ToProjected(Coordinate c) { double[] p = new double[] { c.X, c.Y }; double[] z = new double[] { 0 }; Reproject.ReprojectPoints(p, z, _geodetic, Projection, 0, 1); return new Coordinate(p[0], p[1]); } public Envelope ToProjected(Envelope extent) { Coordinate min = ToProjected(new Coordinate(extent.MinX, extent.MinY)); Coordinate max = ToProjected(new Coordinate(extent.MaxX, extent.MaxY)); return new Envelope(min, max); } public IGeometry ToProjected(IGeometry geometry) { Coordinate[] points; switch (geometry.OgcGeometryType) { case OgcGeometryType.Point: return new Point(ToProjected(geometry.Coordinate)); case OgcGeometryType.LineString: ILineString lineString = (ILineString)geometry; points = new Coordinate[lineString.Coordinates.Length]; for (int i = 0; i < lineString.Coordinates.Length; ++i) { points[i] = ToProjected(lineString.Coordinates[i]); } return new LineString(points); case OgcGeometryType.Polygon: IPolygon polygon = (IPolygon)geometry; points = new Coordinate[polygon.ExteriorRing.Coordinates.Length]; for (int i = 0; i < polygon.ExteriorRing.Coordinates.Length; ++i) { points[i] = ToProjected(polygon.ExteriorRing.Coordinates[i]); } return new Polygon(new LinearRing(points)); } return null; } public ILineString ToProjected(ILineString lineString) { return (ILineString)ToProjected((IGeometry)lineString); } public IPolygon ToProjected(IPolygon polygon) { return (IPolygon)ToProjected((IGeometry)polygon); } public string ToProj4String() { return Projection.ToProj4String().Trim(); } }
#region license // Copyright (c) 2005 - 2007 Ayende Rahien ([email protected]) // 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 Ayende Rahien 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. #endregion using System; using System.Collections.Generic; using Boo.Lang.Compiler; using Boo.Lang.Compiler.Ast; using Rhino.Commons.Binsor.Configuration; namespace Rhino.Commons.Binsor.Macros { [CLSCompliant(false)] public class HashConfigurationBuilder : DepthFirstVisitor { private bool _skip; private bool _found; private bool _applied; private bool _attributesOnly; private CompilerErrorCollection _compileErrors; private HashLiteralExpression _configuration; private Dictionary<string, object> _childContext; public bool BuildConfig(Block block, CompilerErrorCollection compileErrors) { return Build(block, false, compileErrors); } public bool BuildAttributes(Block block, CompilerErrorCollection compileErrors) { return Build(block, true, compileErrors); } private bool Build(Block block, bool attributesOnly, CompilerErrorCollection compileErrors) { _attributesOnly = attributesOnly; _compileErrors = compileErrors; _configuration = new HashLiteralExpression(); _childContext = new Dictionary<string, object>(); return BuildHashConfiguration(block); } public bool HasConfiguration { get { return _configuration.Items.Count > 0; } } public HashLiteralExpression HashConfiguration { get { return _configuration; } } public override void OnBinaryExpression(BinaryExpression node) { _found = true; _applied = MacroHelper.IsAssignment(node, out node) && BuildConfigurationNode(node, false); } public override void OnMethodInvocationExpression(MethodInvocationExpression child) { _found = true; if ((_skip = _attributesOnly) == false) { _applied = BuildConfigurationChild(child); } } public override void OnStringLiteralExpression(StringLiteralExpression literal) { _found = true; if ((_skip = _attributesOnly) == false) { _applied = BuildConfigurationChild(literal); } } private bool BuildHashConfiguration(Block block) { _skip = false; _applied = true; if (!block.IsEmpty) { for (int i = 0; i < block.Statements.Count;) { var statement = block.Statements[i]; var expression = statement as ExpressionStatement; if (expression == null) { _compileErrors.Add(CompilerErrorFactory.CustomError( statement.LexicalInfo, "Unrecgonized configuration syntax")); return false; } _found = false; Visit(expression.Expression); if (_found == false) { _compileErrors.Add(CompilerErrorFactory.CustomError( expression.LexicalInfo, "Unrecgonized configuration syntax")); return false; } if (_applied) { if (_skip == false) { block.Statements.RemoveAt(i); } else ++i; } else { return false; } } } return true; } private bool BuildConfigurationNode(BinaryExpression node, bool asAttribute) { return BuildConfigurationNode(node, asAttribute, _configuration); } private bool BuildConfigurationNode(BinaryExpression node, bool asAttribute, HashLiteralExpression configuration) { var nodeVisitor = new ConfigurationNodeVisitor(); if (!nodeVisitor.GetNode(node.Left, asAttribute, _compileErrors)) return false; if (nodeVisitor.IsAttribute || asAttribute) { return BuildConfigurationAttribute(nodeVisitor.Node, node.Right, configuration); } if ((_skip =_attributesOnly) == false) { return BuildConfigurationChild(nodeVisitor.Node, node.Right); } return true; } private bool BuildConfigurationAttribute(Expression node, Expression value, HashLiteralExpression configuration) { ArrayLiteralExpression attributes; if (MacroHelper.IsCompoundAssignment(value, out attributes)) { // @attrib1=value1, attrib2=value2: Multiple attributes foreach(var attribute in attributes.Items) { if (attribute == attributes.Items[0]) { configuration.Items.Add(new ExpressionPair(node, attribute)); } else if (BuildAttribute(attribute, configuration) == false) { return false; } } } else { // @attrib=value: Single attribute configuration.Items.Add(new ExpressionPair(node, value)); } return true; } private bool BuildConfigurationChild(StringLiteralExpression child) { return BuildConfigurationChild(child, null, null); } private bool BuildConfigurationChild(Expression node, Expression value) { ArrayLiteralExpression attribs; List<Expression> attributes = null; if (MacroHelper.IsCompoundAssignment(value, out attribs)) { attributes = new List<Expression>(); foreach(var attribute in attribs.Items) { if (attribute == attribs.Items[0]) { value = attribute; } else { attributes.Add(attribute); } } } return BuildConfigurationChild(node, value, attributes); } private bool BuildConfigurationChild(MethodInvocationExpression child) { Block configBlock; var attributes = new List<Expression>(); var nodeVisitor = new ConfigurationNodeVisitor(); if (nodeVisitor.GetNode(child, _compileErrors) == false) return false; if (MacroHelper.IsNewBlock(child, out configBlock) == false) { attributes.AddRange(child.Arguments); return BuildConfigurationChild(nodeVisitor.Node, null, attributes); } else { if (configBlock.IsEmpty == false) { var nested = new HashConfigurationBuilder(); if (nested.BuildConfig(configBlock, _compileErrors) && nested.HasConfiguration) { _configuration.Items.Add(new ExpressionPair(nodeVisitor.Node, nested.HashConfiguration)); return true; } } else { return BuildConfigurationChild(nodeVisitor.Node, null, null); } } return false; } private bool BuildConfigurationChild(Expression child, Expression value, ICollection<Expression> attributes) { child = EnsureUniqueChild(child); if (attributes != null && attributes.Count > 0) { var childAttributes = new HashLiteralExpression(); if (value != null) { childAttributes.Items.Add(new ExpressionPair(new StringLiteralExpression("value"), value)); } // child=value, attrib2=value2: Child with attributes foreach(var attribute in attributes) { if (BuildAttribute(attribute, childAttributes) == false) { return false; } } _configuration.Items.Add(new ExpressionPair(child, childAttributes)); } else { // child=value: Child without attributes _configuration.Items.Add(new ExpressionPair(child, value ?? new StringLiteralExpression(""))); } return true; } private Expression EnsureUniqueChild(Expression node) { if (node is StringLiteralExpression) { var name = (StringLiteralExpression)node; if (_childContext.ContainsKey(name.Value)) { node = CreateChild(name); } else { _childContext.Add(name.Value, null); } } return node; } private bool BuildAttribute(Expression expression, HashLiteralExpression configuration) { BinaryExpression attribute; if (MacroHelper.IsAssignment(expression, out attribute)) { BuildConfigurationNode(attribute, true, configuration); } else { _compileErrors.Add(CompilerErrorFactory.CustomError(expression.LexicalInfo, "Attributes must be in the format @attrib1=value1, attrib2=value2,...")); return false; } return true; } private static Expression CreateChild(StringLiteralExpression name) { var child = new MethodInvocationExpression( AstUtil.CreateReferenceExpression(typeof(ChildBuilder).FullName) ); child.Arguments.Add(name); return child; } } }
using Newtonsoft.Json; using SendGrid; using SendGrid.Helpers.Mail; // If you are using the Mail Helper using System; var apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY"); var client = new SendGridClient(apiKey); //////////////////////////////////////////////////////// // Create a domain authentication. // POST /whitelabel/domains string data = @"{ 'automatic_security': false, 'custom_spf': true, 'default': true, 'domain': 'example.com', 'ips': [ '192.168.1.1', '192.168.1.2' ], 'subdomain': 'news', 'username': '[email protected]' }"; Object json = JsonConvert.DeserializeObject<Object>(data); data = json.ToString(); var response = await client.RequestAsync(method: SendGridClient.Method.POST, urlPath: "whitelabel/domains", requestBody: data); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Body.ReadAsStringAsync().Result); Console.WriteLine(response.Headers.ToString()); Console.ReadLine(); //////////////////////////////////////////////////////// // List all domain authentication. // GET /whitelabel/domains string queryParams = @"{ 'domain': 'test_string', 'exclude_subusers': 'true', 'limit': 1, 'offset': 1, 'username': 'test_string' }"; var response = await client.RequestAsync(method: SendGridClient.Method.GET, urlPath: "whitelabel/domains", queryParams: queryParams); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Body.ReadAsStringAsync().Result); Console.WriteLine(response.Headers.ToString()); Console.ReadLine(); //////////////////////////////////////////////////////// // Get the default domain authentication. // GET /whitelabel/domains/default var response = await client.RequestAsync(method: SendGridClient.Method.GET, urlPath: "whitelabel/domains/_("default")"); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Body.ReadAsStringAsync().Result); Console.WriteLine(response.Headers.ToString()); Console.ReadLine(); //////////////////////////////////////////////////////// // List the domain authentication associated with the given user. // GET /whitelabel/domains/subuser var response = await client.RequestAsync(method: SendGridClient.Method.GET, urlPath: "whitelabel/domains/subuser"); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Body.ReadAsStringAsync().Result); Console.WriteLine(response.Headers.ToString()); Console.ReadLine(); //////////////////////////////////////////////////////// // Disassociate a domain authentication from a given user. // DELETE /whitelabel/domains/subuser var response = await client.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "whitelabel/domains/subuser"); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Body.ReadAsStringAsync().Result); Console.WriteLine(response.Headers.ToString()); Console.ReadLine(); //////////////////////////////////////////////////////// // Update a domain authentication. // PATCH /whitelabel/domains/{domain_id} string data = @"{ 'custom_spf': true, 'default': false }"; Object json = JsonConvert.DeserializeObject<Object>(data); data = json.ToString(); var domain_id = "test_url_param"; var response = await client.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "whitelabel/domains/" + domain_id, requestBody: data); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Body.ReadAsStringAsync().Result); Console.WriteLine(response.Headers.ToString()); Console.ReadLine(); //////////////////////////////////////////////////////// // Retrieve a domain authentication. // GET /whitelabel/domains/{domain_id} var domain_id = "test_url_param"; var response = await client.RequestAsync(method: SendGridClient.Method.GET, urlPath: "whitelabel/domains/" + domain_id); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Body.ReadAsStringAsync().Result); Console.WriteLine(response.Headers.ToString()); Console.ReadLine(); //////////////////////////////////////////////////////// // Delete a domain authentication. // DELETE /whitelabel/domains/{domain_id} var domain_id = "test_url_param"; var response = await client.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "whitelabel/domains/" + domain_id); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Body.ReadAsStringAsync().Result); Console.WriteLine(response.Headers.ToString()); Console.ReadLine(); //////////////////////////////////////////////////////// // Associate a domain authentication with a given user. // POST /whitelabel/domains/{domain_id}/subuser string data = @"{ 'username': '[email protected]' }"; Object json = JsonConvert.DeserializeObject<Object>(data); data = json.ToString(); var domain_id = "test_url_param"; var response = await client.RequestAsync(method: SendGridClient.Method.POST, urlPath: "whitelabel/domains/" + domain_id + "/subuser", requestBody: data); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Body.ReadAsStringAsync().Result); Console.WriteLine(response.Headers.ToString()); Console.ReadLine(); //////////////////////////////////////////////////////// // Add an IP to a domain authentication. // POST /whitelabel/domains/{id}/ips string data = @"{ 'ip': '192.168.0.1' }"; Object json = JsonConvert.DeserializeObject<Object>(data); data = json.ToString(); var id = "test_url_param"; var response = await client.RequestAsync(method: SendGridClient.Method.POST, urlPath: "whitelabel/domains/" + id + "/ips", requestBody: data); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Body.ReadAsStringAsync().Result); Console.WriteLine(response.Headers.ToString()); Console.ReadLine(); //////////////////////////////////////////////////////// // Remove an IP from a domain authentication. // DELETE /whitelabel/domains/{id}/ips/{ip} var id = "test_url_param"; var ip = "test_url_param"; var response = await client.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "whitelabel/domains/" + id + "/ips/" + ip); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Body.ReadAsStringAsync().Result); Console.WriteLine(response.Headers.ToString()); Console.ReadLine(); //////////////////////////////////////////////////////// // Validate a domain authentication. // POST /whitelabel/domains/{id}/validate var id = "test_url_param"; var response = await client.RequestAsync(method: SendGridClient.Method.POST, urlPath: "whitelabel/domains/" + id + "/validate"); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Body.ReadAsStringAsync().Result); Console.WriteLine(response.Headers.ToString()); Console.ReadLine(); //////////////////////////////////////////////////////// // Create a reverse DNS record // POST /whitelabel/ips string data = @"{ 'domain': 'example.com', 'ip': '192.168.1.1', 'subdomain': 'email' }"; Object json = JsonConvert.DeserializeObject<Object>(data); data = json.ToString(); var response = await client.RequestAsync(method: SendGridClient.Method.POST, urlPath: "whitelabel/ips", requestBody: data); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Body.ReadAsStringAsync().Result); Console.WriteLine(response.Headers.ToString()); Console.ReadLine(); //////////////////////////////////////////////////////// // Retrieve a reverse DNS record // GET /whitelabel/ips string queryParams = @"{ 'ip': 'test_string', 'limit': 1, 'offset': 1 }"; var response = await client.RequestAsync(method: SendGridClient.Method.GET, urlPath: "whitelabel/ips", queryParams: queryParams); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Body.ReadAsStringAsync().Result); Console.WriteLine(response.Headers.ToString()); Console.ReadLine(); //////////////////////////////////////////////////////// // Retrieve a reverse DNS record // GET /whitelabel/ips/{id} var id = "test_url_param"; var response = await client.RequestAsync(method: SendGridClient.Method.GET, urlPath: "whitelabel/ips/" + id); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Body.ReadAsStringAsync().Result); Console.WriteLine(response.Headers.ToString()); Console.ReadLine(); //////////////////////////////////////////////////////// // Delete a reverse DNS record // DELETE /whitelabel/ips/{id} var id = "test_url_param"; var response = await client.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "whitelabel/ips/" + id); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Body.ReadAsStringAsync().Result); Console.WriteLine(response.Headers.ToString()); Console.ReadLine(); //////////////////////////////////////////////////////// // Validate a reverse DNS record // POST /whitelabel/ips/{id}/validate var id = "test_url_param"; var response = await client.RequestAsync(method: SendGridClient.Method.POST, urlPath: "whitelabel/ips/" + id + "/validate"); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Body.ReadAsStringAsync().Result); Console.WriteLine(response.Headers.ToString()); Console.ReadLine(); //////////////////////////////////////////////////////// // Create a Link Branding // POST /whitelabel/links string data = @"{ 'default': true, 'domain': 'example.com', 'subdomain': 'mail' }"; Object json = JsonConvert.DeserializeObject<Object>(data); data = json.ToString(); string queryParams = @"{ 'limit': 1, 'offset': 1 }"; var response = await client.RequestAsync(method: SendGridClient.Method.POST, urlPath: "whitelabel/links", requestBody: data, queryParams: queryParams); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Body.ReadAsStringAsync().Result); Console.WriteLine(response.Headers.ToString()); Console.ReadLine(); //////////////////////////////////////////////////////// // Retrieve all link brandings // GET /whitelabel/links string queryParams = @"{ 'limit': 1 }"; var response = await client.RequestAsync(method: SendGridClient.Method.GET, urlPath: "whitelabel/links", queryParams: queryParams); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Body.ReadAsStringAsync().Result); Console.WriteLine(response.Headers.ToString()); Console.ReadLine(); //////////////////////////////////////////////////////// // Retrieve a Default Link Branding // GET /whitelabel/links/default string queryParams = @"{ 'domain': 'test_string' }"; var response = await client.RequestAsync(method: SendGridClient.Method.GET, urlPath: "whitelabel/links/_("default")", queryParams: queryParams); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Body.ReadAsStringAsync().Result); Console.WriteLine(response.Headers.ToString()); Console.ReadLine(); //////////////////////////////////////////////////////// // Retrieve Associated Link Branding // GET /whitelabel/links/subuser string queryParams = @"{ 'username': 'test_string' }"; var response = await client.RequestAsync(method: SendGridClient.Method.GET, urlPath: "whitelabel/links/subuser", queryParams: queryParams); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Body.ReadAsStringAsync().Result); Console.WriteLine(response.Headers.ToString()); Console.ReadLine(); //////////////////////////////////////////////////////// // Disassociate a Link Branding // DELETE /whitelabel/links/subuser string queryParams = @"{ 'username': 'test_string' }"; var response = await client.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "whitelabel/links/subuser", queryParams: queryParams); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Body.ReadAsStringAsync().Result); Console.WriteLine(response.Headers.ToString()); Console.ReadLine(); //////////////////////////////////////////////////////// // Update a Link Branding // PATCH /whitelabel/links/{id} string data = @"{ 'default': true }"; Object json = JsonConvert.DeserializeObject<Object>(data); data = json.ToString(); var id = "test_url_param"; var response = await client.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "whitelabel/links/" + id, requestBody: data); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Body.ReadAsStringAsync().Result); Console.WriteLine(response.Headers.ToString()); Console.ReadLine(); //////////////////////////////////////////////////////// // Retrieve a Link Branding // GET /whitelabel/links/{id} var id = "test_url_param"; var response = await client.RequestAsync(method: SendGridClient.Method.GET, urlPath: "whitelabel/links/" + id); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Body.ReadAsStringAsync().Result); Console.WriteLine(response.Headers.ToString()); Console.ReadLine(); //////////////////////////////////////////////////////// // Delete a Link Branding // DELETE /whitelabel/links/{id} var id = "test_url_param"; var response = await client.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "whitelabel/links/" + id); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Body.ReadAsStringAsync().Result); Console.WriteLine(response.Headers.ToString()); Console.ReadLine(); //////////////////////////////////////////////////////// // Validate a Link Branding // POST /whitelabel/links/{id}/validate var id = "test_url_param"; var response = await client.RequestAsync(method: SendGridClient.Method.POST, urlPath: "whitelabel/links/" + id + "/validate"); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Body.ReadAsStringAsync().Result); Console.WriteLine(response.Headers.ToString()); Console.ReadLine(); //////////////////////////////////////////////////////// // Associate a Link Branding // POST /whitelabel/links/{link_id}/subuser string data = @"{ 'username': '[email protected]' }"; Object json = JsonConvert.DeserializeObject<Object>(data); data = json.ToString(); var link_id = "test_url_param"; var response = await client.RequestAsync(method: SendGridClient.Method.POST, urlPath: "whitelabel/links/" + link_id + "/subuser", requestBody: data); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Body.ReadAsStringAsync().Result); Console.WriteLine(response.Headers.ToString()); Console.ReadLine();
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Microsoft.WindowsAzure.Management.Network; using Microsoft.WindowsAzure.Management.Network.Models; namespace Microsoft.WindowsAzure.Management.Network { /// <summary> /// The Network Management API includes operations for managing the static /// IPs for your subscription. /// </summary> internal partial class StaticIPOperations : IServiceOperations<NetworkManagementClient>, Microsoft.WindowsAzure.Management.Network.IStaticIPOperations { /// <summary> /// Initializes a new instance of the StaticIPOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal StaticIPOperations(NetworkManagementClient client) { this._client = client; } private NetworkManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.Network.NetworkManagementClient. /// </summary> public NetworkManagementClient Client { get { return this._client; } } /// <summary> /// The Check Static IP operation retrieves the details for the /// availability of static IP addresses for the given virtual network. /// </summary> /// <param name='networkName'> /// Required. The name of the virtual network. /// </param> /// <param name='ipAddress'> /// Required. The address of the static IP. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A response that indicates the availability of a static IP address, /// and if not, provides a list of suggestions. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Network.Models.NetworkStaticIPAvailabilityResponse> CheckAsync(string networkName, string ipAddress, CancellationToken cancellationToken) { // Validate if (networkName == null) { throw new ArgumentNullException("networkName"); } if (ipAddress == null) { throw new ArgumentNullException("ipAddress"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("networkName", networkName); tracingParameters.Add("ipAddress", ipAddress); Tracing.Enter(invocationId, this, "CheckAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/networking/" + networkName.Trim() + "?"; url = url + "op=checkavailability"; url = url + "&address=" + Uri.EscapeDataString(ipAddress); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result NetworkStaticIPAvailabilityResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new NetworkStaticIPAvailabilityResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement addressAvailabilityResponseElement = responseDoc.Element(XName.Get("AddressAvailabilityResponse", "http://schemas.microsoft.com/windowsazure")); if (addressAvailabilityResponseElement != null) { XElement isAvailableElement = addressAvailabilityResponseElement.Element(XName.Get("IsAvailable", "http://schemas.microsoft.com/windowsazure")); if (isAvailableElement != null) { bool isAvailableInstance = bool.Parse(isAvailableElement.Value); result.IsAvailable = isAvailableInstance; } XElement availableAddressesSequenceElement = addressAvailabilityResponseElement.Element(XName.Get("AvailableAddresses", "http://schemas.microsoft.com/windowsazure")); if (availableAddressesSequenceElement != null) { foreach (XElement availableAddressesElement in availableAddressesSequenceElement.Elements(XName.Get("AvailableAddress", "http://schemas.microsoft.com/windowsazure"))) { result.AvailableAddresses.Add(availableAddressesElement.Value); } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
#region license // Copyright (c) 2009 Rodrigo B. de Oliveira ([email protected]) // 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 Rodrigo B. de Oliveira 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. #endregion using System; using Boo.Lang.Compiler.Ast; using Boo.Lang.Compiler.TypeSystem; namespace Boo.Lang.Compiler.Steps { //TODO: constant propagation (which allows precise unreachable branch detection) public class ConstantFolding : AbstractTransformerCompilerStep { public const string FoldedExpression = "foldedExpression"; override public void Run() { if (Errors.Count > 0) return; Visit(CompileUnit); } override public void OnModule(Module node) { Visit(node.Members); } object GetLiteralValue(Expression node) { switch (node.NodeType) { case NodeType.CastExpression: return GetLiteralValue(((CastExpression) node).Target); case NodeType.BoolLiteralExpression: return ((BoolLiteralExpression) node).Value; case NodeType.IntegerLiteralExpression: return ((IntegerLiteralExpression) node).Value; case NodeType.DoubleLiteralExpression: return ((DoubleLiteralExpression) node).Value; case NodeType.MemberReferenceExpression: { IField field = node.Entity as IField; if (null != field && field.IsLiteral) { if (field.Type.IsEnum) { object o = field.StaticValue; if (null != o && o != Error.Default) return o; } else { Expression e = field.StaticValue as Expression; return (null != e) ? GetLiteralValue(e) : field.StaticValue; } } break; } } return null; } override public void LeaveEnumMember(EnumMember node) { if (node.Initializer.NodeType == NodeType.IntegerLiteralExpression) return; IType type = node.Initializer.ExpressionType; if (null != type && (TypeSystemServices.IsIntegerNumber(type) || type.IsEnum)) { object val = GetLiteralValue(node.Initializer); if (null != val && val != Error.Default) node.Initializer = new IntegerLiteralExpression(Convert.ToInt64(val)); } return; } override public void LeaveBinaryExpression(BinaryExpression node) { if (AstUtil.GetBinaryOperatorKind(node.Operator) == BinaryOperatorKind.Assignment || node.Operator == BinaryOperatorType.ReferenceEquality || node.Operator == BinaryOperatorType.ReferenceInequality) return; if (null == node.Left.ExpressionType || null == node.Right.ExpressionType) return; object lhs = GetLiteralValue(node.Left); object rhs = GetLiteralValue(node.Right); if (null == lhs || null == rhs) return; Expression folded = null; IType lhsType = GetExpressionType(node.Left); IType rhsType = GetExpressionType(node.Right); if (TypeSystemServices.BoolType == lhsType && TypeSystemServices.BoolType == rhsType) { folded = GetFoldedBoolLiteral(node.Operator, Convert.ToBoolean(lhs), Convert.ToBoolean(rhs)); } else if (TypeSystemServices.DoubleType == lhsType || TypeSystemServices.SingleType == lhsType || TypeSystemServices.DoubleType == rhsType || TypeSystemServices.SingleType == rhsType) { folded = GetFoldedDoubleLiteral(node.Operator, Convert.ToDouble(lhs), Convert.ToDouble(rhs)); } else if (TypeSystemServices.IsIntegerNumber(lhsType) || lhsType.IsEnum) { bool lhsSigned = TypeSystemServices.IsSignedNumber(lhsType); bool rhsSigned = TypeSystemServices.IsSignedNumber(rhsType); if (lhsSigned == rhsSigned) //mixed signed/unsigned not supported for folding { folded = lhsSigned ? GetFoldedIntegerLiteral(node.Operator, Convert.ToInt64(lhs), Convert.ToInt64(rhs)) : GetFoldedIntegerLiteral(node.Operator, Convert.ToUInt64(lhs), Convert.ToUInt64(rhs)); } } if (null != folded) { folded.LexicalInfo = node.LexicalInfo; folded.ExpressionType = GetExpressionType(node); folded.Annotate(FoldedExpression, node); ReplaceCurrentNode(folded); } } override public void LeaveUnaryExpression(UnaryExpression node) { if (node.Operator == UnaryOperatorType.Explode || node.Operator == UnaryOperatorType.AddressOf || node.Operator == UnaryOperatorType.Indirection || node.Operator == UnaryOperatorType.LogicalNot) return; if (null == node.Operand.ExpressionType) return; object operand = GetLiteralValue(node.Operand); if (null == operand) return; Expression folded = null; IType operandType = GetExpressionType(node.Operand); if (TypeSystemServices.DoubleType == operandType || TypeSystemServices.SingleType == operandType) { folded = GetFoldedDoubleLiteral(node.Operator, Convert.ToDouble(operand)); } else if (TypeSystemServices.IsIntegerNumber(operandType) || operandType.IsEnum) { folded = GetFoldedIntegerLiteral(node.Operator, Convert.ToInt64(operand)); } if (null != folded) { folded.LexicalInfo = node.LexicalInfo; folded.ExpressionType = GetExpressionType(node); ReplaceCurrentNode(folded); } } static BoolLiteralExpression GetFoldedBoolLiteral(BinaryOperatorType @operator, bool lhs, bool rhs) { bool result; switch (@operator) { //comparison case BinaryOperatorType.Equality: result = (lhs == rhs); break; case BinaryOperatorType.Inequality: result = (lhs != rhs); break; //bitwise case BinaryOperatorType.BitwiseOr: result = lhs | rhs; break; case BinaryOperatorType.BitwiseAnd: result = lhs & rhs; break; case BinaryOperatorType.ExclusiveOr: result = lhs ^ rhs; break; //logical case BinaryOperatorType.And: result = lhs && rhs; break; case BinaryOperatorType.Or: result = lhs || rhs; break; default: return null; //not supported } return new BoolLiteralExpression(result); } static LiteralExpression GetFoldedIntegerLiteral(BinaryOperatorType @operator, long lhs, long rhs) { long result; switch (@operator) { //arithmetic case BinaryOperatorType.Addition: result = lhs + rhs; break; case BinaryOperatorType.Subtraction: result = lhs - rhs; break; case BinaryOperatorType.Multiply: result = lhs * rhs; break; case BinaryOperatorType.Division: result = lhs / rhs; break; case BinaryOperatorType.Modulus: result = lhs % rhs; break; case BinaryOperatorType.Exponentiation: result = (long) Math.Pow(lhs, rhs); break; //bitwise case BinaryOperatorType.BitwiseOr: result = lhs | rhs; break; case BinaryOperatorType.BitwiseAnd: result = lhs & rhs; break; case BinaryOperatorType.ExclusiveOr: result = lhs ^ rhs; break; case BinaryOperatorType.ShiftLeft: result = lhs << (int) rhs; break; case BinaryOperatorType.ShiftRight: result = lhs >> (int) rhs; break; //comparison case BinaryOperatorType.LessThan: return new BoolLiteralExpression(lhs < rhs); case BinaryOperatorType.LessThanOrEqual: return new BoolLiteralExpression(lhs <= rhs); case BinaryOperatorType.GreaterThan: return new BoolLiteralExpression(lhs > rhs); case BinaryOperatorType.GreaterThanOrEqual: return new BoolLiteralExpression(lhs >= rhs); case BinaryOperatorType.Equality: return new BoolLiteralExpression(lhs == rhs); case BinaryOperatorType.Inequality: return new BoolLiteralExpression(lhs != rhs); default: return null; //not supported } return new IntegerLiteralExpression(result); } static LiteralExpression GetFoldedIntegerLiteral(BinaryOperatorType @operator, ulong lhs, ulong rhs) { ulong result; switch (@operator) { //arithmetic case BinaryOperatorType.Addition: result = lhs + rhs; break; case BinaryOperatorType.Subtraction: result = lhs - rhs; break; case BinaryOperatorType.Multiply: result = lhs * rhs; break; case BinaryOperatorType.Division: result = lhs / rhs; break; case BinaryOperatorType.Modulus: result = lhs % rhs; break; case BinaryOperatorType.Exponentiation: result = (ulong) Math.Pow(lhs, rhs); break; //bitwise case BinaryOperatorType.BitwiseOr: result = lhs | rhs; break; case BinaryOperatorType.BitwiseAnd: result = lhs & rhs; break; case BinaryOperatorType.ExclusiveOr: result = lhs ^ rhs; break; case BinaryOperatorType.ShiftLeft: result = lhs << (int) rhs; break; case BinaryOperatorType.ShiftRight: result = lhs >> (int) rhs; break; //comparison case BinaryOperatorType.LessThan: return new BoolLiteralExpression(lhs < rhs); case BinaryOperatorType.LessThanOrEqual: return new BoolLiteralExpression(lhs <= rhs); case BinaryOperatorType.GreaterThan: return new BoolLiteralExpression(lhs > rhs); case BinaryOperatorType.GreaterThanOrEqual: return new BoolLiteralExpression(lhs >= rhs); case BinaryOperatorType.Equality: return new BoolLiteralExpression(lhs == rhs); case BinaryOperatorType.Inequality: return new BoolLiteralExpression(lhs != rhs); default: return null; //not supported } return new IntegerLiteralExpression((long) result); } static LiteralExpression GetFoldedDoubleLiteral(BinaryOperatorType @operator, double lhs, double rhs) { double result; switch (@operator) { //arithmetic case BinaryOperatorType.Addition: result = lhs + rhs; break; case BinaryOperatorType.Subtraction: result = lhs - rhs; break; case BinaryOperatorType.Multiply: result = lhs * rhs; break; case BinaryOperatorType.Division: result = lhs / rhs; break; case BinaryOperatorType.Modulus: result = lhs % rhs; break; case BinaryOperatorType.Exponentiation: result = Math.Pow(lhs, rhs); break; //comparison case BinaryOperatorType.LessThan: return new BoolLiteralExpression(lhs < rhs); case BinaryOperatorType.LessThanOrEqual: return new BoolLiteralExpression(lhs <= rhs); case BinaryOperatorType.GreaterThan: return new BoolLiteralExpression(lhs > rhs); case BinaryOperatorType.GreaterThanOrEqual: return new BoolLiteralExpression(lhs >= rhs); case BinaryOperatorType.Equality: return new BoolLiteralExpression(lhs == rhs); case BinaryOperatorType.Inequality: return new BoolLiteralExpression(lhs != rhs); default: return null; //not supported } return new DoubleLiteralExpression(result); } static LiteralExpression GetFoldedIntegerLiteral(UnaryOperatorType @operator, long operand) { long result; switch (@operator) { case UnaryOperatorType.UnaryNegation: result = -operand; break; case UnaryOperatorType.OnesComplement: result = ~operand; break; default: return null; //not supported } return new IntegerLiteralExpression(result); } static LiteralExpression GetFoldedDoubleLiteral(UnaryOperatorType @operator, double operand) { double result; switch (@operator) { case UnaryOperatorType.UnaryNegation: result = -operand; break; default: return null; //not supported } return new DoubleLiteralExpression(result); } } }
//--------------------------------------------------------------------- // <copyright file="RelationshipConstraintValidator.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- namespace System.Data.Mapping.Update.Internal { using System.Collections.Generic; using System.Data.Common; using System.Data.Common.Utils; using System.Data.Entity; using System.Data.Metadata.Edm; using System.Diagnostics; using System.Globalization; using System.Linq; internal partial class UpdateTranslator { /// <summary> /// Class validating relationship cardinality constraints. Only reasons about constraints that can be inferred /// by examining change requests from the store. /// (no attempt is made to ensure consistency of the store subsequently, since this would require pulling in all /// values from the store). /// </summary> private class RelationshipConstraintValidator { #region Constructor internal RelationshipConstraintValidator(UpdateTranslator updateTranslator) { m_existingRelationships = new Dictionary<DirectionalRelationship, DirectionalRelationship>(EqualityComparer<DirectionalRelationship>.Default); m_impliedRelationships = new Dictionary<DirectionalRelationship, IEntityStateEntry>(EqualityComparer<DirectionalRelationship>.Default); m_referencingRelationshipSets = new Dictionary<EntitySet, List<AssociationSet>>(EqualityComparer<EntitySet>.Default); m_updateTranslator = updateTranslator; } #endregion #region Fields /// <summary> /// Relationships registered in the validator. /// </summary> private readonly Dictionary<DirectionalRelationship, DirectionalRelationship> m_existingRelationships; /// <summary> /// Relationships the validator determines are required based on registered entities. /// </summary> private readonly Dictionary<DirectionalRelationship, IEntityStateEntry> m_impliedRelationships; /// <summary> /// Cache used to store relationship sets with ends bound to entity sets. /// </summary> private readonly Dictionary<EntitySet, List<AssociationSet>> m_referencingRelationshipSets; /// <summary> /// Update translator containing session context. /// </summary> private readonly UpdateTranslator m_updateTranslator; #endregion #region Methods /// <summary> /// Add an entity to be tracked by the validator. Requires that the input describes an entity. /// </summary> /// <param name="stateEntry">State entry for the entity being tracked.</param> internal void RegisterEntity(IEntityStateEntry stateEntry) { EntityUtil.CheckArgumentNull(stateEntry, "stateEntry"); if (EntityState.Added == stateEntry.State || EntityState.Deleted == stateEntry.State) { // We only track added and deleted entities because modifications to entities do not affect // cardinality constraints. Relationships are based on end keys, and it is not // possible to modify key values. Debug.Assert(null != (object)stateEntry.EntityKey, "entity state entry must have an entity key"); EntityKey entityKey = EntityUtil.CheckArgumentNull(stateEntry.EntityKey, "stateEntry.EntityKey"); EntitySet entitySet = (EntitySet)stateEntry.EntitySet; EntityType entityType = EntityState.Added == stateEntry.State ? GetEntityType(stateEntry.CurrentValues) : GetEntityType(stateEntry.OriginalValues); // figure out relationship set ends that are associated with this entity set foreach (AssociationSet associationSet in GetReferencingAssocationSets(entitySet)) { // describe unidirectional relationships in which the added entity is the "destination" var ends = associationSet.AssociationSetEnds; foreach (var fromEnd in ends) { foreach (var toEnd in ends) { // end to itself does not describe an interesting relationship subpart if (object.ReferenceEquals(toEnd.CorrespondingAssociationEndMember, fromEnd.CorrespondingAssociationEndMember)) { continue; } // skip ends that don't target the current entity set if (!toEnd.EntitySet.EdmEquals(entitySet)) { continue; } // skip ends that aren't required if (0 == MetadataHelper.GetLowerBoundOfMultiplicity( fromEnd.CorrespondingAssociationEndMember.RelationshipMultiplicity)) { continue; } // skip ends that don't target the current entity type if (!MetadataHelper.GetEntityTypeForEnd(toEnd.CorrespondingAssociationEndMember) .IsAssignableFrom(entityType)) { continue; } // register the relationship so that we know it's required DirectionalRelationship relationship = new DirectionalRelationship(entityKey, fromEnd.CorrespondingAssociationEndMember, toEnd.CorrespondingAssociationEndMember, associationSet, stateEntry); m_impliedRelationships.Add(relationship, stateEntry); } } } } } // requires: input is an IExtendedDataRecord representing an entity // returns: entity type for the given record private static EntityType GetEntityType(DbDataRecord dbDataRecord) { IExtendedDataRecord extendedRecord = dbDataRecord as IExtendedDataRecord; Debug.Assert(extendedRecord != null); Debug.Assert(BuiltInTypeKind.EntityType == extendedRecord.DataRecordInfo.RecordType.EdmType.BuiltInTypeKind); return (EntityType)extendedRecord.DataRecordInfo.RecordType.EdmType; } /// <summary> /// Add a relationship to be tracked by the validator. /// </summary> /// <param name="associationSet">Relationship set to which the given record belongs.</param> /// <param name="record">Relationship record. Must conform to the type of the relationship set.</param> /// <param name="stateEntry">State entry for the relationship being tracked</param> internal void RegisterAssociation(AssociationSet associationSet, IExtendedDataRecord record, IEntityStateEntry stateEntry) { EntityUtil.CheckArgumentNull(associationSet, "relationshipSet"); EntityUtil.CheckArgumentNull(record, "record"); EntityUtil.CheckArgumentNull(stateEntry, "stateEntry"); Debug.Assert(associationSet.ElementType.Equals(record.DataRecordInfo.RecordType.EdmType)); // retrieve the ends of the relationship Dictionary<string, EntityKey> endNameToKeyMap = new Dictionary<string, EntityKey>( StringComparer.Ordinal); foreach (FieldMetadata field in record.DataRecordInfo.FieldMetadata) { string endName = field.FieldType.Name; EntityKey entityKey = (EntityKey)record.GetValue(field.Ordinal); endNameToKeyMap.Add(endName, entityKey); } // register each unidirectional relationship subpart in the relationship instance var ends = associationSet.AssociationSetEnds; foreach (var fromEnd in ends) { foreach (var toEnd in ends) { // end to itself does not describe an interesting relationship subpart if (object.ReferenceEquals(toEnd.CorrespondingAssociationEndMember, fromEnd.CorrespondingAssociationEndMember)) { continue; } EntityKey toEntityKey = endNameToKeyMap[toEnd.CorrespondingAssociationEndMember.Name]; DirectionalRelationship relationship = new DirectionalRelationship(toEntityKey, fromEnd.CorrespondingAssociationEndMember, toEnd.CorrespondingAssociationEndMember, associationSet, stateEntry); AddExistingRelationship(relationship); } } } /// <summary> /// Validates cardinality constraints for all added entities/relationships. /// </summary> internal void ValidateConstraints() { // ensure all expected relationships exist foreach (KeyValuePair<DirectionalRelationship, IEntityStateEntry> expected in m_impliedRelationships) { DirectionalRelationship expectedRelationship = expected.Key; IEntityStateEntry stateEntry = expected.Value; // determine actual end cardinality int count = GetDirectionalRelationshipCountDelta(expectedRelationship); if (EntityState.Deleted == stateEntry.State) { // our cardinality expectations are reversed for delete (cardinality of 1 indicates // we want -1 operation total) count = -count; } // determine expected cardinality int minimumCount = MetadataHelper.GetLowerBoundOfMultiplicity(expectedRelationship.FromEnd.RelationshipMultiplicity); int? maximumCountDeclared = MetadataHelper.GetUpperBoundOfMultiplicity(expectedRelationship.FromEnd.RelationshipMultiplicity); int maximumCount = maximumCountDeclared.HasValue ? maximumCountDeclared.Value : count; // negative value // indicates unlimited cardinality if (count < minimumCount || count > maximumCount) { // We could in theory "fix" the cardinality constraint violation by introducing surrogates, // but we risk doing work on behalf of the user they don't want performed (e.g., deleting an // entity or relationship the user has intentionally left untouched). throw EntityUtil.UpdateRelationshipCardinalityConstraintViolation( expectedRelationship.AssociationSet.Name, minimumCount, maximumCountDeclared, TypeHelpers.GetFullName(expectedRelationship.ToEntityKey.EntityContainerName, expectedRelationship.ToEntityKey.EntitySetName), count, expectedRelationship.FromEnd.Name, stateEntry); } } // ensure actual relationships have required ends foreach (DirectionalRelationship actualRelationship in m_existingRelationships.Keys) { int addedCount; int deletedCount; actualRelationship.GetCountsInEquivalenceSet(out addedCount, out deletedCount); int absoluteCount = Math.Abs(addedCount - deletedCount); int minimumCount = MetadataHelper.GetLowerBoundOfMultiplicity(actualRelationship.FromEnd.RelationshipMultiplicity); int? maximumCount = MetadataHelper.GetUpperBoundOfMultiplicity(actualRelationship.FromEnd.RelationshipMultiplicity); // Check that we haven't inserted or deleted too many relationships if (maximumCount.HasValue) { EntityState? violationType = default(EntityState?); int? violationCount = default(int?); if (addedCount > maximumCount.Value) { violationType = EntityState.Added; violationCount = addedCount; } else if (deletedCount > maximumCount.Value) { violationType = EntityState.Deleted; violationCount = deletedCount; } if (violationType.HasValue) { throw EntityUtil.Update(Strings.Update_RelationshipCardinalityViolation(maximumCount.Value, violationType.Value, actualRelationship.AssociationSet.ElementType.FullName, actualRelationship.FromEnd.Name, actualRelationship.ToEnd.Name, violationCount.Value), null, actualRelationship.GetEquivalenceSet().Select(reln => reln.StateEntry)); } } // We care about the case where there is a relationship but no entity when // the relationship and entity map to the same table. If there is a relationship // with 1..1 cardinality to the entity and the relationship is being added or deleted, // it is required that the entity is also added or deleted. if (1 == absoluteCount && 1 == minimumCount && 1 == maximumCount) // 1..1 relationship being added/deleted { bool isAdd = addedCount > deletedCount; // Ensure the entity is also being added or deleted IEntityStateEntry entityEntry; // Identify the following error conditions: // - the entity is not being modified at all // - the entity is being modified, but not in the way we expect (it's not being added or deleted) if (!m_impliedRelationships.TryGetValue(actualRelationship, out entityEntry) || (isAdd && EntityState.Added != entityEntry.State) || (!isAdd && EntityState.Deleted != entityEntry.State)) { throw EntityUtil.UpdateEntityMissingConstraintViolation(actualRelationship.AssociationSet.Name, actualRelationship.ToEnd.Name, actualRelationship.StateEntry); } } } } /// <summary> /// Determines the net change in relationship count. /// For instance, if the directional relationship is added 2 times and deleted 3, the return value is -1. /// </summary> private int GetDirectionalRelationshipCountDelta(DirectionalRelationship expectedRelationship) { // lookup up existing relationship from expected relationship DirectionalRelationship existingRelationship; if (m_existingRelationships.TryGetValue(expectedRelationship, out existingRelationship)) { int addedCount; int deletedCount; existingRelationship.GetCountsInEquivalenceSet(out addedCount, out deletedCount); return addedCount - deletedCount; } else { // no modifications to the relationship... return 0 (no net change) return 0; } } private void AddExistingRelationship(DirectionalRelationship relationship) { DirectionalRelationship existingRelationship; if (m_existingRelationships.TryGetValue(relationship, out existingRelationship)) { existingRelationship.AddToEquivalenceSet(relationship); } else { m_existingRelationships.Add(relationship, relationship); } } /// <summary> /// Determine which relationship sets reference the given entity set. /// </summary> /// <param name="entitySet">Entity set for which to identify relationships</param> /// <returns>Relationship sets referencing the given entity set</returns> private IEnumerable<AssociationSet> GetReferencingAssocationSets(EntitySet entitySet) { List<AssociationSet> relationshipSets; // check if this information is cached if (!m_referencingRelationshipSets.TryGetValue(entitySet, out relationshipSets)) { relationshipSets = new List<AssociationSet>(); // relationship sets must live in the same container as the entity sets they reference EntityContainer container = entitySet.EntityContainer; foreach (EntitySetBase extent in container.BaseEntitySets) { AssociationSet associationSet = extent as AssociationSet; if (null != associationSet && !associationSet.ElementType.IsForeignKey) { foreach (var end in associationSet.AssociationSetEnds) { if (end.EntitySet.Equals(entitySet)) { relationshipSets.Add(associationSet); break; } } } } // add referencing relationship information to the cache m_referencingRelationshipSets.Add(entitySet, relationshipSets); } return relationshipSets; } #endregion #region Nested types /// <summary> /// An instance of an actual or expected relationship. This class describes one direction /// of the relationship. /// </summary> private class DirectionalRelationship : IEquatable<DirectionalRelationship> { /// <summary> /// Entity key for the entity being referenced by the relationship. /// </summary> internal readonly EntityKey ToEntityKey; /// <summary> /// Name of the end referencing the entity key. /// </summary> internal readonly AssociationEndMember FromEnd; /// <summary> /// Name of the end the entity key references. /// </summary> internal readonly AssociationEndMember ToEnd; /// <summary> /// State entry containing this relationship. /// </summary> internal readonly IEntityStateEntry StateEntry; /// <summary> /// Reference to the relationship set. /// </summary> internal readonly AssociationSet AssociationSet; /// <summary> /// Reference to next 'equivalent' relationship in circular linked list. /// </summary> private DirectionalRelationship _equivalenceSetLinkedListNext; private readonly int _hashCode; internal DirectionalRelationship(EntityKey toEntityKey, AssociationEndMember fromEnd, AssociationEndMember toEnd, AssociationSet associationSet, IEntityStateEntry stateEntry) { ToEntityKey = EntityUtil.CheckArgumentNull(toEntityKey, "toEntityKey"); FromEnd = EntityUtil.CheckArgumentNull(fromEnd, "fromEnd"); ToEnd = EntityUtil.CheckArgumentNull(toEnd, "toEnd"); AssociationSet = EntityUtil.CheckArgumentNull(associationSet, "associationSet"); StateEntry = EntityUtil.CheckArgumentNull(stateEntry, "stateEntry"); _equivalenceSetLinkedListNext = this; _hashCode = toEntityKey.GetHashCode() ^ fromEnd.GetHashCode() ^ toEnd.GetHashCode() ^ associationSet.GetHashCode(); } /// <summary> /// Requires: 'other' must refer to the same relationship metadata and the same target entity and /// must not already be a part of an equivalent set. /// Adds the given relationship to linked list containing all equivalent relationship instances /// for this relationship (e.g. all orders associated with a specific customer) /// </summary> internal void AddToEquivalenceSet(DirectionalRelationship other) { Debug.Assert(null != other, "other must not be null"); Debug.Assert(this.Equals(other), "other must be another instance of the same relationship target"); Debug.Assert(Object.ReferenceEquals(other._equivalenceSetLinkedListNext, other), "other must not be part of an equivalence set yet"); DirectionalRelationship currentSuccessor = this._equivalenceSetLinkedListNext; this._equivalenceSetLinkedListNext = other; other._equivalenceSetLinkedListNext = currentSuccessor; } /// <summary> /// Returns all relationships in equivalence set. /// </summary> internal IEnumerable<DirectionalRelationship> GetEquivalenceSet() { // yield everything in circular linked list DirectionalRelationship current = this; do { yield return current; current = current._equivalenceSetLinkedListNext; } while (!object.ReferenceEquals(current, this)); } /// <summary> /// Determines the number of add and delete operations contained in this equivalence set. /// </summary> internal void GetCountsInEquivalenceSet(out int addedCount, out int deletedCount) { addedCount = 0; deletedCount = 0; // yield everything in circular linked list DirectionalRelationship current = this; do { if (current.StateEntry.State == EntityState.Added) { addedCount++; } else if (current.StateEntry.State == EntityState.Deleted) { deletedCount++; } current = current._equivalenceSetLinkedListNext; } while (!object.ReferenceEquals(current, this)); } public override int GetHashCode() { return _hashCode; } public bool Equals(DirectionalRelationship other) { if (object.ReferenceEquals(this, other)) { return true; } if (null == other) { return false; } if (ToEntityKey != other.ToEntityKey) { return false; } if (AssociationSet != other.AssociationSet) { return false; } if (ToEnd != other.ToEnd) { return false; } if (FromEnd != other.FromEnd) { return false; } return true; } public override bool Equals(object obj) { Debug.Fail("use only typed Equals method"); return Equals(obj as DirectionalRelationship); } public override string ToString() { return String.Format(CultureInfo.InvariantCulture, "{0}.{1}-->{2}: {3}", AssociationSet.Name, FromEnd.Name, ToEnd.Name, StringUtil.BuildDelimitedList(ToEntityKey.EntityKeyValues, null, null)); } } #endregion } } }
/* * XmlElement.cs - Implementation of the "System.Xml.XmlElement" class. * * Copyright (C) 2002 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Xml { using System; using System.Xml.Private; #if ECMA_COMPAT internal #else public #endif class XmlElement : XmlLinkedNode { // Internal state. private NameCache.NameInfo name; private XmlAttributeCollection attributes; private bool isEmpty; // Constructor. internal XmlElement(XmlNode parent, NameCache.NameInfo name) : base(parent) { this.name = name; this.attributes = null; this.isEmpty = true; } protected internal XmlElement(String prefix, String localName, String namespaceURI, XmlDocument doc) : base(doc) { this.name = doc.nameCache.Add(localName, prefix, namespaceURI); } // Get a collection that contains all of the attributes for this node. public override XmlAttributeCollection Attributes { get { if(attributes == null) { attributes = new XmlAttributeCollection(this); } return attributes; } } // Determine if this element node has attributes. public virtual bool HasAttributes { get { return (attributes != null && attributes.Count != 0); } } // Get the inner text version of this node. public override String InnerText { get { return base.InnerText; } set { XmlNode child = NodeList.GetFirstChild(this); if(child != null && NodeList.GetNextSibling(child) == null && child.NodeType == XmlNodeType.Text) { // Special-case the case of a single text child. child.Value = value; } else { // Remove the children and create a new text node. RemoveContents(); AppendChild(OwnerDocument.CreateTextNode(value)); IsEmpty=false; } } } // Get the markup that represents the children of this node. public override String InnerXml { get { return base.InnerXml; } set { // remove the children from this element RemoveContents(); // bail out now if there's nothing to parse if(value == null || value.Length == 0) { return; } // get the owner document XmlDocument doc = FindOwnerQuick(); // get the name table XmlNameTable nt = doc.NameTable; // declare the lang and space String lang; XmlSpace space; // create the namespace manager XmlNamespaceManager nm = new XmlNamespaceManager(nt); // collect all the ancestor information needed for parsing CollectAncestorInformation(ref nm, out lang, out space); // create the parser context XmlParserContext context = new XmlParserContext (nt, nm, lang, space); // set the base uri in the parser context context.BaseURI = BaseURI; // create the reader XmlTextReader r = new XmlTextReader (value, XmlNodeType.Element, context); // move to the first node r.Read(); // add the child nodes do { // read the next child node XmlNode child = doc.ReadNodeInternal(r); // append the child (ReadNodeInternal should // advance reader) if(child != null) { // append the new child node AppendChild(child); } } while(r.ReadState == ReadState.Interactive); } } // Get or set the empty state of this element. public bool IsEmpty { get { // only override the flag if there's content if(FirstChild != null) { isEmpty = false; } // return the empty flag return isEmpty; } set { if(value) { RemoveContents(); } isEmpty = value; } } // Get the local name associated with this node. public override String LocalName { get { return name.localName; } } // Get the name associated with this node. public override String Name { get { return name.name; } } // Get the namespace URI associated with this node. public override String NamespaceURI { get { return name.ns; } } // Get the next node immediately following this one. public override XmlNode NextSibling { get { return NodeList.GetNextSibling(this); } } // Get the type that is associated with this node. public override XmlNodeType NodeType { get { return XmlNodeType.Element; } } // Get the document that owns this node. public override XmlDocument OwnerDocument { get { return base.OwnerDocument; } } // Get the previous node immediately preceding this one. public override XmlNode PreviousSibling { get { return NodeList.GetPreviousSibling(this); } } // Get the prefix associated with this node. public override String Prefix { get { return name.prefix; } } // Clone this node in either shallow or deep mode. public override XmlNode CloneNode(bool deep) { XmlElement clone = OwnerDocument.CreateElement (Prefix, LocalName, NamespaceURI); if(attributes != null) { foreach(XmlAttribute attr in Attributes) { clone.Attributes.Append ((XmlAttribute)(attr.CloneNode(true))); } } if(deep) { clone.CloneChildrenFrom(this, deep); } return clone; } // Get the value of an attribute with a specific name. public virtual String GetAttribute(String name) { XmlAttribute attr = GetAttributeNode(name); if(attr != null) { return attr.Value; } else { return String.Empty; } } // Get the value of an attribute with a specific name and namespace. public virtual String GetAttribute(String localName, String namespaceURI) { XmlAttribute attr = GetAttributeNode(localName, namespaceURI); if(attr != null) { return attr.Value; } else { return String.Empty; } } // Get the node of an attribute with a specific name. public virtual XmlAttribute GetAttributeNode(String name) { if(attributes != null) { return attributes[name]; } else { return null; } } // Get the node of an attribute with a specific name and namespace. public virtual XmlAttribute GetAttributeNode (String localName, String namespaceURI) { if(attributes != null) { return attributes[localName, namespaceURI]; } else { return null; } } // Get a list of all descendents that match a particular name. public virtual XmlNodeList GetElementsByTagName(String name) { name = (FindOwnerQuick()).NameTable.Add(name); return new ElementList(this, name); } // Get a list of all descendents that match a particular name and namespace. public virtual XmlNodeList GetElementsByTagName (String localName, String namespaceURI) { XmlNameTable nt = FindOwnerQuick().NameTable; localName = nt.Add(localName); namespaceURI = nt.Add(namespaceURI); return new ElementList(this, localName, namespaceURI); } // Determine if this element has a particular attribute. public virtual bool HasAttribute(String name) { return (GetAttributeNode(name) != null); } // Determine if this element has a particular attribute. public virtual bool HasAttribute(String localName, String namespaceURI) { return (GetAttributeNode(localName, namespaceURI) != null); } // Remove all children and attributes from this node. public override void RemoveAll() { RemoveAllAttributes(); base.RemoveAll(); } // Remove all of the attributes from this node. public virtual void RemoveAllAttributes() { if(attributes != null) { attributes.RemoveAll(); } } // Remove the element contents, but not the attributes. private void RemoveContents() { base.RemoveAll(); } // Remove a specified attribute by name. public virtual void RemoveAttribute(String name) { if(attributes != null) { attributes.RemoveNamedItem(name); } } // Remove a specified attribute by name and namespace. public virtual void RemoveAttribute(String localName, String namespaceURI) { if(attributes != null) { attributes.RemoveNamedItem(localName, namespaceURI); } } // Remove a specified attribute by index. public virtual XmlNode RemoveAttributeAt(int i) { if(attributes != null) { return attributes.RemoveAt(i); } else { return null; } } // Remove a particular attribute node and return the node. public virtual XmlAttribute RemoveAttributeNode(XmlAttribute oldAttr) { if(attributes != null) { return (XmlAttribute)(attributes.Remove(oldAttr)); } else { return null; } } // Remove a particular attribute by name and return the node. public virtual XmlAttribute RemoveAttributeNode (String localName, String namespaceURI) { if(attributes != null) { return (XmlAttribute)(attributes.RemoveNamedItem (localName, namespaceURI)); } else { return null; } } // Set an attribute to a specific value. public virtual void SetAttribute(String name, String value) { XmlAttribute attr = GetAttributeNode(name); if(attr != null) { attr.Value = value; } else { attr = OwnerDocument.CreateAttribute(name); attr.Value = value; /* TODO : figure out if this is better done lower down */ attr.parent = this; Attributes.Append(attr); } } // Set an attribute to a specific value. public virtual String SetAttribute (String localName, String namespaceURI, String value) { XmlAttribute attr = GetAttributeNode(localName, namespaceURI); if(attr != null) { attr.Value = value; } else { attr = OwnerDocument.CreateAttribute (localName, namespaceURI); attr.Value = value; Attributes.Append(attr); } return attr.Value; } // Set an attribute by node. public virtual XmlAttribute SetAttributeNode(XmlAttribute newAttr) { if(newAttr.OwnerElement == null) { /* TODO : figure out if this is better done lower down */ newAttr.parent = this; return (XmlAttribute)(Attributes.SetNamedItem(newAttr)); } else { throw new InvalidOperationException (S._("Xml_AttrAlreadySet")); } } // Create a new attribute node and return it. public virtual XmlAttribute SetAttributeNode (String localName, String namespaceURI) { XmlAttribute attr = GetAttributeNode(localName, namespaceURI); if(attr != null) { attr = OwnerDocument.CreateAttribute (localName, namespaceURI); /* TODO : figure out if this is better done lower down */ attr.parent = this; Attributes.Append(attr); } return attr; } // Writes the contents of this node to a specified XmlWriter. public override void WriteContentTo(XmlWriter w) { WriteChildrenTo(w); } // Write this node and all of its contents to a specified XmlWriter. public override void WriteTo(XmlWriter w) { w.WriteStartElement(Prefix, LocalName, NamespaceURI); if(attributes != null) { foreach(XmlAttribute attr in attributes) { attr.WriteTo(w); } } if(!IsEmpty) { WriteContentTo(w); w.WriteFullEndElement(); } else { w.WriteEndElement(); } } // Determine if a particular node type can be inserted as // a child of the current node. internal override bool CanInsert(XmlNodeType type) { switch(type) { case XmlNodeType.Element: case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.EntityReference: case XmlNodeType.ProcessingInstruction: case XmlNodeType.Comment: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: { return true; } // Not reached. default: break; } return false; } }; // class XmlElement }; // namespace System.Xml
// 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 OLEDB.Test.ModuleCore; using Xunit; namespace System.Xml.Tests { public partial class XmlWriterTestModule : CTestModule { private static void RunTestCase(Func<CTestBase> testCaseGenerator) { var module = new XmlWriterTestModule(); module.Init(null); module.AddChild(testCaseGenerator()); module.Execute(); Assert.Equal(0, module.FailCount); } private static void RunTest(Func<CTestBase> testCaseGenerator) { CModInfo.CommandLine = "/WriterType UnicodeWriter"; RunTestCase(testCaseGenerator); CModInfo.CommandLine = "/WriterType UnicodeWriter /Async true"; RunTestCase(testCaseGenerator); CModInfo.CommandLine = "/WriterType UTF8Writer"; RunTestCase(testCaseGenerator); CModInfo.CommandLine = "/WriterType UTF8Writer /Async true"; RunTestCase(testCaseGenerator); } [Fact] [OuterLoop] static public void TCErrorState() { RunTest(() => new TCErrorState() { Attribute = new TestCase() { Name = "Invalid State Combinations" } }); } [Fact] [OuterLoop] static public void TCAutoComplete() { RunTest(() => new TCAutoComplete() { Attribute = new TestCase() { Name = "Auto-completion of tokens" } }); } [Fact] [OuterLoop] static public void TCDocument() { RunTest(() => new TCDocument() { Attribute = new TestCase() { Name = "WriteStart/EndDocument" } }); } [Fact] [OuterLoop] static public void TCDocType() { RunTest(() => new TCDocType() { Attribute = new TestCase() { Name = "WriteDocType" } }); } [Fact] [OuterLoop] static public void TCElement() { RunTest(() => new TCElement() { Attribute = new TestCase() { Name = "WriteStart/EndElement" } }); } [Fact] [OuterLoop] static public void TCAttribute() { RunTest(() => new TCAttribute() { Attribute = new TestCase() { Name = "WriteStart/EndAttribute" } }); } [Fact] [OuterLoop] static public void TCWriteAttributes() { RunTest(() => new TCWriteAttributes() { Attribute = new TestCase() { Name = "WriteAttributes(CoreReader)", Param = "COREREADER" } }); } [Fact] [OuterLoop] static public void TCWriteNode_XmlReader() { RunTest(() => new TCWriteNode_XmlReader() { Attribute = new TestCase() { Name = "WriteNode(CoreReader)", Param = "COREREADER" } }); } [Fact] [OuterLoop] static public void TCWriteNode_With_ReadValueChunk() { RunTest(() => new TCWriteNode_With_ReadValueChunk() { Attribute = new TestCase() { Name = "WriteNode with streaming API ReadValueChunk - COREREADER", Param = "COREREADER" } }); } [Fact] [OuterLoop] [ActiveIssue(1491)] static public void TCFullEndElement() { RunTest(() => new TCFullEndElement() { Attribute = new TestCase() { Name = "WriteFullEndElement" } }); } [Fact] [OuterLoop] static public void TCEOFHandling() { RunTest(() => new TCEOFHandling() { Attribute = new TestCase() { Name = "XmlWriterSettings: NewLineHandling" } }); } [Fact] [OuterLoop] static public void TCErrorConditionWriter() { RunTest(() => new TCErrorConditionWriter() { Attribute = new TestCase() { Name = "ErrorCondition" } }); } [Fact] [OuterLoop] static public void TCNamespaceHandling() { RunTest(() => new TCNamespaceHandling() { Attribute = new TestCase() { Name = "XmlWriterSettings: NamespaceHandling" } }); } [Fact] [OuterLoop] static public void TCDefaultWriterSettings() { RunTest(() => new TCDefaultWriterSettings() { Attribute = new TestCase() { Name = "XmlWriterSettings: Default Values" } }); } [Fact] [OuterLoop] static public void TCWriterSettingsMisc() { RunTest(() => new TCWriterSettingsMisc() { Attribute = new TestCase() { Name = "XmlWriterSettings: Reset/Clone" } }); } [Fact] [OuterLoop] static public void TCOmitXmlDecl() { RunTest(() => new TCOmitXmlDecl() { Attribute = new TestCase() { Name = "XmlWriterSettings: OmitXmlDeclaration" } }); } [Fact] [OuterLoop] static public void TCCheckChars() { RunTest(() => new TCCheckChars() { Attribute = new TestCase() { Name = "XmlWriterSettings: CheckCharacters" } }); } [Fact] [OuterLoop] static public void TCNewLineHandling() { RunTest(() => new TCNewLineHandling() { Attribute = new TestCase() { Name = "XmlWriterSettings: NewLineHandling" } }); } [Fact] [OuterLoop] static public void TCNewLineChars() { RunTest(() => new TCNewLineChars() { Attribute = new TestCase() { Name = "XmlWriterSettings: NewLineChars" } }); } [Fact] [OuterLoop] static public void TCIndent() { RunTest(() => new TCIndent() { Attribute = new TestCase() { Name = "XmlWriterSettings: Indent" } }); } [Fact] [OuterLoop] static public void TCIndentChars() { RunTest(() => new TCIndentChars() { Attribute = new TestCase() { Name = "XmlWriterSettings: IndentChars" } }); } [Fact] [OuterLoop] static public void TCNewLineOnAttributes() { RunTest(() => new TCNewLineOnAttributes() { Attribute = new TestCase() { Name = "XmlWriterSettings: NewLineOnAttributes" } }); } [Fact] [OuterLoop] static public void TCStandAlone() { RunTest(() => new TCStandAlone() { Attribute = new TestCase() { Name = "Standalone" } }); } [Fact] [OuterLoop] static public void TCCloseOutput() { RunTest(() => new TCCloseOutput() { Attribute = new TestCase() { Name = "XmlWriterSettings: CloseOutput" } }); } [Fact] [OuterLoop] static public void TCFragmentCL() { RunTest(() => new TCFragmentCL() { Attribute = new TestCase() { Name = "CL = Fragment Tests" } }); } [Fact] [OuterLoop] static public void TCAutoCL() { RunTest(() => new TCAutoCL() { Attribute = new TestCase() { Name = "CL = Auto Tests" } }); } [Fact] [OuterLoop] static public void TCFlushClose() { RunTest(() => new TCFlushClose() { Attribute = new TestCase() { Name = "Close()/Flush()" } }); } [Fact] [OuterLoop] static public void TCWriterWithMemoryStream() { RunTest(() => new TCWriterWithMemoryStream() { Attribute = new TestCase() { Name = "XmlWriter with MemoryStream" } }); } [Fact] [OuterLoop] static public void TCWriteEndDocumentOnCloseTest() { RunTest(() => new TCWriteEndDocumentOnCloseTest() { Attribute = new TestCase() { Name = "XmlWriterSettings: WriteEndDocumentOnClose" } }); } } }
// 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 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Logic { using Azure; using Management; using Rest; using Rest.Azure; using 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> /// SchemasOperations operations. /// </summary> internal partial class SchemasOperations : IServiceOperations<LogicManagementClient>, ISchemasOperations { /// <summary> /// Initializes a new instance of the SchemasOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal SchemasOperations(LogicManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the LogicManagementClient /// </summary> public LogicManagementClient Client { get; private set; } /// <summary> /// Gets a list of integration account schemas. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='integrationAccountName'> /// The integration account name. /// </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<IntegrationAccountSchema>>> ListByIntegrationAccountsWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, ODataQuery<IntegrationAccountSchemaFilter> odataQuery = default(ODataQuery<IntegrationAccountSchemaFilter>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (integrationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "integrationAccountName"); } 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("resourceGroupName", resourceGroupName); tracingParameters.Add("integrationAccountName", integrationAccountName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByIntegrationAccounts", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/schemas").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{integrationAccountName}", System.Uri.EscapeDataString(integrationAccountName)); 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 System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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<IntegrationAccountSchema>>(); _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<IntegrationAccountSchema>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets an integration account schema. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='integrationAccountName'> /// The integration account name. /// </param> /// <param name='schemaName'> /// The integration account schema name. /// </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<IntegrationAccountSchema>> GetWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, string schemaName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (integrationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "integrationAccountName"); } if (schemaName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "schemaName"); } 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("resourceGroupName", resourceGroupName); tracingParameters.Add("integrationAccountName", integrationAccountName); tracingParameters.Add("schemaName", schemaName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/schemas/{schemaName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{integrationAccountName}", System.Uri.EscapeDataString(integrationAccountName)); _url = _url.Replace("{schemaName}", System.Uri.EscapeDataString(schemaName)); 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 System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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<IntegrationAccountSchema>(); _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<IntegrationAccountSchema>(_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> /// Creates or updates an integration account schema. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='integrationAccountName'> /// The integration account name. /// </param> /// <param name='schemaName'> /// The integration account schema name. /// </param> /// <param name='schema'> /// The integration account schema. /// </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<IntegrationAccountSchema>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, string schemaName, IntegrationAccountSchema schema, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (integrationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "integrationAccountName"); } if (schemaName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "schemaName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (schema == null) { throw new ValidationException(ValidationRules.CannotBeNull, "schema"); } if (schema != null) { schema.Validate(); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("integrationAccountName", integrationAccountName); tracingParameters.Add("schemaName", schemaName); tracingParameters.Add("schema", schema); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/schemas/{schemaName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{integrationAccountName}", System.Uri.EscapeDataString(integrationAccountName)); _url = _url.Replace("{schemaName}", System.Uri.EscapeDataString(schemaName)); 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 System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(schema != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(schema, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = 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<IntegrationAccountSchema>(); _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<IntegrationAccountSchema>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<IntegrationAccountSchema>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes an integration account schema. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='integrationAccountName'> /// The integration account name. /// </param> /// <param name='schemaName'> /// The integration account schema name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, string schemaName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (integrationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "integrationAccountName"); } if (schemaName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "schemaName"); } 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("resourceGroupName", resourceGroupName); tracingParameters.Add("integrationAccountName", integrationAccountName); tracingParameters.Add("schemaName", schemaName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/schemas/{schemaName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{integrationAccountName}", System.Uri.EscapeDataString(integrationAccountName)); _url = _url.Replace("{schemaName}", System.Uri.EscapeDataString(schemaName)); 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 System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets a list of integration account schemas. /// </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<IntegrationAccountSchema>>> ListByIntegrationAccountsNextWithHttpMessagesAsync(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, "ListByIntegrationAccountsNext", 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 System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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<IntegrationAccountSchema>>(); _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<IntegrationAccountSchema>>(_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; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.Diagnostics; using Test.Utilities; using Xunit; namespace System.Runtime.Analyzers.UnitTests { public class ProvideCorrectArgumentsToFormattingMethodsTests : DiagnosticAnalyzerTestBase { protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() { return new ProvideCorrectArgumentsToFormattingMethodsAnalyzer(); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new ProvideCorrectArgumentsToFormattingMethodsAnalyzer(); } #region Diagnostic Tests [Fact] public void CA2241CSharpString() { VerifyCSharp(@" using System; public class C { void Method() { var a = String.Format("""", 1); var b = String.Format(""{0}"", 1, 2); var c = String.Format(""{0} {1}"", 1, 2, 3); var d = String.Format(""{0} {1} {2}"", 1, 2, 3, 4); var e = string.Format(""{0} {0}"", 1, 2); IFormatProvider p = null; var f = String.Format(p, """", 1); var g = String.Format(p, ""{0}"", 1, 2); var h = String.Format(p, ""{0} {1}"", 1, 2, 3); var i = String.Format(p, ""{0} {1} {2}"", 1, 2, 3, 4); } } ", GetCA2241CSharpResultAt(8, 17), GetCA2241CSharpResultAt(9, 17), GetCA2241CSharpResultAt(10, 17), GetCA2241CSharpResultAt(11, 17), GetCA2241CSharpResultAt(12, 17), GetCA2241CSharpResultAt(15, 17), GetCA2241CSharpResultAt(16, 17), GetCA2241CSharpResultAt(17, 17), GetCA2241CSharpResultAt(18, 17)); } [Fact] public void CA2241CSharpConsoleWrite() { VerifyCSharp(@" using System; public class C { void Method() { Console.Write("""", 1); Console.Write(""{0}"", 1, 2); Console.Write(""{0} {1}"", 1, 2, 3); Console.Write(""{0} {1} {2}"", 1, 2, 3, 4); Console.Write(""{0} {1} {2} {3}"", 1, 2, 3, 4, 5); } } ", GetCA2241CSharpResultAt(8, 9), GetCA2241CSharpResultAt(9, 9), GetCA2241CSharpResultAt(10, 9), GetCA2241CSharpResultAt(11, 9), GetCA2241CSharpResultAt(12, 9)); } [Fact] public void CA2241CSharpConsoleWriteLine() { VerifyCSharp(@" using System; public class C { void Method() { Console.WriteLine("""", 1); Console.WriteLine(""{0}"", 1, 2); Console.WriteLine(""{0} {1}"", 1, 2, 3); Console.WriteLine(""{0} {1} {2}"", 1, 2, 3, 4); Console.WriteLine(""{0} {1} {2} {3}"", 1, 2, 3, 4, 5); } } ", GetCA2241CSharpResultAt(8, 9), GetCA2241CSharpResultAt(9, 9), GetCA2241CSharpResultAt(10, 9), GetCA2241CSharpResultAt(11, 9), GetCA2241CSharpResultAt(12, 9)); } [Fact] public void CA2241CSharpPassing() { VerifyCSharp(@" using System; public class C { void Method() { var a = String.Format(""{0}"", 1); var b = String.Format(""{0} {1}"", 1, 2); var c = String.Format(""{0} {1} {2}"", 1, 2, 3); var d = String.Format(""{0} {1} {2} {3}"", 1, 2, 3, 4); var e = String.Format(""{0} {1} {2} {0}"", 1, 2, 3); Console.Write(""{0}"", 1); Console.Write(""{0} {1}"", 1, 2); Console.Write(""{0} {1} {2}"", 1, 2, 3); Console.Write(""{0} {1} {2} {3}"", 1, 2, 3, 4); Console.Write(""{0} {1} {2} {3} {4}"", 1, 2, 3, 4, 5); Console.Write(""{0} {1} {2} {3} {0}"", 1, 2, 3, 4); Console.WriteLine(""{0}"", 1); Console.WriteLine(""{0} {1}"", 1, 2); Console.WriteLine(""{0} {1} {2}"", 1, 2, 3); Console.WriteLine(""{0} {1} {2} {3}"", 1, 2, 3, 4); Console.WriteLine(""{0} {1} {2} {3} {4}"", 1, 2, 3, 4, 5); Console.WriteLine(""{0} {1} {2} {3} {0}"", 1, 2, 3, 4); } } "); } [Fact] public void CA2241CSharpExplicitObjectArrayNotSupported() { // currently not supported due to "https://github.com/dotnet/roslyn/issues/7342" VerifyCSharp(@" using System; public class C { void Method() { var s = String.Format(""{0} {1} {2} {3}"", new object[] {1, 2}); Console.Write(""{0} {1} {2} {3}"", new object[] {1, 2, 3, 4, 5}); Console.WriteLine(""{0} {1} {2} {3}"", new object[] {1, 2, 3, 4, 5}); } } "); } [Fact] public void CA2241CSharpVarArgsNotSupported() { // currently not supported due to "https://github.com/dotnet/roslyn/issues/7346" VerifyCSharp(@" using System; public class C { void Method() { Console.Write(""{0} {1} {2} {3} {4}"", 1, 2, 3, 4, __arglist(5)); Console.WriteLine(""{0} {1} {2} {3} {4}"", 1, 2, 3, 4, __arglist(5)); } } "); } [Fact] public void CA2241VBString() { VerifyBasic(@" Imports System Public Class C Sub Method() Dim a = String.Format("""", 1) Dim b = String.Format(""{0}"", 1, 2) Dim c = String.Format(""{0} {1}"", 1, 2, 3) Dim d = String.Format(""{0} {1} {2}"", 1, 2, 3, 4) Dim p as IFormatProvider = Nothing Dim e = String.Format(p, """", 1) Dim f = String.Format(p, ""{0}"", 1, 2) Dim g = String.Format(p, ""{0} {1}"", 1, 2, 3) Dim h = String.Format(p, ""{0} {1} {2}"", 1, 2, 3, 4) End Sub End Class ", GetCA2241BasicResultAt(6, 17), GetCA2241BasicResultAt(7, 17), GetCA2241BasicResultAt(8, 17), GetCA2241BasicResultAt(9, 17), GetCA2241BasicResultAt(12, 17), GetCA2241BasicResultAt(13, 17), GetCA2241BasicResultAt(14, 17), GetCA2241BasicResultAt(15, 17)); } [Fact] public void CA2241VBConsoleWrite() { // this works in VB // Dim s = Console.WriteLine(""{0} {1} {2}"", 1, 2, 3, 4) // since VB bind it to __arglist version where we skip analysis // due to a bug - https://github.com/dotnet/roslyn/issues/7346 // we might skip it only in C# since VB doesnt support __arglist VerifyBasic(@" Imports System Public Class C Sub Method() Console.Write("""", 1) Console.Write(""{0}"", 1, 2) Console.Write(""{0} {1}"", 1, 2, 3) Console.Write(""{0} {1} {2}"", 1, 2, 3, 4) Console.Write(""{0} {1} {2} {3}"", 1, 2, 3, 4, 5) End Sub End Class ", GetCA2241BasicResultAt(6, 9), GetCA2241BasicResultAt(7, 9), GetCA2241BasicResultAt(8, 9), GetCA2241BasicResultAt(10, 9)); } [Fact] public void CA2241VBConsoleWriteLine() { // this works in VB // Dim s = Console.WriteLine(""{0} {1} {2}"", 1, 2, 3, 4) // since VB bind it to __arglist version where we skip analysis // due to a bug - https://github.com/dotnet/roslyn/issues/7346 // we might skip it only in C# since VB doesnt support __arglist VerifyBasic(@" Imports System Public Class C Sub Method() Console.WriteLine("""", 1) Console.WriteLine(""{0}"", 1, 2) Console.WriteLine(""{0} {1}"", 1, 2, 3) Console.WriteLine(""{0} {1} {2}"", 1, 2, 3, 4) Console.WriteLine(""{0} {1} {2} {3}"", 1, 2, 3, 4, 5) End Sub End Class ", GetCA2241BasicResultAt(6, 9), GetCA2241BasicResultAt(7, 9), GetCA2241BasicResultAt(8, 9), GetCA2241BasicResultAt(10, 9)); } [Fact] public void CA2241VBPassing() { VerifyBasic(@" Imports System Public Class C Sub Method() Dim a = String.Format(""{0}"", 1) Dim b = String.Format(""{0} {1}"", 1, 2) Dim c = String.Format(""{0} {1} {2}"", 1, 2, 3) Dim d = String.Format(""{0} {1} {2} {3}"", 1, 2, 3, 4) Console.Write(""{0}"", 1) Console.Write(""{0} {1}"", 1, 2) Console.Write(""{0} {1} {2}"", 1, 2, 3) Console.Write(""{0} {1} {2} {3}"", 1, 2, 3, 4) Console.Write(""{0} {1} {2} {3} {4}"", 1, 2, 3, 4, 5) Console.WriteLine(""{0}"", 1) Console.WriteLine(""{0} {1}"", 1, 2) Console.WriteLine(""{0} {1} {2}"", 1, 2, 3) Console.WriteLine(""{0} {1} {2} {3}"", 1, 2, 3, 4) Console.WriteLine(""{0} {1} {2} {3} {4}"", 1, 2, 3, 4, 5) End Sub End Class "); } [Fact] public void CA2241VBExplicitObjectArraySupported() { VerifyBasic(@" Imports System Public Class C Sub Method() Dim s = String.Format(""{0} {1} {2} {3}"", New Object() {1, 2}) Console.Write(""{0} {1} {2} {3}"", New Object() {1, 2, 3, 4, 5}) Console.WriteLine(""{0} {1} {2} {3}"", New Object() {1, 2, 3, 4, 5}) End Sub End Class ", GetCA2241BasicResultAt(6, 17), GetCA2241BasicResultAt(7, 9), GetCA2241BasicResultAt(8, 9)); } [Fact] public void CA2241CSharpFormatStringParser() { VerifyCSharp(@" using System; public class C { void Method() { var a = String.Format(""{0,-4 :xd}"", 1); var b = String.Format(""{0 , 5 : d} {1}"", 1, 2); var c = String.Format(""{0:d} {1} {2}"", 1, 2, 3); var d = String.Format(""{0, 5} {1} {2} {3}"", 1, 2, 3, 4); Console.Write(""{0,1}"", 1); Console.Write(""{0: x} {1}"", 1, 2); Console.Write(""{{escape}}{0} {1} {2}"", 1, 2, 3); Console.Write(""{0: {{escape}} x} {1} {2} {3}"", 1, 2, 3, 4); Console.Write(""{0 , -10 : {{escape}} y} {1} {2} {3} {4}"", 1, 2, 3, 4, 5); } } "); } #endregion private static DiagnosticResult GetCA2241CSharpResultAt(int line, int column) { return GetCSharpResultAt(line, column, ProvideCorrectArgumentsToFormattingMethodsAnalyzer.RuleId, SystemRuntimeAnalyzersResources.ProvideCorrectArgumentsToFormattingMethodsMessage); } private static DiagnosticResult GetCA2241BasicResultAt(int line, int column) { return GetBasicResultAt(line, column, ProvideCorrectArgumentsToFormattingMethodsAnalyzer.RuleId, SystemRuntimeAnalyzersResources.ProvideCorrectArgumentsToFormattingMethodsMessage); } } }
using System; using Microsoft.Extensions.Configuration; using Serilog; using Serilog.Events; using Umbraco.Cms.Core.Hosting; using Umbraco.Cms.Infrastructure.Logging.Serilog; using Umbraco.Extensions; namespace Umbraco.Cms.Core.Logging.Serilog { ///<summary> /// Implements MS ILogger on top of Serilog. ///</summary> public class SerilogLogger : IDisposable { public global::Serilog.ILogger SerilogLog { get; } public SerilogLogger(LoggerConfiguration logConfig) { //Configure Serilog static global logger with config passed in SerilogLog = logConfig.CreateLogger(); } /// <summary> /// Creates a logger with some pre-defined configuration and remainder from config file /// </summary> /// <remarks>Used by UmbracoApplicationBase to get its logger.</remarks> public static SerilogLogger CreateWithDefaultConfiguration( IHostingEnvironment hostingEnvironment, ILoggingConfiguration loggingConfiguration, IConfiguration configuration, out UmbracoFileConfiguration umbracoFileConfig) { var serilogConfig = new LoggerConfiguration() .MinimalConfiguration(hostingEnvironment, loggingConfiguration, configuration, out umbracoFileConfig) .ReadFrom.Configuration(configuration); return new SerilogLogger(serilogConfig); } /// <summary> /// Gets a contextualized logger. /// </summary> private global::Serilog.ILogger LoggerFor(Type reporting) => SerilogLog.ForContext(reporting); /// <summary> /// Maps Umbraco's log level to Serilog's. /// </summary> private LogEventLevel MapLevel(LogLevel level) { switch (level) { case LogLevel.Debug: return LogEventLevel.Debug; case LogLevel.Error: return LogEventLevel.Error; case LogLevel.Fatal: return LogEventLevel.Fatal; case LogLevel.Information: return LogEventLevel.Information; case LogLevel.Verbose: return LogEventLevel.Verbose; case LogLevel.Warning: return LogEventLevel.Warning; } throw new NotSupportedException($"LogLevel \"{level}\" is not supported."); } /// <inheritdoc/> public bool IsEnabled(Type reporting, LogLevel level) => LoggerFor(reporting).IsEnabled(MapLevel(level)); /// <inheritdoc/> public void Fatal(Type reporting, Exception exception, string message) { var logger = LoggerFor(reporting); logger.Fatal(exception, message); } /// <inheritdoc/> public void Fatal(Type reporting, Exception exception) { var logger = LoggerFor(reporting); var message = "Exception."; logger.Fatal(exception, message); } /// <inheritdoc/> public void Fatal(Type reporting, string message) { LoggerFor(reporting).Fatal(message); } /// <inheritdoc/> public void Fatal(Type reporting, string messageTemplate, params object[] propertyValues) { LoggerFor(reporting).Fatal(messageTemplate, propertyValues); } /// <inheritdoc/> public void Fatal(Type reporting, Exception exception, string messageTemplate, params object[] propertyValues) { var logger = LoggerFor(reporting); logger.Fatal(exception, messageTemplate, propertyValues); } /// <inheritdoc/> public void Error(Type reporting, Exception exception, string message) { var logger = LoggerFor(reporting); logger.Error(exception, message); } /// <inheritdoc/> public void Error(Type reporting, Exception exception) { var logger = LoggerFor(reporting); var message = "Exception"; logger.Error(exception, message); } /// <inheritdoc/> public void Error(Type reporting, string message) { LoggerFor(reporting).Error(message); } /// <inheritdoc/> public void Error(Type reporting, string messageTemplate, params object[] propertyValues) { LoggerFor(reporting).Error(messageTemplate, propertyValues); } /// <inheritdoc/> public void Error(Type reporting, Exception exception, string messageTemplate, params object[] propertyValues) { var logger = LoggerFor(reporting); logger.Error(exception, messageTemplate, propertyValues); } /// <inheritdoc/> public void Warn(Type reporting, string message) { LoggerFor(reporting).Warning(message); } /// <inheritdoc/> public void Warn(Type reporting, string message, params object[] propertyValues) { LoggerFor(reporting).Warning(message, propertyValues); } /// <inheritdoc/> public void Warn(Type reporting, Exception exception, string message) { LoggerFor(reporting).Warning(exception, message); } /// <inheritdoc/> public void Warn(Type reporting, Exception exception, string messageTemplate, params object[] propertyValues) { LoggerFor(reporting).Warning(exception, messageTemplate, propertyValues); } /// <inheritdoc/> public void Info(Type reporting, string message) { LoggerFor(reporting).Information(message); } /// <inheritdoc/> public void Info(Type reporting, string messageTemplate, params object[] propertyValues) { LoggerFor(reporting).Information(messageTemplate, propertyValues); } /// <inheritdoc/> public void Debug(Type reporting, string message) { LoggerFor(reporting).Debug(message); } /// <inheritdoc/> public void Debug(Type reporting, string messageTemplate, params object[] propertyValues) { LoggerFor(reporting).Debug(messageTemplate, propertyValues); } /// <inheritdoc/> public void Verbose(Type reporting, string message) { LoggerFor(reporting).Verbose(message); } /// <inheritdoc/> public void Verbose(Type reporting, string messageTemplate, params object[] propertyValues) { LoggerFor(reporting).Verbose(messageTemplate, propertyValues); } public void Dispose() { SerilogLog.DisposeIfDisposable(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System; using System.Reflection; using System.Collections.Generic; namespace System.Reflection.Tests { public class TypeInfoDeclaredGenericTypeArgumentsTests { //Interfaces // Verify Generic Arguments [Fact] public static void TestGenericArguments1() { VerifyGenericTypeArguments(typeof(Test_I), new String[] { }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments2() { VerifyGenericTypeArguments(typeof(Test_IG<>), new String[] { }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments3() { VerifyGenericTypeArguments(typeof(Test_IG<Int32>), new String[] { "Int32" }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments4() { VerifyGenericTypeArguments(typeof(Test_IG2<,>), new String[] { }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments5() { VerifyGenericTypeArguments(typeof(Test_IG2<Int32, String>), new String[] { "Int32", "String" }, null); } // For Structs // Verify Generic Arguments [Fact] public static void TestGenericArguments6() { VerifyGenericTypeArguments(typeof(Test_S), new String[] { }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments7() { VerifyGenericTypeArguments(typeof(Test_SG<>), new String[] { }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments8() { VerifyGenericTypeArguments(typeof(Test_SG<Int32>), new String[] { "Int32" }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments9() { VerifyGenericTypeArguments(typeof(Test_SG2<,>), new String[] { }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments10() { VerifyGenericTypeArguments(typeof(Test_SG2<Int32, String>), new String[] { "Int32", "String" }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments11() { VerifyGenericTypeArguments(typeof(Test_SI), new String[] { }, new String[] { }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments12() { VerifyGenericTypeArguments(typeof(Test_SIG<>), new String[] { }, new String[] { "TS" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments13() { VerifyGenericTypeArguments(typeof(Test_SIG<Int32>), new String[] { "Int32" }, new String[] { "Int32" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments14() { VerifyGenericTypeArguments(typeof(Test_SIG2<,>), new String[] { }, new String[] { "TS", "VS" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments15() { VerifyGenericTypeArguments(typeof(Test_SIG2<Int32, String>), new String[] { "Int32", "String" }, new String[] { "Int32", "String" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments16() { VerifyGenericTypeArguments(typeof(Test_SI_Int), new String[] { }, new String[] { "Int32" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments17() { VerifyGenericTypeArguments(typeof(Test_SIG_Int<>), new String[] { }, new String[] { "TS", "Int32" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments18() { VerifyGenericTypeArguments(typeof(Test_SIG_Int<String>), new String[] { "String" }, new String[] { "String", "Int32" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments19() { VerifyGenericTypeArguments(typeof(Test_SIG_Int_Int), new String[] { }, new String[] { "Int32", "Int32" }); } //For classes // Verify Generic Arguments [Fact] public static void TestGenericArguments20() { VerifyGenericTypeArguments(typeof(Test_C), new String[] { }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments21() { VerifyGenericTypeArguments(typeof(Test_CG<>), new String[] { }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments22() { VerifyGenericTypeArguments(typeof(Test_CG<Int32>), new String[] { "Int32" }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments23() { VerifyGenericTypeArguments(typeof(Test_CG2<,>), new String[] { }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments24() { VerifyGenericTypeArguments(typeof(Test_CG2<Int32, String>), new String[] { "Int32", "String" }, null); } // Verify Generic Arguments [Fact] public static void TestGenericArguments25() { VerifyGenericTypeArguments(typeof(Test_CI), new String[] { }, new String[] { }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments26() { VerifyGenericTypeArguments(typeof(Test_CIG<Int32>), new String[] { "Int32" }, new String[] { "Int32" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments27() { VerifyGenericTypeArguments(typeof(Test_CIG2<,>), new String[] { }, new String[] { "T", "V" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments28() { VerifyGenericTypeArguments(typeof(Test_CIG2<Int32, String>), new String[] { "Int32", "String" }, new String[] { "Int32", "String" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments29() { VerifyGenericTypeArguments(typeof(Test_CI_Int), new String[] { }, new String[] { "Int32" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments30() { VerifyGenericTypeArguments(typeof(Test_CIG_Int<>), new String[] { }, new String[] { "T", "Int32" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments31() { VerifyGenericTypeArguments(typeof(Test_CIG_Int<String>), new String[] { "String" }, new String[] { "String", "Int32" }); } // Verify Generic Arguments [Fact] public static void TestGenericArguments32() { VerifyGenericTypeArguments(typeof(Test_CIG_Int_Int), new String[] { }, new String[] { "Int32", "Int32" }); } //private helper methods private static void VerifyGenericTypeArguments(Type type, String[] expectedGTA, String[] expectedBaseGTA) { //Fix to initialize Reflection String str = typeof(Object).Name; TypeInfo typeInfo = type.GetTypeInfo(); Type[] retGenericTypeArguments = typeInfo.GenericTypeArguments; Assert.Equal(expectedGTA.Length, retGenericTypeArguments.Length); for (int i = 0; i < retGenericTypeArguments.Length; i++) { Assert.Equal(expectedGTA[i], retGenericTypeArguments[i].Name); } Type baseType = typeInfo.BaseType; if (baseType == null) return; if (baseType == typeof(ValueType) || baseType == typeof(Object)) { Type[] interfaces = getInterfaces(typeInfo); if (interfaces.Length == 0) return; baseType = interfaces[0]; } TypeInfo typeInfoBase = baseType.GetTypeInfo(); retGenericTypeArguments = typeInfoBase.GenericTypeArguments; Assert.Equal(expectedBaseGTA.Length, retGenericTypeArguments.Length); for (int i = 0; i < retGenericTypeArguments.Length; i++) { Assert.Equal(expectedBaseGTA[i], retGenericTypeArguments[i].Name); } } private static Type[] getInterfaces(TypeInfo ti) { List<Type> list = new List<Type>(); IEnumerator<Type> allinterfaces = ti.ImplementedInterfaces.GetEnumerator(); while (allinterfaces.MoveNext()) { list.Add(allinterfaces.Current); } return list.ToArray(); } } //Metadata for Reflection public interface Test_I { } public interface Test_IG<TI> { } public interface Test_IG2<TI, VI> { } public struct Test_S { } public struct Test_SG<TS> { } public struct Test_SG2<TS, VS> { } public struct Test_SI : Test_I { } public struct Test_SIG<TS> : Test_IG<TS> { } public struct Test_SIG2<TS, VS> : Test_IG2<TS, VS> { } public struct Test_SI_Int : Test_IG<Int32> { } public struct Test_SIG_Int<TS> : Test_IG2<TS, Int32> { } public struct Test_SIG_Int_Int : Test_IG2<Int32, Int32> { } public class Test_C { } public class Test_CG<T> { } public class Test_CG2<T, V> { } public class Test_CI : Test_I { } public class Test_CIG<T> : Test_IG<T> { } public class Test_CIG2<T, V> : Test_IG2<T, V> { } public class Test_CI_Int : Test_IG<Int32> { } public class Test_CIG_Int<T> : Test_CG2<T, Int32> { } public class Test_CIG_Int_Int : Test_CG2<Int32, Int32> { } }
using System; using System.IO; using System.Collections.Specialized; using System.Net; using System.Net.Cache; using System.Text; using System.Web; using System.Security.Cryptography; using Newtonsoft.Json; using System.Security.Cryptography.X509Certificates; using System.Net.Security; using SteamKit2; namespace SteamTrade { public class SteamWeb { public const string SteamCommunityDomain = "steamcommunity.com"; public string Token { get; private set; } public string SessionId { get; private set; } public string TokenSecure { get; private set; } private CookieContainer _cookies = new CookieContainer(); public string Fetch(string url, string method, NameValueCollection data = null, bool ajax = true, string referer = "") { using (HttpWebResponse response = Request(url, method, data, ajax, referer)) { using (Stream responseStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(responseStream)) { return reader.ReadToEnd(); } } } } public HttpWebResponse Request(string url, string method, NameValueCollection data = null, bool ajax = true, string referer = "") { //Append the data to the URL for GET-requests bool isGetMethod = (method.ToLower() == "get"); string dataString = (data == null ? null : String.Join("&", Array.ConvertAll(data.AllKeys, key => String.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(data[key])) ))); if (isGetMethod && !String.IsNullOrEmpty(dataString)) { url += (url.Contains("?") ? "&" : "?") + dataString; } //Setup the request HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = method; request.Accept = "application/json, text/javascript;q=0.9, */*;q=0.5"; request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; //request.Host is set automatically request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36"; request.Referer = string.IsNullOrEmpty(referer) ? "http://steamcommunity.com/trade/1" : referer; request.Timeout = 50000; //Timeout after 50 seconds request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Revalidate); request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; if (ajax) { request.Headers.Add("X-Requested-With", "XMLHttpRequest"); request.Headers.Add("X-Prototype-Version", "1.7"); } // Cookies request.CookieContainer = _cookies; // Write the data to the body for POST and other methods if (!isGetMethod && !String.IsNullOrEmpty(dataString)) { byte[] dataBytes = Encoding.UTF8.GetBytes(dataString); request.ContentLength = dataBytes.Length; using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(dataBytes, 0, dataBytes.Length); } } // Get the response return request.GetResponse() as HttpWebResponse; } /// <summary> /// Executes the login by using the Steam Website. /// </summary> public bool DoLogin(string username, string password) { var data = new NameValueCollection(); data.Add("username", username); string response = Fetch("https://steamcommunity.com/login/getrsakey", "POST", data, false); GetRsaKey rsaJSON = JsonConvert.DeserializeObject<GetRsaKey>(response); // Validate if (!rsaJSON.success) { return false; } //RSA Encryption RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); RSAParameters rsaParameters = new RSAParameters(); rsaParameters.Exponent = HexToByte(rsaJSON.publickey_exp); rsaParameters.Modulus = HexToByte(rsaJSON.publickey_mod); rsa.ImportParameters(rsaParameters); byte[] bytePassword = Encoding.ASCII.GetBytes(password); byte[] encodedPassword = rsa.Encrypt(bytePassword, false); string encryptedBase64Password = Convert.ToBase64String(encodedPassword); SteamResult loginJson = null; CookieCollection cookieCollection; string steamGuardText = ""; string steamGuardId = ""; do { Console.WriteLine("SteamWeb: Logging In..."); bool captcha = loginJson != null && loginJson.captcha_needed == true; bool steamGuard = loginJson != null && loginJson.emailauth_needed == true; string time = Uri.EscapeDataString(rsaJSON.timestamp); string capGID = loginJson == null ? null : Uri.EscapeDataString(loginJson.captcha_gid); data = new NameValueCollection(); data.Add("password", encryptedBase64Password); data.Add("username", username); // Captcha string capText = ""; if (captcha) { Console.WriteLine("SteamWeb: Captcha is needed."); System.Diagnostics.Process.Start("https://steamcommunity.com/public/captcha.php?gid=" + loginJson.captcha_gid); Console.WriteLine("SteamWeb: Type the captcha:"); capText = Uri.EscapeDataString(Console.ReadLine()); } data.Add("captchagid", captcha ? capGID : ""); data.Add("captcha_text", captcha ? capText : ""); // Captcha end // SteamGuard if (steamGuard) { Console.WriteLine("SteamWeb: SteamGuard is needed."); Console.WriteLine("SteamWeb: Type the code:"); steamGuardText = Uri.EscapeDataString(Console.ReadLine()); steamGuardId = loginJson.emailsteamid; } data.Add("emailauth", steamGuardText); data.Add("emailsteamid", steamGuardId); // SteamGuard end data.Add("rsatimestamp", time); using(HttpWebResponse webResponse = Request("https://steamcommunity.com/login/dologin/", "POST", data, false)) { using(StreamReader reader = new StreamReader(webResponse.GetResponseStream())) { string json = reader.ReadToEnd(); loginJson = JsonConvert.DeserializeObject<SteamResult>(json); cookieCollection = webResponse.Cookies; } } } while (loginJson.captcha_needed || loginJson.emailauth_needed); if (loginJson.success) { _cookies = new CookieContainer(); foreach (Cookie cookie in cookieCollection) { _cookies.Add(cookie); } SubmitCookies(_cookies); return true; } else { Console.WriteLine("SteamWeb Error: " + loginJson.message); return false; } } ///<summary> /// Authenticate using SteamKit2 and ISteamUserAuth. /// This does the same as SteamWeb.DoLogin(), but without contacting the Steam Website. /// </summary> /// <remarks>Should this one doesnt work anymore, use <see cref="SteamWeb.DoLogin"/></remarks> public bool Authenticate(string myUniqueId, SteamClient client, string myLoginKey) { Token = TokenSecure = ""; SessionId = Convert.ToBase64String(Encoding.UTF8.GetBytes(myUniqueId)); _cookies = new CookieContainer(); using (dynamic userAuth = WebAPI.GetInterface("ISteamUserAuth")) { // generate an AES session key var sessionKey = CryptoHelper.GenerateRandomBlock(32); // rsa encrypt it with the public key for the universe we're on byte[] cryptedSessionKey = null; using (RSACrypto rsa = new RSACrypto(KeyDictionary.GetPublicKey(client.ConnectedUniverse))) { cryptedSessionKey = rsa.Encrypt(sessionKey); } byte[] loginKey = new byte[20]; Array.Copy(Encoding.ASCII.GetBytes(myLoginKey), loginKey, myLoginKey.Length); // aes encrypt the loginkey with our session key byte[] cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey); KeyValue authResult; try { authResult = userAuth.AuthenticateUser( steamid: client.SteamID.ConvertToUInt64(), sessionkey: HttpUtility.UrlEncode(cryptedSessionKey), encrypted_loginkey: HttpUtility.UrlEncode(cryptedLoginKey), method: "POST", secure: true ); } catch (Exception) { Token = TokenSecure = null; return false; } Token = authResult["token"].AsString(); TokenSecure = authResult["tokensecure"].AsString(); _cookies.Add(new Cookie("sessionid", SessionId, String.Empty, SteamCommunityDomain)); _cookies.Add(new Cookie("steamLogin", Token, String.Empty, SteamCommunityDomain)); _cookies.Add(new Cookie("steamLoginSecure", TokenSecure, String.Empty, SteamCommunityDomain)); return true; } } /// <summary> /// Helper method to verify our precious cookies. /// </summary> /// <param name="cookies">CookieContainer with our cookies.</param> /// <returns>true if cookies are correct; false otherwise</returns> public bool VerifyCookies() { using (HttpWebResponse response = Request("http://steamcommunity.com/", "HEAD")) { return response.Cookies["steamLogin"] == null || !response.Cookies["steamLogin"].Value.Equals("deleted"); } } static void SubmitCookies (CookieContainer cookies) { HttpWebRequest w = WebRequest.Create("https://steamcommunity.com/") as HttpWebRequest; w.Method = "POST"; w.ContentType = "application/x-www-form-urlencoded"; w.CookieContainer = cookies; w.GetResponse().Close(); } private byte[] HexToByte(string hex) { if (hex.Length % 2 == 1) throw new Exception("The binary key cannot have an odd number of digits"); byte[] arr = new byte[hex.Length >> 1]; int l = hex.Length; for (int i = 0; i < (l >> 1); ++i) { arr[i] = (byte)((GetHexVal(hex[i << 1]) << 4) + (GetHexVal(hex[(i << 1) + 1]))); } return arr; } private int GetHexVal(char hex) { int val = (int)hex; return val - (val < 58 ? 48 : 55); } public bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) { // allow all certificates return true; } } // JSON Classes public class GetRsaKey { public bool success { get; set; } public string publickey_mod { get; set; } public string publickey_exp { get; set; } public string timestamp { get; set; } } public class SteamResult { public bool success { get; set; } public string message { get; set; } public bool captcha_needed { get; set; } public string captcha_gid { get; set; } public bool emailauth_needed { get; set; } public string emailsteamid { get; set; } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.ServiceModel.Description { using System.CodeDom; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime; using System.Runtime.Serialization; using System.ServiceModel.Channels; using System.ServiceModel.Dispatcher; class DataContractSerializerOperationGenerator : IOperationBehavior, IOperationContractGenerationExtension { Dictionary<OperationDescription, DataContractFormatAttribute> operationAttributes = new Dictionary<OperationDescription, DataContractFormatAttribute>(); OperationGenerator operationGenerator; Dictionary<MessagePartDescription, ICollection<CodeTypeReference>> knownTypes; Dictionary<MessagePartDescription, bool> isNonNillableReferenceTypes; CodeCompileUnit codeCompileUnit; public DataContractSerializerOperationGenerator() : this(new CodeCompileUnit()) { } public DataContractSerializerOperationGenerator(CodeCompileUnit codeCompileUnit) { this.codeCompileUnit = codeCompileUnit; this.operationGenerator = new OperationGenerator(); } internal void Add(MessagePartDescription part, CodeTypeReference typeReference, ICollection<CodeTypeReference> knownTypeReferences, bool isNonNillableReferenceType) { OperationGenerator.ParameterTypes.Add(part, typeReference); if (knownTypeReferences != null) KnownTypes.Add(part, knownTypeReferences); if (isNonNillableReferenceType) { if (isNonNillableReferenceTypes == null) isNonNillableReferenceTypes = new Dictionary<MessagePartDescription, bool>(); isNonNillableReferenceTypes.Add(part, isNonNillableReferenceType); } } internal OperationGenerator OperationGenerator { get { return this.operationGenerator; } } internal Dictionary<OperationDescription, DataContractFormatAttribute> OperationAttributes { get { return operationAttributes; } } internal Dictionary<MessagePartDescription, ICollection<CodeTypeReference>> KnownTypes { get { if (this.knownTypes == null) this.knownTypes = new Dictionary<MessagePartDescription, ICollection<CodeTypeReference>>(); return this.knownTypes; } } void IOperationBehavior.Validate(OperationDescription description) { } void IOperationBehavior.ApplyDispatchBehavior(OperationDescription description, DispatchOperation dispatch) { } void IOperationBehavior.ApplyClientBehavior(OperationDescription description, ClientOperation proxy) { } void IOperationBehavior.AddBindingParameters(OperationDescription description, BindingParameterCollection parameters) { } // Assumption: gets called exactly once per operation void IOperationContractGenerationExtension.GenerateOperation(OperationContractGenerationContext context) { DataContractSerializerOperationBehavior DataContractSerializerOperationBehavior = context.Operation.Behaviors.Find<DataContractSerializerOperationBehavior>() as DataContractSerializerOperationBehavior; DataContractFormatAttribute dataContractFormatAttribute = (DataContractSerializerOperationBehavior == null) ? new DataContractFormatAttribute() : DataContractSerializerOperationBehavior.DataContractFormatAttribute; OperationFormatStyle style = dataContractFormatAttribute.Style; operationGenerator.GenerateOperation(context, ref style, false/*isEncoded*/, new WrappedBodyTypeGenerator(this, context), knownTypes); dataContractFormatAttribute.Style = style; if (dataContractFormatAttribute.Style != TypeLoader.DefaultDataContractFormatAttribute.Style) context.SyncMethod.CustomAttributes.Add(OperationGenerator.GenerateAttributeDeclaration(context.Contract.ServiceContractGenerator, dataContractFormatAttribute)); if (knownTypes != null) { Dictionary<CodeTypeReference, object> operationKnownTypes = new Dictionary<CodeTypeReference, object>(new CodeTypeReferenceComparer()); foreach (MessageDescription message in context.Operation.Messages) { foreach (MessagePartDescription part in message.Body.Parts) AddKnownTypesForPart(context, part, operationKnownTypes); foreach (MessageHeaderDescription header in message.Headers) AddKnownTypesForPart(context, header, operationKnownTypes); if (OperationFormatter.IsValidReturnValue(message.Body.ReturnValue)) AddKnownTypesForPart(context, message.Body.ReturnValue, operationKnownTypes); } } UpdateTargetCompileUnit(context, this.codeCompileUnit); } void AddKnownTypesForPart(OperationContractGenerationContext context, MessagePartDescription part, Dictionary<CodeTypeReference, object> operationKnownTypes) { ICollection<CodeTypeReference> knownTypesForPart; if (knownTypes.TryGetValue(part, out knownTypesForPart)) { foreach (CodeTypeReference knownTypeReference in knownTypesForPart) { object value; if (!operationKnownTypes.TryGetValue(knownTypeReference, out value)) { operationKnownTypes.Add(knownTypeReference, null); CodeAttributeDeclaration knownTypeAttribute = new CodeAttributeDeclaration(typeof(ServiceKnownTypeAttribute).FullName); knownTypeAttribute.Arguments.Add(new CodeAttributeArgument(new CodeTypeOfExpression(knownTypeReference))); context.SyncMethod.CustomAttributes.Add(knownTypeAttribute); } } } } internal static void UpdateTargetCompileUnit(OperationContractGenerationContext context, CodeCompileUnit codeCompileUnit) { CodeCompileUnit targetCompileUnit = context.ServiceContractGenerator.TargetCompileUnit; if (!Object.ReferenceEquals(targetCompileUnit, codeCompileUnit)) { foreach (CodeNamespace codeNamespace in codeCompileUnit.Namespaces) if (!targetCompileUnit.Namespaces.Contains(codeNamespace)) targetCompileUnit.Namespaces.Add(codeNamespace); foreach (string referencedAssembly in codeCompileUnit.ReferencedAssemblies) if (!targetCompileUnit.ReferencedAssemblies.Contains(referencedAssembly)) targetCompileUnit.ReferencedAssemblies.Add(referencedAssembly); foreach (CodeAttributeDeclaration assemblyCustomAttribute in codeCompileUnit.AssemblyCustomAttributes) if (!targetCompileUnit.AssemblyCustomAttributes.Contains(assemblyCustomAttribute)) targetCompileUnit.AssemblyCustomAttributes.Add(assemblyCustomAttribute); foreach (CodeDirective startDirective in codeCompileUnit.StartDirectives) if (!targetCompileUnit.StartDirectives.Contains(startDirective)) targetCompileUnit.StartDirectives.Add(startDirective); foreach (CodeDirective endDirective in codeCompileUnit.EndDirectives) if (!targetCompileUnit.EndDirectives.Contains(endDirective)) targetCompileUnit.EndDirectives.Add(endDirective); foreach (DictionaryEntry userData in codeCompileUnit.UserData) targetCompileUnit.UserData[userData.Key] = userData.Value; } } internal class WrappedBodyTypeGenerator : IWrappedBodyTypeGenerator { static CodeTypeReference dataContractAttributeTypeRef = new CodeTypeReference(typeof(DataContractAttribute)); int memberCount; OperationContractGenerationContext context; DataContractSerializerOperationGenerator dataContractSerializerOperationGenerator; public void ValidateForParameterMode(OperationDescription operation) { if (dataContractSerializerOperationGenerator.isNonNillableReferenceTypes == null) return; foreach (MessageDescription messageDescription in operation.Messages) { if (messageDescription.Body != null) { if (messageDescription.Body.ReturnValue != null) ValidateForParameterMode(messageDescription.Body.ReturnValue); foreach (MessagePartDescription bodyPart in messageDescription.Body.Parts) { ValidateForParameterMode(bodyPart); } } } } void ValidateForParameterMode(MessagePartDescription part) { if (dataContractSerializerOperationGenerator.isNonNillableReferenceTypes.ContainsKey(part)) { ParameterModeException parameterModeException = new ParameterModeException(SR.GetString(SR.SFxCannotImportAsParameters_ElementIsNotNillable, part.Name, part.Namespace)); parameterModeException.MessageContractType = MessageContractType.BareMessageContract; throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(parameterModeException); } } public WrappedBodyTypeGenerator(DataContractSerializerOperationGenerator dataContractSerializerOperationGenerator, OperationContractGenerationContext context) { this.context = context; this.dataContractSerializerOperationGenerator = dataContractSerializerOperationGenerator; } public void AddMemberAttributes(XmlName messageName, MessagePartDescription part, CodeAttributeDeclarationCollection attributesImported, CodeAttributeDeclarationCollection typeAttributes, CodeAttributeDeclarationCollection fieldAttributes) { CodeAttributeDeclaration dataContractAttributeDecl = null; foreach (CodeAttributeDeclaration attr in typeAttributes) { if (attr.AttributeType.BaseType == dataContractAttributeTypeRef.BaseType) { dataContractAttributeDecl = attr; break; } } if (dataContractAttributeDecl == null) { Fx.Assert(String.Format(CultureInfo.InvariantCulture, "Cannot find DataContract attribute for {0}", messageName)); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(String.Format(CultureInfo.InvariantCulture, "Cannot find DataContract attribute for {0}", messageName))); } bool nsAttrFound = false; foreach (CodeAttributeArgument attrArg in dataContractAttributeDecl.Arguments) { if (attrArg.Name == "Namespace") { nsAttrFound = true; string nsValue = ((CodePrimitiveExpression)attrArg.Value).Value.ToString(); if (nsValue != part.Namespace) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxWrapperTypeHasMultipleNamespaces, messageName))); } } if (!nsAttrFound) dataContractAttributeDecl.Arguments.Add(new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(part.Namespace))); DataMemberAttribute dataMemberAttribute = new DataMemberAttribute(); dataMemberAttribute.Order = memberCount++; dataMemberAttribute.EmitDefaultValue = !IsNonNillableReferenceType(part); fieldAttributes.Add(OperationGenerator.GenerateAttributeDeclaration(context.Contract.ServiceContractGenerator, dataMemberAttribute)); } private bool IsNonNillableReferenceType(MessagePartDescription part) { if (dataContractSerializerOperationGenerator.isNonNillableReferenceTypes == null) return false; return dataContractSerializerOperationGenerator.isNonNillableReferenceTypes.ContainsKey(part); } public void AddTypeAttributes(string messageName, string typeNS, CodeAttributeDeclarationCollection typeAttributes, bool isEncoded) { typeAttributes.Add(OperationGenerator.GenerateAttributeDeclaration(context.Contract.ServiceContractGenerator, new DataContractAttribute())); memberCount = 0; } } class CodeTypeReferenceComparer : IEqualityComparer<CodeTypeReference> { public bool Equals(CodeTypeReference x, CodeTypeReference y) { if (Object.ReferenceEquals(x, y)) return true; if (x == null || y == null || x.ArrayRank != y.ArrayRank || x.BaseType != y.BaseType) return false; CodeTypeReferenceCollection xTypeArgs = x.TypeArguments; CodeTypeReferenceCollection yTypeArgs = y.TypeArguments; if (yTypeArgs.Count == xTypeArgs.Count) { foreach (CodeTypeReference xTypeArg in xTypeArgs) { foreach (CodeTypeReference yTypeArg in yTypeArgs) { if (!this.Equals(xTypeArg, xTypeArg)) return false; } } } return true; } public int GetHashCode(CodeTypeReference obj) { return obj.GetHashCode(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal sealed class ExpressionTreeRewriter : ExprVisitorBase { public static ExprBinOp Rewrite(ExprBoundLambda expr) => new ExpressionTreeRewriter().VisitBoundLambda(expr); protected override Expr Dispatch(Expr expr) { Debug.Assert(expr != null); Expr result = base.Dispatch(expr); if (result == expr) { throw Error.InternalCompilerError(); } return result; } ///////////////////////////////////////////////////////////////////////////////// // Statement types. protected override Expr VisitASSIGNMENT(ExprAssignment assignment) { Debug.Assert(assignment != null); // For assignments, we either have a member assignment or an indexed assignment. //Debug.Assert(assignment.GetLHS().isPROP() || assignment.GetLHS().isFIELD() || assignment.GetLHS().isARRAYINDEX() || assignment.GetLHS().isLOCAL()); Expr lhs; if (assignment.LHS is ExprProperty prop) { if (prop.OptionalArguments== null) { // Regular property. lhs = Visit(prop); } else { // Indexed assignment. Here we need to find the instance of the object, create the // PropInfo for the thing, and get the array of expressions that make up the index arguments. // // The LHS becomes Expression.Property(instance, indexerInfo, arguments). Expr instance = Visit(prop.MemberGroup.OptionalObject); Expr propInfo = ExprFactory.CreatePropertyInfo(prop.PropWithTypeSlot.Prop(), prop.PropWithTypeSlot.Ats); Expr arguments = GenerateParamsArray( GenerateArgsList(prop.OptionalArguments), PredefinedType.PT_EXPRESSION); lhs = GenerateCall(PREDEFMETH.PM_EXPRESSION_PROPERTY, instance, propInfo, arguments); } } else { lhs = Visit(assignment.LHS); } Expr rhs = Visit(assignment.RHS); return GenerateCall(PREDEFMETH.PM_EXPRESSION_ASSIGN, lhs, rhs); } protected override Expr VisitMULTIGET(ExprMultiGet pExpr) { return Visit(pExpr.OptionalMulti.Left); } protected override Expr VisitMULTI(ExprMulti pExpr) { Expr rhs = Visit(pExpr.Operator); Expr lhs = Visit(pExpr.Left); return GenerateCall(PREDEFMETH.PM_EXPRESSION_ASSIGN, lhs, rhs); } ///////////////////////////////////////////////////////////////////////////////// // Expression types. private ExprBinOp VisitBoundLambda(ExprBoundLambda anonmeth) { Debug.Assert(anonmeth != null); MethodSymbol lambdaMethod = GetPreDefMethod(PREDEFMETH.PM_EXPRESSION_LAMBDA); AggregateType delegateType = anonmeth.DelegateType; TypeArray lambdaTypeParams = TypeArray.Allocate(delegateType); AggregateType expressionType = SymbolLoader.GetPredefindType(PredefinedType.PT_EXPRESSION); MethWithInst mwi = new MethWithInst(lambdaMethod, expressionType, lambdaTypeParams); Expr createParameters = CreateWraps(anonmeth); Debug.Assert(createParameters != null); Debug.Assert(anonmeth.Expression != null); Expr body = Visit(anonmeth.Expression); Debug.Assert(anonmeth.ArgumentScope.nextChild == null); Expr parameters = GenerateParamsArray(null, PredefinedType.PT_PARAMETEREXPRESSION); Expr args = ExprFactory.CreateList(body, parameters); CType typeRet = TypeManager.SubstType(mwi.Meth().RetType, mwi.GetType(), mwi.TypeArgs); ExprMemberGroup pMemGroup = ExprFactory.CreateMemGroup(null, mwi); ExprCall call = ExprFactory.CreateCall(0, typeRet, args, pMemGroup, mwi); call.PredefinedMethod = PREDEFMETH.PM_EXPRESSION_LAMBDA; return ExprFactory.CreateSequence(createParameters, call); } protected override Expr VisitCONSTANT(ExprConstant expr) { Debug.Assert(expr != null); return GenerateConstant(expr); } protected override Expr VisitLOCAL(ExprLocal local) { Debug.Assert(local != null); Debug.Assert(local.Local.wrap != null); return local.Local.wrap; } protected override Expr VisitFIELD(ExprField expr) { Debug.Assert(expr != null); Expr pObject; if (expr.OptionalObject== null) { pObject = ExprFactory.CreateNull(); } else { pObject = Visit(expr.OptionalObject); } ExprFieldInfo pFieldInfo = ExprFactory.CreateFieldInfo(expr.FieldWithType.Field(), expr.FieldWithType.GetType()); return GenerateCall(PREDEFMETH.PM_EXPRESSION_FIELD, pObject, pFieldInfo); } protected override Expr VisitUSERDEFINEDCONVERSION(ExprUserDefinedConversion expr) { Debug.Assert(expr != null); return GenerateUserDefinedConversion(expr, expr.Argument); } protected override Expr VisitCAST(ExprCast pExpr) { Debug.Assert(pExpr != null); Expr pArgument = pExpr.Argument; // If we have generated an identity cast or reference cast to a base class // we can omit the cast. if (pArgument.Type == pExpr.Type || SymbolLoader.IsBaseClassOfClass(pArgument.Type, pExpr.Type) || CConversions.FImpRefConv(pArgument.Type, pExpr.Type)) { return Visit(pArgument); } // If we have a cast to PredefinedType.PT_G_EXPRESSION and the thing that we're casting is // a EXPRBOUNDLAMBDA that is an expression tree, then just visit the expression tree. if (pExpr.Type != null && pExpr.Type.IsPredefType(PredefinedType.PT_G_EXPRESSION) && pArgument is ExprBoundLambda) { return Visit(pArgument); } Expr result = GenerateConversion(pArgument, pExpr.Type, pExpr.isChecked()); if ((pExpr.Flags & EXPRFLAG.EXF_UNBOXRUNTIME) != 0) { // Propagate the unbox flag to the call for the ExpressionTreeCallRewriter. result.Flags |= EXPRFLAG.EXF_UNBOXRUNTIME; } return result; } protected override Expr VisitCONCAT(ExprConcat expr) { Debug.Assert(expr != null); PREDEFMETH pdm; if (expr.FirstArgument.Type.IsPredefType(PredefinedType.PT_STRING) && expr.SecondArgument.Type.IsPredefType(PredefinedType.PT_STRING)) { pdm = PREDEFMETH.PM_STRING_CONCAT_STRING_2; } else { pdm = PREDEFMETH.PM_STRING_CONCAT_OBJECT_2; } Expr p1 = Visit(expr.FirstArgument); Expr p2 = Visit(expr.SecondArgument); MethodSymbol method = GetPreDefMethod(pdm); Expr methodInfo = ExprFactory.CreateMethodInfo(method, SymbolLoader.GetPredefindType(PredefinedType.PT_STRING), null); return GenerateCall(PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED, p1, p2, methodInfo); } protected override Expr VisitBINOP(ExprBinOp expr) { Debug.Assert(expr != null); if (expr.UserDefinedCallMethod != null) { return GenerateUserDefinedBinaryOperator(expr); } else { return GenerateBuiltInBinaryOperator(expr); } } protected override Expr VisitUNARYOP(ExprUnaryOp pExpr) { Debug.Assert(pExpr != null); if (pExpr.UserDefinedCallMethod != null) { return GenerateUserDefinedUnaryOperator(pExpr); } else { return GenerateBuiltInUnaryOperator(pExpr); } } protected override Expr VisitARRAYINDEX(ExprArrayIndex pExpr) { Debug.Assert(pExpr != null); Expr arr = Visit(pExpr.Array); Expr args = GenerateIndexList(pExpr.Index); if (args is ExprList) { Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION); return GenerateCall(PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2, arr, Params); } return GenerateCall(PREDEFMETH.PM_EXPRESSION_ARRAYINDEX, arr, args); } protected override Expr VisitCALL(ExprCall expr) { Debug.Assert(expr != null); switch (expr.NullableCallLiftKind) { default: break; case NullableCallLiftKind.NullableIntermediateConversion: case NullableCallLiftKind.NullableConversion: case NullableCallLiftKind.NullableConversionConstructor: return GenerateConversion(expr.OptionalArguments, expr.Type, expr.isChecked()); case NullableCallLiftKind.NotLiftedIntermediateConversion: case NullableCallLiftKind.UserDefinedConversion: return GenerateUserDefinedConversion(expr.OptionalArguments, expr.Type, expr.MethWithInst); } if (expr.MethWithInst.Meth().IsConstructor()) { return GenerateConstructor(expr); } ExprMemberGroup memberGroup = expr.MemberGroup; if (memberGroup.IsDelegate) { return GenerateDelegateInvoke(expr); } Expr pObject; if (expr.MethWithInst.Meth().isStatic || expr.MemberGroup.OptionalObject== null) { pObject = ExprFactory.CreateNull(); } else { pObject = expr.MemberGroup.OptionalObject; // If we have, say, an int? which is the object of a call to ToString // then we do NOT want to generate ((object)i).ToString() because that // will convert a null-valued int? to a null object. Rather what we want // to do is box it to a ValueType and call ValueType.ToString. // // To implement this we say that if the object of the call is an implicit boxing cast // then just generate the object, not the cast. If the cast is explicit in the // source code then it will be an EXPLICITCAST and we will visit it normally. // // It might be better to rewrite the expression tree API so that it // can handle in the general case all implicit boxing conversions. Right now it // requires that all arguments to a call that need to be boxed be explicitly boxed. if (pObject != null && pObject is ExprCast cast && cast.IsBoxingCast) { pObject = cast.Argument; } pObject = Visit(pObject); } Expr methodInfo = ExprFactory.CreateMethodInfo(expr.MethWithInst); Expr args = GenerateArgsList(expr.OptionalArguments); Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION); PREDEFMETH pdm = PREDEFMETH.PM_EXPRESSION_CALL; Debug.Assert(!expr.MethWithInst.Meth().isVirtual || expr.MemberGroup.OptionalObject != null); return GenerateCall(pdm, pObject, methodInfo, Params); } protected override Expr VisitPROP(ExprProperty expr) { Debug.Assert(expr != null); Expr pObject; if (expr.PropWithTypeSlot.Prop().isStatic || expr.MemberGroup.OptionalObject== null) { pObject = ExprFactory.CreateNull(); } else { pObject = Visit(expr.MemberGroup.OptionalObject); } Expr propInfo = ExprFactory.CreatePropertyInfo(expr.PropWithTypeSlot.Prop(), expr.PropWithTypeSlot.GetType()); if (expr.OptionalArguments != null) { // It is an indexer property. Turn it into a virtual method call. Expr args = GenerateArgsList(expr.OptionalArguments); Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION); return GenerateCall(PREDEFMETH.PM_EXPRESSION_PROPERTY, pObject, propInfo, Params); } return GenerateCall(PREDEFMETH.PM_EXPRESSION_PROPERTY, pObject, propInfo); } protected override Expr VisitARRINIT(ExprArrayInit expr) { Debug.Assert(expr != null); // POSSIBLE ERROR: Multi-d should be an error? Expr pTypeOf = CreateTypeOf(((ArrayType)expr.Type).ElementType); Expr args = GenerateArgsList(expr.OptionalArguments); Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION); return GenerateCall(PREDEFMETH.PM_EXPRESSION_NEWARRAYINIT, pTypeOf, Params); } protected override Expr VisitZEROINIT(ExprZeroInit expr) { Debug.Assert(expr != null); return GenerateConstant(expr); } protected override Expr VisitTYPEOF(ExprTypeOf expr) { Debug.Assert(expr != null); return GenerateConstant(expr); } private Expr GenerateDelegateInvoke(ExprCall expr) { Debug.Assert(expr != null); ExprMemberGroup memberGroup = expr.MemberGroup; Debug.Assert(memberGroup.IsDelegate); Expr oldObject = memberGroup.OptionalObject; Debug.Assert(oldObject != null); Expr pObject = Visit(oldObject); Expr args = GenerateArgsList(expr.OptionalArguments); Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION); return GenerateCall(PREDEFMETH.PM_EXPRESSION_INVOKE, pObject, Params); } private Expr GenerateBuiltInBinaryOperator(ExprBinOp expr) { Debug.Assert(expr != null); PREDEFMETH pdm; switch (expr.Kind) { case ExpressionKind.LeftShirt: pdm = PREDEFMETH.PM_EXPRESSION_LEFTSHIFT; break; case ExpressionKind.RightShift: pdm = PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT; break; case ExpressionKind.BitwiseExclusiveOr: pdm = PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR; break; case ExpressionKind.BitwiseOr: pdm = PREDEFMETH.PM_EXPRESSION_OR; break; case ExpressionKind.BitwiseAnd: pdm = PREDEFMETH.PM_EXPRESSION_AND; break; case ExpressionKind.LogicalAnd: pdm = PREDEFMETH.PM_EXPRESSION_ANDALSO; break; case ExpressionKind.LogicalOr: pdm = PREDEFMETH.PM_EXPRESSION_ORELSE; break; case ExpressionKind.StringEq: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL; break; case ExpressionKind.Eq: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL; break; case ExpressionKind.StringNotEq: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL; break; case ExpressionKind.NotEq: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL; break; case ExpressionKind.GreaterThanOrEqual: pdm = PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL; break; case ExpressionKind.LessThanOrEqual: pdm = PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL; break; case ExpressionKind.LessThan: pdm = PREDEFMETH.PM_EXPRESSION_LESSTHAN; break; case ExpressionKind.GreaterThan: pdm = PREDEFMETH.PM_EXPRESSION_GREATERTHAN; break; case ExpressionKind.Modulo: pdm = PREDEFMETH.PM_EXPRESSION_MODULO; break; case ExpressionKind.Divide: pdm = PREDEFMETH.PM_EXPRESSION_DIVIDE; break; case ExpressionKind.Multiply: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED : PREDEFMETH.PM_EXPRESSION_MULTIPLY; break; case ExpressionKind.Subtract: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED : PREDEFMETH.PM_EXPRESSION_SUBTRACT; break; case ExpressionKind.Add: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_ADDCHECKED : PREDEFMETH.PM_EXPRESSION_ADD; break; default: throw Error.InternalCompilerError(); } Expr origL = expr.OptionalLeftChild; Expr origR = expr.OptionalRightChild; Debug.Assert(origL != null); Debug.Assert(origR != null); CType typeL = origL.Type; CType typeR = origR.Type; Expr newL = Visit(origL); Expr newR = Visit(origR); bool didEnumConversion = false; CType convertL = null; CType convertR = null; if (typeL.IsEnumType) { // We have already inserted casts if not lifted, so we should never see an enum. Debug.Assert(expr.IsLifted); convertL = TypeManager.GetNullable(typeL.UnderlyingEnumType); typeL = convertL; didEnumConversion = true; } else if (typeL is NullableType nubL && nubL.UnderlyingType.IsEnumType) { Debug.Assert(expr.IsLifted); convertL = TypeManager.GetNullable(nubL.UnderlyingType.UnderlyingEnumType); typeL = convertL; didEnumConversion = true; } if (typeR.IsEnumType) { Debug.Assert(expr.IsLifted); convertR = TypeManager.GetNullable(typeR.UnderlyingEnumType); typeR = convertR; didEnumConversion = true; } else if (typeR is NullableType nubR && nubR.UnderlyingType.IsEnumType) { Debug.Assert(expr.IsLifted); convertR = TypeManager.GetNullable(nubR.UnderlyingType.UnderlyingEnumType); typeR = convertR; didEnumConversion = true; } if (typeL is NullableType nubL2 && nubL2.UnderlyingType == typeR) { convertR = typeL; } if (typeR is NullableType nubR2 && nubR2.UnderlyingType == typeL) { convertL = typeR; } if (convertL != null) { newL = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, newL, CreateTypeOf(convertL)); } if (convertR != null) { newR = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, newR, CreateTypeOf(convertR)); } Expr call = GenerateCall(pdm, newL, newR); if (didEnumConversion && expr.Type.StripNubs().IsEnumType) { call = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, call, CreateTypeOf(expr.Type)); } return call; } private Expr GenerateBuiltInUnaryOperator(ExprUnaryOp expr) { Debug.Assert(expr != null); PREDEFMETH pdm; switch (expr.Kind) { case ExpressionKind.UnaryPlus: return Visit(expr.Child); case ExpressionKind.BitwiseNot: pdm = PREDEFMETH.PM_EXPRESSION_NOT; break; case ExpressionKind.LogicalNot: pdm = PREDEFMETH.PM_EXPRESSION_NOT; break; case ExpressionKind.Negate: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_NEGATECHECKED : PREDEFMETH.PM_EXPRESSION_NEGATE; break; default: throw Error.InternalCompilerError(); } Expr origOp = expr.Child; // Such operations are always already casts on operations on casts. Debug.Assert(!(origOp.Type is NullableType nub) || !nub.UnderlyingType.IsEnumType); return GenerateCall(pdm, Visit(origOp)); } private Expr GenerateUserDefinedBinaryOperator(ExprBinOp expr) { Debug.Assert(expr != null); PREDEFMETH pdm; switch (expr.Kind) { case ExpressionKind.LogicalOr: pdm = PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED; break; case ExpressionKind.LogicalAnd: pdm = PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED; break; case ExpressionKind.LeftShirt: pdm = PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED; break; case ExpressionKind.RightShift: pdm = PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED; break; case ExpressionKind.BitwiseExclusiveOr: pdm = PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED; break; case ExpressionKind.BitwiseOr: pdm = PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED; break; case ExpressionKind.BitwiseAnd: pdm = PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED; break; case ExpressionKind.Modulo: pdm = PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED; break; case ExpressionKind.Divide: pdm = PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED; break; case ExpressionKind.StringEq: case ExpressionKind.StringNotEq: case ExpressionKind.DelegateEq: case ExpressionKind.DelegateNotEq: case ExpressionKind.Eq: case ExpressionKind.NotEq: case ExpressionKind.GreaterThanOrEqual: case ExpressionKind.GreaterThan: case ExpressionKind.LessThanOrEqual: case ExpressionKind.LessThan: return GenerateUserDefinedComparisonOperator(expr); case ExpressionKind.DelegateSubtract: case ExpressionKind.Subtract: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED; break; case ExpressionKind.DelegateAdd: case ExpressionKind.Add: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED; break; case ExpressionKind.Multiply: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED; break; default: throw Error.InternalCompilerError(); } Expr p1 = expr.OptionalLeftChild; Expr p2 = expr.OptionalRightChild; Expr udcall = expr.OptionalUserDefinedCall; if (udcall != null) { Debug.Assert(udcall.Kind == ExpressionKind.Call || udcall.Kind == ExpressionKind.UserLogicalOp); if (udcall is ExprCall ascall) { ExprList args = (ExprList)ascall.OptionalArguments; Debug.Assert(args.OptionalNextListNode.Kind != ExpressionKind.List); p1 = args.OptionalElement; p2 = args.OptionalNextListNode; } else { ExprUserLogicalOp userLogOp = udcall as ExprUserLogicalOp; Debug.Assert(userLogOp != null); ExprList args = (ExprList)userLogOp.OperatorCall.OptionalArguments; Debug.Assert(args.OptionalNextListNode.Kind != ExpressionKind.List); p1 = ((ExprWrap)args.OptionalElement).OptionalExpression; p2 = args.OptionalNextListNode; } } p1 = Visit(p1); p2 = Visit(p2); FixLiftedUserDefinedBinaryOperators(expr, ref p1, ref p2); Expr methodInfo = ExprFactory.CreateMethodInfo(expr.UserDefinedCallMethod); Expr call = GenerateCall(pdm, p1, p2, methodInfo); // Delegate add/subtract generates a call to Combine/Remove, which returns System.Delegate, // not the operand delegate CType. We must cast to the delegate CType. if (expr.Kind == ExpressionKind.DelegateSubtract || expr.Kind == ExpressionKind.DelegateAdd) { Expr pTypeOf = CreateTypeOf(expr.Type); return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, call, pTypeOf); } return call; } private Expr GenerateUserDefinedUnaryOperator(ExprUnaryOp expr) { Debug.Assert(expr != null); PREDEFMETH pdm; Expr arg = expr.Child; ExprCall call = (ExprCall)expr.OptionalUserDefinedCall; if (call != null) { // Use the actual argument of the call; it may contain user-defined // conversions or be a bound lambda, and that will not be in the original // argument stashed away in the left child of the operator. arg = call.OptionalArguments; } Debug.Assert(arg != null && arg.Kind != ExpressionKind.List); switch (expr.Kind) { case ExpressionKind.True: case ExpressionKind.False: return Visit(call); case ExpressionKind.UnaryPlus: pdm = PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED; break; case ExpressionKind.BitwiseNot: pdm = PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED; break; case ExpressionKind.LogicalNot: pdm = PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED; break; case ExpressionKind.DecimalNegate: case ExpressionKind.Negate: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED; break; case ExpressionKind.Inc: case ExpressionKind.Dec: case ExpressionKind.DecimalInc: case ExpressionKind.DecimalDec: pdm = PREDEFMETH.PM_EXPRESSION_CALL; break; default: throw Error.InternalCompilerError(); } Expr op = Visit(arg); Expr methodInfo = ExprFactory.CreateMethodInfo(expr.UserDefinedCallMethod); if (expr.Kind == ExpressionKind.Inc || expr.Kind == ExpressionKind.Dec || expr.Kind == ExpressionKind.DecimalInc || expr.Kind == ExpressionKind.DecimalDec) { return GenerateCall(pdm, null, methodInfo, GenerateParamsArray(op, PredefinedType.PT_EXPRESSION)); } return GenerateCall(pdm, op, methodInfo); } private Expr GenerateUserDefinedComparisonOperator(ExprBinOp expr) { Debug.Assert(expr != null); PREDEFMETH pdm; switch (expr.Kind) { case ExpressionKind.StringEq: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED; break; case ExpressionKind.StringNotEq: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED; break; case ExpressionKind.DelegateEq: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED; break; case ExpressionKind.DelegateNotEq: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED; break; case ExpressionKind.Eq: pdm = PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED; break; case ExpressionKind.NotEq: pdm = PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED; break; case ExpressionKind.LessThanOrEqual: pdm = PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED; break; case ExpressionKind.LessThan: pdm = PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED; break; case ExpressionKind.GreaterThanOrEqual: pdm = PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED; break; case ExpressionKind.GreaterThan: pdm = PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED; break; default: throw Error.InternalCompilerError(); } Expr p1 = expr.OptionalLeftChild; Expr p2 = expr.OptionalRightChild; if (expr.OptionalUserDefinedCall != null) { ExprCall udcall = (ExprCall)expr.OptionalUserDefinedCall; ExprList args = (ExprList)udcall.OptionalArguments; Debug.Assert(args.OptionalNextListNode.Kind != ExpressionKind.List); p1 = args.OptionalElement; p2 = args.OptionalNextListNode; } p1 = Visit(p1); p2 = Visit(p2); FixLiftedUserDefinedBinaryOperators(expr, ref p1, ref p2); Expr lift = ExprFactory.CreateBoolConstant(false); // We never lift to null in C#. Expr methodInfo = ExprFactory.CreateMethodInfo(expr.UserDefinedCallMethod); return GenerateCall(pdm, p1, p2, lift, methodInfo); } private Expr GenerateConversion(Expr arg, CType CType, bool bChecked) => GenerateConversionWithSource(Visit(arg), CType, bChecked || arg.isChecked()); private static Expr GenerateConversionWithSource(Expr pTarget, CType pType, bool bChecked) { PREDEFMETH pdm = bChecked ? PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED : PREDEFMETH.PM_EXPRESSION_CONVERT; Expr pTypeOf = CreateTypeOf(pType); return GenerateCall(pdm, pTarget, pTypeOf); } private Expr GenerateValueAccessConversion(Expr pArgument) { Debug.Assert(pArgument != null); CType pStrippedTypeOfArgument = pArgument.Type.StripNubs(); Expr pStrippedTypeExpr = CreateTypeOf(pStrippedTypeOfArgument); return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, Visit(pArgument), pStrippedTypeExpr); } private Expr GenerateUserDefinedConversion(Expr arg, CType type, MethWithInst method) { Expr target = Visit(arg); return GenerateUserDefinedConversion(arg, type, target, method); } private static Expr GenerateUserDefinedConversion(Expr arg, CType CType, Expr target, MethWithInst method) { // The user-defined explicit conversion from enum? to decimal or decimal? requires // that we convert the enum? to its nullable underlying CType. if (isEnumToDecimalConversion(arg.Type, CType)) { // Special case: If we have enum? to decimal? then we need to emit // a conversion from enum? to its nullable underlying CType first. // This is unfortunate; we ought to reorganize how conversions are // represented in the Expr tree so that this is more transparent. // converting an enum to its underlying CType never fails, so no need to check it. CType underlyingType = arg.Type.StripNubs().UnderlyingEnumType; CType nullableType = TypeManager.GetNullable(underlyingType); Expr typeofNubEnum = CreateTypeOf(nullableType); target = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, target, typeofNubEnum); } // If the methodinfo does not return the target CType AND this is not a lifted conversion // from one value CType to another, then we need to wrap the whole thing in another conversion, // e.g. if we have a user-defined conversion from int to S? and we have (S)myint, then we need to generate // Convert(Convert(myint, typeof(S?), op_implicit), typeof(S)) CType pMethodReturnType = TypeManager.SubstType(method.Meth().RetType, method.GetType(), method.TypeArgs); bool fDontLiftReturnType = (pMethodReturnType == CType || (IsNullableValueType(arg.Type) && IsNullableValueType(CType))); Expr typeofInner = CreateTypeOf(fDontLiftReturnType ? CType : pMethodReturnType); Expr methodInfo = ExprFactory.CreateMethodInfo(method); PREDEFMETH pdmInner = arg.isChecked() ? PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED; Expr callUserDefinedConversion = GenerateCall(pdmInner, target, typeofInner, methodInfo); if (fDontLiftReturnType) { return callUserDefinedConversion; } PREDEFMETH pdmOuter = arg.isChecked() ? PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED : PREDEFMETH.PM_EXPRESSION_CONVERT; Expr typeofOuter = CreateTypeOf(CType); return GenerateCall(pdmOuter, callUserDefinedConversion, typeofOuter); } private Expr GenerateUserDefinedConversion(ExprUserDefinedConversion pExpr, Expr pArgument) { Expr pCastCall = pExpr.UserDefinedCall; Expr pCastArgument = pExpr.Argument; Expr pConversionSource; if (!isEnumToDecimalConversion(pArgument.Type, pExpr.Type) && IsNullableValueAccess(pCastArgument, pArgument)) { // We have an implicit conversion of nullable CType to the value CType, generate a convert node for it. pConversionSource = GenerateValueAccessConversion(pArgument); } else { ExprCall call = pCastCall as ExprCall; Expr pUDConversion = call?.PConversions; if (pUDConversion != null) { if (pUDConversion is ExprCall convCall) { Expr pUDConversionArgument = convCall.OptionalArguments; if (IsNullableValueAccess(pUDConversionArgument, pArgument)) { pConversionSource = GenerateValueAccessConversion(pArgument); } else { pConversionSource = Visit(pUDConversionArgument); } return GenerateConversionWithSource(pConversionSource, pCastCall.Type, call.isChecked()); } // This can happen if we have a UD conversion from C to, say, int, // and we have an explicit cast to decimal?. The conversion should // then be bound as two chained user-defined conversions. Debug.Assert(pUDConversion is ExprUserDefinedConversion); // Just recurse. return GenerateUserDefinedConversion((ExprUserDefinedConversion)pUDConversion, pArgument); } pConversionSource = Visit(pCastArgument); } return GenerateUserDefinedConversion(pCastArgument, pExpr.Type, pConversionSource, pExpr.UserDefinedCallMethod); } private static Expr GenerateParameter(string name, CType CType) { SymbolLoader.GetPredefindType(PredefinedType.PT_STRING); // force an ensure state ExprConstant nameString = ExprFactory.CreateStringConstant(name); ExprTypeOf pTypeOf = CreateTypeOf(CType); return GenerateCall(PREDEFMETH.PM_EXPRESSION_PARAMETER, pTypeOf, nameString); } private static MethodSymbol GetPreDefMethod(PREDEFMETH pdm) => PredefinedMembers.GetMethod(pdm); private static ExprTypeOf CreateTypeOf(CType type) => ExprFactory.CreateTypeOf(type); private static Expr CreateWraps(ExprBoundLambda anonmeth) { Expr sequence = null; for (Symbol sym = anonmeth.ArgumentScope.firstChild; sym != null; sym = sym.nextChild) { if (!(sym is LocalVariableSymbol local)) { continue; } Debug.Assert(anonmeth.Expression != null); Expr create = GenerateParameter(local.name.Text, local.GetType()); local.wrap = ExprFactory.CreateWrap(create); Expr save = ExprFactory.CreateSave(local.wrap); if (sequence == null) { sequence = save; } else { sequence = ExprFactory.CreateSequence(sequence, save); } } return sequence; } private Expr GenerateConstructor(ExprCall expr) { Debug.Assert(expr != null); Debug.Assert(expr.MethWithInst.Meth().IsConstructor()); Expr constructorInfo = ExprFactory.CreateMethodInfo(expr.MethWithInst); Expr args = GenerateArgsList(expr.OptionalArguments); Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION); return GenerateCall(PREDEFMETH.PM_EXPRESSION_NEW, constructorInfo, Params); } private Expr GenerateArgsList(Expr oldArgs) { Expr newArgs = null; Expr newArgsTail = newArgs; for (ExpressionIterator it = new ExpressionIterator(oldArgs); !it.AtEnd(); it.MoveNext()) { Expr oldArg = it.Current(); ExprFactory.AppendItemToList(Visit(oldArg), ref newArgs, ref newArgsTail); } return newArgs; } private Expr GenerateIndexList(Expr oldIndices) { CType intType = SymbolLoader.GetPredefindType(PredefinedType.PT_INT); Expr newIndices = null; Expr newIndicesTail = newIndices; for (ExpressionIterator it = new ExpressionIterator(oldIndices); !it.AtEnd(); it.MoveNext()) { Expr newIndex = it.Current(); if (newIndex.Type != intType) { newIndex = ExprFactory.CreateCast(EXPRFLAG.EXF_INDEXEXPR, intType, newIndex); newIndex.Flags |= EXPRFLAG.EXF_CHECKOVERFLOW; } Expr rewrittenIndex = Visit(newIndex); ExprFactory.AppendItemToList(rewrittenIndex, ref newIndices, ref newIndicesTail); } return newIndices; } private static Expr GenerateConstant(Expr expr) { EXPRFLAG flags = 0; AggregateType pObject = SymbolLoader.GetPredefindType(PredefinedType.PT_OBJECT); if (expr.Type is NullType) { ExprTypeOf pTypeOf = CreateTypeOf(pObject); return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE, expr, pTypeOf); } AggregateType stringType = SymbolLoader.GetPredefindType(PredefinedType.PT_STRING); if (expr.Type != stringType) { flags = EXPRFLAG.EXF_BOX; } ExprCast cast = ExprFactory.CreateCast(flags, pObject, expr); ExprTypeOf pTypeOf2 = CreateTypeOf(expr.Type); return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE, cast, pTypeOf2); } private static ExprCall GenerateCall(PREDEFMETH pdm, Expr arg1) { MethodSymbol method = GetPreDefMethod(pdm); // this should be enforced in an earlier pass and the transform pass should not // be handling this error if (method == null) return null; AggregateType expressionType = SymbolLoader.GetPredefindType(PredefinedType.PT_EXPRESSION); MethWithInst mwi = new MethWithInst(method, expressionType); ExprMemberGroup pMemGroup = ExprFactory.CreateMemGroup(null, mwi); ExprCall call = ExprFactory.CreateCall(0, mwi.Meth().RetType, arg1, pMemGroup, mwi); call.PredefinedMethod = pdm; return call; } private static ExprCall GenerateCall(PREDEFMETH pdm, Expr arg1, Expr arg2) { MethodSymbol method = GetPreDefMethod(pdm); if (method == null) return null; AggregateType expressionType = SymbolLoader.GetPredefindType(PredefinedType.PT_EXPRESSION); Expr args = ExprFactory.CreateList(arg1, arg2); MethWithInst mwi = new MethWithInst(method, expressionType); ExprMemberGroup pMemGroup = ExprFactory.CreateMemGroup(null, mwi); ExprCall call = ExprFactory.CreateCall(0, mwi.Meth().RetType, args, pMemGroup, mwi); call.PredefinedMethod = pdm; return call; } private static ExprCall GenerateCall(PREDEFMETH pdm, Expr arg1, Expr arg2, Expr arg3) { MethodSymbol method = GetPreDefMethod(pdm); if (method == null) return null; AggregateType expressionType = SymbolLoader.GetPredefindType(PredefinedType.PT_EXPRESSION); Expr args = ExprFactory.CreateList(arg1, arg2, arg3); MethWithInst mwi = new MethWithInst(method, expressionType); ExprMemberGroup pMemGroup = ExprFactory.CreateMemGroup(null, mwi); ExprCall call = ExprFactory.CreateCall(0, mwi.Meth().RetType, args, pMemGroup, mwi); call.PredefinedMethod = pdm; return call; } private static ExprCall GenerateCall(PREDEFMETH pdm, Expr arg1, Expr arg2, Expr arg3, Expr arg4) { MethodSymbol method = GetPreDefMethod(pdm); if (method == null) return null; AggregateType expressionType = SymbolLoader.GetPredefindType(PredefinedType.PT_EXPRESSION); Expr args = ExprFactory.CreateList(arg1, arg2, arg3, arg4); MethWithInst mwi = new MethWithInst(method, expressionType); ExprMemberGroup pMemGroup = ExprFactory.CreateMemGroup(null, mwi); ExprCall call = ExprFactory.CreateCall(0, mwi.Meth().RetType, args, pMemGroup, mwi); call.PredefinedMethod = pdm; return call; } private static ExprArrayInit GenerateParamsArray(Expr args, PredefinedType pt) { int parameterCount = ExpressionIterator.Count(args); AggregateType paramsArrayElementType = SymbolLoader.GetPredefindType(pt); ArrayType paramsArrayType = TypeManager.GetArray(paramsArrayElementType, 1, true); ExprConstant paramsArrayArg = ExprFactory.CreateIntegerConstant(parameterCount); return ExprFactory.CreateArrayInit(paramsArrayType, args, paramsArrayArg, new int[] { parameterCount }); } private static void FixLiftedUserDefinedBinaryOperators(ExprBinOp expr, ref Expr pp1, ref Expr pp2) { // If we have lifted T1 op T2 to T1? op T2?, and we have an expression T1 op T2? or T1? op T2 then // we need to ensure that the unlifted actual arguments are promoted to their nullable CType. Debug.Assert(expr != null); Debug.Assert(pp1 != null); Debug.Assert(pp1 != null); Debug.Assert(pp2 != null); Debug.Assert(pp2 != null); MethodSymbol method = expr.UserDefinedCallMethod.Meth(); Expr orig1 = expr.OptionalLeftChild; Expr orig2 = expr.OptionalRightChild; Debug.Assert(orig1 != null && orig2 != null); Expr new1 = pp1; Expr new2 = pp2; CType fptype1 = method.Params[0]; CType fptype2 = method.Params[1]; CType aatype1 = orig1.Type; CType aatype2 = orig2.Type; // Is the operator even a candidate for lifting? if (!(fptype1 is AggregateType fat1) || !fat1.OwningAggregate.IsValueType() || !(fptype2 is AggregateType fat2) || !fat2.OwningAggregate.IsValueType()) { return; } CType nubfptype1 = TypeManager.GetNullable(fptype1); CType nubfptype2 = TypeManager.GetNullable(fptype2); // If we have null op X, or T1 op T2?, or T1 op null, lift first arg to T1? if (aatype1 is NullType || aatype1 == fptype1 && (aatype2 == nubfptype2 || aatype2 is NullType)) { new1 = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, new1, CreateTypeOf(nubfptype1)); } // If we have X op null, or T1? op T2, or null op T2, lift second arg to T2? if (aatype2 is NullType || aatype2 == fptype2 && (aatype1 == nubfptype1 || aatype1 is NullType)) { new2 = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, new2, CreateTypeOf(nubfptype2)); } pp1 = new1; pp2 = new2; } private static bool IsNullableValueType(CType pType) => pType is NullableType && pType.StripNubs() is AggregateType agg && agg.OwningAggregate.IsValueType(); private static bool IsNullableValueAccess(Expr pExpr, Expr pObject) { Debug.Assert(pExpr != null); return pExpr is ExprProperty prop && prop.MemberGroup.OptionalObject == pObject && pObject.Type is NullableType; } private static bool isEnumToDecimalConversion(CType argtype, CType desttype) => argtype.StripNubs().IsEnumType && desttype.StripNubs().IsPredefType(PredefinedType.PT_DECIMAL); } }
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Windows.Forms.Design; using System.Drawing; using System.Drawing.Design; using System.ComponentModel; using AxiomCoders.PdfTemplateEditor.EditorStuff; using AxiomCoders.PdfTemplateEditor.Common; using System.Xml; namespace AxiomCoders.PdfTemplateEditor.EditorItems { [System.Reflection.Obfuscation(Exclude = true)] class DynamicImage : EditorItem , EditorToolBarPlugin, DynamicEditorItemInterface { private string sourceColumn; private string sourceDataStream; Image pictureForDisplay = AxiomCoders.PdfTemplateEditor.Properties.Resources.NoDynamicImage; /// <summary> /// Constructor /// </summary> public DynamicImage() { sourceColumn = string.Empty; sourceDataStream = string.Empty; this.WidthInUnits = 3; this.HeightInUnits = 3; } /// <summary> /// Save Item /// </summary> /// <param name="txW"></param> public override void SaveItem(XmlDocument doc, XmlElement element) { XmlElement el = doc.CreateElement("Item"); base.SaveItem(doc, el); XmlAttribute attr = doc.CreateAttribute("Type"); attr.Value = "DynamicImage"; el.SetAttributeNode(attr); attr = doc.CreateAttribute("Version"); attr.Value = "1.0"; el.SetAttributeNode(attr); XmlElement el2 = doc.CreateElement("Text"); attr = doc.CreateAttribute("DataStream"); attr.Value = this.SourceDataStream; el2.SetAttributeNode(attr); attr = doc.CreateAttribute("SourceColumn"); attr.Value = this.SourceColumn; el2.SetAttributeNode(attr); attr = doc.CreateAttribute("ImageType"); attr.Value = this.ImageType; el2.SetAttributeNode(attr); el.AppendChild(el2); element.AppendChild(el); } /// <summary> /// Load Item /// </summary> /// <param name="txR"></param> public override void Load(System.Xml.XmlNode element) { base.Load(element); // Load source data stream and column XmlNode node = element.SelectSingleNode("Text"); if (node != null) { this.SourceDataStream = node.Attributes["DataStream"].Value; this.SourceColumn = node.Attributes["SourceColumn"].Value; this.ImageType = node.Attributes["ImageType"].Value; } } /// <summary> /// Gets or sets source column name of item. /// </summary> [Browsable(true), DisplayName("Column"), Description("Source column name of item."), Category("Standard"), EditorAttribute(typeof(ComboBoxPropertyEditor), typeof(UITypeEditor))] public string SourceColumn { get { if(SourceDataStream != "") { int tmpCount = 0; string[] tmpList = null; int i = 0; foreach(DataStream tmpStream in EditorController.Instance.EditorProject.DataStreams) { if(tmpStream.Name == SourceDataStream) { tmpCount = tmpStream.Columns.Count; tmpList = new string[tmpCount]; foreach(Column tmpCol in tmpStream.Columns) { tmpList[i] = tmpCol.Name; i++; } ComboBoxPropertyEditor.ItemList = tmpList; break; } } } return sourceColumn; } set { sourceColumn = value; } } /// <summary> /// Gets or sets source Data Stream of item. /// </summary> [Browsable(true), DisplayName("Data Stream"), Description("Source Data Stream name of item."), Category("Standard"), EditorAttribute(typeof(ComboBoxPropertyEditor), typeof(UITypeEditor))] public string SourceDataStream { get { ComboBoxPropertyEditor.ItemList = null; int tmpCount = EditorController.Instance.EditorProject.DataStreams.Count; if(tmpCount > 0) { string[] tmpList = new string[tmpCount]; int i = 0; foreach(DataStream tmpItem in EditorController.Instance.EditorProject.DataStreams) { tmpList[i] = tmpItem.Name; i++; } ComboBoxPropertyEditor.ItemList = tmpList; } return sourceDataStream; } set { SourceColumn = ""; sourceDataStream = value; } } private string imageType = "Data"; /// <summary> /// Type of image, bmp, DataJpg, DataGif, DataBmp, FileSystem /// </summary> [Browsable(true), DisplayName("Image Type"), Description("Image type"), Category("Standard"), EditorAttribute(typeof(ComboBoxPropertyEditor), typeof(UITypeEditor))] public string ImageType { get { ComboBoxPropertyEditor.ItemList = null; string[] tmpList = new string[2]; tmpList[0] = "FileSystem"; tmpList[1] = "Data"; ComboBoxPropertyEditor.ItemList = tmpList; return imageType; } set { imageType = value; } } /// <summary> /// Relative X location comparing to ballon location. /// </summary> [Browsable(true), DisplayName("Location X In Pixels"), Category("Standard")] [Description("Relative X location comparing to balloon location.")] public override float LocationInPixelsX { get { return base.LocationInPixelsX; } } /// <summary> /// Relative Y location comparing to balloon location. /// </summary> [Browsable(true), DisplayName("Location Y In Pixels"), Category("Standard")] [Description("Relative Y location comparing to balloon location.")] public override float LocationInPixelsY { get { return base.LocationInPixelsY; } } public override void DisplayItem(Graphics gc) { if(IsSelected) { if(pictureForDisplay != null) { gc.DrawImage(pictureForDisplay, 0, 0, (float)this.WidthInPixels, (float)this.HeightInPixels); } //gc.DrawRectangle(Pens.Red, 0, 0, (float)this.WidthInPixels, (float)this.HeightInPixels); } else { if(pictureForDisplay != null) { gc.DrawImage(pictureForDisplay, 0, 0, (float)this.WidthInPixels, (float)this.HeightInPixels); } else { //if (Disabled) //{ // gc.DrawRectangle(Pens.LightGray, 0, 0, (float)this.WidthInPixels, (float)this.HeightInPixels); //} //else //{ gc.DrawRectangle(Pens.Black, 0, 0, (float)this.WidthInPixels, (float)this.HeightInPixels); //} } } } #region EditorToolBarPlugin Members void EditorToolBarPlugin.AddToToolStrip(ToolStrip toolStrip, ToolStripGroup group) { //ToolStripButton tbbNew = new ToolStripButton("DynamicImage"); //tbbNew.Image = AxiomCoders.PdfTemplateEditor.Properties.Resources.DynamicImage; //tbbNew.DisplayStyle = ToolStripItemDisplayStyle.Image; //toolStrip.Items.Add(tbbNew); //tbbNew.Click += new EventHandler(tbbNew_Click); } void tbbNew_Click(object sender, EventArgs e) { //ToolStripButton tbbButton = sender as ToolStripButton; //tbbButton.Checked = !tbbButton.Checked; //if (tbbButton.Checked) //{ // EditorController.Instance.TbbCheckedForCreate = tbbButton; // EditorController.Instance.EditorItemSelectedForCreation = this.GetType(); //} //else //{ // EditorController.Instance.EditorItemSelectedForCreation = null; //} } #endregion } }
/* Copyright 2015 System Era Softworks Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. * The Strange IOC Framework is hosted at https://github.com/strangeioc/strangeioc. * Code contained here may contain modified code which is subject to the license * at this link. */ using System; using System.Collections.Generic; using strange.extensions.signal.impl; namespace strange.extensions.policysignal.impl { /// Base concrete form for a Signal with no parameters public class PolicySignalBase : BaseSignal { public event Action Listener = delegate { }; public event Action OnceListener = delegate { }; public void AddListener(Action callback) { Listener += callback; } public void AddOnce(Action callback) { OnceListener += callback; } public void RemoveListener(Action callback) { Listener -= callback; } public override List<Type> GetTypes() { return new List<Type>(); } public void Dispatch() { Listener(); OnceListener(); OnceListener = delegate { }; base.Dispatch(null); } } public class PolicySignal : PolicySignalBase { private Dictionary<object, Signal> namedSignals = new Dictionary<object, Signal>(); public void Dispatch(object name) { if (name != null && namedSignals.ContainsKey(name)) namedSignals[name].Dispatch(); } public void AddListener(object name, Action callback) { if (!namedSignals.ContainsKey(name)) namedSignals.Add(name, new Signal()); namedSignals[name].AddListener(callback); } public void AddOnce(object name, Action callback) { if (!namedSignals.ContainsKey(name)) namedSignals.Add(name, new Signal()); namedSignals[name].AddOnce(callback); } public void RemoveListener(object name, Action callback) { if (namedSignals.ContainsKey(name)) namedSignals[name].RemoveListener(callback); } } /// Base concrete form for a Signal with one parameter public class PolicySignalBase<T> : BaseSignal { public event Action<T> Listener = delegate { }; public event Action<T> OnceListener = delegate { }; public void AddListener(Action<T> callback) { Listener += callback; } public void AddOnce(Action<T> callback) { OnceListener += callback; } public void RemoveListener(Action<T> callback) { Listener -= callback; } public override List<Type> GetTypes() { List<Type> retv = new List<Type>(); retv.Add(typeof(T)); return retv; } public void Dispatch(T type1) { Listener(type1); OnceListener(type1); OnceListener = delegate { }; object[] outv = { type1 }; base.Dispatch(outv); } } public class PolicySignal<T> : PolicySignalBase<T> { private Dictionary<object, Signal<T>> namedSignals = new Dictionary<object, Signal<T>>(); public void Dispatch(object name, T type1) { if (name != null && namedSignals.ContainsKey(name)) namedSignals[name].Dispatch(type1); } public void AddListener(object name, Action<T> callback) { if (!namedSignals.ContainsKey(name)) namedSignals.Add(name, new Signal<T>()); namedSignals[name].AddListener(callback); } public void AddOnce(object name, Action<T> callback) { if (!namedSignals.ContainsKey(name)) namedSignals.Add(name, new Signal<T>()); namedSignals[name].AddOnce(callback); } public void RemoveListener(object name, Action<T> callback) { if (namedSignals.ContainsKey(name)) namedSignals[name].RemoveListener(callback); } } /// Base concrete form for a Signal with two parameters public class PolicySignalBase<T, U> : BaseSignal { public event Action<T, U> Listener = delegate { }; public event Action<T, U> OnceListener = delegate { }; public void AddListener(Action<T, U> callback) { Listener += callback; } public void AddOnce(Action<T, U> callback) { OnceListener += callback; } public void RemoveListener(Action<T, U> callback) { Listener -= callback; } public override List<Type> GetTypes() { List<Type> retv = new List<Type>(); retv.Add(typeof(T)); retv.Add(typeof(U)); return retv; } public void Dispatch(T type1, U type2) { Listener(type1, type2); OnceListener(type1, type2); OnceListener = delegate { }; object[] outv = { type1, type2 }; base.Dispatch(outv); } } public class PolicySignal<T, U> : PolicySignalBase<T, U> { private Dictionary<object, Signal<T, U>> namedSignals = new Dictionary<object, Signal<T, U>>(); public void Dispatch(object name, T type1, U type2) { if (name != null && namedSignals.ContainsKey(name)) namedSignals[name].Dispatch(type1, type2); } public void AddListener(object name, Action<T, U> callback) { if (!namedSignals.ContainsKey(name)) namedSignals.Add(name, new Signal<T, U>()); namedSignals[name].AddListener(callback); } public void AddOnce(object name, Action<T, U> callback) { if (!namedSignals.ContainsKey(name)) namedSignals.Add(name, new Signal<T, U>()); namedSignals[name].AddOnce(callback); } public void RemoveListener(object name, Action<T, U> callback) { if (namedSignals.ContainsKey(name)) namedSignals[name].RemoveListener(callback); } } /// Base concrete form for a Signal with three parameters public class PolicySignalBase<T, U, V> : BaseSignal { public event Action<T, U, V> Listener = delegate { }; public event Action<T, U, V> OnceListener = delegate { }; public void AddListener(Action<T, U, V> callback) { Listener += callback; } public void AddOnce(Action<T, U, V> callback) { OnceListener += callback; } public void RemoveListener(Action<T, U, V> callback) { Listener -= callback; } public override List<Type> GetTypes() { List<Type> retv = new List<Type>(); retv.Add(typeof(T)); retv.Add(typeof(U)); retv.Add(typeof(V)); return retv; } public void Dispatch(T type1, U type2, V type3) { Listener(type1, type2, type3); OnceListener(type1, type2, type3); OnceListener = delegate { }; object[] outv = { type1, type2, type3 }; base.Dispatch(outv); } } public class PolicySignal<T, U, V> : PolicySignalBase<T, U, V> { private Dictionary<object, Signal<T, U, V>> namedSignals = new Dictionary<object, Signal<T, U, V>>(); public void Dispatch(object name, T type1, U type2, V type3) { if (name != null && namedSignals.ContainsKey(name)) namedSignals[name].Dispatch(type1, type2, type3); } public void AddListener(object name, Action<T, U, V> callback) { if (!namedSignals.ContainsKey(name)) namedSignals.Add(name, new Signal<T, U, V>()); namedSignals[name].AddListener(callback); } public void AddOnce(object name, Action<T, U, V> callback) { if (!namedSignals.ContainsKey(name)) namedSignals.Add(name, new Signal<T, U, V>()); namedSignals[name].AddOnce(callback); } public void RemoveListener(object name, Action<T, U, V> callback) { if (namedSignals.ContainsKey(name)) namedSignals[name].RemoveListener(callback); } } /// Base concrete form for a Signal with four parameters public class PolicySignalBase<T, U, V, W> : BaseSignal { public event Action<T, U, V, W> Listener = delegate { }; public event Action<T, U, V, W> OnceListener = delegate { }; public void AddListener(Action<T, U, V, W> callback) { Listener += callback; } public void AddOnce(Action<T, U, V, W> callback) { OnceListener += callback; } public void RemoveListener(Action<T, U, V, W> callback) { Listener -= callback; } public override List<Type> GetTypes() { List<Type> retv = new List<Type>(); retv.Add(typeof(T)); retv.Add(typeof(U)); retv.Add(typeof(V)); retv.Add(typeof(W)); return retv; } public void Dispatch(T type1, U type2, V type3, W type4) { Listener(type1, type2, type3, type4); OnceListener(type1, type2, type3, type4); OnceListener = delegate { }; object[] outv = { type1, type2, type3, type4 }; base.Dispatch(outv); } } public class PolicySignal<T, U, V, W> : PolicySignalBase<T, U, V, W> { private Dictionary<object, Signal<T, U, V, W>> namedSignals = new Dictionary<object, Signal<T, U, V, W>>(); public void Dispatch(object name, T type1, U type2, V type3, W type4) { if (name != null && namedSignals.ContainsKey(name)) namedSignals[name].Dispatch(type1, type2, type3, type4); } public void AddListener(object name, Action<T, U, V, W> callback) { if (!namedSignals.ContainsKey(name)) namedSignals.Add(name, new Signal<T, U, V, W>()); namedSignals[name].AddListener(callback); } public void AddOnce(object name, Action<T, U, V, W> callback) { if (!namedSignals.ContainsKey(name)) namedSignals.Add(name, new Signal<T, U, V, W>()); namedSignals[name].AddOnce(callback); } public void RemoveListener(object name, Action<T, U, V, W> callback) { if (namedSignals.ContainsKey(name)) namedSignals[name].RemoveListener(callback); } } }
using System.Collections.Generic; namespace Wasm.Instructions { /// <summary> /// A collection of operator definitions. /// </summary> public static class Operators { static Operators() { opsByOpCode = new Dictionary<byte, Operator>(); Unreachable = Register<NullaryOperator>(new NullaryOperator(0x00, WasmType.Empty, "unreachable")); Nop = Register<NullaryOperator>(new NullaryOperator(0x01, WasmType.Empty, "nop")); Block = Register<BlockOperator>(new BlockOperator(0x02, WasmType.Empty, "block")); Loop = Register<BlockOperator>(new BlockOperator(0x03, WasmType.Empty, "loop")); If = Register<IfElseOperator>(new IfElseOperator(0x04, WasmType.Empty, "if")); Br = Register<VarUInt32Operator>(new VarUInt32Operator(0x0c, WasmType.Empty, "br")); BrIf = Register<VarUInt32Operator>(new VarUInt32Operator(0x0d, WasmType.Empty, "br_if")); BrTable = Register<BrTableOperator>(new BrTableOperator(0x0e, WasmType.Empty, "br_table")); Return = Register<NullaryOperator>(new NullaryOperator(0x0f, WasmType.Empty, "return")); Drop = Register<NullaryOperator>(new NullaryOperator(0x1a, WasmType.Empty, "drop")); Select = Register<NullaryOperator>(new NullaryOperator(0x1b, WasmType.Empty, "select")); Call = Register<VarUInt32Operator>(new VarUInt32Operator(0x10, WasmType.Empty, "call")); CallIndirect = Register<CallIndirectOperator>(new CallIndirectOperator(0x11, WasmType.Empty, "call_indirect")); GetLocal = Register<VarUInt32Operator>(new VarUInt32Operator(0x20, WasmType.Empty, "get_local")); SetLocal = Register<VarUInt32Operator>(new VarUInt32Operator(0x21, WasmType.Empty, "set_local")); TeeLocal = Register<VarUInt32Operator>(new VarUInt32Operator(0x22, WasmType.Empty, "tee_local")); GetGlobal = Register<VarUInt32Operator>(new VarUInt32Operator(0x23, WasmType.Empty, "get_global")); SetGlobal = Register<VarUInt32Operator>(new VarUInt32Operator(0x24, WasmType.Empty, "set_global")); Int32Const = Register<VarInt32Operator>(new VarInt32Operator(0x41, WasmType.Int32, "const")); Int64Const = Register<VarInt64Operator>(new VarInt64Operator(0x42, WasmType.Int64, "const")); Float32Const = Register<Float32Operator>(new Float32Operator(0x43, WasmType.Float32, "const")); Float64Const = Register<Float64Operator>(new Float64Operator(0x44, WasmType.Float64, "const")); Int32Load = Register<MemoryOperator>(new MemoryOperator(0x28, WasmType.Int32, "load")); Int64Load = Register<MemoryOperator>(new MemoryOperator(0x29, WasmType.Int64, "load")); Float32Load = Register<MemoryOperator>(new MemoryOperator(0x2a, WasmType.Float32, "load")); Float64Load = Register<MemoryOperator>(new MemoryOperator(0x2b, WasmType.Float64, "load")); Int32Load8S = Register<MemoryOperator>(new MemoryOperator(0x2c, WasmType.Int32, "load8_s")); Int32Load8U = Register<MemoryOperator>(new MemoryOperator(0x2d, WasmType.Int32, "load8_u")); Int32Load16S = Register<MemoryOperator>(new MemoryOperator(0x2e, WasmType.Int32, "load16_s")); Int32Load16U = Register<MemoryOperator>(new MemoryOperator(0x2f, WasmType.Int32, "load16_u")); Int64Load8S = Register<MemoryOperator>(new MemoryOperator(0x30, WasmType.Int64, "load8_s")); Int64Load8U = Register<MemoryOperator>(new MemoryOperator(0x31, WasmType.Int64, "load8_u")); Int64Load16S = Register<MemoryOperator>(new MemoryOperator(0x32, WasmType.Int64, "load16_s")); Int64Load16U = Register<MemoryOperator>(new MemoryOperator(0x33, WasmType.Int64, "load16_u")); Int64Load32S = Register<MemoryOperator>(new MemoryOperator(0x34, WasmType.Int64, "load32_s")); Int64Load32U = Register<MemoryOperator>(new MemoryOperator(0x35, WasmType.Int64, "load32_u")); Int32Store = Register<MemoryOperator>(new MemoryOperator(0x36, WasmType.Int32, "store")); Int64Store = Register<MemoryOperator>(new MemoryOperator(0x37, WasmType.Int64, "store")); Float32Store = Register<MemoryOperator>(new MemoryOperator(0x38, WasmType.Float32, "store")); Float64Store = Register<MemoryOperator>(new MemoryOperator(0x39, WasmType.Float64, "store")); Int32Store8 = Register<MemoryOperator>(new MemoryOperator(0x3a, WasmType.Int32, "store8")); Int32Store16 = Register<MemoryOperator>(new MemoryOperator(0x3b, WasmType.Int32, "store16")); Int64Store8 = Register<MemoryOperator>(new MemoryOperator(0x3c, WasmType.Int64, "store8")); Int64Store16 = Register<MemoryOperator>(new MemoryOperator(0x3d, WasmType.Int64, "store16")); Int64Store32 = Register<MemoryOperator>(new MemoryOperator(0x3e, WasmType.Int64, "store32")); CurrentMemory = Register<VarUInt32Operator>(new VarUInt32Operator(0x3f, WasmType.Empty, "current_memory")); GrowMemory = Register<VarUInt32Operator>(new VarUInt32Operator(0x40, WasmType.Empty, "grow_memory")); // The code below has been auto-generated by nullary-opcode-generator. Int32Eqz = Register<NullaryOperator>(new NullaryOperator(0x45, WasmType.Int32, "eqz")); Int32Eq = Register<NullaryOperator>(new NullaryOperator(0x46, WasmType.Int32, "eq")); Int32Ne = Register<NullaryOperator>(new NullaryOperator(0x47, WasmType.Int32, "ne")); Int32LtS = Register<NullaryOperator>(new NullaryOperator(0x48, WasmType.Int32, "lt_s")); Int32LtU = Register<NullaryOperator>(new NullaryOperator(0x49, WasmType.Int32, "lt_u")); Int32GtS = Register<NullaryOperator>(new NullaryOperator(0x4a, WasmType.Int32, "gt_s")); Int32GtU = Register<NullaryOperator>(new NullaryOperator(0x4b, WasmType.Int32, "gt_u")); Int32LeS = Register<NullaryOperator>(new NullaryOperator(0x4c, WasmType.Int32, "le_s")); Int32LeU = Register<NullaryOperator>(new NullaryOperator(0x4d, WasmType.Int32, "le_u")); Int32GeS = Register<NullaryOperator>(new NullaryOperator(0x4e, WasmType.Int32, "ge_s")); Int32GeU = Register<NullaryOperator>(new NullaryOperator(0x4f, WasmType.Int32, "ge_u")); Int64Eqz = Register<NullaryOperator>(new NullaryOperator(0x50, WasmType.Int64, "eqz")); Int64Eq = Register<NullaryOperator>(new NullaryOperator(0x51, WasmType.Int64, "eq")); Int64Ne = Register<NullaryOperator>(new NullaryOperator(0x52, WasmType.Int64, "ne")); Int64LtS = Register<NullaryOperator>(new NullaryOperator(0x53, WasmType.Int64, "lt_s")); Int64LtU = Register<NullaryOperator>(new NullaryOperator(0x54, WasmType.Int64, "lt_u")); Int64GtS = Register<NullaryOperator>(new NullaryOperator(0x55, WasmType.Int64, "gt_s")); Int64GtU = Register<NullaryOperator>(new NullaryOperator(0x56, WasmType.Int64, "gt_u")); Int64LeS = Register<NullaryOperator>(new NullaryOperator(0x57, WasmType.Int64, "le_s")); Int64LeU = Register<NullaryOperator>(new NullaryOperator(0x58, WasmType.Int64, "le_u")); Int64GeS = Register<NullaryOperator>(new NullaryOperator(0x59, WasmType.Int64, "ge_s")); Int64GeU = Register<NullaryOperator>(new NullaryOperator(0x5a, WasmType.Int64, "ge_u")); Float32Eq = Register<NullaryOperator>(new NullaryOperator(0x5b, WasmType.Float32, "eq")); Float32Ne = Register<NullaryOperator>(new NullaryOperator(0x5c, WasmType.Float32, "ne")); Float32Lt = Register<NullaryOperator>(new NullaryOperator(0x5d, WasmType.Float32, "lt")); Float32Gt = Register<NullaryOperator>(new NullaryOperator(0x5e, WasmType.Float32, "gt")); Float32Le = Register<NullaryOperator>(new NullaryOperator(0x5f, WasmType.Float32, "le")); Float32Ge = Register<NullaryOperator>(new NullaryOperator(0x60, WasmType.Float32, "ge")); Float64Eq = Register<NullaryOperator>(new NullaryOperator(0x61, WasmType.Float64, "eq")); Float64Ne = Register<NullaryOperator>(new NullaryOperator(0x62, WasmType.Float64, "ne")); Float64Lt = Register<NullaryOperator>(new NullaryOperator(0x63, WasmType.Float64, "lt")); Float64Gt = Register<NullaryOperator>(new NullaryOperator(0x64, WasmType.Float64, "gt")); Float64Le = Register<NullaryOperator>(new NullaryOperator(0x65, WasmType.Float64, "le")); Float64Ge = Register<NullaryOperator>(new NullaryOperator(0x66, WasmType.Float64, "ge")); Int32Clz = Register<NullaryOperator>(new NullaryOperator(0x67, WasmType.Int32, "clz")); Int32Ctz = Register<NullaryOperator>(new NullaryOperator(0x68, WasmType.Int32, "ctz")); Int32Popcnt = Register<NullaryOperator>(new NullaryOperator(0x69, WasmType.Int32, "popcnt")); Int32Add = Register<NullaryOperator>(new NullaryOperator(0x6a, WasmType.Int32, "add")); Int32Sub = Register<NullaryOperator>(new NullaryOperator(0x6b, WasmType.Int32, "sub")); Int32Mul = Register<NullaryOperator>(new NullaryOperator(0x6c, WasmType.Int32, "mul")); Int32DivS = Register<NullaryOperator>(new NullaryOperator(0x6d, WasmType.Int32, "div_s")); Int32DivU = Register<NullaryOperator>(new NullaryOperator(0x6e, WasmType.Int32, "div_u")); Int32RemS = Register<NullaryOperator>(new NullaryOperator(0x6f, WasmType.Int32, "rem_s")); Int32RemU = Register<NullaryOperator>(new NullaryOperator(0x70, WasmType.Int32, "rem_u")); Int32And = Register<NullaryOperator>(new NullaryOperator(0x71, WasmType.Int32, "and")); Int32Or = Register<NullaryOperator>(new NullaryOperator(0x72, WasmType.Int32, "or")); Int32Xor = Register<NullaryOperator>(new NullaryOperator(0x73, WasmType.Int32, "xor")); Int32Shl = Register<NullaryOperator>(new NullaryOperator(0x74, WasmType.Int32, "shl")); Int32ShrS = Register<NullaryOperator>(new NullaryOperator(0x75, WasmType.Int32, "shr_s")); Int32ShrU = Register<NullaryOperator>(new NullaryOperator(0x76, WasmType.Int32, "shr_u")); Int32Rotl = Register<NullaryOperator>(new NullaryOperator(0x77, WasmType.Int32, "rotl")); Int32Rotr = Register<NullaryOperator>(new NullaryOperator(0x78, WasmType.Int32, "rotr")); Int64Clz = Register<NullaryOperator>(new NullaryOperator(0x79, WasmType.Int64, "clz")); Int64Ctz = Register<NullaryOperator>(new NullaryOperator(0x7a, WasmType.Int64, "ctz")); Int64Popcnt = Register<NullaryOperator>(new NullaryOperator(0x7b, WasmType.Int64, "popcnt")); Int64Add = Register<NullaryOperator>(new NullaryOperator(0x7c, WasmType.Int64, "add")); Int64Sub = Register<NullaryOperator>(new NullaryOperator(0x7d, WasmType.Int64, "sub")); Int64Mul = Register<NullaryOperator>(new NullaryOperator(0x7e, WasmType.Int64, "mul")); Int64DivS = Register<NullaryOperator>(new NullaryOperator(0x7f, WasmType.Int64, "div_s")); Int64DivU = Register<NullaryOperator>(new NullaryOperator(0x80, WasmType.Int64, "div_u")); Int64RemS = Register<NullaryOperator>(new NullaryOperator(0x81, WasmType.Int64, "rem_s")); Int64RemU = Register<NullaryOperator>(new NullaryOperator(0x82, WasmType.Int64, "rem_u")); Int64And = Register<NullaryOperator>(new NullaryOperator(0x83, WasmType.Int64, "and")); Int64Or = Register<NullaryOperator>(new NullaryOperator(0x84, WasmType.Int64, "or")); Int64Xor = Register<NullaryOperator>(new NullaryOperator(0x85, WasmType.Int64, "xor")); Int64Shl = Register<NullaryOperator>(new NullaryOperator(0x86, WasmType.Int64, "shl")); Int64ShrS = Register<NullaryOperator>(new NullaryOperator(0x87, WasmType.Int64, "shr_s")); Int64ShrU = Register<NullaryOperator>(new NullaryOperator(0x88, WasmType.Int64, "shr_u")); Int64Rotl = Register<NullaryOperator>(new NullaryOperator(0x89, WasmType.Int64, "rotl")); Int64Rotr = Register<NullaryOperator>(new NullaryOperator(0x8a, WasmType.Int64, "rotr")); Float32Abs = Register<NullaryOperator>(new NullaryOperator(0x8b, WasmType.Float32, "abs")); Float32Neg = Register<NullaryOperator>(new NullaryOperator(0x8c, WasmType.Float32, "neg")); Float32Ceil = Register<NullaryOperator>(new NullaryOperator(0x8d, WasmType.Float32, "ceil")); Float32Floor = Register<NullaryOperator>(new NullaryOperator(0x8e, WasmType.Float32, "floor")); Float32Trunc = Register<NullaryOperator>(new NullaryOperator(0x8f, WasmType.Float32, "trunc")); Float32Nearest = Register<NullaryOperator>(new NullaryOperator(0x90, WasmType.Float32, "nearest")); Float32Sqrt = Register<NullaryOperator>(new NullaryOperator(0x91, WasmType.Float32, "sqrt")); Float32Add = Register<NullaryOperator>(new NullaryOperator(0x92, WasmType.Float32, "add")); Float32Sub = Register<NullaryOperator>(new NullaryOperator(0x93, WasmType.Float32, "sub")); Float32Mul = Register<NullaryOperator>(new NullaryOperator(0x94, WasmType.Float32, "mul")); Float32Div = Register<NullaryOperator>(new NullaryOperator(0x95, WasmType.Float32, "div")); Float32Min = Register<NullaryOperator>(new NullaryOperator(0x96, WasmType.Float32, "min")); Float32Max = Register<NullaryOperator>(new NullaryOperator(0x97, WasmType.Float32, "max")); Float32Copysign = Register<NullaryOperator>(new NullaryOperator(0x98, WasmType.Float32, "copysign")); Float64Abs = Register<NullaryOperator>(new NullaryOperator(0x99, WasmType.Float64, "abs")); Float64Neg = Register<NullaryOperator>(new NullaryOperator(0x9a, WasmType.Float64, "neg")); Float64Ceil = Register<NullaryOperator>(new NullaryOperator(0x9b, WasmType.Float64, "ceil")); Float64Floor = Register<NullaryOperator>(new NullaryOperator(0x9c, WasmType.Float64, "floor")); Float64Trunc = Register<NullaryOperator>(new NullaryOperator(0x9d, WasmType.Float64, "trunc")); Float64Nearest = Register<NullaryOperator>(new NullaryOperator(0x9e, WasmType.Float64, "nearest")); Float64Sqrt = Register<NullaryOperator>(new NullaryOperator(0x9f, WasmType.Float64, "sqrt")); Float64Add = Register<NullaryOperator>(new NullaryOperator(0xa0, WasmType.Float64, "add")); Float64Sub = Register<NullaryOperator>(new NullaryOperator(0xa1, WasmType.Float64, "sub")); Float64Mul = Register<NullaryOperator>(new NullaryOperator(0xa2, WasmType.Float64, "mul")); Float64Div = Register<NullaryOperator>(new NullaryOperator(0xa3, WasmType.Float64, "div")); Float64Min = Register<NullaryOperator>(new NullaryOperator(0xa4, WasmType.Float64, "min")); Float64Max = Register<NullaryOperator>(new NullaryOperator(0xa5, WasmType.Float64, "max")); Float64Copysign = Register<NullaryOperator>(new NullaryOperator(0xa6, WasmType.Float64, "copysign")); Int32WrapInt64 = Register<NullaryOperator>(new NullaryOperator(0xa7, WasmType.Int32, "wrap/i64")); Int32TruncSFloat32 = Register<NullaryOperator>(new NullaryOperator(0xa8, WasmType.Int32, "trunc_s/f32")); Int32TruncUFloat32 = Register<NullaryOperator>(new NullaryOperator(0xa9, WasmType.Int32, "trunc_u/f32")); Int32TruncSFloat64 = Register<NullaryOperator>(new NullaryOperator(0xaa, WasmType.Int32, "trunc_s/f64")); Int32TruncUFloat64 = Register<NullaryOperator>(new NullaryOperator(0xab, WasmType.Int32, "trunc_u/f64")); Int64ExtendSInt32 = Register<NullaryOperator>(new NullaryOperator(0xac, WasmType.Int64, "extend_s/i32")); Int64ExtendUInt32 = Register<NullaryOperator>(new NullaryOperator(0xad, WasmType.Int64, "extend_u/i32")); Int64TruncSFloat32 = Register<NullaryOperator>(new NullaryOperator(0xae, WasmType.Int64, "trunc_s/f32")); Int64TruncUFloat32 = Register<NullaryOperator>(new NullaryOperator(0xaf, WasmType.Int64, "trunc_u/f32")); Int64TruncSFloat64 = Register<NullaryOperator>(new NullaryOperator(0xb0, WasmType.Int64, "trunc_s/f64")); Int64TruncUFloat64 = Register<NullaryOperator>(new NullaryOperator(0xb1, WasmType.Int64, "trunc_u/f64")); Float32ConvertSInt32 = Register<NullaryOperator>(new NullaryOperator(0xb2, WasmType.Float32, "convert_s/i32")); Float32ConvertUInt32 = Register<NullaryOperator>(new NullaryOperator(0xb3, WasmType.Float32, "convert_u/i32")); Float32ConvertSInt64 = Register<NullaryOperator>(new NullaryOperator(0xb4, WasmType.Float32, "convert_s/i64")); Float32ConvertUInt64 = Register<NullaryOperator>(new NullaryOperator(0xb5, WasmType.Float32, "convert_u/i64")); Float32DemoteFloat64 = Register<NullaryOperator>(new NullaryOperator(0xb6, WasmType.Float32, "demote/f64")); Float64ConvertSInt32 = Register<NullaryOperator>(new NullaryOperator(0xb7, WasmType.Float64, "convert_s/i32")); Float64ConvertUInt32 = Register<NullaryOperator>(new NullaryOperator(0xb8, WasmType.Float64, "convert_u/i32")); Float64ConvertSInt64 = Register<NullaryOperator>(new NullaryOperator(0xb9, WasmType.Float64, "convert_s/i64")); Float64ConvertUInt64 = Register<NullaryOperator>(new NullaryOperator(0xba, WasmType.Float64, "convert_u/i64")); Float64PromoteFloat32 = Register<NullaryOperator>(new NullaryOperator(0xbb, WasmType.Float64, "promote/f32")); Int32ReinterpretFloat32 = Register<NullaryOperator>(new NullaryOperator(0xbc, WasmType.Int32, "reinterpret/f32")); Int64ReinterpretFloat64 = Register<NullaryOperator>(new NullaryOperator(0xbd, WasmType.Int64, "reinterpret/f64")); Float32ReinterpretInt32 = Register<NullaryOperator>(new NullaryOperator(0xbe, WasmType.Float32, "reinterpret/i32")); Float64ReinterpretInt64 = Register<NullaryOperator>(new NullaryOperator(0xbf, WasmType.Float64, "reinterpret/i64")); } /// <summary> /// A map of opcodes to the operators that define them. /// </summary> private static Dictionary<byte, Operator> opsByOpCode; /// <summary> /// Gets a map of opcodes to the operators that define them. /// </summary> public static IReadOnlyDictionary<byte, Operator> OperatorsByOpCode => opsByOpCode; /// <summary> /// Gets a sequence that contains all WebAssembly operators defined by this class. /// </summary> public static IEnumerable<Operator> AllOperators => opsByOpCode.Values; /// <summary> /// Registers the given operator. /// </summary> /// <param name="op">The operator to register.</param> /// <returns>The operator.</returns> private static T Register<T>(T op) where T : Operator { opsByOpCode.Add(op.OpCode, op); return op; } /// <summary> /// Gets the operator with the given opcode. /// </summary> /// <param name="opCode">The opcode to find an operator for.</param> /// <returns>The operator with the given opcode.</returns> public static Operator GetOperatorByOpCode(byte opCode) { Operator result; if (OperatorsByOpCode.TryGetValue(opCode, out result)) { return result; } else { throw new WasmException( string.Format("Unknown opcode: {0}", DumpHelpers.FormatHex(opCode))); } } /// <summary> /// The 'unreachable' operator, which traps immediately. /// </summary> public static readonly NullaryOperator Unreachable; /// <summary> /// The 'nop' operator, which does nothing. /// </summary> public static readonly NullaryOperator Nop; /// <summary> /// The 'block' operator, which begins a sequence of expressions, yielding 0 or 1 values. /// </summary> public static readonly BlockOperator Block; /// <summary> /// The 'loop' operator, which begins a block which can also form control flow loops /// </summary> public static readonly BlockOperator Loop; /// <summary> /// The 'if' operator, which runs one of two sequences of expressions. /// </summary> public static readonly IfElseOperator If; /// <summary> /// The 'br' operator: a break that targets an outer nested block. /// </summary> public static readonly VarUInt32Operator Br; /// <summary> /// The 'br_if' operator: a conditional break that targets an outer nested block. /// </summary> public static readonly VarUInt32Operator BrIf; /// <summary> /// The 'br_table' operator, which begins a break table. /// </summary> public static readonly BrTableOperator BrTable; /// <summary> /// The 'return' operator, which returns zero or one value from a function. /// </summary> public static readonly NullaryOperator Return; /// <summary> /// The 'drop' operator, which pops the top-of-stack value and ignores it. /// </summary> public static readonly NullaryOperator Drop; /// <summary> /// The 'select' operator, which selects one of two values based on a condition. /// </summary> public static readonly NullaryOperator Select; /// <summary> /// The 'call' operator, which calls a function by its index. /// </summary> public static readonly VarUInt32Operator Call; /// <summary> /// The 'call_indirect' operator, which calls a function pointer. /// </summary> public static readonly CallIndirectOperator CallIndirect; /// <summary> /// The 'get_local' operator, which reads a local variable or parameter. /// </summary> public static readonly VarUInt32Operator GetLocal; /// <summary> /// The 'set_local' operator, which writes a value to a local variable or parameter. /// </summary> public static readonly VarUInt32Operator SetLocal; /// <summary> /// The 'tee_local' operator, which writes a value to a local variable or parameter /// and then returns the same value. /// </summary> public static readonly VarUInt32Operator TeeLocal; /// <summary> /// The 'get_global' operator, which reads a global variable. /// </summary> public static readonly VarUInt32Operator GetGlobal; /// <summary> /// The 'set_global' operator, which writes a value to a global variable. /// </summary> public static readonly VarUInt32Operator SetGlobal; /// <summary> /// The 'i32.load' operator, which loads a 32-bit integer from linear memory. /// </summary> public static readonly MemoryOperator Int32Load; /// <summary> /// The 'i64.load' operator, which loads a 64-bit integer from linear memory. /// </summary> public static readonly MemoryOperator Int64Load; /// <summary> /// The 'f32.load' operator, which loads a 32-bit floating-point number from linear memory. /// </summary> public static readonly MemoryOperator Float32Load; /// <summary> /// The 'f64.load' operator, which loads a 64-bit floating-point number from linear memory. /// </summary> public static readonly MemoryOperator Float64Load; /// <summary> /// The 'i32.load8_s' operator, which loads a byte from memory and sign-extends it to /// a 32-bit integer. /// </summary> public static readonly MemoryOperator Int32Load8S; /// <summary> /// The 'i32.load8_u' operator, which loads a byte from memory and zero-extends it to /// a 32-bit integer. /// </summary> public static readonly MemoryOperator Int32Load8U; /// <summary> /// The 'i32.load16_s' operator, which loads a 16-bit integer from memory and /// sign-extends it to a 32-bit integer. /// </summary> public static readonly MemoryOperator Int32Load16S; /// <summary> /// The 'i32.load16_u' operator, which loads a 16-bit integer from memory and /// zero-extends it to a 32-bit integer. /// </summary> public static readonly MemoryOperator Int32Load16U; /// <summary> /// The 'i64.load8_s' operator, which loads a byte from memory and sign-extends it to /// a 64-bit integer. /// </summary> public static readonly MemoryOperator Int64Load8S; /// <summary> /// The 'i64.load8_u' operator, which loads a byte from memory and zero-extends it to /// a 64-bit integer. /// </summary> public static readonly MemoryOperator Int64Load8U; /// <summary> /// The 'i64.load16_s' operator, which loads a 16-bit integer from memory and /// sign-extends it to a 64-bit integer. /// </summary> public static readonly MemoryOperator Int64Load16S; /// <summary> /// The 'i64.load16_u' operator, which loads a 16-bit integer from memory and /// zero-extends it to a 64-bit integer. /// </summary> public static readonly MemoryOperator Int64Load16U; /// <summary> /// The 'i64.load32_s' operator, which loads a 32-bit integer from memory and /// sign-extends it to a 64-bit integer. /// </summary> public static readonly MemoryOperator Int64Load32S; /// <summary> /// The 'i64.load32_u' operator, which loads a 32-bit integer from memory and /// zero-extends it to a 64-bit integer. /// </summary> public static readonly MemoryOperator Int64Load32U; /// <summary> /// The 'i32.store' operator, which stores a 32-bit integer in linear memory. /// </summary> public static readonly MemoryOperator Int32Store; /// <summary> /// The 'i64.store' operator, which stores a 64-bit integer in linear memory. /// </summary> public static readonly MemoryOperator Int64Store; /// <summary> /// The 'f32.store' operator, which stores a 32-bit floating-point number in /// linear memory. /// </summary> public static readonly MemoryOperator Float32Store; /// <summary> /// The 'f64.store' operator, which stores a 64-bit floating-point number in /// linear memory. /// </summary> public static readonly MemoryOperator Float64Store; /// <summary> /// The 'i32.store' operator, which truncates a 32-bit integer to a byte and stores /// it in linear memory. /// </summary> public static readonly MemoryOperator Int32Store8; /// <summary> /// The 'i32.store' operator, which truncates a 32-bit integer to a 16-bit integer /// and stores it in linear memory. /// </summary> public static readonly MemoryOperator Int32Store16; /// <summary> /// The 'i64.store' operator, which truncates a 64-bit integer to a byte and stores /// it in linear memory. /// </summary> public static readonly MemoryOperator Int64Store8; /// <summary> /// The 'i64.store' operator, which truncates a 64-bit integer to a 16-bit integer /// and stores it in linear memory. /// </summary> public static readonly MemoryOperator Int64Store16; /// <summary> /// The 'i64.store' operator, which truncates a 64-bit integer to a 32-bit integer /// and stores it in linear memory. /// </summary> public static readonly MemoryOperator Int64Store32; /// <summary> /// The 'current_memory' operator, which queries the memory size. /// </summary> public static readonly VarUInt32Operator CurrentMemory; /// <summary> /// The 'grow_memory' operator, which grows the memory size. /// </summary> public static readonly VarUInt32Operator GrowMemory; /// <summary> /// The 'i32.const' operator, which loads a constant 32-bit integer onto the stack. /// </summary> public static readonly VarInt32Operator Int32Const; /// <summary> /// The 'i64.const' operator, which loads a constant 64-bit integer onto the stack. /// </summary> public static readonly VarInt64Operator Int64Const; /// <summary> /// The 'f32.const' operator, which loads a constant 32-bit floating-point number onto the stack. /// </summary> public static readonly Float32Operator Float32Const; /// <summary> /// The 'f64.const' operator, which loads a constant 64-bit floating-point number onto the stack. /// </summary> public static readonly Float64Operator Float64Const; /// <summary> /// The 'else' opcode, which begins an 'if' expression's 'else' block. /// </summary> public const byte ElseOpCode = 0x05; /// <summary> /// The 'end' opcode, which ends a block, loop or if. /// </summary> public const byte EndOpCode = 0x0b; #region Auto-generated nullaries // This region was auto-generated by nullary-opcode-generator. Please don't make any // manual changes. /// <summary> /// The 'i32.eqz' operator: compare equal to zero (return 1 if operand is zero, 0 otherwise). /// </summary> public static readonly NullaryOperator Int32Eqz; /// <summary> /// The 'i32.eq' operator: sign-agnostic compare equal. /// </summary> public static readonly NullaryOperator Int32Eq; /// <summary> /// The 'i32.ne' operator: sign-agnostic compare unequal. /// </summary> public static readonly NullaryOperator Int32Ne; /// <summary> /// The 'i32.lt_s' operator: signed less than. /// </summary> public static readonly NullaryOperator Int32LtS; /// <summary> /// The 'i32.lt_u' operator: unsigned less than. /// </summary> public static readonly NullaryOperator Int32LtU; /// <summary> /// The 'i32.gt_s' operator: signed greater than. /// </summary> public static readonly NullaryOperator Int32GtS; /// <summary> /// The 'i32.gt_u' operator: unsigned greater than. /// </summary> public static readonly NullaryOperator Int32GtU; /// <summary> /// The 'i32.le_s' operator: signed less than or equal. /// </summary> public static readonly NullaryOperator Int32LeS; /// <summary> /// The 'i32.le_u' operator: unsigned less than or equal. /// </summary> public static readonly NullaryOperator Int32LeU; /// <summary> /// The 'i32.ge_s' operator: signed greater than or equal. /// </summary> public static readonly NullaryOperator Int32GeS; /// <summary> /// The 'i32.ge_u' operator: unsigned greater than or equal. /// </summary> public static readonly NullaryOperator Int32GeU; /// <summary> /// The 'i64.eqz' operator: compare equal to zero (return 1 if operand is zero, 0 otherwise). /// </summary> public static readonly NullaryOperator Int64Eqz; /// <summary> /// The 'i64.eq' operator: sign-agnostic compare equal. /// </summary> public static readonly NullaryOperator Int64Eq; /// <summary> /// The 'i64.ne' operator: sign-agnostic compare unequal. /// </summary> public static readonly NullaryOperator Int64Ne; /// <summary> /// The 'i64.lt_s' operator: signed less than. /// </summary> public static readonly NullaryOperator Int64LtS; /// <summary> /// The 'i64.lt_u' operator: unsigned less than. /// </summary> public static readonly NullaryOperator Int64LtU; /// <summary> /// The 'i64.gt_s' operator: signed greater than. /// </summary> public static readonly NullaryOperator Int64GtS; /// <summary> /// The 'i64.gt_u' operator: unsigned greater than. /// </summary> public static readonly NullaryOperator Int64GtU; /// <summary> /// The 'i64.le_s' operator: signed less than or equal. /// </summary> public static readonly NullaryOperator Int64LeS; /// <summary> /// The 'i64.le_u' operator: unsigned less than or equal. /// </summary> public static readonly NullaryOperator Int64LeU; /// <summary> /// The 'i64.ge_s' operator: signed greater than or equal. /// </summary> public static readonly NullaryOperator Int64GeS; /// <summary> /// The 'i64.ge_u' operator: unsigned greater than or equal. /// </summary> public static readonly NullaryOperator Int64GeU; /// <summary> /// The 'f32.eq' operator: compare ordered and equal. /// </summary> public static readonly NullaryOperator Float32Eq; /// <summary> /// The 'f32.ne' operator: compare unordered or unequal. /// </summary> public static readonly NullaryOperator Float32Ne; /// <summary> /// The 'f32.lt' operator: compare ordered and less than. /// </summary> public static readonly NullaryOperator Float32Lt; /// <summary> /// The 'f32.gt' operator: compare ordered and greater than. /// </summary> public static readonly NullaryOperator Float32Gt; /// <summary> /// The 'f32.le' operator: compare ordered and less than or equal. /// </summary> public static readonly NullaryOperator Float32Le; /// <summary> /// The 'f32.ge' operator: compare ordered and greater than or equal. /// </summary> public static readonly NullaryOperator Float32Ge; /// <summary> /// The 'f64.eq' operator: compare ordered and equal. /// </summary> public static readonly NullaryOperator Float64Eq; /// <summary> /// The 'f64.ne' operator: compare unordered or unequal. /// </summary> public static readonly NullaryOperator Float64Ne; /// <summary> /// The 'f64.lt' operator: compare ordered and less than. /// </summary> public static readonly NullaryOperator Float64Lt; /// <summary> /// The 'f64.gt' operator: compare ordered and greater than. /// </summary> public static readonly NullaryOperator Float64Gt; /// <summary> /// The 'f64.le' operator: compare ordered and less than or equal. /// </summary> public static readonly NullaryOperator Float64Le; /// <summary> /// The 'f64.ge' operator: compare ordered and greater than or equal. /// </summary> public static readonly NullaryOperator Float64Ge; /// <summary> /// The 'i32.clz' operator: sign-agnostic count leading zero bits (All zero bits are considered leading if the value is zero). /// </summary> public static readonly NullaryOperator Int32Clz; /// <summary> /// The 'i32.ctz' operator: sign-agnostic count trailing zero bits (All zero bits are considered trailing if the value is zero). /// </summary> public static readonly NullaryOperator Int32Ctz; /// <summary> /// The 'i32.popcnt' operator: sign-agnostic count number of one bits. /// </summary> public static readonly NullaryOperator Int32Popcnt; /// <summary> /// The 'i32.add' operator: sign-agnostic addition. /// </summary> public static readonly NullaryOperator Int32Add; /// <summary> /// The 'i32.sub' operator: sign-agnostic subtraction. /// </summary> public static readonly NullaryOperator Int32Sub; /// <summary> /// The 'i32.mul' operator: sign-agnostic multiplication (lower 32-bits). /// </summary> public static readonly NullaryOperator Int32Mul; /// <summary> /// The 'i32.div_s' operator: signed division (result is truncated toward zero). /// </summary> public static readonly NullaryOperator Int32DivS; /// <summary> /// The 'i32.div_u' operator: unsigned division (result is floored). /// </summary> public static readonly NullaryOperator Int32DivU; /// <summary> /// The 'i32.rem_s' operator: signed remainder (result has the sign of the dividend). /// </summary> public static readonly NullaryOperator Int32RemS; /// <summary> /// The 'i32.rem_u' operator: unsigned remainder. /// </summary> public static readonly NullaryOperator Int32RemU; /// <summary> /// The 'i32.and' operator: sign-agnostic bitwise and. /// </summary> public static readonly NullaryOperator Int32And; /// <summary> /// The 'i32.or' operator: sign-agnostic bitwise inclusive or. /// </summary> public static readonly NullaryOperator Int32Or; /// <summary> /// The 'i32.xor' operator: sign-agnostic bitwise exclusive or. /// </summary> public static readonly NullaryOperator Int32Xor; /// <summary> /// The 'i32.shl' operator: sign-agnostic shift left. /// </summary> public static readonly NullaryOperator Int32Shl; /// <summary> /// The 'i32.shr_s' operator: sign-replicating (arithmetic) shift right. /// </summary> public static readonly NullaryOperator Int32ShrS; /// <summary> /// The 'i32.shr_u' operator: zero-replicating (logical) shift right. /// </summary> public static readonly NullaryOperator Int32ShrU; /// <summary> /// The 'i32.rotl' operator: sign-agnostic rotate left. /// </summary> public static readonly NullaryOperator Int32Rotl; /// <summary> /// The 'i32.rotr' operator: sign-agnostic rotate right. /// </summary> public static readonly NullaryOperator Int32Rotr; /// <summary> /// The 'i64.clz' operator: sign-agnostic count leading zero bits (All zero bits are considered leading if the value is zero). /// </summary> public static readonly NullaryOperator Int64Clz; /// <summary> /// The 'i64.ctz' operator: sign-agnostic count trailing zero bits (All zero bits are considered trailing if the value is zero). /// </summary> public static readonly NullaryOperator Int64Ctz; /// <summary> /// The 'i64.popcnt' operator: sign-agnostic count number of one bits. /// </summary> public static readonly NullaryOperator Int64Popcnt; /// <summary> /// The 'i64.add' operator: sign-agnostic addition. /// </summary> public static readonly NullaryOperator Int64Add; /// <summary> /// The 'i64.sub' operator: sign-agnostic subtraction. /// </summary> public static readonly NullaryOperator Int64Sub; /// <summary> /// The 'i64.mul' operator: sign-agnostic multiplication (lower 32-bits). /// </summary> public static readonly NullaryOperator Int64Mul; /// <summary> /// The 'i64.div_s' operator: signed division (result is truncated toward zero). /// </summary> public static readonly NullaryOperator Int64DivS; /// <summary> /// The 'i64.div_u' operator: unsigned division (result is floored). /// </summary> public static readonly NullaryOperator Int64DivU; /// <summary> /// The 'i64.rem_s' operator: signed remainder (result has the sign of the dividend). /// </summary> public static readonly NullaryOperator Int64RemS; /// <summary> /// The 'i64.rem_u' operator: unsigned remainder. /// </summary> public static readonly NullaryOperator Int64RemU; /// <summary> /// The 'i64.and' operator: sign-agnostic bitwise and. /// </summary> public static readonly NullaryOperator Int64And; /// <summary> /// The 'i64.or' operator: sign-agnostic bitwise inclusive or. /// </summary> public static readonly NullaryOperator Int64Or; /// <summary> /// The 'i64.xor' operator: sign-agnostic bitwise exclusive or. /// </summary> public static readonly NullaryOperator Int64Xor; /// <summary> /// The 'i64.shl' operator: sign-agnostic shift left. /// </summary> public static readonly NullaryOperator Int64Shl; /// <summary> /// The 'i64.shr_s' operator: sign-replicating (arithmetic) shift right. /// </summary> public static readonly NullaryOperator Int64ShrS; /// <summary> /// The 'i64.shr_u' operator: zero-replicating (logical) shift right. /// </summary> public static readonly NullaryOperator Int64ShrU; /// <summary> /// The 'i64.rotl' operator: sign-agnostic rotate left. /// </summary> public static readonly NullaryOperator Int64Rotl; /// <summary> /// The 'i64.rotr' operator: sign-agnostic rotate right. /// </summary> public static readonly NullaryOperator Int64Rotr; /// <summary> /// The 'f32.abs' operator: absolute value. /// </summary> public static readonly NullaryOperator Float32Abs; /// <summary> /// The 'f32.neg' operator: negation. /// </summary> public static readonly NullaryOperator Float32Neg; /// <summary> /// The 'f32.ceil' operator: ceiling operator. /// </summary> public static readonly NullaryOperator Float32Ceil; /// <summary> /// The 'f32.floor' operator: floor operator. /// </summary> public static readonly NullaryOperator Float32Floor; /// <summary> /// The 'f32.trunc' operator: round to nearest integer towards zero. /// </summary> public static readonly NullaryOperator Float32Trunc; /// <summary> /// The 'f32.nearest' operator: round to nearest integer, ties to even. /// </summary> public static readonly NullaryOperator Float32Nearest; /// <summary> /// The 'f32.sqrt' operator: square root. /// </summary> public static readonly NullaryOperator Float32Sqrt; /// <summary> /// The 'f32.add' operator: addition. /// </summary> public static readonly NullaryOperator Float32Add; /// <summary> /// The 'f32.sub' operator: subtraction. /// </summary> public static readonly NullaryOperator Float32Sub; /// <summary> /// The 'f32.mul' operator: multiplication. /// </summary> public static readonly NullaryOperator Float32Mul; /// <summary> /// The 'f32.div' operator: division. /// </summary> public static readonly NullaryOperator Float32Div; /// <summary> /// The 'f32.min' operator: minimum (binary operator); if either operand is NaN, returns NaN. /// </summary> public static readonly NullaryOperator Float32Min; /// <summary> /// The 'f32.max' operator: maximum (binary operator); if either operand is NaN, returns NaN. /// </summary> public static readonly NullaryOperator Float32Max; /// <summary> /// The 'f32.copysign' operator: copysign. /// </summary> public static readonly NullaryOperator Float32Copysign; /// <summary> /// The 'f64.abs' operator: absolute value. /// </summary> public static readonly NullaryOperator Float64Abs; /// <summary> /// The 'f64.neg' operator: negation. /// </summary> public static readonly NullaryOperator Float64Neg; /// <summary> /// The 'f64.ceil' operator: ceiling operator. /// </summary> public static readonly NullaryOperator Float64Ceil; /// <summary> /// The 'f64.floor' operator: floor operator. /// </summary> public static readonly NullaryOperator Float64Floor; /// <summary> /// The 'f64.trunc' operator: round to nearest integer towards zero. /// </summary> public static readonly NullaryOperator Float64Trunc; /// <summary> /// The 'f64.nearest' operator: round to nearest integer, ties to even. /// </summary> public static readonly NullaryOperator Float64Nearest; /// <summary> /// The 'f64.sqrt' operator: square root. /// </summary> public static readonly NullaryOperator Float64Sqrt; /// <summary> /// The 'f64.add' operator: addition. /// </summary> public static readonly NullaryOperator Float64Add; /// <summary> /// The 'f64.sub' operator: subtraction. /// </summary> public static readonly NullaryOperator Float64Sub; /// <summary> /// The 'f64.mul' operator: multiplication. /// </summary> public static readonly NullaryOperator Float64Mul; /// <summary> /// The 'f64.div' operator: division. /// </summary> public static readonly NullaryOperator Float64Div; /// <summary> /// The 'f64.min' operator: minimum (binary operator); if either operand is NaN, returns NaN. /// </summary> public static readonly NullaryOperator Float64Min; /// <summary> /// The 'f64.max' operator: maximum (binary operator); if either operand is NaN, returns NaN. /// </summary> public static readonly NullaryOperator Float64Max; /// <summary> /// The 'f64.copysign' operator: copysign. /// </summary> public static readonly NullaryOperator Float64Copysign; /// <summary> /// The 'i32.wrap/i64' operator: wrap a 64-bit integer to a 32-bit integer. /// </summary> public static readonly NullaryOperator Int32WrapInt64; /// <summary> /// The 'i32.trunc_s/f32' operator: truncate a 32-bit float to a signed 32-bit integer. /// </summary> public static readonly NullaryOperator Int32TruncSFloat32; /// <summary> /// The 'i32.trunc_u/f32' operator: truncate a 32-bit float to an unsigned 32-bit integer. /// </summary> public static readonly NullaryOperator Int32TruncUFloat32; /// <summary> /// The 'i32.trunc_s/f64' operator: truncate a 64-bit float to a signed 32-bit integer. /// </summary> public static readonly NullaryOperator Int32TruncSFloat64; /// <summary> /// The 'i32.trunc_u/f64' operator: truncate a 64-bit float to an unsigned 32-bit integer. /// </summary> public static readonly NullaryOperator Int32TruncUFloat64; /// <summary> /// The 'i64.extend_s/i32' operator: extend a signed 32-bit integer to a 64-bit integer. /// </summary> public static readonly NullaryOperator Int64ExtendSInt32; /// <summary> /// The 'i64.extend_u/i32' operator: extend an unsigned 32-bit integer to a 64-bit integer. /// </summary> public static readonly NullaryOperator Int64ExtendUInt32; /// <summary> /// The 'i64.trunc_s/f32' operator: truncate a 32-bit float to a signed 64-bit integer. /// </summary> public static readonly NullaryOperator Int64TruncSFloat32; /// <summary> /// The 'i64.trunc_u/f32' operator: truncate a 32-bit float to an unsigned 64-bit integer. /// </summary> public static readonly NullaryOperator Int64TruncUFloat32; /// <summary> /// The 'i64.trunc_s/f64' operator: truncate a 64-bit float to a signed 64-bit integer. /// </summary> public static readonly NullaryOperator Int64TruncSFloat64; /// <summary> /// The 'i64.trunc_u/f64' operator: truncate a 64-bit float to an unsigned 64-bit integer. /// </summary> public static readonly NullaryOperator Int64TruncUFloat64; /// <summary> /// The 'f32.convert_s/i32' operator: convert a signed 32-bit integer to a 32-bit float. /// </summary> public static readonly NullaryOperator Float32ConvertSInt32; /// <summary> /// The 'f32.convert_u/i32' operator: convert an unsigned 32-bit integer to a 32-bit float. /// </summary> public static readonly NullaryOperator Float32ConvertUInt32; /// <summary> /// The 'f32.convert_s/i64' operator: convert a signed 64-bit integer to a 32-bit float. /// </summary> public static readonly NullaryOperator Float32ConvertSInt64; /// <summary> /// The 'f32.convert_u/i64' operator: convert an unsigned 64-bit integer to a 32-bit float. /// </summary> public static readonly NullaryOperator Float32ConvertUInt64; /// <summary> /// The 'f32.demote/f64' operator: demote a 64-bit float to a 32-bit float. /// </summary> public static readonly NullaryOperator Float32DemoteFloat64; /// <summary> /// The 'f64.convert_s/i32' operator: convert a signed 32-bit integer to a 64-bit float. /// </summary> public static readonly NullaryOperator Float64ConvertSInt32; /// <summary> /// The 'f64.convert_u/i32' operator: convert an unsigned 32-bit integer to a 64-bit float. /// </summary> public static readonly NullaryOperator Float64ConvertUInt32; /// <summary> /// The 'f64.convert_s/i64' operator: convert a signed 64-bit integer to a 64-bit float. /// </summary> public static readonly NullaryOperator Float64ConvertSInt64; /// <summary> /// The 'f64.convert_u/i64' operator: convert an unsigned 64-bit integer to a 64-bit float. /// </summary> public static readonly NullaryOperator Float64ConvertUInt64; /// <summary> /// The 'f64.promote/f32' operator: promote a 32-bit float to a 64-bit float. /// </summary> public static readonly NullaryOperator Float64PromoteFloat32; /// <summary> /// The 'i32.reinterpret/f32' operator: reinterpret the bits of a 32-bit float as a 32-bit integer. /// </summary> public static readonly NullaryOperator Int32ReinterpretFloat32; /// <summary> /// The 'i64.reinterpret/f64' operator: reinterpret the bits of a 64-bit float as a 64-bit integer. /// </summary> public static readonly NullaryOperator Int64ReinterpretFloat64; /// <summary> /// The 'f32.reinterpret/i32' operator: reinterpret the bits of a 32-bit integer as a 32-bit float. /// </summary> public static readonly NullaryOperator Float32ReinterpretInt32; /// <summary> /// The 'f64.reinterpret/i64' operator: reinterpret the bits of a 64-bit integer as a 64-bit float. /// </summary> public static readonly NullaryOperator Float64ReinterpretInt64; #endregion } }
using J2N.Threading; using J2N.Threading.Atomic; using NUnit.Framework; using System; using System.Collections.Generic; using System.Threading; using Assert = Lucene.Net.TestFramework.Assert; 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 LuceneTestCase = Lucene.Net.Util.LuceneTestCase; /// <summary> /// Tests for <seealso cref="DocumentsWriterStallControl"/> /// </summary> [TestFixture] public class TestDocumentsWriterStallControl : LuceneTestCase { [Test] public virtual void TestSimpleStall() { DocumentsWriterStallControl ctrl = new DocumentsWriterStallControl(); ctrl.UpdateStalled(false); ThreadJob[] waitThreads = WaitThreads(AtLeast(1), ctrl); Start(waitThreads); Assert.IsFalse(ctrl.HasBlocked); Assert.IsFalse(ctrl.AnyStalledThreads()); Join(waitThreads); // now stall threads and wake them up again ctrl.UpdateStalled(true); waitThreads = WaitThreads(AtLeast(1), ctrl); Start(waitThreads); AwaitState(ThreadState.WaitSleepJoin, waitThreads); Assert.IsTrue(ctrl.HasBlocked); Assert.IsTrue(ctrl.AnyStalledThreads()); ctrl.UpdateStalled(false); Assert.IsFalse(ctrl.AnyStalledThreads()); Join(waitThreads); } [Test] public virtual void TestRandom() { DocumentsWriterStallControl ctrl = new DocumentsWriterStallControl(); ctrl.UpdateStalled(false); ThreadJob[] stallThreads = new ThreadJob[AtLeast(3)]; for (int i = 0; i < stallThreads.Length; i++) { int stallProbability = 1 + Random.Next(10); stallThreads[i] = new ThreadAnonymousInnerClassHelper(ctrl, stallProbability); } Start(stallThreads); long time = Environment.TickCount; /* * use a 100 sec timeout to make sure we not hang forever. join will fail in * that case */ while ((Environment.TickCount - time) < 100 * 1000 && !Terminated(stallThreads)) { ctrl.UpdateStalled(false); if (Random.NextBoolean()) { Thread.Sleep(0); } else { Thread.Sleep(1); } } Join(stallThreads); } private class ThreadAnonymousInnerClassHelper : ThreadJob { private readonly DocumentsWriterStallControl ctrl; private readonly int stallProbability; public ThreadAnonymousInnerClassHelper(DocumentsWriterStallControl ctrl, int stallProbability) { this.ctrl = ctrl; this.stallProbability = stallProbability; } public override void Run() { int iters = AtLeast(1000); for (int j = 0; j < iters; j++) { ctrl.UpdateStalled(Random.Next(stallProbability) == 0); if (Random.Next(5) == 0) // thread 0 only updates { ctrl.WaitIfStalled(); } } } } [Test] public virtual void TestAccquireReleaseRace() { DocumentsWriterStallControl ctrl = new DocumentsWriterStallControl(); ctrl.UpdateStalled(false); AtomicBoolean stop = new AtomicBoolean(false); AtomicBoolean checkPoint = new AtomicBoolean(true); int numStallers = AtLeast(1); int numReleasers = AtLeast(1); int numWaiters = AtLeast(1); var sync = new Synchronizer(numStallers + numReleasers, numStallers + numReleasers + numWaiters); var threads = new ThreadJob[numReleasers + numStallers + numWaiters]; IList<Exception> exceptions = new SynchronizedList<Exception>(); for (int i = 0; i < numReleasers; i++) { threads[i] = new Updater(stop, checkPoint, ctrl, sync, true, exceptions); } for (int i = numReleasers; i < numReleasers + numStallers; i++) { threads[i] = new Updater(stop, checkPoint, ctrl, sync, false, exceptions); } for (int i = numReleasers + numStallers; i < numReleasers + numStallers + numWaiters; i++) { threads[i] = new Waiter(stop, checkPoint, ctrl, sync, exceptions); } Start(threads); int iters = AtLeast(10000); float checkPointProbability = TestNightly ? 0.5f : 0.1f; for (int i = 0; i < iters; i++) { if (checkPoint) { Assert.IsTrue(sync.updateJoin.Wait(new TimeSpan(0, 0, 0, 10)), "timed out waiting for update threads - deadlock?"); if (exceptions.Count > 0) { foreach (Exception throwable in exceptions) { Console.WriteLine(throwable.ToString()); Console.Write(throwable.StackTrace); } Assert.Fail("got exceptions in threads"); } if (ctrl.HasBlocked && ctrl.IsHealthy) { AssertState(numReleasers, numStallers, numWaiters, threads, ctrl); } checkPoint.Value = (false); sync.waiter.Signal(); sync.leftCheckpoint.Wait(); } Assert.IsFalse(checkPoint); Assert.AreEqual(0, sync.waiter.CurrentCount); if (checkPointProbability >= (float)Random.NextDouble()) { sync.Reset(numStallers + numReleasers, numStallers + numReleasers + numWaiters); checkPoint.Value = (true); } } if (!checkPoint) { sync.Reset(numStallers + numReleasers, numStallers + numReleasers + numWaiters); checkPoint.Value = (true); } Assert.IsTrue(sync.updateJoin.Wait(new TimeSpan(0, 0, 0, 10))); AssertState(numReleasers, numStallers, numWaiters, threads, ctrl); checkPoint.Value = (false); stop.Value = (true); sync.waiter.Signal(); sync.leftCheckpoint.Wait(); for (int i = 0; i < threads.Length; i++) { ctrl.UpdateStalled(false); threads[i].Join(2000); if (threads[i].IsAlive && threads[i] is Waiter) { if (threads[i].State == ThreadState.WaitSleepJoin) { Assert.Fail("waiter is not released - anyThreadsStalled: " + ctrl.AnyStalledThreads()); } } } } private void AssertState(int numReleasers, int numStallers, int numWaiters, ThreadJob[] threads, DocumentsWriterStallControl ctrl) { int millisToSleep = 100; while (true) { if (ctrl.HasBlocked && ctrl.IsHealthy) { for (int n = numReleasers + numStallers; n < numReleasers + numStallers + numWaiters; n++) { if (ctrl.IsThreadQueued(threads[n])) { if (millisToSleep < 60000) { Thread.Sleep(millisToSleep); millisToSleep *= 2; break; } else { Assert.Fail("control claims no stalled threads but waiter seems to be blocked "); } } } break; } else { break; } } } internal class Waiter : ThreadJob { internal Synchronizer sync; internal DocumentsWriterStallControl ctrl; internal AtomicBoolean checkPoint; internal AtomicBoolean stop; internal IList<Exception> exceptions; public Waiter(AtomicBoolean stop, AtomicBoolean checkPoint, DocumentsWriterStallControl ctrl, Synchronizer sync, IList<Exception> exceptions) : base("waiter") { this.stop = stop; this.checkPoint = checkPoint; this.ctrl = ctrl; this.sync = sync; this.exceptions = exceptions; } public override void Run() { try { while (!stop) { ctrl.WaitIfStalled(); if (checkPoint) { #if FEATURE_THREAD_INTERRUPT try { #endif Assert.IsTrue(sync.await()); #if FEATURE_THREAD_INTERRUPT } catch (ThreadInterruptedException /*e*/) { Console.WriteLine("[Waiter] got interrupted - wait count: " + sync.waiter.CurrentCount); //throw new ThreadInterruptedException("Thread Interrupted Exception", e); throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details) } #endif } } } catch (Exception e) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); exceptions.Add(e); } } } internal class Updater : ThreadJob { internal Synchronizer sync; internal DocumentsWriterStallControl ctrl; internal AtomicBoolean checkPoint; internal AtomicBoolean stop; internal bool release; internal IList<Exception> exceptions; public Updater(AtomicBoolean stop, AtomicBoolean checkPoint, DocumentsWriterStallControl ctrl, Synchronizer sync, bool release, IList<Exception> exceptions) : base("updater") { this.stop = stop; this.checkPoint = checkPoint; this.ctrl = ctrl; this.sync = sync; this.release = release; this.exceptions = exceptions; } public override void Run() { try { while (!stop) { int internalIters = release && Random.NextBoolean() ? AtLeast(5) : 1; for (int i = 0; i < internalIters; i++) { ctrl.UpdateStalled(Random.NextBoolean()); } if (checkPoint) { sync.updateJoin.Signal(); try { Assert.IsTrue(sync.await()); } #if FEATURE_THREAD_INTERRUPT catch (ThreadInterruptedException /*e*/) { Console.WriteLine("[Updater] got interrupted - wait count: " + sync.waiter.CurrentCount); //throw new ThreadInterruptedException("Thread Interrupted Exception", e); throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details) } #endif catch (Exception e) { Console.Write("signal failed with : " + e); throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details) } sync.leftCheckpoint.Signal(); } if (Random.NextBoolean()) { Thread.Sleep(0); } } } catch (Exception e) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); exceptions.Add(e); } if (!sync.updateJoin.IsSet) { sync.updateJoin.Signal(); } } } public static bool Terminated(ThreadJob[] threads) { foreach (ThreadJob thread in threads) { if (ThreadState.Stopped != thread.State) { return false; } } return true; } public static void Start(ThreadJob[] tostart) { foreach (ThreadJob thread in tostart) { thread.Start(); } Thread.Sleep(1); // let them start } public static void Join(ThreadJob[] toJoin) { foreach (ThreadJob thread in toJoin) { thread.Join(); } } internal static ThreadJob[] WaitThreads(int num, DocumentsWriterStallControl ctrl) { ThreadJob[] array = new ThreadJob[num]; for (int i = 0; i < array.Length; i++) { array[i] = new ThreadAnonymousInnerClassHelper2(ctrl); } return array; } private class ThreadAnonymousInnerClassHelper2 : ThreadJob { private readonly DocumentsWriterStallControl ctrl; public ThreadAnonymousInnerClassHelper2(DocumentsWriterStallControl ctrl) { this.ctrl = ctrl; } public override void Run() { ctrl.WaitIfStalled(); } } /// <summary> /// Waits for all incoming threads to be in wait() /// methods. /// </summary> public static void AwaitState(ThreadState state, params ThreadJob[] threads) { while (true) { bool done = true; foreach (ThreadJob thread in threads) { if (thread.State != state) { done = false; break; } } if (done) { return; } if (Random.NextBoolean()) { Thread.Sleep(0); } else { Thread.Sleep(1); } } } public sealed class Synchronizer { internal volatile CountdownEvent waiter; internal volatile CountdownEvent updateJoin; internal volatile CountdownEvent leftCheckpoint; public Synchronizer(int numUpdater, int numThreads) { Reset(numUpdater, numThreads); } public void Reset(int numUpdaters, int numThreads) { this.waiter = new CountdownEvent(1); this.updateJoin = new CountdownEvent(numUpdaters); this.leftCheckpoint = new CountdownEvent(numUpdaters); } public bool @await() { return waiter.Wait(new TimeSpan(0, 0, 0, 10)); } } } }
// 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: A collection of methods for manipulating Files. ** ** April 09,2000 (some design refactorization) ** ===========================================================*/ using System; using System.Security.Permissions; using PermissionSet = System.Security.PermissionSet; using Win32Native = Microsoft.Win32.Win32Native; using System.Runtime.InteropServices; using System.Security; #if FEATURE_MACL using System.Security.AccessControl; #endif using System.Text; using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.Globalization; using System.Runtime.Versioning; using System.Diagnostics.Contracts; namespace System.IO { // Class for creating FileStream objects, and some basic file management // routines such as Delete, etc. [ComVisible(true)] public static class File { internal const int GENERIC_READ = unchecked((int)0x80000000); private const int GENERIC_WRITE = unchecked((int)0x40000000); private const int FILE_SHARE_WRITE = 0x00000002; private const int FILE_SHARE_DELETE = 0x00000004; private const int GetFileExInfoStandard = 0; public static StreamReader OpenText(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.EndContractBlock(); return new StreamReader(path); } public static StreamWriter CreateText(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.EndContractBlock(); return new StreamWriter(path,false); } public static StreamWriter AppendText(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.EndContractBlock(); return new StreamWriter(path,true); } // Copies an existing file to a new file. An exception is raised if the // destination file already exists. Use the // Copy(String, String, boolean) method to allow // overwriting an existing file. // // The caller must have certain FileIOPermissions. The caller must have // Read permission to sourceFileName and Create // and Write permissions to destFileName. // public static void Copy(String sourceFileName, String destFileName) { if (sourceFileName == null) throw new ArgumentNullException("sourceFileName", Environment.GetResourceString("ArgumentNull_FileName")); if (destFileName == null) throw new ArgumentNullException("destFileName", Environment.GetResourceString("ArgumentNull_FileName")); if (sourceFileName.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "sourceFileName"); if (destFileName.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName"); Contract.EndContractBlock(); InternalCopy(sourceFileName, destFileName, false, true); } // Copies an existing file to a new file. If overwrite is // false, then an IOException is thrown if the destination file // already exists. If overwrite is true, the file is // overwritten. // // The caller must have certain FileIOPermissions. The caller must have // Read permission to sourceFileName // and Write permissions to destFileName. // public static void Copy(String sourceFileName, String destFileName, bool overwrite) { if (sourceFileName == null) throw new ArgumentNullException("sourceFileName", Environment.GetResourceString("ArgumentNull_FileName")); if (destFileName == null) throw new ArgumentNullException("destFileName", Environment.GetResourceString("ArgumentNull_FileName")); if (sourceFileName.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "sourceFileName"); if (destFileName.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName"); Contract.EndContractBlock(); InternalCopy(sourceFileName, destFileName, overwrite, true); } [System.Security.SecurityCritical] internal static void UnsafeCopy(String sourceFileName, String destFileName, bool overwrite) { if (sourceFileName == null) throw new ArgumentNullException("sourceFileName", Environment.GetResourceString("ArgumentNull_FileName")); if (destFileName == null) throw new ArgumentNullException("destFileName", Environment.GetResourceString("ArgumentNull_FileName")); if (sourceFileName.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "sourceFileName"); if (destFileName.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName"); Contract.EndContractBlock(); InternalCopy(sourceFileName, destFileName, overwrite, false); } /// <devdoc> /// Note: This returns the fully qualified name of the destination file. /// </devdoc> [System.Security.SecuritySafeCritical] internal static String InternalCopy(String sourceFileName, String destFileName, bool overwrite, bool checkHost) { Contract.Requires(sourceFileName != null); Contract.Requires(destFileName != null); Contract.Requires(sourceFileName.Length > 0); Contract.Requires(destFileName.Length > 0); String fullSourceFileName = Path.GetFullPathInternal(sourceFileName); String fullDestFileName = Path.GetFullPathInternal(destFileName); #if FEATURE_CORECLR if (checkHost) { FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read, sourceFileName, fullSourceFileName); FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destFileName, fullDestFileName); sourceState.EnsureState(); destState.EnsureState(); } #else FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullSourceFileName, false, false); FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullDestFileName, false, false); #endif bool r = Win32Native.CopyFile(fullSourceFileName, fullDestFileName, !overwrite); if (!r) { // Save Win32 error because subsequent checks will overwrite this HRESULT. int errorCode = Marshal.GetLastWin32Error(); String fileName = destFileName; if (errorCode != Win32Native.ERROR_FILE_EXISTS) { #if !FEATURE_CORECLR // For a number of error codes (sharing violation, path // not found, etc) we don't know if the problem was with // the source or dest file. Try reading the source file. using(SafeFileHandle handle = Win32Native.UnsafeCreateFile(fullSourceFileName, GENERIC_READ, FileShare.Read, null, FileMode.Open, 0, IntPtr.Zero)) { if (handle.IsInvalid) fileName = sourceFileName; } #endif // !FEATURE_CORECLR if (errorCode == Win32Native.ERROR_ACCESS_DENIED) { if (Directory.InternalExists(fullDestFileName)) throw new IOException(Environment.GetResourceString("Arg_FileIsDirectory_Name", destFileName), Win32Native.ERROR_ACCESS_DENIED, fullDestFileName); } } __Error.WinIOError(errorCode, fileName); } return fullDestFileName; } // Creates a file in a particular path. If the file exists, it is replaced. // The file is opened with ReadWrite accessand cannot be opened by another // application until it has been closed. An IOException is thrown if the // directory specified doesn't exist. // // Your application must have Create, Read, and Write permissions to // the file. // public static FileStream Create(String path) { return Create(path, FileStream.DefaultBufferSize); } // Creates a file in a particular path. If the file exists, it is replaced. // The file is opened with ReadWrite access and cannot be opened by another // application until it has been closed. An IOException is thrown if the // directory specified doesn't exist. // // Your application must have Create, Read, and Write permissions to // the file. // public static FileStream Create(String path, int bufferSize) { return new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize); } public static FileStream Create(String path, int bufferSize, FileOptions options) { return new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, options); } #if FEATURE_MACL public static FileStream Create(String path, int bufferSize, FileOptions options, FileSecurity fileSecurity) { return new FileStream(path, FileMode.Create, FileSystemRights.Read | FileSystemRights.Write, FileShare.None, bufferSize, options, fileSecurity); } #endif // Deletes a file. The file specified by the designated path is deleted. // If the file does not exist, Delete succeeds without throwing // an exception. // // On NT, Delete will fail for a file that is open for normal I/O // or a file that is memory mapped. // // Your application must have Delete permission to the target file. // [System.Security.SecuritySafeCritical] public static void Delete(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.EndContractBlock(); InternalDelete(path, true); } [System.Security.SecurityCritical] internal static void UnsafeDelete(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.EndContractBlock(); InternalDelete(path, false); } [System.Security.SecurityCritical] internal static void InternalDelete(String path, bool checkHost) { String fullPath = Path.GetFullPathInternal(path); #if FEATURE_CORECLR if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, path, fullPath); state.EnsureState(); } #else // For security check, path should be resolved to an absolute path. FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullPath, false, false); #endif bool r = Win32Native.DeleteFile(fullPath); if (!r) { int hr = Marshal.GetLastWin32Error(); if (hr==Win32Native.ERROR_FILE_NOT_FOUND) return; else __Error.WinIOError(hr, fullPath); } } [System.Security.SecuritySafeCritical] // auto-generated public static void Decrypt(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.EndContractBlock(); String fullPath = Path.GetFullPathInternal(path); FileIOPermission.QuickDemand(FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, fullPath, false, false); bool r = Win32Native.DecryptFile(fullPath, 0); if (!r) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Win32Native.ERROR_ACCESS_DENIED) { // Check to see if the file system is not NTFS. If so, // throw a different exception. DriveInfo di = new DriveInfo(Path.GetPathRoot(fullPath)); if (!String.Equals("NTFS", di.DriveFormat)) throw new NotSupportedException(Environment.GetResourceString("NotSupported_EncryptionNeedsNTFS")); } __Error.WinIOError(errorCode, fullPath); } } [System.Security.SecuritySafeCritical] // auto-generated public static void Encrypt(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.EndContractBlock(); String fullPath = Path.GetFullPathInternal(path); FileIOPermission.QuickDemand(FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, fullPath, false, false); bool r = Win32Native.EncryptFile(fullPath); if (!r) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Win32Native.ERROR_ACCESS_DENIED) { // Check to see if the file system is not NTFS. If so, // throw a different exception. DriveInfo di = new DriveInfo(Path.GetPathRoot(fullPath)); if (!String.Equals("NTFS", di.DriveFormat)) throw new NotSupportedException(Environment.GetResourceString("NotSupported_EncryptionNeedsNTFS")); } __Error.WinIOError(errorCode, fullPath); } } // Tests if a file exists. The result is true if the file // given by the specified path exists; otherwise, the result is // false. Note that if path describes a directory, // Exists will return true. // // Your application must have Read permission for the target directory. // [System.Security.SecuritySafeCritical] public static bool Exists(String path) { return InternalExistsHelper(path, true); } [System.Security.SecurityCritical] internal static bool UnsafeExists(String path) { return InternalExistsHelper(path, false); } [System.Security.SecurityCritical] private static bool InternalExistsHelper(String path, bool checkHost) { try { if (path == null) return false; if (path.Length == 0) return false; path = Path.GetFullPathInternal(path); // After normalizing, check whether path ends in directory separator. // Otherwise, FillAttributeInfo removes it and we may return a false positive. // GetFullPathInternal should never return null Contract.Assert(path != null, "File.Exists: GetFullPathInternal returned null"); if (path.Length > 0 && Path.IsDirectorySeparator(path[path.Length - 1])) { return false; } #if FEATURE_CORECLR if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, path); state.EnsureState(); } #else FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, path, false, false); #endif return InternalExists(path); } catch (ArgumentException) { } catch (NotSupportedException) { } // Security can throw this on ":" catch (SecurityException) { } catch (IOException) { } catch (UnauthorizedAccessException) { } return false; } [System.Security.SecurityCritical] // auto-generated internal static bool InternalExists(String path) { Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA(); int dataInitialised = FillAttributeInfo(path, ref data, false, true); return (dataInitialised == 0) && (data.fileAttributes != -1) && ((data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) == 0); } public static FileStream Open(String path, FileMode mode) { return Open(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None); } public static FileStream Open(String path, FileMode mode, FileAccess access) { return Open(path,mode, access, FileShare.None); } public static FileStream Open(String path, FileMode mode, FileAccess access, FileShare share) { return new FileStream(path, mode, access, share); } #if !FEATURE_CORECLR public static void SetCreationTime(String path, DateTime creationTime) { SetCreationTimeUtc(path, creationTime.ToUniversalTime()); } [System.Security.SecuritySafeCritical] // auto-generated public unsafe static void SetCreationTimeUtc(String path, DateTime creationTimeUtc) { SafeFileHandle handle; using(OpenFile(path, FileAccess.Write, out handle)) { Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(creationTimeUtc.ToFileTimeUtc()); bool r = Win32Native.SetFileTime(handle, &fileTime, null, null); if (!r) { int errorCode = Marshal.GetLastWin32Error(); __Error.WinIOError(errorCode, path); } } } #endif // !FEATURE_CORECLR [System.Security.SecuritySafeCritical] public static DateTime GetCreationTime(String path) { return InternalGetCreationTimeUtc(path, true).ToLocalTime(); } [System.Security.SecuritySafeCritical] // auto-generated public static DateTime GetCreationTimeUtc(String path) { return InternalGetCreationTimeUtc(path, false); // this API isn't exposed in Silverlight } [System.Security.SecurityCritical] private static DateTime InternalGetCreationTimeUtc(String path, bool checkHost) { String fullPath = Path.GetFullPathInternal(path); #if FEATURE_CORECLR if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath); state.EnsureState(); } #else FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false); #endif Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA(); int dataInitialised = FillAttributeInfo(fullPath, ref data, false, false); if (dataInitialised != 0) __Error.WinIOError(dataInitialised, fullPath); long dt = ((long)(data.ftCreationTimeHigh) << 32) | ((long)data.ftCreationTimeLow); return DateTime.FromFileTimeUtc(dt); } #if !FEATURE_CORECLR public static void SetLastAccessTime(String path, DateTime lastAccessTime) { SetLastAccessTimeUtc(path, lastAccessTime.ToUniversalTime()); } [System.Security.SecuritySafeCritical] // auto-generated public unsafe static void SetLastAccessTimeUtc(String path, DateTime lastAccessTimeUtc) { SafeFileHandle handle; using(OpenFile(path, FileAccess.Write, out handle)) { Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(lastAccessTimeUtc.ToFileTimeUtc()); bool r = Win32Native.SetFileTime(handle, null, &fileTime, null); if (!r) { int errorCode = Marshal.GetLastWin32Error(); __Error.WinIOError(errorCode, path); } } } #endif // FEATURE_CORECLR [System.Security.SecuritySafeCritical] public static DateTime GetLastAccessTime(String path) { return InternalGetLastAccessTimeUtc(path, true).ToLocalTime(); } [System.Security.SecuritySafeCritical] // auto-generated public static DateTime GetLastAccessTimeUtc(String path) { return InternalGetLastAccessTimeUtc(path, false); // this API isn't exposed in Silverlight } [System.Security.SecurityCritical] private static DateTime InternalGetLastAccessTimeUtc(String path, bool checkHost) { String fullPath = Path.GetFullPathInternal(path); #if FEATURE_CORECLR if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath); state.EnsureState(); } #else FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false); #endif Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA(); int dataInitialised = FillAttributeInfo(fullPath, ref data, false, false); if (dataInitialised != 0) __Error.WinIOError(dataInitialised, fullPath); long dt = ((long)(data.ftLastAccessTimeHigh) << 32) | ((long)data.ftLastAccessTimeLow); return DateTime.FromFileTimeUtc(dt); } #if !FEATURE_CORECLR public static void SetLastWriteTime(String path, DateTime lastWriteTime) { SetLastWriteTimeUtc(path, lastWriteTime.ToUniversalTime()); } [System.Security.SecuritySafeCritical] // auto-generated public unsafe static void SetLastWriteTimeUtc(String path, DateTime lastWriteTimeUtc) { SafeFileHandle handle; using(OpenFile(path, FileAccess.Write, out handle)) { Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(lastWriteTimeUtc.ToFileTimeUtc()); bool r = Win32Native.SetFileTime(handle, null, null, &fileTime); if (!r) { int errorCode = Marshal.GetLastWin32Error(); __Error.WinIOError(errorCode, path); } } } #endif // !FEATURE_CORECLR [System.Security.SecuritySafeCritical] public static DateTime GetLastWriteTime(String path) { return InternalGetLastWriteTimeUtc(path, true).ToLocalTime(); } [System.Security.SecuritySafeCritical] // auto-generated public static DateTime GetLastWriteTimeUtc(String path) { return InternalGetLastWriteTimeUtc(path, false); // this API isn't exposed in Silverlight } [System.Security.SecurityCritical] private static DateTime InternalGetLastWriteTimeUtc(String path, bool checkHost) { String fullPath = Path.GetFullPathInternal(path); #if FEATURE_CORECLR if (checkHost) { FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath); state.EnsureState(); } #else FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false); #endif Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA(); int dataInitialised = FillAttributeInfo(fullPath, ref data, false, false); if (dataInitialised != 0) __Error.WinIOError(dataInitialised, fullPath); long dt = ((long)data.ftLastWriteTimeHigh << 32) | ((long)data.ftLastWriteTimeLow); return DateTime.FromFileTimeUtc(dt); } [System.Security.SecuritySafeCritical] public static FileAttributes GetAttributes(String path) { String fullPath = Path.GetFullPathInternal(path); #if FEATURE_CORECLR FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath); state.EnsureState(); #else FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false); #endif Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA(); int dataInitialised = FillAttributeInfo(fullPath, ref data, false, true); if (dataInitialised != 0) __Error.WinIOError(dataInitialised, fullPath); return (FileAttributes) data.fileAttributes; } #if FEATURE_CORECLR [System.Security.SecurityCritical] #else [System.Security.SecuritySafeCritical] #endif public static void SetAttributes(String path, FileAttributes fileAttributes) { String fullPath = Path.GetFullPathInternal(path); #if !FEATURE_CORECLR FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullPath, false, false); #endif bool r = Win32Native.SetFileAttributes(fullPath, (int) fileAttributes); if (!r) { int hr = Marshal.GetLastWin32Error(); if (hr==ERROR_INVALID_PARAMETER) throw new ArgumentException(Environment.GetResourceString("Arg_InvalidFileAttrs")); __Error.WinIOError(hr, fullPath); } } #if FEATURE_MACL public static FileSecurity GetAccessControl(String path) { return GetAccessControl(path, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group); } public static FileSecurity GetAccessControl(String path, AccessControlSections includeSections) { // Appropriate security check should be done for us by FileSecurity. return new FileSecurity(path, includeSections); } [System.Security.SecuritySafeCritical] // auto-generated public static void SetAccessControl(String path, FileSecurity fileSecurity) { if (fileSecurity == null) throw new ArgumentNullException("fileSecurity"); Contract.EndContractBlock(); String fullPath = Path.GetFullPathInternal(path); // Appropriate security check should be done for us by FileSecurity. fileSecurity.Persist(fullPath); } #endif public static FileStream OpenRead(String path) { return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); } public static FileStream OpenWrite(String path) { return new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); } [System.Security.SecuritySafeCritical] // auto-generated public static String ReadAllText(String path) { if (path == null) throw new ArgumentNullException("path"); if (path.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath")); Contract.EndContractBlock(); return InternalReadAllText(path, Encoding.UTF8, true); } [System.Security.SecuritySafeCritical] // auto-generated public static String ReadAllText(String path, Encoding encoding) { if (path == null) throw new ArgumentNullException("path"); if (encoding == null) throw new ArgumentNullException("encoding"); if (path.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath")); Contract.EndContractBlock(); return InternalReadAllText(path, encoding, true); } [System.Security.SecurityCritical] internal static String UnsafeReadAllText(String path) { if (path == null) throw new ArgumentNullException("path"); if (path.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath")); Contract.EndContractBlock(); return InternalReadAllText(path, Encoding.UTF8, false); } [System.Security.SecurityCritical] private static String InternalReadAllText(String path, Encoding encoding, bool checkHost) { Contract.Requires(path != null); Contract.Requires(encoding != null); Contract.Requires(path.Length > 0); using (StreamReader sr = new StreamReader(path, encoding, true, StreamReader.DefaultBufferSize, checkHost)) return sr.ReadToEnd(); } [System.Security.SecuritySafeCritical] // auto-generated public static void WriteAllText(String path, String contents) { if (path == null) throw new ArgumentNullException("path"); if (path.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath")); Contract.EndContractBlock(); InternalWriteAllText(path, contents, StreamWriter.UTF8NoBOM, true); } [System.Security.SecuritySafeCritical] // auto-generated public static void WriteAllText(String path, String contents, Encoding encoding) { if (path == null) throw new ArgumentNullException("path"); if (encoding == null) throw new ArgumentNullException("encoding"); if (path.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath")); Contract.EndContractBlock(); InternalWriteAllText(path, contents, encoding, true); } [System.Security.SecurityCritical] internal static void UnsafeWriteAllText(String path, String contents) { if (path == null) throw new ArgumentNullException("path"); if (path.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath")); Contract.EndContractBlock(); InternalWriteAllText(path, contents, StreamWriter.UTF8NoBOM, false); } [System.Security.SecurityCritical] private static void InternalWriteAllText(String path, String contents, Encoding encoding, bool checkHost) { Contract.Requires(path != null); Contract.Requires(encoding != null); Contract.Requires(path.Length > 0); using (StreamWriter sw = new StreamWriter(path, false, encoding, StreamWriter.DefaultBufferSize, checkHost)) sw.Write(contents); } [System.Security.SecuritySafeCritical] // auto-generated public static byte[] ReadAllBytes(String path) { return InternalReadAllBytes(path, true); } [System.Security.SecurityCritical] internal static byte[] UnsafeReadAllBytes(String path) { return InternalReadAllBytes(path, false); } [System.Security.SecurityCritical] private static byte[] InternalReadAllBytes(String path, bool checkHost) { byte[] bytes; using(FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, FileStream.DefaultBufferSize, FileOptions.None, Path.GetFileName(path), false, false, checkHost)) { // Do a blocking read int index = 0; long fileLength = fs.Length; if (fileLength > Int32.MaxValue) throw new IOException(Environment.GetResourceString("IO.IO_FileTooLong2GB")); int count = (int) fileLength; bytes = new byte[count]; while(count > 0) { int n = fs.Read(bytes, index, count); if (n == 0) __Error.EndOfFile(); index += n; count -= n; } } return bytes; } [System.Security.SecuritySafeCritical] // auto-generated public static void WriteAllBytes(String path, byte[] bytes) { if (path == null) throw new ArgumentNullException("path", Environment.GetResourceString("ArgumentNull_Path")); if (path.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath")); if (bytes == null) throw new ArgumentNullException("bytes"); Contract.EndContractBlock(); InternalWriteAllBytes(path, bytes, true); } [System.Security.SecurityCritical] internal static void UnsafeWriteAllBytes(String path, byte[] bytes) { if (path == null) throw new ArgumentNullException("path", Environment.GetResourceString("ArgumentNull_Path")); if (path.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath")); if (bytes == null) throw new ArgumentNullException("bytes"); Contract.EndContractBlock(); InternalWriteAllBytes(path, bytes, false); } [System.Security.SecurityCritical] private static void InternalWriteAllBytes(String path, byte[] bytes, bool checkHost) { Contract.Requires(path != null); Contract.Requires(path.Length != 0); Contract.Requires(bytes != null); using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, FileStream.DefaultBufferSize, FileOptions.None, Path.GetFileName(path), false, false, checkHost)) { fs.Write(bytes, 0, bytes.Length); } } public static String[] ReadAllLines(String path) { if (path == null) throw new ArgumentNullException("path"); if (path.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath")); Contract.EndContractBlock(); return InternalReadAllLines(path, Encoding.UTF8); } public static String[] ReadAllLines(String path, Encoding encoding) { if (path == null) throw new ArgumentNullException("path"); if (encoding == null) throw new ArgumentNullException("encoding"); if (path.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath")); Contract.EndContractBlock(); return InternalReadAllLines(path, encoding); } private static String[] InternalReadAllLines(String path, Encoding encoding) { Contract.Requires(path != null); Contract.Requires(encoding != null); Contract.Requires(path.Length != 0); String line; List<String> lines = new List<String>(); using (StreamReader sr = new StreamReader(path, encoding)) while ((line = sr.ReadLine()) != null) lines.Add(line); return lines.ToArray(); } public static IEnumerable<String> ReadLines(String path) { if (path == null) throw new ArgumentNullException("path"); if (path.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"), "path"); Contract.EndContractBlock(); return ReadLinesIterator.CreateIterator(path, Encoding.UTF8); } public static IEnumerable<String> ReadLines(String path, Encoding encoding) { if (path == null) throw new ArgumentNullException("path"); if (encoding == null) throw new ArgumentNullException("encoding"); if (path.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"), "path"); Contract.EndContractBlock(); return ReadLinesIterator.CreateIterator(path, encoding); } public static void WriteAllLines(String path, String[] contents) { if (path == null) throw new ArgumentNullException("path"); if (contents == null) throw new ArgumentNullException("contents"); if (path.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath")); Contract.EndContractBlock(); InternalWriteAllLines(new StreamWriter(path, false, StreamWriter.UTF8NoBOM), contents); } public static void WriteAllLines(String path, String[] contents, Encoding encoding) { if (path == null) throw new ArgumentNullException("path"); if (contents == null) throw new ArgumentNullException("contents"); if (encoding == null) throw new ArgumentNullException("encoding"); if (path.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath")); Contract.EndContractBlock(); InternalWriteAllLines(new StreamWriter(path, false, encoding), contents); } public static void WriteAllLines(String path, IEnumerable<String> contents) { if (path == null) throw new ArgumentNullException("path"); if (contents == null) throw new ArgumentNullException("contents"); if (path.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath")); Contract.EndContractBlock(); InternalWriteAllLines(new StreamWriter(path, false, StreamWriter.UTF8NoBOM), contents); } public static void WriteAllLines(String path, IEnumerable<String> contents, Encoding encoding) { if (path == null) throw new ArgumentNullException("path"); if (contents == null) throw new ArgumentNullException("contents"); if (encoding == null) throw new ArgumentNullException("encoding"); if (path.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath")); Contract.EndContractBlock(); InternalWriteAllLines(new StreamWriter(path, false, encoding), contents); } private static void InternalWriteAllLines(TextWriter writer, IEnumerable<String> contents) { Contract.Requires(writer != null); Contract.Requires(contents != null); using (writer) { foreach (String line in contents) { writer.WriteLine(line); } } } public static void AppendAllText(String path, String contents) { if (path == null) throw new ArgumentNullException("path"); if (path.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath")); Contract.EndContractBlock(); InternalAppendAllText(path, contents, StreamWriter.UTF8NoBOM); } public static void AppendAllText(String path, String contents, Encoding encoding) { if (path == null) throw new ArgumentNullException("path"); if (encoding == null) throw new ArgumentNullException("encoding"); if (path.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath")); Contract.EndContractBlock(); InternalAppendAllText(path, contents, encoding); } private static void InternalAppendAllText(String path, String contents, Encoding encoding) { Contract.Requires(path != null); Contract.Requires(encoding != null); Contract.Requires(path.Length > 0); using (StreamWriter sw = new StreamWriter(path, true, encoding)) sw.Write(contents); } public static void AppendAllLines(String path, IEnumerable<String> contents) { if (path == null) throw new ArgumentNullException("path"); if (contents == null) throw new ArgumentNullException("contents"); if (path.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath")); Contract.EndContractBlock(); InternalWriteAllLines(new StreamWriter(path, true, StreamWriter.UTF8NoBOM), contents); } public static void AppendAllLines(String path, IEnumerable<String> contents, Encoding encoding) { if (path == null) throw new ArgumentNullException("path"); if (contents == null) throw new ArgumentNullException("contents"); if (encoding == null) throw new ArgumentNullException("encoding"); if (path.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath")); Contract.EndContractBlock(); InternalWriteAllLines(new StreamWriter(path, true, encoding), contents); } // Moves a specified file to a new location and potentially a new file name. // This method does work across volumes. // // The caller must have certain FileIOPermissions. The caller must // have Read and Write permission to // sourceFileName and Write // permissions to destFileName. // [System.Security.SecuritySafeCritical] public static void Move(String sourceFileName, String destFileName) { InternalMove(sourceFileName, destFileName, true); } [System.Security.SecurityCritical] internal static void UnsafeMove(String sourceFileName, String destFileName) { InternalMove(sourceFileName, destFileName, false); } [System.Security.SecurityCritical] private static void InternalMove(String sourceFileName, String destFileName, bool checkHost) { if (sourceFileName == null) throw new ArgumentNullException("sourceFileName", Environment.GetResourceString("ArgumentNull_FileName")); if (destFileName == null) throw new ArgumentNullException("destFileName", Environment.GetResourceString("ArgumentNull_FileName")); if (sourceFileName.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "sourceFileName"); if (destFileName.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName"); Contract.EndContractBlock(); String fullSourceFileName = Path.GetFullPathInternal(sourceFileName); String fullDestFileName = Path.GetFullPathInternal(destFileName); #if FEATURE_CORECLR if (checkHost) { FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, sourceFileName, fullSourceFileName); FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destFileName, fullDestFileName); sourceState.EnsureState(); destState.EnsureState(); } #else FileIOPermission.QuickDemand(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, fullSourceFileName, false, false); FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullDestFileName, false, false); #endif if (!InternalExists(fullSourceFileName)) __Error.WinIOError(Win32Native.ERROR_FILE_NOT_FOUND, fullSourceFileName); if (!Win32Native.MoveFile(fullSourceFileName, fullDestFileName)) { __Error.WinIOError(); } } public static void Replace(String sourceFileName, String destinationFileName, String destinationBackupFileName) { if (sourceFileName == null) throw new ArgumentNullException("sourceFileName"); if (destinationFileName == null) throw new ArgumentNullException("destinationFileName"); Contract.EndContractBlock(); InternalReplace(sourceFileName, destinationFileName, destinationBackupFileName, false); } public static void Replace(String sourceFileName, String destinationFileName, String destinationBackupFileName, bool ignoreMetadataErrors) { if (sourceFileName == null) throw new ArgumentNullException("sourceFileName"); if (destinationFileName == null) throw new ArgumentNullException("destinationFileName"); Contract.EndContractBlock(); InternalReplace(sourceFileName, destinationFileName, destinationBackupFileName, ignoreMetadataErrors); } [System.Security.SecuritySafeCritical] private static void InternalReplace(String sourceFileName, String destinationFileName, String destinationBackupFileName, bool ignoreMetadataErrors) { Contract.Requires(sourceFileName != null); Contract.Requires(destinationFileName != null); // Write permission to all three files, read permission to source // and dest. String fullSrcPath = Path.GetFullPathInternal(sourceFileName); String fullDestPath = Path.GetFullPathInternal(destinationFileName); String fullBackupPath = null; if (destinationBackupFileName != null) fullBackupPath = Path.GetFullPathInternal(destinationBackupFileName); #if FEATURE_CORECLR FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read | FileSecurityStateAccess.Write, sourceFileName, fullSrcPath); FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Read | FileSecurityStateAccess.Write, destinationFileName, fullDestPath); FileSecurityState backupState = new FileSecurityState(FileSecurityStateAccess.Read | FileSecurityStateAccess.Write, destinationBackupFileName, fullBackupPath); sourceState.EnsureState(); destState.EnsureState(); backupState.EnsureState(); #else FileIOPermission perm = new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, new String[] { fullSrcPath, fullDestPath}); if (destinationBackupFileName != null) perm.AddPathList(FileIOPermissionAccess.Write, fullBackupPath); perm.Demand(); #endif int flags = Win32Native.REPLACEFILE_WRITE_THROUGH; if (ignoreMetadataErrors) flags |= Win32Native.REPLACEFILE_IGNORE_MERGE_ERRORS; bool r = Win32Native.ReplaceFile(fullDestPath, fullSrcPath, fullBackupPath, flags, IntPtr.Zero, IntPtr.Zero); if (!r) __Error.WinIOError(); } // Returns 0 on success, otherwise a Win32 error code. Note that // classes should use -1 as the uninitialized state for dataInitialized. [System.Security.SecurityCritical] // auto-generated internal static int FillAttributeInfo(String path, ref Win32Native.WIN32_FILE_ATTRIBUTE_DATA data, bool tryagain, bool returnErrorOnNotFound) { int dataInitialised = 0; if (tryagain) // someone has a handle to the file open, or other error { Win32Native.WIN32_FIND_DATA findData; findData = new Win32Native.WIN32_FIND_DATA (); // Remove trialing slash since this can cause grief to FindFirstFile. You will get an invalid argument error String tempPath = path.TrimEnd(new char [] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar}); // For floppy drives, normally the OS will pop up a dialog saying // there is no disk in drive A:, please insert one. We don't want that. // SetErrorMode will let us disable this, but we should set the error // mode back, since this may have wide-ranging effects. int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS); try { bool error = false; SafeFindHandle handle = Win32Native.FindFirstFile(tempPath,findData); try { if (handle.IsInvalid) { error = true; dataInitialised = Marshal.GetLastWin32Error(); if (dataInitialised == Win32Native.ERROR_FILE_NOT_FOUND || dataInitialised == Win32Native.ERROR_PATH_NOT_FOUND || dataInitialised == Win32Native.ERROR_NOT_READY) // floppy device not ready { if (!returnErrorOnNotFound) { // Return default value for backward compatibility dataInitialised = 0; data.fileAttributes = -1; } } return dataInitialised; } } finally { // Close the Win32 handle try { handle.Close(); } catch { // if we're already returning an error, don't throw another one. if (!error) { Contract.Assert(false, "File::FillAttributeInfo - FindClose failed!"); __Error.WinIOError(); } } } } finally { Win32Native.SetErrorMode(oldMode); } // Copy the information to data data.PopulateFrom(findData); } else { // For floppy drives, normally the OS will pop up a dialog saying // there is no disk in drive A:, please insert one. We don't want that. // SetErrorMode will let us disable this, but we should set the error // mode back, since this may have wide-ranging effects. bool success = false; int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS); try { success = Win32Native.GetFileAttributesEx(path, GetFileExInfoStandard, ref data); } finally { Win32Native.SetErrorMode(oldMode); } if (!success) { dataInitialised = Marshal.GetLastWin32Error(); if (dataInitialised != Win32Native.ERROR_FILE_NOT_FOUND && dataInitialised != Win32Native.ERROR_PATH_NOT_FOUND && dataInitialised != Win32Native.ERROR_NOT_READY) // floppy device not ready { // In case someone latched onto the file. Take the perf hit only for failure return FillAttributeInfo(path, ref data, true, returnErrorOnNotFound); } else { if (!returnErrorOnNotFound) { // Return default value for backward compbatibility dataInitialised = 0; data.fileAttributes = -1; } } } } return dataInitialised; } #if !FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated private static FileStream OpenFile(String path, FileAccess access, out SafeFileHandle handle) { FileStream fs = new FileStream(path, FileMode.Open, access, FileShare.ReadWrite, 1); handle = fs.SafeFileHandle; if (handle.IsInvalid) { // Return a meaningful error, using the RELATIVE path to // the file to avoid returning extra information to the caller. // NT5 oddity - when trying to open "C:\" as a FileStream, // we usually get ERROR_PATH_NOT_FOUND from the OS. We should // probably be consistent w/ every other directory. int hr = Marshal.GetLastWin32Error(); String FullPath = Path.GetFullPathInternal(path); if (hr==__Error.ERROR_PATH_NOT_FOUND && FullPath.Equals(Directory.GetDirectoryRoot(FullPath))) hr = __Error.ERROR_ACCESS_DENIED; __Error.WinIOError(hr, path); } return fs; } #endif // !FEATURE_CORECLR // Defined in WinError.h private const int ERROR_INVALID_PARAMETER = 87; private const int ERROR_ACCESS_DENIED = 0x5; } }
#region Copyright (c) 2004 Ian Davis and James Carlyle /*------------------------------------------------------------------------------ COPYRIGHT AND PERMISSION NOTICE Copyright (c) 2004 Ian Davis and James Carlyle Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------*/ #endregion using MySql.Data.MySqlClient; namespace SemPlan.Spiral.MySql { using SemPlan.Spiral.Core; using SemPlan.Spiral.Utility; using System; using System.Collections; using System.IO; using System.Data; using System.Configuration; using System.Text; public class DatabaseTripleStore : TripleStore, ICloneable { private StatementHandler itsStatementHandler; protected MySqlConnection itsConn; public bool trace = false; private int itsHashCode; private bool itsVerbose; private MySqlCommand itsAddStatementCommand; private BatchedWriteStrategy itsWriteStrategy; public DatabaseTripleStore() : this( "urn:uuid:" + Guid.NewGuid().ToString() ) { } public DatabaseTripleStore(string graphUri) { itsHashCode = graphUri.GetHashCode(); itsStatementHandler = new StatementHandler(Add); //~ string connectionString = String.Format("server={0};user id={1}; password={2}; database={3}; pooling=true", //~ ConfigurationSettings.AppSettings["server"], //~ ConfigurationSettings.AppSettings["uid"], //~ ConfigurationSettings.AppSettings["pwd"], //~ ConfigurationSettings.AppSettings["database"]); string connectionString = ConfigurationSettings.AppSettings["connectionString"]; //~ string connectionString = String.Format("Server={0};Uid={1};Pwd={2};Database={3}; pooling=true; resetpooledconnections=false", //~ ConfigurationSettings.AppSettings["server"], //~ ConfigurationSettings.AppSettings["uid"], //~ ConfigurationSettings.AppSettings["pwd"], //~ ConfigurationSettings.AppSettings["database"]); itsConn = new MySqlConnection(connectionString); itsConn.Open(); PrepareStatements(); EnsureGraphExistsInDb(); itsWriteStrategy = new BatchedWriteStrategy(this); itsWriteStrategy.Connection = itsConn; } ~DatabaseTripleStore() { Dispose(); } public void Dispose() { try { //Clear(); if ( null != itsConn ) { itsConn.Close(); itsConn = null; } } finally { } } private void PrepareStatements() { itsAddStatementCommand = new MySqlCommand(); itsAddStatementCommand.Connection = itsConn; itsAddStatementCommand.CommandText = "INSERT IGNORE INTO Statements (subjectHash, predicateHash, objectHash, graphId) VALUES ( ?subj, ?pred, ?obj, ?graph);"; itsAddStatementCommand.Prepare(); itsAddStatementCommand.Parameters.Add("?subj", MySqlDbType.Int32); itsAddStatementCommand.Parameters.Add("?pred", MySqlDbType.Int32); itsAddStatementCommand.Parameters.Add("?obj", MySqlDbType.Int32); itsAddStatementCommand.Parameters.Add("?graph", MySqlDbType.Int32); } public override int GetHashCode() { return itsHashCode; } public bool IsAvailable { get { return (itsConn.State == ConnectionState.Open); } } internal MySqlConnection Connection { get { return itsConn; } } public int WriteCacheSize { get { return itsWriteStrategy.WriteCacheSize; } set { itsWriteStrategy.WriteCacheSize = value; } } public int NodeCount { get { MySqlCommand cmd = new MySqlCommand("SELECT COUNT(*) FROM ResourceNodes WHERE graphId = " + itsHashCode, itsConn); return Convert.ToInt32(cmd.ExecuteScalar()); } } public int ResourceCount { get { MySqlCommand cmd = new MySqlCommand("SELECT COUNT(*) FROM Resources WHERE graphId = " + itsHashCode, itsConn); return Convert.ToInt32(cmd.ExecuteScalar()); } } public ResourceMap ResourceMap{ get { return this; } } public bool Verbose { get { return itsVerbose; } set { itsVerbose = value; itsWriteStrategy.Verbose = value; } } public void Clear() { MySqlCommand cmd = new MySqlCommand("DELETE FROM Statements WHERE graphId = " + itsHashCode, itsConn); cmd.ExecuteNonQuery(); cmd.CommandText = "DELETE FROM ResourceNodes WHERE graphId = " + itsHashCode; cmd.ExecuteNonQuery(); cmd.CommandText = "DELETE FROM Resources WHERE graphId = " + itsHashCode; cmd.ExecuteNonQuery(); cmd.CommandText = "DELETE FROM Graphs WHERE graphId = " + itsHashCode; cmd.ExecuteNonQuery(); } private void EnsureGraphExistsInDb() { MySqlCommand cmd = new MySqlCommand("INSERT IGNORE INTO Graphs (graphId, description) VALUES (" + itsHashCode + ", '" + itsHashCode + "')", itsConn); cmd.ExecuteNonQuery(); } public void Add(Statement statement) { itsWriteStrategy.Add( statement ); } internal void FlushWriteCache() { itsWriteStrategy.EnsureAllWritesAreComplete(); } public void Add(ResourceStatement statement) { AddStatement(statement.GetSubject().GetHashCode(), statement.GetPredicate().GetHashCode(), statement.GetObject().GetHashCode()); } private void AddStatement(int subjectResourceHash, int predicateResourceHash, int objectResourceHash) { //~ MySqlCommand cmd = new MySqlCommand("INSERT IGNORE INTO Statements (subjectHash, predicateHash, objectHash, graphId) VALUES (" + //~ subjectResourceHash + ", " + predicateResourceHash + ", " + objectResourceHash + ", " + itsHashCode + ")", itsConn); //~ cmd.ExecuteNonQuery(); itsAddStatementCommand.Parameters["?subj"].Value = subjectResourceHash; itsAddStatementCommand.Parameters["?pred"].Value = predicateResourceHash; itsAddStatementCommand.Parameters["?obj"].Value = objectResourceHash; itsAddStatementCommand.Parameters["?graph"].Value = itsHashCode; itsAddStatementCommand.ExecuteNonQuery(); } public IDictionary GetResourcesDenotedBy( ICollection nodeList ) { if (nodeList.Count == 0) return new Hashtable(); Hashtable resourcesIndexedByNode = new Hashtable(); Hashtable nodesIndexedByHashCode = new Hashtable(); string sql = "SELECT nodeHash, resourceHash FROM ResourceNodes WHERE graphId=" + itsHashCode + " AND nodeHash IN ("; bool doneFirst = false; foreach (Node node in nodeList) { if ( doneFirst ) { sql = sql + ","; } else { doneFirst = true; } sql = sql + node.GetHashCode().ToString(); nodesIndexedByHashCode[ node.GetHashCode() ] = node; } sql = sql + ");"; MySqlCommand cmd = new MySqlCommand( sql, itsConn ); MySqlDataReader dataReader = cmd.ExecuteReader(); const int NODE_HASH_COL = 0; const int RESOURCE_HASH_COL = 1; while (dataReader.Read()) { if ( nodesIndexedByHashCode.ContainsKey( dataReader.GetInt32( NODE_HASH_COL ) ) ) { resourcesIndexedByNode[ nodesIndexedByHashCode[ dataReader.GetInt32( NODE_HASH_COL ) ] ] = new Resource(dataReader.GetInt32( RESOURCE_HASH_COL)); } } dataReader.Close(); return resourcesIndexedByNode; } public virtual Resource GetResourceDenotedBy(GraphMember theMember) { ArrayList list = new ArrayList(); list.Add( theMember ); IDictionary resourcesIndexedByNode = itsWriteStrategy.CreateAndGetResourcesDenotedBy( list ); return (Resource)resourcesIndexedByNode[ theMember ]; } private void EnsureDatatypeExistsInDb(TypedLiteral node) { int hash = node.GetDataType().GetHashCode(); MySqlCommand cmd = new MySqlCommand("INSERT IGNORE INTO Datatypes (hash, value) VALUES (" + hash + ", '" + node.GetDataType() + "')", itsConn); cmd.ExecuteNonQuery(); } private void EnsureLanguageExistsInDb(PlainLiteral node) { int hash = node.GetLanguage().GetHashCode(); MySqlCommand cmd = new MySqlCommand("INSERT IGNORE INTO Languages (hash, value) VALUES (" + hash + ", '" + node.GetLanguage() + "')", itsConn); cmd.ExecuteNonQuery(); } public bool IsEmpty() { return (StatementCount == 0); } public bool HasResourceDenotedBy(GraphMember theMember) { MySqlCommand cmd = new MySqlCommand("SELECT EXISTS (SELECT * FROM ResourceNodes WHERE graphId = " + itsHashCode + " AND nodeHash = " + theMember.GetHashCode() + ")", itsConn); return (Convert.ToInt32(cmd.ExecuteScalar()) > 0); } public void Write(RdfWriter writer) { writer.StartOutput(); IEnumerator statementEnum = GetStatementEnumerator(); while (statementEnum.MoveNext()) { ResourceStatement statement = (ResourceStatement)statementEnum.Current; writer.StartSubject(); GetBestDenotingNode(statement.GetSubject()).Write(writer); writer.StartPredicate(); GetBestDenotingNode(statement.GetPredicate()).Write(writer); writer.StartObject(); GetBestDenotingNode(statement.GetObject()).Write(writer); writer.EndObject(); writer.EndPredicate(); writer.EndSubject(); } writer.EndOutput(); } public override string ToString() { StringWriter stringWriter = new StringWriter(); NTripleWriter writer = new NTripleWriter(stringWriter); Write(writer); return stringWriter.ToString(); } public StatementHandler GetStatementHandler() { return itsStatementHandler; } public Object Clone() { DatabaseTripleStore dbts = new DatabaseTripleStore(); dbts.Add(this); return dbts; } public void Add(TripleStore other) { if (this == other) return; Merge( other, other ); } public void Merge(ResourceStatementCollection statements, ResourceMap map) { IEnumerator statementEnumerator = statements.GetStatementEnumerator(); while (statementEnumerator.MoveNext()) { ResourceStatement resStatement = (ResourceStatement)statementEnumerator.Current; Node theSubject = (Node)map.GetBestDenotingNode(resStatement.GetSubject()); Arc thePredicate = (Arc)map.GetBestDenotingNode(resStatement.GetPredicate()); Node theObject = (Node)map.GetBestDenotingNode(resStatement.GetObject()); Statement statement = new Statement(theSubject, thePredicate, theObject); Add(statement); } } public void Dump() { } public IEnumerator GetStatementEnumerator() { ArrayList statements = new ArrayList(); MySqlCommand cmd = new MySqlCommand("SELECT s.subjectHash, s.predicateHash, s.objectHash FROM Statements s WHERE s.graphId = " + itsHashCode, itsConn); MySqlDataReader dataReader = cmd.ExecuteReader(); while (dataReader.Read()) { Resource theSubject = new Resource(dataReader.GetInt32(0)); Resource thePredicate = new Resource(dataReader.GetInt32(1)); Resource theObject = new Resource(dataReader.GetInt32(2)); statements.Add(new ResourceStatement(theSubject, thePredicate, theObject)); } dataReader.Close(); return statements.GetEnumerator(); } public bool Contains(Statement statement) { string sql = "SELECT EXISTS (SELECT * FROM Statements s " + "JOIN ResourceNodes rn1 ON s.subjectHash = rn1.resourceHash AND s.graphId = rn1.graphId " + "JOIN ResourceNodes rn2 ON s.predicateHash = rn2.resourceHash AND s.graphId = rn2.graphId " + "JOIN ResourceNodes rn3 ON s.objectHash = rn3.resourceHash AND s.graphId = rn3.graphId " + "WHERE s.graphId = " + itsHashCode + " AND rn1.nodeHash = " + statement.GetSubject().GetHashCode() + " AND rn2.nodeHash = " + statement.GetPredicate().GetHashCode() + " AND rn3.nodeHash = " + statement.GetObject().GetHashCode() + ")"; MySqlCommand cmd = new MySqlCommand(sql, itsConn); return (Convert.ToInt32(cmd.ExecuteScalar()) > 0); } public bool Contains(ResourceStatement statement) { MySqlCommand cmd = new MySqlCommand("SELECT EXISTS (SELECT * FROM Statements s " + "WHERE s.graphId = " + itsHashCode + " AND s.subjectHash = " + statement.GetSubject().GetHashCode() + " AND s.predicateHash = " + statement.GetPredicate().GetHashCode() + " AND s.objectHash = " + statement.GetObject().GetHashCode() + ")", itsConn); return (Convert.ToInt32(cmd.ExecuteScalar()) > 0); } public bool HasNodeDenoting(Resource theResource) { MySqlCommand cmd = new MySqlCommand("SELECT EXISTS (SELECT rs.* FROM ResourceNodes rs " + "WHERE s.graphId = " + itsHashCode + " AND rs.resourceHash = " + theResource.GetHashCode() + ")", itsConn); return (Convert.ToInt32(cmd.ExecuteScalar()) > 0); } public GraphMember GetBestDenotingNode(Resource theResource) { IList nodes = GetNodesDenoting(theResource, true); if (nodes.Count > 0) return (GraphMember)nodes[0]; else return null; } public IList GetNodesDenoting(Resource theResource) { return GetNodesDenoting(theResource, false); } private IList GetNodesDenoting(Resource theResource, bool onlyTheBest) { ArrayList theNodes = new ArrayList(); MySqlCommand cmd = new MySqlCommand( "SELECT rn.nodeHash, rn.nodeType, u.uri, pl.value, l.value, tl.value, t.value " + "FROM resourcenodes rn " + "LEFT OUTER JOIN UriRefs u ON rn.nodeHash=u.hash AND rn.nodeType='u' " + "LEFT OUTER JOIN Plainliterals pl ON rn.nodeHash = pl.hash AND rn.nodeType='p' " + "LEFT OUTER JOIN Languages l ON pl.languageHash = l.hash " + "LEFT OUTER JOIN TypedLiterals tl ON rn.nodehash = tl.hash AND rn.nodeType = 't' " + "LEFT OUTER JOIN DataTypes t ON tl.datatypeHash = t.hash " + "WHERE rn.graphId = " + itsHashCode + " AND rn.resourceHash = " + theResource.GetHashCode() + (onlyTheBest == true ? " LIMIT 1" : ""), itsConn); MySqlDataReader dataReader = cmd.ExecuteReader(); int nodeHash; char nodeType; while (dataReader.Read()) { nodeHash = dataReader.GetInt32(0); nodeType = dataReader.GetChar(1); GraphMember node = null; switch (nodeType) { case 'u': node = new UriRef(dataReader.GetString(2)); break; case 'b': node = new BlankNode(nodeHash); break; case 'p': node = new PlainLiteral(dataReader.GetString(3), dataReader.GetString(4)); break; case 't': node = new TypedLiteral(dataReader.GetString(5), dataReader.GetString(6)); break; } theNodes.Add(node); } dataReader.Close(); return theNodes; } public void Remove(ResourceStatement resourceStatement) { MySqlCommand cmd = new MySqlCommand("DELETE FROM Statements WHERE " + "subjectHash = " + resourceStatement.GetSubject().GetHashCode() + " AND " + "predicateHash = " + resourceStatement.GetPredicate().GetHashCode() + " AND " + "objectHash = " + resourceStatement.GetObject().GetHashCode() + " AND " + "graphId = " + itsHashCode, itsConn); cmd.ExecuteNonQuery(); } public IList Resources { get { return ReferencedResources; } } public IList ReferencedResources { get { ArrayList resources = new ArrayList(); MySqlCommand cmd = new MySqlCommand("SELECT resourceHash FROM Resources WHERE graphId = " + itsHashCode, itsConn); MySqlDataReader dataReader = cmd.ExecuteReader(); while (dataReader.Read()) { resources.Add(new Resource(dataReader.GetInt32(0))); } dataReader.Close(); return resources; } } public int StatementCount { get { MySqlCommand cmd = new MySqlCommand("SELECT COUNT(*) FROM Statements WHERE graphId = " + itsHashCode, itsConn); return Convert.ToInt32(cmd.ExecuteScalar()); } } public IEnumerator Solve(Query query) { FlushWriteCache(); return new DatabaseQuerySolver(query, this); } public MySqlDataReader ExecuteSqlQuery(string sqlQuery) { MySqlCommand cmd = new MySqlCommand(sqlQuery, itsConn); return cmd.ExecuteReader(); } // TODO: replace implementation with database specific rule processor public void Evaluate(SemPlan.Spiral.Core.Rule rule) { SimpleRuleProcessor ruleProcessor = new SimpleRuleProcessor(); ruleProcessor.Process( rule, this ); } public void AddDenotation(GraphMember member, Resource theResource) { MySqlCommand cmd = new MySqlCommand("INSERT IGNORE INTO ResourceNodes (graphId, resourceHash, nodeHash) VALUES (" + itsHashCode + ", " + theResource.GetHashCode() + ", " + member.GetHashCode() + ")", itsConn); cmd.ExecuteNonQuery(); } public string EscapeString( string input ) { return input.Replace( "'", "\\'" ); } public void Add(ResourceDescription description) { // TODO throw new NotImplementedException(); } /// <returns>A bounded description generated according to the specified strategy.</returns> public virtual ResourceDescription GetDescriptionOf(Resource theResource, BoundingStrategy strategy) { return strategy.GetDescriptionOf( theResource, this ); } /// <returns>A bounded description generated according to the specified strategy.</returns> public virtual ResourceDescription GetDescriptionOf(Node theNode, BoundingStrategy strategy) { return GetDescriptionOf( GetResourceDenotedBy(theNode), strategy ); } } }
/// <Licensing> /// ?2011 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEditor; using UnityEngine; using System; using System.Collections; using System.Collections.Generic; /// <summary> /// Functions to help with custom editors /// </summary> public static class PGEditorUtils { // Constants for major settings public const int CONTROLS_DEFAULT_LABEL_WIDTH = 140; public const string FOLD_OUT_TOOL_TIP = "Click to Expand/Collapse"; #region Managment Utilities /// <summary> /// Will get an asset file at the specified path (and create one if none exists) /// The file will be named the same as the type passed with '.asset' appended /// </summary> /// <param name="basePath">The folder to look in</param> /// <returns>A reference to the asset component</returns> public static T GetDataAsset<T>(string basePath) where T : ScriptableObject { string fileName = typeof(T).ToString(); string filePath = string.Format("{0}/{1}.asset", basePath, fileName); T asset; asset = (T)AssetDatabase.LoadAssetAtPath(filePath, typeof(T)); if (!asset) { asset = ScriptableObject.CreateInstance<T>(); AssetDatabase.CreateAsset(asset, filePath); asset.hideFlags = HideFlags.HideInHierarchy; } return asset; } #endregion Managment Utilities #region Layout Utilities /// <summary> /// Does the same thing as EditorGUIUtility.LookLikeControls but with a defaut /// label width closer to the regular inspector look /// </summary> public static void LookLikeControls() { #if (UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) EditorGUIUtility.LookLikeControls(CONTROLS_DEFAULT_LABEL_WIDTH); #else EditorGUIUtility.labelWidth = CONTROLS_DEFAULT_LABEL_WIDTH; #endif } /// <summary> /// A generic version of EditorGUILayout.ObjectField. /// Allows objects to be drag and dropped or picked. /// This version defaults to 'allowSceneObjects = true'. /// /// Instead of this: /// var script = (MyScript)target; /// script.xform = (Transform)EditorGUILayout.ObjectField("My Transform", script.xform, typeof(Transform), true); /// /// Do this: /// var script = (MyScript)target; /// script.xform = EditorGUILayout.ObjectField<Transform>("My Transform", script.xform); /// </summary> /// <typeparam name="T">The type of object to use</typeparam> /// <param name="label">The label (text) to show to the left of the field</param> /// <param name="obj">The obj variable of the script this GUI field is for</param> /// <returns>A reference to what is in the field. An object or null.</returns> public static T ObjectField<T>(string label, T obj) where T : UnityEngine.Object { return ObjectField<T>(label, obj, true); } /// <summary> /// A generic version of EditorGUILayout.ObjectField. /// Allows objects to be drag and dropped or picked. /// </summary> /// <typeparam name="T">The type of object to use</typeparam> /// <param name="label">The label (text) to show to the left of the field</param> /// <param name="obj">The obj variable of the script this GUI field is for</param> /// <param name="allowSceneObjects">Allow scene objects. See Unity Docs for more.</param> /// <returns>A reference to what is in the field. An object or null.</returns> public static T ObjectField<T>(string label, T obj, bool allowSceneObjects) where T : UnityEngine.Object { return (T)EditorGUILayout.ObjectField(label, obj, typeof(T), allowSceneObjects); } /// <summary> /// A generic version of EditorGUILayout.ObjectField. /// Allows objects to be drag and dropped or picked. /// </summary> /// <typeparam name="T">The type of object to use</typeparam> /// <param name="label">The label (text) to show to the left of the field</param> /// <param name="obj">The obj variable of the script this GUI field is for</param> /// <param name="allowSceneObjects">Allow scene objects. See Unity docs for more.</param> /// <param name="options">Layout options. See Unity docs for more.</param> /// <returns>A reference to what is in the field. An object or null.</returns> public static T ObjectField<T>(string label, T obj, bool allowSceneObjects, GUILayoutOption[] options) where T : UnityEngine.Object { return (T)EditorGUILayout.ObjectField(label, obj, typeof(T), allowSceneObjects, options); } /// <summary> /// A generic version of EditorGUILayout.EnumPopup. /// Displays an enum as a pop-up list of options /// /// Instead of this: /// var script = (MyScript)target; /// script.options = (MyScript.MY_ENUM_OPTIONS)EditorGUILayout.EnumPopup("Options", (System.Enum)script.options); /// /// Do this: /// var script = (MyScript)target; /// script.options = EditorGUILayout.EnumPopup<MyScript.MY_ENUM_OPTIONS>("Options", script.options); /// </summary> /// <typeparam name="T">The enum type</typeparam> /// <param name="label">The label (text) to show to the left of the field</param> /// <param name="enumVar">The enum variable of the script this GUI field is for</param> /// <returns>The chosen option</returns> public static T EnumPopup<T>(string label, T enumVal) where T : struct, IFormattable, IConvertible, IComparable { Enum e; if ((e = enumVal as Enum) == null) throw new ArgumentException("value must be an Enum"); object res = EditorGUILayout.EnumPopup(label, e); return (T)res; } /// <summary> /// See EnumPopup<T>(string label, T enumVal). /// This enables label-less GUI fields. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="enumVal"></param> /// <returns></returns> public static T EnumPopup<T>(T enumVal) where T : struct, IFormattable, IConvertible, IComparable { Enum e; if ((e = enumVal as Enum) == null) throw new ArgumentException("value must be an Enum"); object res = EditorGUILayout.EnumPopup(e); return (T)res; } /// <summary> /// Add a LayerMash field. This hasn't been made available by Unity even though /// it exists in the automated version of the inspector (when no custom editor). /// </summary> /// <param name="label">The string to display to the left of the control</param> /// <param name="selected">The LayerMask variable</param> /// <returns>A new LayerMask value</returns> public static LayerMask LayerMaskField(string label, LayerMask selected) { return LayerMaskField(label, selected, true); } /// <summary> /// Add a LayerMash field. This hasn't been made available by Unity even though /// it exists in the automated version of the inspector (when no custom editor). /// Contains code from: /// http://answers.unity3d.com/questions/60959/mask-field-in-the-editor.html /// </summary> /// <param name="label">The string to display to the left of the control</param> /// <param name="selected">The LayerMask variable</param> /// <param name="showSpecial">True to display "Nothing" & "Everything" options</param> /// <returns>A new LayerMask value</returns> public static LayerMask LayerMaskField(string label, LayerMask selected, bool showSpecial) { string selectedLayers = ""; for (int i = 0; i < 32; i++) { string layerName = LayerMask.LayerToName(i); if (layerName == "") continue; // Skip empty layers if (selected == (selected | (1 << i))) { if (selectedLayers == "") { selectedLayers = layerName; } else { selectedLayers = "Mixed"; break; } } } List<string> layers = new List<string>(); List<int> layerNumbers = new List<int>(); 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); } string check = "[x] "; string noCheck = " "; if (showSpecial) { layers.Add((selected.value == 0 ? check : noCheck) + "Nothing"); layerNumbers.Add(-2); layers.Add((selected.value == -1 ? check : noCheck) + "Everything"); layerNumbers.Add(-3); } // A LayerMask is based on a 32bit field, so there are 32 'slots' max available for (int i = 0; i < 32; i++) { string layerName = LayerMask.LayerToName(i); if (layerName != "") { // Add a check box to the left of any selected layer's names if (selected == (selected | (1 << i))) layers.Add(check + layerName); else layers.Add(noCheck + 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) { if (showSpecial && newSelected == 0) selected = 0; else if (showSpecial && newSelected == 1) selected = -1; else { if (selected == (selected | (1 << layerNumbers[newSelected]))) selected &= ~(1 << layerNumbers[newSelected]); else selected = selected | (1 << layerNumbers[newSelected]); } } else { GUI.changed = preChange; } return selected; } #endregion Layout Utilities #region Foldout Fields and Utilities /// <summary> /// Adds a fold-out list GUI from a generic list of any serialized object type /// </summary> /// <param name="list">A generic List</param> /// <param name="expanded">A bool to determine the state of the primary fold-out</param> public static bool FoldOutTextList(string label, List<string> list, bool expanded) { // Store the previous indent and return the flow to it at the end int indent = EditorGUI.indentLevel; EditorGUI.indentLevel = 0; // A copy of toolbarButton with left alignment for foldouts var foldoutStyle = new GUIStyle(EditorStyles.toolbarButton); foldoutStyle.alignment = TextAnchor.MiddleLeft; expanded = AddFoldOutListHeader<string>(label, list, expanded, indent); // START. Will consist of one row with two columns. // The second column has the content EditorGUILayout.BeginHorizontal(); // SPACER COLUMN / INDENT EditorGUILayout.BeginVertical(); EditorGUILayout.BeginHorizontal(GUILayout.MinWidth((indent + 3) * 9)); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); EditorGUILayout.EndVertical(); // CONTENT COLUMN... EditorGUILayout.BeginVertical(); // Use a for, instead of foreach, to avoid the iterator since we will be // be changing the loop in place when buttons are pressed. Even legal // changes can throw an error when changes are detected for (int i = 0; i < list.Count; i++) { string item = list[i]; EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); // FIELD... if (item == null) item = ""; list[i] = EditorGUILayout.TextField(item); LIST_BUTTONS listButtonPressed = AddFoldOutListItemButtons(); EditorGUILayout.EndHorizontal(); GUILayout.Space(2); UpdateFoldOutListOnButtonPressed<string>(list, i, listButtonPressed); } EditorGUILayout.EndVertical(); EditorGUILayout.EndHorizontal(); EditorGUI.indentLevel = indent; return expanded; } /// <summary> /// Adds a fold-out list GUI from a generic list of any serialized object type /// </summary> /// <param name="list">A generic List</param> /// <param name="expanded">A bool to determine the state of the primary fold-out</param> public static bool FoldOutObjList<T>(string label, List<T> list, bool expanded) where T : UnityEngine.Object { // Store the previous indent and return the flow to it at the end int indent = EditorGUI.indentLevel; EditorGUI.indentLevel = 0; // Space will handle this for the header // A copy of toolbarButton with left alignment for foldouts var foldoutStyle = new GUIStyle(EditorStyles.toolbarButton); foldoutStyle.alignment = TextAnchor.MiddleLeft; if (!AddFoldOutListHeader<T>(label, list, expanded, indent)) return false; // Use a for, instead of foreach, to avoid the iterator since we will be // be changing the loop in place when buttons are pressed. Even legal // changes can throw an error when changes are detected for (int i = 0; i < list.Count; i++) { T item = list[i]; EditorGUILayout.BeginHorizontal(); GUILayout.Space((indent + 3) * 6); // Matches the content indent // OBJECT FIELD... // Count is always in sync bec T fieldVal = (T)EditorGUILayout.ObjectField(item, typeof(T), true); // This is weird but have to replace the item with the new value, can't // find a way to set in-place in a more stable way list.RemoveAt(i); list.Insert(i, fieldVal); LIST_BUTTONS listButtonPressed = AddFoldOutListItemButtons(); EditorGUILayout.EndHorizontal(); GUILayout.Space(2); #region Process List Changes // Don't allow 'up' presses for the first list item switch (listButtonPressed) { case LIST_BUTTONS.None: // Nothing was pressed, do nothing break; case LIST_BUTTONS.Up: if (i > 0) { T shiftItem = list[i]; list.RemoveAt(i); list.Insert(i - 1, shiftItem); } break; case LIST_BUTTONS.Down: // Don't allow 'down' presses for the last list item if (i + 1 < list.Count) { T shiftItem = list[i]; list.RemoveAt(i); list.Insert(i + 1, shiftItem); } break; case LIST_BUTTONS.Remove: list.RemoveAt(i); break; case LIST_BUTTONS.Add: list.Insert(i, null); break; } #endregion Process List Changes } EditorGUI.indentLevel = indent; return true; } /// <summary> /// Adds a fold-out list GUI from a generic list of any serialized object type. /// Uses System.Reflection to add all fields for a passed serialized object /// instance. Handles most basic types including automatic naming like the /// inspector does by default /// </summary> /// <param name="label"> The field label</param> /// <param name="list">A generic List</param> /// <param name="expanded">A bool to determine the state of the primary fold-out</param> /// <param name="foldOutStates">Dictionary<object, bool> used to track list item states</param> /// <returns>The new foldout state from user input. Just like Unity's foldout</returns> public static bool FoldOutSerializedObjList<T>(string label, List<T> list, bool expanded, ref Dictionary<object, bool> foldOutStates) where T : new() { return SerializedObjFoldOutList<T>(label, list, expanded, ref foldOutStates, false); } /// <summary> /// Adds a fold-out list GUI from a generic list of any serialized object type. /// Uses System.Reflection to add all fields for a passed serialized object /// instance. Handles most basic types including automatic naming like the /// inspector does by default /// /// Adds collapseBools (see docs below) /// </summary> /// <param name="label"> The field label</param> /// <param name="list">A generic List</param> /// <param name="expanded">A bool to determine the state of the primary fold-out</param> /// <param name="foldOutStates">Dictionary<object, bool> used to track list item states</param> /// <param name="collapseBools"> /// If true, bools on list items will collapse fields which follow them /// </param> /// <returns>The new foldout state from user input. Just like Unity's foldout</returns> public static bool SerializedObjFoldOutList<T>(string label, List<T> list, bool expanded, ref Dictionary<object, bool> foldOutStates, bool collapseBools) where T : new() { // Store the previous indent and return the flow to it at the end int indent = EditorGUI.indentLevel; EditorGUI.indentLevel = 0; int buttonSpacer = 6; #region Header Foldout // Use a Horizanal space or the toolbar will extend to the left no matter what EditorGUILayout.BeginHorizontal(); EditorGUI.indentLevel = 0; // Space will handle this for the header GUILayout.Space(indent * 6); // Matches the content indent EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); expanded = Foldout(expanded, label); if (!expanded) { // Don't add the '+' button when the contents are collapsed. Just quit. EditorGUILayout.EndHorizontal(); EditorGUILayout.EndHorizontal(); EditorGUI.indentLevel = indent; // Return to the last indent return expanded; } // BUTTONS... EditorGUILayout.BeginHorizontal(GUILayout.MaxWidth(100)); // Add expand/collapse buttons if there are items in the list bool masterCollapse = false; bool masterExpand = false; if (list.Count > 0) { GUIContent content; var collapseIcon = '\u2261'.ToString(); content = new GUIContent(collapseIcon, "Click to collapse all"); masterCollapse = GUILayout.Button(content, EditorStyles.toolbarButton); var expandIcon = '\u25A1'.ToString(); content = new GUIContent(expandIcon, "Click to expand all"); masterExpand = GUILayout.Button(content, EditorStyles.toolbarButton); } else { GUILayout.FlexibleSpace(); } EditorGUILayout.BeginHorizontal(GUILayout.MaxWidth(50)); // A little space between button groups GUILayout.Space(buttonSpacer); // Main Add button if (GUILayout.Button(new GUIContent("+", "Click to add"), EditorStyles.toolbarButton)) list.Add(new T()); EditorGUILayout.EndHorizontal(); EditorGUILayout.EndHorizontal(); EditorGUILayout.EndHorizontal(); EditorGUILayout.EndHorizontal(); #endregion Header Foldout #region List Items // Use a for, instead of foreach, to avoid the iterator since we will be // be changing the loop in place when buttons are pressed. Even legal // changes can throw an error when changes are detected for (int i = 0; i < list.Count; i++) { T item = list[i]; #region Section Header // If there is a field with the name 'name' use it for our label string itemLabel = PGEditorUtils.GetSerializedObjFieldName<T>(item); if (itemLabel == "") itemLabel = string.Format("Element {0}", i); // Get the foldout state. // If this item is new, add it too (singleton) // Singleton works better than multiple Add() calls because we can do // it all at once, and in one place. bool foldOutState; if (!foldOutStates.TryGetValue(item, out foldOutState)) { foldOutStates[item] = true; foldOutState = true; } // Force states if master buttons were pressed if (masterCollapse) foldOutState = false; if (masterExpand) foldOutState = true; // Use a Horizanal space or the toolbar will extend to the start no matter what EditorGUILayout.BeginHorizontal(); EditorGUI.indentLevel = 0; // Space will handle this for the header GUILayout.Space((indent+3)*6); // Matches the content indent EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); // Display foldout with current state foldOutState = Foldout(foldOutState, itemLabel); foldOutStates[item] = foldOutState; // Used again below LIST_BUTTONS listButtonPressed = AddFoldOutListItemButtons(); EditorGUILayout.EndHorizontal(); EditorGUILayout.EndHorizontal(); #endregion Section Header // If folded out, display all serialized fields if (foldOutState == true) { EditorGUI.indentLevel = indent + 3; // Display Fields for the list instance PGEditorUtils.SerializedObjectFields<T>(item, collapseBools); GUILayout.Space(2); } #region Process List Changes // Don't allow 'up' presses for the first list item switch (listButtonPressed) { case LIST_BUTTONS.None: // Nothing was pressed, do nothing break; case LIST_BUTTONS.Up: if (i > 0) { T shiftItem = list[i]; list.RemoveAt(i); list.Insert(i - 1, shiftItem); } break; case LIST_BUTTONS.Down: // Don't allow 'down' presses for the last list item if (i + 1 < list.Count) { T shiftItem = list[i]; list.RemoveAt(i); list.Insert(i + 1, shiftItem); } break; case LIST_BUTTONS.Remove: list.RemoveAt(i); foldOutStates.Remove(item); // Clean-up break; case LIST_BUTTONS.Add: list.Insert(i, new T()); break; } #endregion Process List Changes } #endregion List Items EditorGUI.indentLevel = indent; return expanded; } /// <summary> /// Searches a serialized object for a field matching "name" (not case-sensitve), /// and if found, returns the value /// </summary> /// <param name="instance"> /// An instance of the given type. Must be System.Serializable. /// </param> /// <returns>The name field's value or ""</returns> public static string GetSerializedObjFieldName<T>(T instance) { // get all public properties of T to see if there is one called 'name' System.Reflection.FieldInfo[] fields = typeof(T).GetFields(); // If there is a field with the name 'name' return its value foreach (System.Reflection.FieldInfo fieldInfo in fields) if (fieldInfo.Name.ToLower() == "name") return ((string)fieldInfo.GetValue(instance)).DeCamel(); // If a field type is a UnityEngine object, return its name // This is done in a second loop because the first is fast as is foreach (System.Reflection.FieldInfo fieldInfo in fields) { try { var val = (UnityEngine.Object)fieldInfo.GetValue(instance); return val.name.DeCamel(); } catch { } } return ""; } /// <summary> /// Uses System.Reflection to add all fields for a passed serialized object /// instance. Handles most basic types including automatic naming like the /// inspector does by default /// /// Optionally, this will make a bool switch collapse the following members if they /// share the first 4 characters in their name or are not a bool (will collapse from /// bool until it finds another bool that doesn't share the first 4 characters) /// </summary> /// <param name="instance"> /// An instance of the given type. Must be System.Serializable. /// </param> public static void SerializedObjectFields<T>(T instance) { SerializedObjectFields<T>(instance, false); } public static void SerializedObjectFields<T>(T instance, bool collapseBools) { // get all public properties of T to see if there is one called 'name' System.Reflection.FieldInfo[] fields = typeof(T).GetFields(); bool boolCollapseState = false; // False until bool is found string boolCollapseName = ""; // The name of the last bool member string currentMemberName = ""; // The name of the member being processed // Display Fields Dynamically foreach (System.Reflection.FieldInfo fieldInfo in fields) { if (!collapseBools) { FieldInfoField<T>(instance, fieldInfo); continue; } // USING collapseBools... currentMemberName = fieldInfo.Name; // If this is a bool. Add the field and set collapse to true until // the end or until another bool is hit if (fieldInfo.FieldType == typeof(bool)) { // If the first 4 letters of this bool match the last one, include this // in the collapse group, rather than starting a new one. if (boolCollapseName.Length > 4 && currentMemberName.StartsWith(boolCollapseName.Substring(0, 4))) { if (!boolCollapseState) FieldInfoField<T>(instance, fieldInfo); continue; } FieldInfoField<T>(instance, fieldInfo); boolCollapseName = currentMemberName; boolCollapseState = !(bool)fieldInfo.GetValue(instance); } else { // Add the field unless collapse is true if (!boolCollapseState) FieldInfoField<T>(instance, fieldInfo); } } } /// <summary> /// Uses a System.Reflection.FieldInfo to add a field /// Handles most built-in types and components /// includes automatic naming like the inspector does /// by default /// </summary> /// <param name="fieldInfo"></param> public static void FieldInfoField<T>(T instance, System.Reflection.FieldInfo fieldInfo) { string label = fieldInfo.Name.DeCamel(); #region Built-in Data Types if (fieldInfo.FieldType == typeof(string)) { var val = (string)fieldInfo.GetValue(instance); val = EditorGUILayout.TextField(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(int)) { var val = (int)fieldInfo.GetValue(instance); val = EditorGUILayout.IntField(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(float)) { var val = (float)fieldInfo.GetValue(instance); val = EditorGUILayout.FloatField(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(bool)) { var val = (bool)fieldInfo.GetValue(instance); val = EditorGUILayout.Toggle(label, val); fieldInfo.SetValue(instance, val); return; } #endregion Built-in Data Types #region Basic Unity Types else if (fieldInfo.FieldType == typeof(GameObject)) { var val = (GameObject)fieldInfo.GetValue(instance); val = ObjectField<GameObject>(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(Transform)) { var val = (Transform)fieldInfo.GetValue(instance); val = ObjectField<Transform>(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(Rigidbody)) { var val = (Rigidbody)fieldInfo.GetValue(instance); val = ObjectField<Rigidbody>(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(Renderer)) { var val = (Renderer)fieldInfo.GetValue(instance); val = ObjectField<Renderer>(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(Mesh)) { var val = (Mesh)fieldInfo.GetValue(instance); val = ObjectField<Mesh>(label, val); fieldInfo.SetValue(instance, val); return; } #endregion Basic Unity Types #region Unity Collider Types else if (fieldInfo.FieldType == typeof(BoxCollider)) { var val = (BoxCollider)fieldInfo.GetValue(instance); val = ObjectField<BoxCollider>(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(SphereCollider)) { var val = (SphereCollider)fieldInfo.GetValue(instance); val = ObjectField<SphereCollider>(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(CapsuleCollider)) { var val = (CapsuleCollider)fieldInfo.GetValue(instance); val = ObjectField<CapsuleCollider>(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(MeshCollider)) { var val = (MeshCollider)fieldInfo.GetValue(instance); val = ObjectField<MeshCollider>(label, val); fieldInfo.SetValue(instance, val); return; } else if (fieldInfo.FieldType == typeof(WheelCollider)) { var val = (WheelCollider)fieldInfo.GetValue(instance); val = ObjectField<WheelCollider>(label, val); fieldInfo.SetValue(instance, val); return; } #endregion Unity Collider Types #region Other Unity Types else if (fieldInfo.FieldType == typeof(CharacterController)) { var val = (CharacterController)fieldInfo.GetValue(instance); val = ObjectField<CharacterController>(label, val); fieldInfo.SetValue(instance, val); return; } #endregion Other Unity Types } /// <summary> /// Adds the GUI header line which contains the label and add buttons. /// </summary> /// <param name="label">The visible label in the GUI</param> /// <param name="list">Needed to add a new item if count is 0</param> /// <param name="expanded"></param> /// <param name="lastIndent"></param> private static bool AddFoldOutListHeader<T>(string label, List<T> list, bool expanded, int lastIndent) { int buttonSpacer = 6; EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); expanded = PGEditorUtils.Foldout(expanded, label); if (!expanded) { // Don't add the '+' button when the contents are collapsed. Just quit. EditorGUILayout.EndHorizontal(); EditorGUI.indentLevel = lastIndent; // Return to the last indent return expanded; } EditorGUILayout.BeginHorizontal(GUILayout.MaxWidth(50)); // 1/2 the item button width GUILayout.Space(buttonSpacer); // Master add at end button. List items will insert if (GUILayout.Button(new GUIContent("+", "Click to add"), EditorStyles.toolbarButton)) list.Add(default(T)); EditorGUILayout.EndHorizontal(); EditorGUILayout.EndHorizontal(); return expanded; } /// <summary> /// Used by AddFoldOutListItemButtons to return which button was pressed, and by /// UpdateFoldOutListOnButtonPressed to process the pressed button for regular lists /// </summary> private enum LIST_BUTTONS { None, Up, Down, Add, Remove } /// <summary> /// Adds the buttons which control a list item /// </summary> /// <returns>LIST_BUTTONS - The LIST_BUTTONS pressed or LIST_BUTTONS.None</returns> private static LIST_BUTTONS AddFoldOutListItemButtons() { #region Layout int buttonSpacer = 6; EditorGUILayout.BeginHorizontal(GUILayout.MaxWidth(100)); // The up arrow will move things towards the beginning of the List var upArrow = '\u25B2'.ToString(); bool upPressed = GUILayout.Button(new GUIContent(upArrow, "Click to shift up"), EditorStyles.toolbarButton); // The down arrow will move things towards the end of the List var dnArrow = '\u25BC'.ToString(); bool downPressed = GUILayout.Button(new GUIContent(dnArrow, "Click to shift down"), EditorStyles.toolbarButton); // A little space between button groups GUILayout.Space(buttonSpacer); // Remove Button - Process presses later bool removePressed = GUILayout.Button(new GUIContent("-", "Click to remove"), EditorStyles.toolbarButton); // Add button - Process presses later bool addPressed = GUILayout.Button(new GUIContent("+", "Click to insert new"), EditorStyles.toolbarButton); EditorGUILayout.EndHorizontal(); #endregion Layout // Return the pressed button if any if (upPressed == true) return LIST_BUTTONS.Up; if (downPressed == true) return LIST_BUTTONS.Down; if (removePressed == true) return LIST_BUTTONS.Remove; if (addPressed == true) return LIST_BUTTONS.Add; return LIST_BUTTONS.None; } /// <summary> /// Used by basic foldout lists to process any list item button presses which will alter /// the order or members of the ist /// </summary> /// <param name="listButtonPressed"></param> private static void UpdateFoldOutListOnButtonPressed<T>(List<T> list, int currentIndex, LIST_BUTTONS listButtonPressed) { // Don't allow 'up' presses for the first list item switch (listButtonPressed) { case LIST_BUTTONS.None: // Nothing was pressed, do nothing break; case LIST_BUTTONS.Up: if (currentIndex > 0) { T shiftItem = list[currentIndex]; list.RemoveAt(currentIndex); list.Insert(currentIndex - 1, shiftItem); } break; case LIST_BUTTONS.Down: // Don't allow 'down' presses for the last list item if (currentIndex + 1 < list.Count) { T shiftItem = list[currentIndex]; list.RemoveAt(currentIndex); list.Insert(currentIndex + 1, shiftItem); } break; case LIST_BUTTONS.Remove: list.RemoveAt(currentIndex); break; case LIST_BUTTONS.Add: list.Insert(currentIndex, default(T)); break; } } /// <summary> /// Adds a foldout in 'LookLikeInspector' which has a full bar to click on, not just /// the little triangle. It also adds a default tool-tip. /// </summary> /// <param name="expanded"></param> /// <param name="label"></param> /// <returns></returns> public static bool Foldout(bool expanded, string label) { #if (UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) EditorGUIUtility.LookLikeInspector(); #endif var content = new GUIContent(label, FOLD_OUT_TOOL_TIP); expanded = EditorGUILayout.Foldout(expanded, content); LookLikeControls(); return expanded; } #endregion Foldout Fields and Utilities } public static class PGEditorToolsStringExtensions { /// <summary> /// Converts a string from camel-case to seperate words that start with /// capital letters. Also removes leading underscores. /// </summary> /// <returns>string</returns> public static string DeCamel(this string s) { if (string.IsNullOrEmpty(s)) return string.Empty; System.Text.StringBuilder newStr = new System.Text.StringBuilder(); char c; for (int i = 0; i < s.Length; i++) { c = s[i]; // Handle spaces and underscores. // Do not keep underscores // Only keep spaces if there is a lower case letter next, and // capitalize the letter if (c == ' ' || c == '_') { // Only check the next character is there IS a next character if (i < s.Length-1 && char.IsLower(s[i+1])) { // If it isn't the first character, add a space before it if (newStr.Length != 0) { newStr.Append(' '); // Add the space newStr.Append(char.ToUpper(s[i + 1])); } else { newStr.Append(s[i + 1]); // Stripped if first char in string } i++; // Skip the next. We already used it } } // Handle uppercase letters else if (char.IsUpper(c)) { // If it isn't the first character, add a space before it if (newStr.Length != 0) { newStr.Append(' '); newStr.Append(c); } else { newStr.Append(c); } } else // Normal character. Store and move on. { newStr.Append(c); } } return newStr.ToString(); } /// <summary> /// Capitalizes only the first letter of a string /// </summary> /// <returns>string</returns> public static string Capitalize(this string s) { if (string.IsNullOrEmpty(s)) return string.Empty; char[] a = s.ToCharArray(); a[0] = char.ToUpper(a[0]); return new string(a); } }
#region License //============================================================================= // Vici Core - Productivity Library for .NET 3.5 // // Copyright (c) 2008-2012 Philippe Leybaert // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //============================================================================= #endregion using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Vici.Core.Parser { public class DynamicObject : IDynamicObject { private readonly Dictionary<string, object> _dic = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); private readonly LinkedList<object> _objects = new LinkedList<object>(); public DynamicObject() { if (GetType() != typeof(DynamicObject)) _objects.AddFirst(this); } public DynamicObject(params object[] dataObjects) : this() { Apply(dataObjects); } public void Apply(DynamicObject source) { foreach (string s in source._dic.Keys) _dic[s] = source._dic[s]; foreach (object obj in source._objects) _objects.AddLast(obj); } public void Apply(object obj) { var dynamicObject = obj as DynamicObject; if (dynamicObject != null) Apply(dynamicObject); else _objects.AddLast(obj); } public void Apply(params object[] objects) { foreach (var obj in objects) Apply(obj); } public DynamicObject Clone() { DynamicObject newContainer = (DynamicObject)Activator.CreateInstance(GetType()); newContainer.Apply(this); return newContainer; } private bool HasProperty(string propertyName) { if (_objects.Count == 0) return false; return _objects.Any(obj => GetMember(obj.GetType(), propertyName) != null); } public bool Contains(string key) { return _dic.ContainsKey(key) || HasProperty(key); } public bool TryGetValue(string key, out object value) { Type type; return TryGetValue(key, out value, out type); } private static MemberInfo GetMember(Type type, string propertyName) { MemberInfo[] members = type.Inspector().GetMember(propertyName); if (members.Length == 0) return null; MemberInfo member = members[0]; if (member is MethodInfo) return member; if (members.Length > 1) // CoolStorage, ActiveRecord and Dynamic Proxy frameworks sometimes return > 1 member { foreach (var memberInfo in members) if (memberInfo.DeclaringType == type) member = memberInfo; } if (member is PropertyInfo || member is FieldInfo) return member; return null; } public bool TryGetValue(string propertyName, out object value, out Type type) { type = typeof(object); if (_dic.TryGetValue(propertyName, out value)) { if (value == null) return true; type = value.GetType(); return true; } if (_objects.Count == 0) return false; foreach (object dataObject in _objects) { MemberInfo member = GetMember(dataObject.GetType(), propertyName); if (member == null) continue; if (member is PropertyInfo) { value = ((PropertyInfo)member).GetValue(dataObject, null); type = ((PropertyInfo)member).PropertyType; return true; } if (member is FieldInfo) { value = ((FieldInfo)member).GetValue(dataObject); type = ((FieldInfo)member).FieldType; return true; } if (member is MethodInfo) { value = new InstanceMethod(dataObject.GetType(), propertyName, dataObject); type = typeof(InstanceMethod); return true; } } return false; } public object this[string key] { get { object value; if (TryGetValue(key, out value)) return value; return null; } set { _dic[key] = value; } } public void AddType(Type t) { this[t.Name] = ContextFactory.CreateType(t); } public void AddType(string name, Type t) { this[name] = ContextFactory.CreateType(t); } public void AddType<T>(string name) { this[name] = ContextFactory.CreateType(typeof(T)); } public void AddType<T>() { this[typeof(T).Name] = ContextFactory.CreateType(typeof(T)); } public void AddFunction<T>(string name, string functionName) { this[name] = ContextFactory.CreateFunction(typeof(T), functionName); } public void AddFunction<T>(string name, string functionName, T targetObject) { this[name] = ContextFactory.CreateFunction(typeof(T), functionName, targetObject); } public void AddFunction(string name, Type type, string functionName) { this[name] = ContextFactory.CreateFunction(type, functionName); } public void AddFunction(string name, Type type, string functionName, object targetObject) { this[name] = ContextFactory.CreateFunction(type, functionName, targetObject); } public void AddFunction(string name, MethodInfo methodInfo) { this[name] = ContextFactory.CreateFunction(methodInfo); } public void AddFunction(string name, MethodInfo methodInfo, object targetObject) { this[name] = ContextFactory.CreateFunction(methodInfo, targetObject); } } }
//----------------------------------------------------------------------- // <copyright file="DefaultSerializationBinder.cs" company="Sirenix IVS"> // Copyright (c) 2018 Sirenix IVS // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> //----------------------------------------------------------------------- namespace Stratus.OdinSerializer { using Stratus.OdinSerializer.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; /// <summary> /// An attribute that lets you help the DefaultSerializationBinder bind type names to types. This is useful if you're renaming a type, /// that would result in data loss, and what to specify the new type name to avoid loss of data. /// </summary> /// <seealso cref="DefaultSerializationBinder" /> /// <example> /// <code> /// [assembly: OdinSerializer.BindTypeNameToType("Namespace.OldTypeName", typeof(Namespace.NewTypeName))] /// //[assembly: OdinSerializer.BindTypeNameToType("Namespace.OldTypeName, OldFullAssemblyName", typeof(Namespace.NewTypeName))] /// /// namespace Namespace /// { /// public class SomeComponent : SerializedMonoBehaviour /// { /// public IInterface test; // Contains an instance of OldTypeName; /// } /// /// public interface IInterface { } /// /// public class NewTypeName : IInterface { } /// /// //public class OldTypeName : IInterface { } /// } /// </code> /// </example> [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public sealed class BindTypeNameToTypeAttribute : Attribute { internal readonly Type NewType; internal readonly string OldTypeName; /// <summary> /// Initializes a new instance of the <see cref="BindTypeNameToTypeAttribute"/> class. /// </summary> /// <param name="oldFullTypeName">Old old full type name. If it's moved to new a new assembly you must specify the old assembly name as well. See example code in the documentation.</param> /// <param name="newType">The new type.</param> public BindTypeNameToTypeAttribute(string oldFullTypeName, Type newType) { this.OldTypeName = oldFullTypeName; this.NewType = newType; } } /// <summary> /// Provides a default, catch-all <see cref="TwoWaySerializationBinder"/> implementation. This binder only includes assembly names, without versions and tokens, in order to increase compatibility. /// </summary> /// <seealso cref="TwoWaySerializationBinder" /> /// <seealso cref="BindTypeNameToTypeAttribute" /> public class DefaultSerializationBinder : TwoWaySerializationBinder { private static readonly object ASSEMBLY_LOOKUP_LOCK = new object(); private static readonly Dictionary<string, Assembly> assemblyNameLookUp = new Dictionary<string, Assembly>(); private static readonly Dictionary<string, Type> customTypeNameToTypeBindings = new Dictionary<string, Type>(); private static readonly object TYPETONAME_LOCK = new object(); private static readonly Dictionary<Type, string> nameMap = new Dictionary<Type, string>(FastTypeComparer.Instance); private static readonly object NAMETOTYPE_LOCK = new object(); private static readonly Dictionary<string, Type> typeMap = new Dictionary<string, Type>(); private static readonly List<string> genericArgNamesList = new List<string>(); private static readonly List<Type> genericArgTypesList = new List<Type>(); static DefaultSerializationBinder() { AppDomain.CurrentDomain.AssemblyLoad += (sender, args) => { RegisterAssembly(args.LoadedAssembly); }; foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { RegisterAssembly(assembly); } } private static void RegisterAssembly(Assembly assembly) { var name = assembly.GetName().Name; bool wasAdded = false; lock (ASSEMBLY_LOOKUP_LOCK) { if (!assemblyNameLookUp.ContainsKey(name)) { assemblyNameLookUp.Add(name, assembly); wasAdded = true; } } if (wasAdded) { try { var customAttributes = assembly.SafeGetCustomAttributes(typeof(BindTypeNameToTypeAttribute), false); if (customAttributes != null) { for (int i = 0; i < customAttributes.Length; i++) { var attr = customAttributes[i] as BindTypeNameToTypeAttribute; if (attr != null && attr.NewType != null) { lock (ASSEMBLY_LOOKUP_LOCK) { //if (attr.OldTypeName.Contains(",")) //{ customTypeNameToTypeBindings[attr.OldTypeName] = attr.NewType; //} //else //{ // customTypeNameToTypeBindings[attr.OldTypeName + ", " + assembly.GetName().Name] = attr.NewType; //} } } } } } catch { } // Assembly is invalid somehow } } /// <summary> /// Bind a type to a name. /// </summary> /// <param name="type">The type to bind.</param> /// <param name="debugContext">The debug context to log to.</param> /// <returns> /// The name that the type has been bound to. /// </returns> /// <exception cref="System.ArgumentNullException">The type argument is null.</exception> public override string BindToName(Type type, DebugContext debugContext = null) { if (type == null) { throw new ArgumentNullException("type"); } string result; lock (TYPETONAME_LOCK) { if (nameMap.TryGetValue(type, out result) == false) { if (type.IsGenericType) { // We track down all assemblies in the generic type definition List<Type> toResolve = type.GetGenericArguments().ToList(); HashSet<Assembly> assemblies = new HashSet<Assembly>(); while (toResolve.Count > 0) { var t = toResolve[0]; if (t.IsGenericType) { toResolve.AddRange(t.GetGenericArguments()); } assemblies.Add(t.Assembly); toResolve.RemoveAt(0); } result = type.FullName + ", " + type.Assembly.GetName().Name; foreach (var ass in assemblies) { result = result.Replace(ass.FullName, ass.GetName().Name); } } else if (type.IsDefined(typeof(CompilerGeneratedAttribute), false)) { result = type.FullName + ", " + type.Assembly.GetName().Name; } else { result = type.FullName + ", " + type.Assembly.GetName().Name; } nameMap.Add(type, result); } } return result; } /// <summary> /// Determines whether the specified type name is mapped. /// </summary> public override bool ContainsType(string typeName) { lock (NAMETOTYPE_LOCK) { return typeMap.ContainsKey(typeName); } } /// <summary> /// Binds a name to type. /// </summary> /// <param name="typeName">The name of the type to bind.</param> /// <param name="debugContext">The debug context to log to.</param> /// <returns> /// The type that the name has been bound to, or null if the type could not be resolved. /// </returns> /// <exception cref="System.ArgumentNullException">The typeName argument is null.</exception> public override Type BindToType(string typeName, DebugContext debugContext = null) { if (typeName == null) { throw new ArgumentNullException("typeName"); } Type result; lock (NAMETOTYPE_LOCK) { if (typeMap.TryGetValue(typeName, out result) == false) { result = this.ParseTypeName(typeName, debugContext); if (result == null && debugContext != null) { debugContext.LogWarning("Failed deserialization type lookup for type name '" + typeName + "'."); } // We allow null values on purpose so we don't have to keep re-performing invalid name lookups typeMap.Add(typeName, result); } } return result; } private Type ParseTypeName(string typeName, DebugContext debugContext) { Type type; lock (ASSEMBLY_LOOKUP_LOCK) { // Look for custom defined type name lookups defined with the BindTypeNameToTypeAttribute. if (customTypeNameToTypeBindings.TryGetValue(typeName, out type)) { return type; } } // Let's try it the traditional .NET way type = Type.GetType(typeName); if (type != null) return type; // Generic/array type name handling type = ParseGenericAndOrArrayType(typeName, debugContext); if (type != null) return type; string typeStr, assemblyStr; ParseName(typeName, out typeStr, out assemblyStr); if (!string.IsNullOrEmpty(typeStr)) { lock (ASSEMBLY_LOOKUP_LOCK) { // Look for custom defined type name lookups defined with the BindTypeNameToTypeAttribute. if (customTypeNameToTypeBindings.TryGetValue(typeStr, out type)) { return type; } } Assembly assembly; // Try to load from the named assembly if (assemblyStr != null) { lock (ASSEMBLY_LOOKUP_LOCK) { assemblyNameLookUp.TryGetValue(assemblyStr, out assembly); } if (assembly == null) { try { assembly = Assembly.Load(assemblyStr); } catch { } } if (assembly != null) { try { type = assembly.GetType(typeStr); } catch { } // Assembly is invalid if (type != null) return type; } } // Try to check all assemblies for the type string var assemblies = AppDomain.CurrentDomain.GetAssemblies(); for (int i = 0; i < assemblies.Length; i++) { assembly = assemblies[i]; try { type = assembly.GetType(typeStr, false); } catch { } // Assembly is invalid if (type != null) return type; } } //type = AssemblyUtilities.GetTypeByCachedFullName(typeStr); //if (type != null) return type; return null; } private static void ParseName(string fullName, out string typeName, out string assemblyName) { typeName = null; assemblyName = null; int firstComma = fullName.IndexOf(','); if (firstComma < 0 || (firstComma + 1) == fullName.Length) { typeName = fullName.Trim(',', ' '); return; } else { typeName = fullName.Substring(0, firstComma); } int secondComma = fullName.IndexOf(',', firstComma + 1); if (secondComma < 0) { assemblyName = fullName.Substring(firstComma).Trim(',', ' '); } else { assemblyName = fullName.Substring(firstComma, secondComma - firstComma).Trim(',', ' '); } } private Type ParseGenericAndOrArrayType(string typeName, DebugContext debugContext) { string actualTypeName; List<string> genericArgNames; bool isGeneric; bool isArray; int arrayRank; if (!TryParseGenericAndOrArrayTypeName(typeName, out actualTypeName, out isGeneric, out genericArgNames, out isArray, out arrayRank)) return null; Type type = this.BindToType(actualTypeName, debugContext); if (type == null) return null; if (isGeneric) { if (!type.IsGenericType) return null; List<Type> args = genericArgTypesList; args.Clear(); for (int i = 0; i < genericArgNames.Count; i++) { Type arg = this.BindToType(genericArgNames[i], debugContext); if (arg == null) return null; args.Add(arg); } var argsArray = args.ToArray(); if (!type.AreGenericConstraintsSatisfiedBy(argsArray)) { if (debugContext != null) { string argsStr = ""; foreach (var arg in args) { if (argsStr != "") argsStr += ", "; argsStr += arg.GetNiceFullName(); } debugContext.LogWarning("Deserialization type lookup failure: The generic type arguments '" + argsStr + "' do not satisfy the generic constraints of generic type definition '" + type.GetNiceFullName() + "'. All this parsed from the full type name string: '" + typeName + "'"); } return null; } type = type.MakeGenericType(argsArray); } if (isArray) { type = type.MakeArrayType(arrayRank); } return type; } private static bool TryParseGenericAndOrArrayTypeName(string typeName, out string actualTypeName, out bool isGeneric, out List<string> genericArgNames, out bool isArray, out int arrayRank) { isGeneric = false; isArray = false; arrayRank = 0; bool parsingGenericArguments = false; string argName; genericArgNames = null; actualTypeName = null; for (int i = 0; i < typeName.Length; i++) { if (typeName[i] == '[') { var next = Peek(typeName, i, 1); if (next == ',' || next == ']') { if (actualTypeName == null) { actualTypeName = typeName.Substring(0, i); } isArray = true; arrayRank = 1; i++; if (next == ',') { while (next == ',') { arrayRank++; next = Peek(typeName, i, 1); i++; } if (next != ']') return false; // Malformed type name } } else { if (!isGeneric) { actualTypeName = typeName.Substring(0, i); isGeneric = true; parsingGenericArguments = true; genericArgNames = genericArgNamesList; genericArgNames.Clear(); } else if (isGeneric && ReadGenericArg(typeName, ref i, out argName)) { genericArgNames.Add(argName); } else return false; // Malformed type name } } else if (typeName[i] == ']') { if (!parsingGenericArguments) return false; // This is not a valid type name, since we're hitting "]" without currently being in the process of parsing the generic arguments or an array thingy parsingGenericArguments = false; } else if (typeName[i] == ',' && !parsingGenericArguments) { actualTypeName += typeName.Substring(i); break; } } return isArray || isGeneric; } private static char Peek(string str, int i, int ahead) { if (i + ahead < str.Length) return str[i + ahead]; return '\0'; } private static bool ReadGenericArg(string typeName, ref int i, out string argName) { argName = null; if (typeName[i] != '[') return false; int start = i + 1; int genericDepth = 0; for (; i < typeName.Length; i++) { if (typeName[i] == '[') genericDepth++; else if (typeName[i] == ']') { genericDepth--; if (genericDepth == 0) { int length = i - start; argName = typeName.Substring(start, length); return true; } } } return false; } } }
using Xunit; namespace Jint.Tests.Ecma { public class Test_15_10_2_6 : EcmaTest { [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A1_T1.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe2() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A1_T2.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe3() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A1_T3.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe4() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A1_T4.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe5() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A1_T5.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe6() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A2_T1.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe7() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A2_T10.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe8() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A2_T2.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe9() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A2_T3.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe10() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A2_T4.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe11() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A2_T5.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe12() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A2_T6.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe13() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A2_T7.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe14() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A2_T8.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe15() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A2_T9.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionBEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A3_T1.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionBEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe2() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A3_T10.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionBEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe3() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A3_T11.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionBEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe4() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A3_T12.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionBEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe5() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A3_T13.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionBEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe6() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A3_T14.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionBEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe7() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A3_T15.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionBEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe8() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A3_T2.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionBEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe9() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A3_T3.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionBEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe10() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A3_T4.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionBEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe11() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A3_T5.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionBEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe12() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A3_T6.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionBEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe13() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A3_T7.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionBEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe14() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A3_T8.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionBEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe15() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A3_T9.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionBEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe16() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A4_T1.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionBEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe17() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A4_T2.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionBEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe18() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A4_T3.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionBEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe19() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A4_T4.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionBEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe20() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A4_T5.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionBEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe21() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A4_T6.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionBEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe22() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A4_T7.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void TheProductionAssertionBEvaluatesByReturningAnInternalAssertiontesterClosureThatTakesAStateArgumentXAndPerformsThe23() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A4_T8.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void SinceAssertionEvaluatingDoNotChangeEndindexRepetitionOfAssertionDoesTheSameResult() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A5_T1.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void SinceAssertionEvaluatingDoNotChangeEndindexRepetitionOfAssertionDoesTheSameResult2() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A5_T2.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void AssertionsInCombination() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A6_T1.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void AssertionsInCombination2() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A6_T2.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void AssertionsInCombination3() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A6_T3.js", false); } [Fact] [Trait("Category", "15.10.2.6")] public void AssertionsInCombination4() { RunTest(@"TestCases/ch15/15.10/15.10.2/15.10.2.6/S15.10.2.6_A6_T4.js", false); } } }
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; using Lucene.Net.Analysis; using Lucene.Net.Analysis.TokenAttributes; using Lucene.Net.Search; using Lucene.Net.Util; namespace Lucene.Net.QueryParsers.Classic { [TestFixture] public class TestMultiAnalyzer_ : BaseTokenStreamTestCase { private static int multiToken = 0; [Test] public virtual void TestMultiAnalyzer() { QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, "", new MultiAnalyzer()); // trivial, no multiple tokens: assertEquals("foo", qp.Parse("foo").toString()); assertEquals("foo", qp.Parse("\"foo\"").toString()); assertEquals("foo foobar", qp.Parse("foo foobar").toString()); assertEquals("\"foo foobar\"", qp.Parse("\"foo foobar\"").toString()); assertEquals("\"foo foobar blah\"", qp.Parse("\"foo foobar blah\"").toString()); // two tokens at the same position: assertEquals("(multi multi2) foo", qp.Parse("multi foo").toString()); assertEquals("foo (multi multi2)", qp.Parse("foo multi").toString()); assertEquals("(multi multi2) (multi multi2)", qp.Parse("multi multi").toString()); assertEquals("+(foo (multi multi2)) +(bar (multi multi2))", qp.Parse("+(foo multi) +(bar multi)").toString()); assertEquals("+(foo (multi multi2)) field:\"bar (multi multi2)\"", qp.Parse("+(foo multi) field:\"bar multi\"").toString()); // phrases: assertEquals("\"(multi multi2) foo\"", qp.Parse("\"multi foo\"").toString()); assertEquals("\"foo (multi multi2)\"", qp.Parse("\"foo multi\"").toString()); assertEquals("\"foo (multi multi2) foobar (multi multi2)\"", qp.Parse("\"foo multi foobar multi\"").toString()); // fields: assertEquals("(field:multi field:multi2) field:foo", qp.Parse("field:multi field:foo").toString()); assertEquals("field:\"(multi multi2) foo\"", qp.Parse("field:\"multi foo\"").toString()); // three tokens at one position: assertEquals("triplemulti multi3 multi2", qp.Parse("triplemulti").toString()); assertEquals("foo (triplemulti multi3 multi2) foobar", qp.Parse("foo triplemulti foobar").toString()); // phrase with non-default slop: assertEquals("\"(multi multi2) foo\"~10", qp.Parse("\"multi foo\"~10").toString()); // phrase with non-default boost: assertEquals("\"(multi multi2) foo\"^2.0", qp.Parse("\"multi foo\"^2").toString()); // phrase after changing default slop qp.PhraseSlop=(99); assertEquals("\"(multi multi2) foo\"~99 bar", qp.Parse("\"multi foo\" bar").toString()); assertEquals("\"(multi multi2) foo\"~99 \"foo bar\"~2", qp.Parse("\"multi foo\" \"foo bar\"~2").toString()); qp.PhraseSlop=(0); // non-default operator: qp.DefaultOperator=(QueryParserBase.AND_OPERATOR); assertEquals("+(multi multi2) +foo", qp.Parse("multi foo").toString()); } [Test] public virtual void TestMultiAnalyzerWithSubclassOfQueryParser() { DumbQueryParser qp = new DumbQueryParser("", new MultiAnalyzer()); qp.PhraseSlop = (99); // modified default slop // direct call to (super's) getFieldQuery to demonstrate differnce // between phrase and multiphrase with modified default slop assertEquals("\"foo bar\"~99", qp.GetSuperFieldQuery("", "foo bar", true).toString()); assertEquals("\"(multi multi2) bar\"~99", qp.GetSuperFieldQuery("", "multi bar", true).toString()); // ask sublcass to parse phrase with modified default slop assertEquals("\"(multi multi2) foo\"~99 bar", qp.Parse("\"multi foo\" bar").toString()); } [Test] public virtual void TestPosIncrementAnalyzer() { #pragma warning disable 612, 618 QueryParser qp = new QueryParser(LuceneVersion.LUCENE_40, "", new PosIncrementAnalyzer()); #pragma warning restore 612, 618 assertEquals("quick brown", qp.Parse("the quick brown").toString()); assertEquals("quick brown fox", qp.Parse("the quick brown fox").toString()); } /// <summary> /// Expands "multi" to "multi" and "multi2", both at the same position, /// and expands "triplemulti" to "triplemulti", "multi3", and "multi2". /// </summary> private class MultiAnalyzer : Analyzer { protected internal override TokenStreamComponents CreateComponents(string fieldName, System.IO.TextReader reader) { Tokenizer result = new MockTokenizer(reader, MockTokenizer.WHITESPACE, true); return new TokenStreamComponents(result, new TestFilter(result)); } } private sealed class TestFilter : TokenFilter { private string prevType; private int prevStartOffset; private int prevEndOffset; private readonly ICharTermAttribute termAtt; private readonly IPositionIncrementAttribute posIncrAtt; private readonly IOffsetAttribute offsetAtt; private readonly ITypeAttribute typeAtt; public TestFilter(TokenStream @in) : base(@in) { termAtt = AddAttribute<ICharTermAttribute>(); posIncrAtt = AddAttribute<IPositionIncrementAttribute>(); offsetAtt = AddAttribute<IOffsetAttribute>(); typeAtt = AddAttribute<ITypeAttribute>(); } public override sealed bool IncrementToken() { if (multiToken > 0) { termAtt.SetEmpty().Append("multi" + (multiToken + 1)); offsetAtt.SetOffset(prevStartOffset, prevEndOffset); typeAtt.Type = (prevType); posIncrAtt.PositionIncrement = (0); multiToken--; return true; } else { bool next = m_input.IncrementToken(); if (!next) { return false; } prevType = typeAtt.Type; prevStartOffset = offsetAtt.StartOffset; prevEndOffset = offsetAtt.EndOffset; string text = termAtt.toString(); if (text.Equals("triplemulti", StringComparison.Ordinal)) { multiToken = 2; return true; } else if (text.Equals("multi", StringComparison.Ordinal)) { multiToken = 1; return true; } else { return true; } } } public override void Reset() { base.Reset(); this.prevType = null; this.prevStartOffset = 0; this.prevEndOffset = 0; } } /// <summary> /// Analyzes "the quick brown" as: quick(incr=2) brown(incr=1). /// Does not work correctly for input other than "the quick brown ...". /// </summary> private class PosIncrementAnalyzer : Analyzer { protected internal override TokenStreamComponents CreateComponents(string fieldName, System.IO.TextReader reader) { Tokenizer result = new MockTokenizer(reader, MockTokenizer.WHITESPACE, true); return new TokenStreamComponents(result, new TestPosIncrementFilter(result)); } } private sealed class TestPosIncrementFilter : TokenFilter { ICharTermAttribute termAtt; IPositionIncrementAttribute posIncrAtt; public TestPosIncrementFilter(TokenStream @in) : base(@in) { termAtt = AddAttribute<ICharTermAttribute>(); posIncrAtt = AddAttribute<IPositionIncrementAttribute>(); } public override sealed bool IncrementToken() { while (m_input.IncrementToken()) { if (termAtt.toString().Equals("the", StringComparison.Ordinal)) { // stopword, do nothing } else if (termAtt.toString().Equals("quick", StringComparison.Ordinal)) { posIncrAtt.PositionIncrement = (2); return true; } else { posIncrAtt.PositionIncrement = (1); return true; } } return false; } } /// <summary> /// a very simple subclass of QueryParser /// </summary> private sealed class DumbQueryParser : QueryParser { public DumbQueryParser(string f, Analyzer a) : base(TEST_VERSION_CURRENT, f, a) { } // expose super's version public Query GetSuperFieldQuery(string f, string t, bool quoted) { return base.GetFieldQuery(f, t, quoted); } // wrap super's version protected internal override Query GetFieldQuery(string field, string queryText, bool quoted) { return new DumbQueryWrapper(GetSuperFieldQuery(field, queryText, quoted)); } } /// <summary> /// A very simple wrapper to prevent instanceof checks but uses /// the toString of the query it wraps. /// </summary> private sealed class DumbQueryWrapper : Query { private Query q; public DumbQueryWrapper(Query q) { this.q = q; } public override string ToString(string field) { return q.ToString(field); } } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * 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 OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules { public class CloudModule : ICloudModule { // private static readonly log4net.ILog m_log // = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private uint m_frame = 0; private int m_frameUpdateRate = 1000; private Random m_rndnums = new Random(Environment.TickCount); private Scene m_scene = null; private bool m_ready = false; private bool m_enabled = false; private float m_cloudDensity = 1.0F; private float[] cloudCover = new float[16 * 16]; public void Initialise(Scene scene, IConfigSource config) { IConfig cloudConfig = config.Configs["Cloud"]; if (cloudConfig != null) { m_enabled = cloudConfig.GetBoolean("enabled", false); m_cloudDensity = cloudConfig.GetFloat("density", 0.5F); m_frameUpdateRate = cloudConfig.GetInt("cloud_update_rate", 1000); } if (m_enabled) { m_scene = scene; scene.EventManager.OnNewClient += CloudsToClient; scene.RegisterModuleInterface<ICloudModule>(this); scene.EventManager.OnFrame += CloudUpdate; GenerateCloudCover(); m_ready = true; } } public void PostInitialise() { } public void Close() { if (m_enabled) { m_ready = false; // Remove our hooks m_scene.EventManager.OnNewClient -= CloudsToClient; m_scene.EventManager.OnFrame -= CloudUpdate; } } public string Name { get { return "CloudModule"; } } public bool IsSharedModule { get { return false; } } public float CloudCover(int x, int y, int z) { float cover = 0f; x /= 16; y /= 16; if (x < 0) x = 0; if (x > 15) x = 15; if (y < 0) y = 0; if (y > 15) y = 15; if (cloudCover != null) { cover = cloudCover[y * 16 + x]; } return cover; } private void UpdateCloudCover() { float[] newCover = new float[16 * 16]; int rowAbove = new int(); int rowBelow = new int(); int columnLeft = new int(); int columnRight = new int(); for (int x = 0; x < 16; x++) { if (x == 0) { columnRight = x + 1; columnLeft = 15; } else if (x == 15) { columnRight = 0; columnLeft = x - 1; } else { columnRight = x + 1; columnLeft = x - 1; } for (int y = 0; y< 16; y++) { if (y == 0) { rowAbove = y + 1; rowBelow = 15; } else if (y == 15) { rowAbove = 0; rowBelow = y - 1; } else { rowAbove = y + 1; rowBelow = y - 1; } float neighborAverage = (cloudCover[rowBelow * 16 + columnLeft] + cloudCover[y * 16 + columnLeft] + cloudCover[rowAbove * 16 + columnLeft] + cloudCover[rowBelow * 16 + x] + cloudCover[rowAbove * 16 + x] + cloudCover[rowBelow * 16 + columnRight] + cloudCover[y * 16 + columnRight] + cloudCover[rowAbove * 16 + columnRight] + cloudCover[y * 16 + x]) / 9; newCover[y * 16 + x] = ((neighborAverage / m_cloudDensity) + 0.175f) % 1.0f; newCover[y * 16 + x] *= m_cloudDensity; } } Array.Copy(newCover, cloudCover, 16 * 16); } private void CloudUpdate() { if (((m_frame++ % m_frameUpdateRate) != 0) || !m_ready || (m_cloudDensity == 0)) { return; } UpdateCloudCover(); } public void CloudsToClient(IClientAPI client) { if (m_ready) { client.SendCloudData(cloudCover); } } /// <summary> /// Calculate the cloud cover over the region. /// </summary> private void GenerateCloudCover() { for (int y = 0; y < 16; y++) { for (int x = 0; x < 16; x++) { cloudCover[y * 16 + x] = (float)(m_rndnums.NextDouble()); // 0 to 1 cloudCover[y * 16 + x] *= m_cloudDensity; } } } } }
#region Copyright //////////////////////////////////////////////////////////////////////////////// // The following FIT Protocol software provided may be used with FIT protocol // devices only and remains the copyrighted property of Dynastream Innovations Inc. // The software is being provided on an "as-is" basis and as an accommodation, // and therefore all warranties, representations, or guarantees of any kind // (whether express, implied or statutory) including, without limitation, // warranties of merchantability, non-infringement, or fitness for a particular // purpose, are specifically disclaimed. // // Copyright 2014 Dynastream Innovations Inc. //////////////////////////////////////////////////////////////////////////////// // ****WARNING**** This file is auto-generated! Do NOT edit this file. // Profile Version = 12.20Release // Tag = $Name$ //////////////////////////////////////////////////////////////////////////////// #endregion namespace FitFilePreviewer.Decode.Fit.Mesgs { /// <summary> /// Implements the WorkoutStep profile message. /// </summary> public class WorkoutStepMesg : Mesg { #region Fields static class DurationValueSubfield { public static ushort DurationTime = 0; public static ushort DurationDistance = 1; public static ushort DurationHr = 2; public static ushort DurationCalories = 3; public static ushort DurationStep = 4; public static ushort DurationPower = 5; public static ushort Subfields = 6; public static ushort Active = Fit.SubfieldIndexActiveSubfield; public static ushort MainField = Fit.SubfieldIndexMainField; } static class TargetValueSubfield { public static ushort TargetHrZone = 0; public static ushort TargetPowerZone = 1; public static ushort RepeatSteps = 2; public static ushort RepeatTime = 3; public static ushort RepeatDistance = 4; public static ushort RepeatCalories = 5; public static ushort RepeatHr = 6; public static ushort RepeatPower = 7; public static ushort Subfields = 8; public static ushort Active = Fit.SubfieldIndexActiveSubfield; public static ushort MainField = Fit.SubfieldIndexMainField; } static class CustomTargetValueLowSubfield { public static ushort CustomTargetSpeedLow = 0; public static ushort CustomTargetHeartRateLow = 1; public static ushort CustomTargetCadenceLow = 2; public static ushort CustomTargetPowerLow = 3; public static ushort Subfields = 4; public static ushort Active = Fit.SubfieldIndexActiveSubfield; public static ushort MainField = Fit.SubfieldIndexMainField; } static class CustomTargetValueHighSubfield { public static ushort CustomTargetSpeedHigh = 0; public static ushort CustomTargetHeartRateHigh = 1; public static ushort CustomTargetCadenceHigh = 2; public static ushort CustomTargetPowerHigh = 3; public static ushort Subfields = 4; public static ushort Active = Fit.SubfieldIndexActiveSubfield; public static ushort MainField = Fit.SubfieldIndexMainField; } #endregion #region Constructors public WorkoutStepMesg() : base((Mesg) Profile.mesgs[Profile.WorkoutStepIndex]) { } public WorkoutStepMesg(Mesg mesg) : base(mesg) { } #endregion // Constructors #region Methods ///<summary> /// Retrieves the MessageIndex field</summary> /// <returns>Returns nullable ushort representing the MessageIndex field</returns> public ushort? GetMessageIndex() { return (ushort?)GetFieldValue(254, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set MessageIndex field</summary> /// <param name="messageIndex_">Nullable field value to be set</param> public void SetMessageIndex(ushort? messageIndex_) { SetFieldValue(254, 0, messageIndex_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the WktStepName field</summary> /// <returns>Returns byte[] representing the WktStepName field</returns> public byte[] GetWktStepName() { return (byte[])GetFieldValue(0, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set WktStepName field</summary> /// <param name="wktStepName_">field value to be set</param> public void SetWktStepName(byte[] wktStepName_) { SetFieldValue(0, 0, wktStepName_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the DurationType field</summary> /// <returns>Returns nullable WktStepDuration enum representing the DurationType field</returns> public Types.WktStepDuration? GetDurationType() { object obj = GetFieldValue(1, 0, Fit.SubfieldIndexMainField); Types.WktStepDuration? value = obj == null ? (Types.WktStepDuration?)null : (Types.WktStepDuration)obj; return value; } /// <summary> /// Set DurationType field</summary> /// <param name="durationType_">Nullable field value to be set</param> public void SetDurationType(Types.WktStepDuration? durationType_) { SetFieldValue(1, 0, durationType_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the DurationValue field</summary> /// <returns>Returns nullable uint representing the DurationValue field</returns> public uint? GetDurationValue() { return (uint?)GetFieldValue(2, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set DurationValue field</summary> /// <param name="durationValue_">Nullable field value to be set</param> public void SetDurationValue(uint? durationValue_) { SetFieldValue(2, 0, durationValue_, Fit.SubfieldIndexMainField); } /// <summary> /// Retrieves the DurationTime subfield /// Units: s</summary> /// <returns>Nullable float representing the DurationTime subfield</returns> public float? GetDurationTime() { return (float?)GetFieldValue(2, 0, DurationValueSubfield.DurationTime); } /// <summary> /// /// Set DurationTime subfield /// Units: s</summary> /// <param name="durationTime">Subfield value to be set</param> public void SetDurationTime(float? durationTime) { SetFieldValue(2, 0, durationTime, DurationValueSubfield.DurationTime); } /// <summary> /// Retrieves the DurationDistance subfield /// Units: m</summary> /// <returns>Nullable float representing the DurationDistance subfield</returns> public float? GetDurationDistance() { return (float?)GetFieldValue(2, 0, DurationValueSubfield.DurationDistance); } /// <summary> /// /// Set DurationDistance subfield /// Units: m</summary> /// <param name="durationDistance">Subfield value to be set</param> public void SetDurationDistance(float? durationDistance) { SetFieldValue(2, 0, durationDistance, DurationValueSubfield.DurationDistance); } /// <summary> /// Retrieves the DurationHr subfield /// Units: % or bpm</summary> /// <returns>Nullable uint representing the DurationHr subfield</returns> public uint? GetDurationHr() { return (uint?)GetFieldValue(2, 0, DurationValueSubfield.DurationHr); } /// <summary> /// /// Set DurationHr subfield /// Units: % or bpm</summary> /// <param name="durationHr">Subfield value to be set</param> public void SetDurationHr(uint? durationHr) { SetFieldValue(2, 0, durationHr, DurationValueSubfield.DurationHr); } /// <summary> /// Retrieves the DurationCalories subfield /// Units: calories</summary> /// <returns>Nullable uint representing the DurationCalories subfield</returns> public uint? GetDurationCalories() { return (uint?)GetFieldValue(2, 0, DurationValueSubfield.DurationCalories); } /// <summary> /// /// Set DurationCalories subfield /// Units: calories</summary> /// <param name="durationCalories">Subfield value to be set</param> public void SetDurationCalories(uint? durationCalories) { SetFieldValue(2, 0, durationCalories, DurationValueSubfield.DurationCalories); } /// <summary> /// Retrieves the DurationStep subfield /// Comment: message_index of step to loop back to. Steps are assumed to be in the order by message_index. custom_name and intensity members are undefined for this duration type.</summary> /// <returns>Nullable uint representing the DurationStep subfield</returns> public uint? GetDurationStep() { return (uint?)GetFieldValue(2, 0, DurationValueSubfield.DurationStep); } /// <summary> /// /// Set DurationStep subfield /// Comment: message_index of step to loop back to. Steps are assumed to be in the order by message_index. custom_name and intensity members are undefined for this duration type.</summary> /// <param name="durationStep">Subfield value to be set</param> public void SetDurationStep(uint? durationStep) { SetFieldValue(2, 0, durationStep, DurationValueSubfield.DurationStep); } /// <summary> /// Retrieves the DurationPower subfield /// Units: % or watts</summary> /// <returns>Nullable uint representing the DurationPower subfield</returns> public uint? GetDurationPower() { return (uint?)GetFieldValue(2, 0, DurationValueSubfield.DurationPower); } /// <summary> /// /// Set DurationPower subfield /// Units: % or watts</summary> /// <param name="durationPower">Subfield value to be set</param> public void SetDurationPower(uint? durationPower) { SetFieldValue(2, 0, durationPower, DurationValueSubfield.DurationPower); } ///<summary> /// Retrieves the TargetType field</summary> /// <returns>Returns nullable WktStepTarget enum representing the TargetType field</returns> public Types.WktStepTarget? GetTargetType() { object obj = GetFieldValue(3, 0, Fit.SubfieldIndexMainField); Types.WktStepTarget? value = obj == null ? (Types.WktStepTarget?)null : (Types.WktStepTarget)obj; return value; } /// <summary> /// Set TargetType field</summary> /// <param name="targetType_">Nullable field value to be set</param> public void SetTargetType(Types.WktStepTarget? targetType_) { SetFieldValue(3, 0, targetType_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the TargetValue field</summary> /// <returns>Returns nullable uint representing the TargetValue field</returns> public uint? GetTargetValue() { return (uint?)GetFieldValue(4, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set TargetValue field</summary> /// <param name="targetValue_">Nullable field value to be set</param> public void SetTargetValue(uint? targetValue_) { SetFieldValue(4, 0, targetValue_, Fit.SubfieldIndexMainField); } /// <summary> /// Retrieves the TargetHrZone subfield /// Comment: hr zone (1-5);Custom =0;</summary> /// <returns>Nullable uint representing the TargetHrZone subfield</returns> public uint? GetTargetHrZone() { return (uint?)GetFieldValue(4, 0, TargetValueSubfield.TargetHrZone); } /// <summary> /// /// Set TargetHrZone subfield /// Comment: hr zone (1-5);Custom =0;</summary> /// <param name="targetHrZone">Subfield value to be set</param> public void SetTargetHrZone(uint? targetHrZone) { SetFieldValue(4, 0, targetHrZone, TargetValueSubfield.TargetHrZone); } /// <summary> /// Retrieves the TargetPowerZone subfield /// Comment: Power Zone ( 1-7); Custom = 0;</summary> /// <returns>Nullable uint representing the TargetPowerZone subfield</returns> public uint? GetTargetPowerZone() { return (uint?)GetFieldValue(4, 0, TargetValueSubfield.TargetPowerZone); } /// <summary> /// /// Set TargetPowerZone subfield /// Comment: Power Zone ( 1-7); Custom = 0;</summary> /// <param name="targetPowerZone">Subfield value to be set</param> public void SetTargetPowerZone(uint? targetPowerZone) { SetFieldValue(4, 0, targetPowerZone, TargetValueSubfield.TargetPowerZone); } /// <summary> /// Retrieves the RepeatSteps subfield /// Comment: # of repetitions</summary> /// <returns>Nullable uint representing the RepeatSteps subfield</returns> public uint? GetRepeatSteps() { return (uint?)GetFieldValue(4, 0, TargetValueSubfield.RepeatSteps); } /// <summary> /// /// Set RepeatSteps subfield /// Comment: # of repetitions</summary> /// <param name="repeatSteps">Subfield value to be set</param> public void SetRepeatSteps(uint? repeatSteps) { SetFieldValue(4, 0, repeatSteps, TargetValueSubfield.RepeatSteps); } /// <summary> /// Retrieves the RepeatTime subfield /// Units: s</summary> /// <returns>Nullable float representing the RepeatTime subfield</returns> public float? GetRepeatTime() { return (float?)GetFieldValue(4, 0, TargetValueSubfield.RepeatTime); } /// <summary> /// /// Set RepeatTime subfield /// Units: s</summary> /// <param name="repeatTime">Subfield value to be set</param> public void SetRepeatTime(float? repeatTime) { SetFieldValue(4, 0, repeatTime, TargetValueSubfield.RepeatTime); } /// <summary> /// Retrieves the RepeatDistance subfield /// Units: m</summary> /// <returns>Nullable float representing the RepeatDistance subfield</returns> public float? GetRepeatDistance() { return (float?)GetFieldValue(4, 0, TargetValueSubfield.RepeatDistance); } /// <summary> /// /// Set RepeatDistance subfield /// Units: m</summary> /// <param name="repeatDistance">Subfield value to be set</param> public void SetRepeatDistance(float? repeatDistance) { SetFieldValue(4, 0, repeatDistance, TargetValueSubfield.RepeatDistance); } /// <summary> /// Retrieves the RepeatCalories subfield /// Units: calories</summary> /// <returns>Nullable uint representing the RepeatCalories subfield</returns> public uint? GetRepeatCalories() { return (uint?)GetFieldValue(4, 0, TargetValueSubfield.RepeatCalories); } /// <summary> /// /// Set RepeatCalories subfield /// Units: calories</summary> /// <param name="repeatCalories">Subfield value to be set</param> public void SetRepeatCalories(uint? repeatCalories) { SetFieldValue(4, 0, repeatCalories, TargetValueSubfield.RepeatCalories); } /// <summary> /// Retrieves the RepeatHr subfield /// Units: % or bpm</summary> /// <returns>Nullable uint representing the RepeatHr subfield</returns> public uint? GetRepeatHr() { return (uint?)GetFieldValue(4, 0, TargetValueSubfield.RepeatHr); } /// <summary> /// /// Set RepeatHr subfield /// Units: % or bpm</summary> /// <param name="repeatHr">Subfield value to be set</param> public void SetRepeatHr(uint? repeatHr) { SetFieldValue(4, 0, repeatHr, TargetValueSubfield.RepeatHr); } /// <summary> /// Retrieves the RepeatPower subfield /// Units: % or watts</summary> /// <returns>Nullable uint representing the RepeatPower subfield</returns> public uint? GetRepeatPower() { return (uint?)GetFieldValue(4, 0, TargetValueSubfield.RepeatPower); } /// <summary> /// /// Set RepeatPower subfield /// Units: % or watts</summary> /// <param name="repeatPower">Subfield value to be set</param> public void SetRepeatPower(uint? repeatPower) { SetFieldValue(4, 0, repeatPower, TargetValueSubfield.RepeatPower); } ///<summary> /// Retrieves the CustomTargetValueLow field</summary> /// <returns>Returns nullable uint representing the CustomTargetValueLow field</returns> public uint? GetCustomTargetValueLow() { return (uint?)GetFieldValue(5, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set CustomTargetValueLow field</summary> /// <param name="customTargetValueLow_">Nullable field value to be set</param> public void SetCustomTargetValueLow(uint? customTargetValueLow_) { SetFieldValue(5, 0, customTargetValueLow_, Fit.SubfieldIndexMainField); } /// <summary> /// Retrieves the CustomTargetSpeedLow subfield /// Units: m/s</summary> /// <returns>Nullable float representing the CustomTargetSpeedLow subfield</returns> public float? GetCustomTargetSpeedLow() { return (float?)GetFieldValue(5, 0, CustomTargetValueLowSubfield.CustomTargetSpeedLow); } /// <summary> /// /// Set CustomTargetSpeedLow subfield /// Units: m/s</summary> /// <param name="customTargetSpeedLow">Subfield value to be set</param> public void SetCustomTargetSpeedLow(float? customTargetSpeedLow) { SetFieldValue(5, 0, customTargetSpeedLow, CustomTargetValueLowSubfield.CustomTargetSpeedLow); } /// <summary> /// Retrieves the CustomTargetHeartRateLow subfield /// Units: % or bpm</summary> /// <returns>Nullable uint representing the CustomTargetHeartRateLow subfield</returns> public uint? GetCustomTargetHeartRateLow() { return (uint?)GetFieldValue(5, 0, CustomTargetValueLowSubfield.CustomTargetHeartRateLow); } /// <summary> /// /// Set CustomTargetHeartRateLow subfield /// Units: % or bpm</summary> /// <param name="customTargetHeartRateLow">Subfield value to be set</param> public void SetCustomTargetHeartRateLow(uint? customTargetHeartRateLow) { SetFieldValue(5, 0, customTargetHeartRateLow, CustomTargetValueLowSubfield.CustomTargetHeartRateLow); } /// <summary> /// Retrieves the CustomTargetCadenceLow subfield /// Units: rpm</summary> /// <returns>Nullable uint representing the CustomTargetCadenceLow subfield</returns> public uint? GetCustomTargetCadenceLow() { return (uint?)GetFieldValue(5, 0, CustomTargetValueLowSubfield.CustomTargetCadenceLow); } /// <summary> /// /// Set CustomTargetCadenceLow subfield /// Units: rpm</summary> /// <param name="customTargetCadenceLow">Subfield value to be set</param> public void SetCustomTargetCadenceLow(uint? customTargetCadenceLow) { SetFieldValue(5, 0, customTargetCadenceLow, CustomTargetValueLowSubfield.CustomTargetCadenceLow); } /// <summary> /// Retrieves the CustomTargetPowerLow subfield /// Units: % or watts</summary> /// <returns>Nullable uint representing the CustomTargetPowerLow subfield</returns> public uint? GetCustomTargetPowerLow() { return (uint?)GetFieldValue(5, 0, CustomTargetValueLowSubfield.CustomTargetPowerLow); } /// <summary> /// /// Set CustomTargetPowerLow subfield /// Units: % or watts</summary> /// <param name="customTargetPowerLow">Subfield value to be set</param> public void SetCustomTargetPowerLow(uint? customTargetPowerLow) { SetFieldValue(5, 0, customTargetPowerLow, CustomTargetValueLowSubfield.CustomTargetPowerLow); } ///<summary> /// Retrieves the CustomTargetValueHigh field</summary> /// <returns>Returns nullable uint representing the CustomTargetValueHigh field</returns> public uint? GetCustomTargetValueHigh() { return (uint?)GetFieldValue(6, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set CustomTargetValueHigh field</summary> /// <param name="customTargetValueHigh_">Nullable field value to be set</param> public void SetCustomTargetValueHigh(uint? customTargetValueHigh_) { SetFieldValue(6, 0, customTargetValueHigh_, Fit.SubfieldIndexMainField); } /// <summary> /// Retrieves the CustomTargetSpeedHigh subfield /// Units: m/s</summary> /// <returns>Nullable float representing the CustomTargetSpeedHigh subfield</returns> public float? GetCustomTargetSpeedHigh() { return (float?)GetFieldValue(6, 0, CustomTargetValueHighSubfield.CustomTargetSpeedHigh); } /// <summary> /// /// Set CustomTargetSpeedHigh subfield /// Units: m/s</summary> /// <param name="customTargetSpeedHigh">Subfield value to be set</param> public void SetCustomTargetSpeedHigh(float? customTargetSpeedHigh) { SetFieldValue(6, 0, customTargetSpeedHigh, CustomTargetValueHighSubfield.CustomTargetSpeedHigh); } /// <summary> /// Retrieves the CustomTargetHeartRateHigh subfield /// Units: % or bpm</summary> /// <returns>Nullable uint representing the CustomTargetHeartRateHigh subfield</returns> public uint? GetCustomTargetHeartRateHigh() { return (uint?)GetFieldValue(6, 0, CustomTargetValueHighSubfield.CustomTargetHeartRateHigh); } /// <summary> /// /// Set CustomTargetHeartRateHigh subfield /// Units: % or bpm</summary> /// <param name="customTargetHeartRateHigh">Subfield value to be set</param> public void SetCustomTargetHeartRateHigh(uint? customTargetHeartRateHigh) { SetFieldValue(6, 0, customTargetHeartRateHigh, CustomTargetValueHighSubfield.CustomTargetHeartRateHigh); } /// <summary> /// Retrieves the CustomTargetCadenceHigh subfield /// Units: rpm</summary> /// <returns>Nullable uint representing the CustomTargetCadenceHigh subfield</returns> public uint? GetCustomTargetCadenceHigh() { return (uint?)GetFieldValue(6, 0, CustomTargetValueHighSubfield.CustomTargetCadenceHigh); } /// <summary> /// /// Set CustomTargetCadenceHigh subfield /// Units: rpm</summary> /// <param name="customTargetCadenceHigh">Subfield value to be set</param> public void SetCustomTargetCadenceHigh(uint? customTargetCadenceHigh) { SetFieldValue(6, 0, customTargetCadenceHigh, CustomTargetValueHighSubfield.CustomTargetCadenceHigh); } /// <summary> /// Retrieves the CustomTargetPowerHigh subfield /// Units: % or watts</summary> /// <returns>Nullable uint representing the CustomTargetPowerHigh subfield</returns> public uint? GetCustomTargetPowerHigh() { return (uint?)GetFieldValue(6, 0, CustomTargetValueHighSubfield.CustomTargetPowerHigh); } /// <summary> /// /// Set CustomTargetPowerHigh subfield /// Units: % or watts</summary> /// <param name="customTargetPowerHigh">Subfield value to be set</param> public void SetCustomTargetPowerHigh(uint? customTargetPowerHigh) { SetFieldValue(6, 0, customTargetPowerHigh, CustomTargetValueHighSubfield.CustomTargetPowerHigh); } ///<summary> /// Retrieves the Intensity field</summary> /// <returns>Returns nullable Intensity enum representing the Intensity field</returns> public Types.Intensity? GetIntensity() { object obj = GetFieldValue(7, 0, Fit.SubfieldIndexMainField); Types.Intensity? value = obj == null ? (Types.Intensity?)null : (Types.Intensity)obj; return value; } /// <summary> /// Set Intensity field</summary> /// <param name="intensity_">Nullable field value to be set</param> public void SetIntensity(Types.Intensity? intensity_) { SetFieldValue(7, 0, intensity_, Fit.SubfieldIndexMainField); } #endregion // Methods } // Class } // namespace
#region Apache License // // 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. // #endregion using System; using System.Globalization; using log4net.Core; using log4net.Repository; using log4net.Util; namespace log4net.Ext.MarshalByRef { /// <summary> /// Marshal By Reference implementation of <see cref="ILog"/> /// </summary> /// <remarks> /// <para> /// Logger wrapper that is <see cref="MarshalByRefObject"/>. These objects /// can be passed by reference across a remoting boundary. /// </para> /// </remarks> public sealed class MarshalByRefLogImpl : MarshalByRefObject, ILog { private readonly static Type ThisDeclaringType = typeof(MarshalByRefLogImpl); private readonly ILogger m_logger; private Level m_levelTrace; private Level m_levelDebug; private Level m_levelInfo; private Level m_levelWarn; private Level m_levelError; private Level m_levelFatal; #region Public Instance Constructors public MarshalByRefLogImpl(ILogger logger) { m_logger = logger; // Listen for changes to the repository logger.Repository.ConfigurationChanged += new LoggerRepositoryConfigurationChangedEventHandler(LoggerRepositoryConfigurationChanged); // load the current levels ReloadLevels(logger.Repository); } #endregion Public Instance Constructors private void ReloadLevels(ILoggerRepository repository) { LevelMap levelMap = repository.LevelMap; m_levelTrace = levelMap.LookupWithDefault(Level.Trace); m_levelDebug = levelMap.LookupWithDefault(Level.Debug); m_levelInfo = levelMap.LookupWithDefault(Level.Info); m_levelWarn = levelMap.LookupWithDefault(Level.Warn); m_levelError = levelMap.LookupWithDefault(Level.Error); m_levelFatal = levelMap.LookupWithDefault(Level.Fatal); } private void LoggerRepositoryConfigurationChanged(object sender, EventArgs e) { ILoggerRepository repository = sender as ILoggerRepository; if (repository != null) { ReloadLevels(repository); } } #region Implementation of ILog public void Trace(object message) { Logger.Log(ThisDeclaringType, m_levelTrace, message, null); } public void Trace(object message, Exception t) { Logger.Log(ThisDeclaringType, m_levelTrace, message, t); } public void TraceFormat(string format, params object[] args) { if (IsTraceEnabled) { Logger.Log(ThisDeclaringType, m_levelTrace, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null); } } public void TraceFormat(string format, object arg0) { if (IsTraceEnabled) { Logger.Log(ThisDeclaringType, m_levelTrace, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null); } } public void TraceFormat(string format, object arg0, object arg1) { if (IsTraceEnabled) { Logger.Log(ThisDeclaringType, m_levelTrace, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null); } } public void TraceFormat(string format, object arg0, object arg1, object arg2) { if (IsTraceEnabled) { Logger.Log(ThisDeclaringType, m_levelTrace, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null); } } public void TraceFormat(IFormatProvider provider, string format, params object[] args) { if (IsTraceEnabled) { Logger.Log(ThisDeclaringType, m_levelTrace, new SystemStringFormat(provider, format, args), null); } } public void Debug(object message) { Logger.Log(ThisDeclaringType, m_levelDebug, message, null); } public void Debug(object message, Exception t) { Logger.Log(ThisDeclaringType, m_levelDebug, message, t); } public void DebugFormat(string format, params object[] args) { if (IsDebugEnabled) { Logger.Log(ThisDeclaringType, m_levelDebug, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null); } } public void DebugFormat(string format, object arg0) { if (IsDebugEnabled) { Logger.Log(ThisDeclaringType, m_levelDebug, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null); } } public void DebugFormat(string format, object arg0, object arg1) { if (IsDebugEnabled) { Logger.Log(ThisDeclaringType, m_levelDebug, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null); } } public void DebugFormat(string format, object arg0, object arg1, object arg2) { if (IsDebugEnabled) { Logger.Log(ThisDeclaringType, m_levelDebug, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null); } } public void DebugFormat(IFormatProvider provider, string format, params object[] args) { if (IsDebugEnabled) { Logger.Log(ThisDeclaringType, m_levelDebug, new SystemStringFormat(provider, format, args), null); } } public void Info(object message) { Logger.Log(ThisDeclaringType, m_levelInfo, message, null); } public void Info(object message, Exception t) { Logger.Log(ThisDeclaringType, m_levelInfo, message, t); } public void InfoFormat(string format, params object[] args) { if (IsInfoEnabled) { Logger.Log(ThisDeclaringType, m_levelInfo, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null); } } public void InfoFormat(string format, object arg0) { if (IsInfoEnabled) { Logger.Log(ThisDeclaringType, m_levelInfo, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null); } } public void InfoFormat(string format, object arg0, object arg1) { if (IsInfoEnabled) { Logger.Log(ThisDeclaringType, m_levelInfo, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null); } } public void InfoFormat(string format, object arg0, object arg1, object arg2) { if (IsInfoEnabled) { Logger.Log(ThisDeclaringType, m_levelInfo, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null); } } public void InfoFormat(IFormatProvider provider, string format, params object[] args) { if (IsInfoEnabled) { Logger.Log(ThisDeclaringType, m_levelInfo, new SystemStringFormat(provider, format, args), null); } } public void Warn(object message) { Logger.Log(ThisDeclaringType, m_levelWarn, message, null); } public void Warn(object message, Exception t) { Logger.Log(ThisDeclaringType, m_levelWarn, message, t); } public void WarnFormat(string format, params object[] args) { if (IsWarnEnabled) { Logger.Log(ThisDeclaringType, m_levelWarn, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null); } } public void WarnFormat(string format, object arg0) { if (IsWarnEnabled) { Logger.Log(ThisDeclaringType, m_levelWarn, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null); } } public void WarnFormat(string format, object arg0, object arg1) { if (IsWarnEnabled) { Logger.Log(ThisDeclaringType, m_levelWarn, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null); } } public void WarnFormat(string format, object arg0, object arg1, object arg2) { if (IsWarnEnabled) { Logger.Log(ThisDeclaringType, m_levelWarn, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null); } } public void WarnFormat(IFormatProvider provider, string format, params object[] args) { if (IsWarnEnabled) { Logger.Log(ThisDeclaringType, m_levelWarn, new SystemStringFormat(provider, format, args), null); } } public void Error(object message) { Logger.Log(ThisDeclaringType, m_levelError, message, null); } public void Error(object message, Exception t) { Logger.Log(ThisDeclaringType, m_levelError, message, t); } public void ErrorFormat(string format, params object[] args) { if (IsErrorEnabled) { Logger.Log(ThisDeclaringType, m_levelError, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null); } } public void ErrorFormat(string format, object arg0) { if (IsErrorEnabled) { Logger.Log(ThisDeclaringType, m_levelError, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null); } } public void ErrorFormat(string format, object arg0, object arg1) { if (IsErrorEnabled) { Logger.Log(ThisDeclaringType, m_levelError, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null); } } public void ErrorFormat(string format, object arg0, object arg1, object arg2) { if (IsErrorEnabled) { Logger.Log(ThisDeclaringType, m_levelError, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null); } } public void ErrorFormat(IFormatProvider provider, string format, params object[] args) { if (IsErrorEnabled) { Logger.Log(ThisDeclaringType, m_levelError, new SystemStringFormat(provider, format, args), null); } } public void Fatal(object message) { Logger.Log(ThisDeclaringType, m_levelFatal, message, null); } public void Fatal(object message, Exception t) { Logger.Log(ThisDeclaringType, m_levelFatal, message, t); } public void FatalFormat(string format, params object[] args) { if (IsFatalEnabled) { Logger.Log(ThisDeclaringType, m_levelFatal, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null); } } public void FatalFormat(string format, object arg0) { if (IsFatalEnabled) { Logger.Log(ThisDeclaringType, m_levelFatal, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0 }), null); } } public void FatalFormat(string format, object arg0, object arg1) { if (IsFatalEnabled) { Logger.Log(ThisDeclaringType, m_levelFatal, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1 }), null); } } public void FatalFormat(string format, object arg0, object arg1, object arg2) { if (IsFatalEnabled) { Logger.Log(ThisDeclaringType, m_levelFatal, new SystemStringFormat(CultureInfo.InvariantCulture, format, new object[] { arg0, arg1, arg2 }), null); } } public void FatalFormat(IFormatProvider provider, string format, params object[] args) { if (IsFatalEnabled) { Logger.Log(ThisDeclaringType, m_levelFatal, new SystemStringFormat(provider, format, args), null); } } public bool IsTraceEnabled { get { return Logger.IsEnabledFor(m_levelTrace); } } public bool IsDebugEnabled { get { return Logger.IsEnabledFor(m_levelDebug); } } public bool IsInfoEnabled { get { return Logger.IsEnabledFor(m_levelInfo); } } public bool IsWarnEnabled { get { return Logger.IsEnabledFor(m_levelWarn); } } public bool IsErrorEnabled { get { return Logger.IsEnabledFor(m_levelError); } } public bool IsFatalEnabled { get { return Logger.IsEnabledFor(m_levelFatal); } } #endregion Implementation of ILog #region Implementation of ILoggerWrapper public ILogger Logger { get { return m_logger; } } #endregion /// <summary> /// Live forever /// </summary> /// <returns><c>null</c></returns> public override object InitializeLifetimeService() { return null; } } }
// 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.ObjectModel; using System.Collections.Generic; using System.Linq; using System.Runtime.ExceptionServices; using Microsoft.CodeAnalysis.Collections; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Xunit; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { public abstract class ResultProviderTestBase { private readonly IDkmClrFormatter _formatter; private readonly IDkmClrResultProvider _resultProvider; internal readonly DkmInspectionContext DefaultInspectionContext; internal static string GetDynamicDebugViewEmptyMessage() { // Value should not be cached since it depends on the current CultureInfo. var exceptionType = typeof(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException).Assembly.GetType( "Microsoft.CSharp.RuntimeBinder.DynamicMetaObjectProviderDebugView+DynamicDebugViewEmptyException"); var emptyProperty = exceptionType.GetProperty("Empty"); return (string)emptyProperty.GetValue(exceptionType.Instantiate()); } protected ResultProviderTestBase(ResultProvider resultProvider, DkmInspectionContext defaultInspectionContext) { _formatter = resultProvider.Formatter; _resultProvider = resultProvider; this.DefaultInspectionContext = defaultInspectionContext; // We never want to swallow Exceptions (generate a non-fatal Watson) when running tests. ExpressionEvaluatorFatalError.IsFailFastEnabled = true; } internal DkmClrValue CreateDkmClrValue( object value, Type type = null, string alias = null, DkmEvaluationResultFlags evalFlags = DkmEvaluationResultFlags.None, DkmClrValueFlags valueFlags = DkmClrValueFlags.None) { if (type == null) { type = value.GetType(); } return new DkmClrValue( value, DkmClrValue.GetHostObjectValue((TypeImpl)type, value), new DkmClrType((TypeImpl)type), alias, _formatter, evalFlags, valueFlags); } internal DkmClrValue CreateDkmClrValue( object value, DkmClrType type, string alias = null, DkmEvaluationResultFlags evalFlags = DkmEvaluationResultFlags.None, DkmClrValueFlags valueFlags = DkmClrValueFlags.None, ulong nativeComPointer = 0) { return new DkmClrValue( value, DkmClrValue.GetHostObjectValue(type.GetLmrType(), value), type, alias, _formatter, evalFlags, valueFlags, nativeComPointer: nativeComPointer); } internal DkmClrValue CreateErrorValue( DkmClrType type, string message) { return new DkmClrValue( value: null, hostObjectValue: message, type: type, alias: null, formatter: _formatter, evalFlags: DkmEvaluationResultFlags.None, valueFlags: DkmClrValueFlags.Error); } #region Formatter Tests internal string FormatNull<T>(bool useHexadecimal = false) { return FormatValue(null, typeof(T), useHexadecimal); } internal string FormatValue(object value, bool useHexadecimal = false) { return FormatValue(value, value.GetType(), useHexadecimal); } internal string FormatValue(object value, Type type, bool useHexadecimal = false) { var clrValue = CreateDkmClrValue(value, type); var inspectionContext = CreateDkmInspectionContext(_formatter, DkmEvaluationFlags.None, radix: useHexadecimal ? 16u : 10u); return clrValue.GetValueString(inspectionContext, Formatter.NoFormatSpecifiers); } internal bool HasUnderlyingString(object value) { return HasUnderlyingString(value, value.GetType()); } internal bool HasUnderlyingString(object value, Type type) { var clrValue = GetValueForUnderlyingString(value, type); return clrValue.HasUnderlyingString(DefaultInspectionContext); } internal string GetUnderlyingString(object value) { var clrValue = GetValueForUnderlyingString(value, value.GetType()); return clrValue.GetUnderlyingString(DefaultInspectionContext); } internal DkmClrValue GetValueForUnderlyingString(object value, Type type) { return CreateDkmClrValue( value, type, evalFlags: DkmEvaluationResultFlags.RawString); } #endregion #region ResultProvider Tests internal DkmInspectionContext CreateDkmInspectionContext( DkmEvaluationFlags flags = DkmEvaluationFlags.None, uint radix = 10, DkmRuntimeInstance runtimeInstance = null) { return CreateDkmInspectionContext(_formatter, flags, radix, runtimeInstance); } internal static DkmInspectionContext CreateDkmInspectionContext( IDkmClrFormatter formatter, DkmEvaluationFlags flags, uint radix, DkmRuntimeInstance runtimeInstance = null) { return new DkmInspectionContext(formatter, flags, radix, runtimeInstance); } internal DkmEvaluationResult FormatResult(string name, DkmClrValue value, DkmClrType declaredType = null, DkmInspectionContext inspectionContext = null) { return FormatResult(name, name, value, declaredType, inspectionContext: inspectionContext); } internal DkmEvaluationResult FormatResult(string name, string fullName, DkmClrValue value, DkmClrType declaredType = null, bool[] declaredTypeInfo = null, DkmInspectionContext inspectionContext = null) { DkmEvaluationResult evaluationResult = null; var workList = new DkmWorkList(); _resultProvider.GetResult( value, workList, declaredType: declaredType ?? value.Type, customTypeInfo: DynamicFlagsCustomTypeInfo.Create(declaredTypeInfo).GetCustomTypeInfo(), inspectionContext: inspectionContext ?? DefaultInspectionContext, formatSpecifiers: Formatter.NoFormatSpecifiers, resultName: name, resultFullName: null, completionRoutine: asyncResult => evaluationResult = asyncResult.Result); workList.Execute(); return evaluationResult; } internal DkmEvaluationResult[] GetChildren(DkmEvaluationResult evalResult, DkmInspectionContext inspectionContext = null) { DkmEvaluationResultEnumContext enumContext; var builder = ArrayBuilder<DkmEvaluationResult>.GetInstance(); // Request 0-3 children. int size; DkmEvaluationResult[] items; for (size = 0; size < 3; size++) { items = GetChildren(evalResult, size, inspectionContext, out enumContext); var totalChildCount = enumContext.Count; Assert.InRange(totalChildCount, 0, int.MaxValue); var expectedSize = (size < totalChildCount) ? size : totalChildCount; Assert.Equal(expectedSize, items.Length); } // Request items (increasing the size of the request with each iteration). size = 1; items = GetChildren(evalResult, size, inspectionContext, out enumContext); while (items.Length > 0) { builder.AddRange(items); Assert.True(builder.Count <= enumContext.Count); int offset = builder.Count; // Request 0 items. items = GetItems(enumContext, offset, 0); Assert.Equal(items.Length, 0); // Request >0 items. size++; items = GetItems(enumContext, offset, size); } Assert.Equal(builder.Count, enumContext.Count); return builder.ToArrayAndFree(); } internal DkmEvaluationResult[] GetChildren(DkmEvaluationResult evalResult, int initialRequestSize, DkmInspectionContext inspectionContext, out DkmEvaluationResultEnumContext enumContext) { DkmGetChildrenAsyncResult getChildrenResult = default(DkmGetChildrenAsyncResult); var workList = new DkmWorkList(); _resultProvider.GetChildren(evalResult, workList, initialRequestSize, inspectionContext ?? DefaultInspectionContext, r => { getChildrenResult = r; }); workList.Execute(); var exception = getChildrenResult.Exception; if (exception != null) { ExceptionDispatchInfo.Capture(exception).Throw(); } enumContext = getChildrenResult.EnumContext; return getChildrenResult.InitialChildren; } internal DkmEvaluationResult[] GetItems(DkmEvaluationResultEnumContext enumContext, int startIndex, int count) { DkmEvaluationEnumAsyncResult getItemsResult = default(DkmEvaluationEnumAsyncResult); var workList = new DkmWorkList(); _resultProvider.GetItems(enumContext, workList, startIndex, count, r => { getItemsResult = r; }); workList.Execute(); var exception = getItemsResult.Exception; if (exception != null) { ExceptionDispatchInfo.Capture(exception).Throw(); } return getItemsResult.Items; } private const DkmEvaluationResultCategory UnspecifiedCategory = (DkmEvaluationResultCategory)(-1); private const DkmEvaluationResultAccessType UnspecifiedAccessType = (DkmEvaluationResultAccessType)(-1); internal static DkmEvaluationResult EvalResult( string name, string value, string type, string fullName, DkmEvaluationResultFlags flags = DkmEvaluationResultFlags.None, DkmEvaluationResultCategory category = UnspecifiedCategory, DkmEvaluationResultAccessType access = UnspecifiedAccessType, string editableValue = null, DkmCustomUIVisualizerInfo[] customUIVisualizerInfo = null) { return DkmSuccessEvaluationResult.Create( null, null, name, fullName, flags, value, editableValue, type, category, access, default(DkmEvaluationResultStorageType), default(DkmEvaluationResultTypeModifierFlags), null, (customUIVisualizerInfo != null) ? new ReadOnlyCollection<DkmCustomUIVisualizerInfo>(customUIVisualizerInfo) : null, null, null); } internal static DkmIntermediateEvaluationResult EvalIntermediateResult( string name, string fullName, string expression, DkmLanguage language) { return DkmIntermediateEvaluationResult.Create( InspectionContext: null, StackFrame: null, Name: name, FullName: fullName, Expression: expression, IntermediateLanguage: language, TargetRuntime: null, DataItem: null); } internal static DkmEvaluationResult EvalFailedResult( string name, string message, string type = null, string fullName = null, DkmEvaluationResultFlags flags = DkmEvaluationResultFlags.None) { return DkmFailedEvaluationResult.Create( null, null, name, fullName, message, flags, type, null); } internal static void Verify(IReadOnlyList<DkmEvaluationResult> actual, params DkmEvaluationResult[] expected) { try { int n = actual.Count; Assert.Equal(expected.Length, n); for (int i = 0; i < n; i++) { Verify(actual[i], expected[i]); } } catch { foreach (var result in actual) { Console.WriteLine("{0}, ", ToString(result)); } throw; } } private static string ToString(DkmEvaluationResult result) { var success = result as DkmSuccessEvaluationResult; if (success != null) return ToString(success); var intermediate = result as DkmIntermediateEvaluationResult; if (intermediate != null) return ToString(intermediate); return ToString((DkmFailedEvaluationResult)result); } private static string ToString(DkmSuccessEvaluationResult result) { var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append("EvalResult("); builder.Append(Quote(result.Name)); builder.Append(", "); builder.Append((result.Value == null) ? "null" : Quote(Escape(result.Value))); builder.Append(", "); builder.Append(Quote(result.Type)); builder.Append(", "); builder.Append((result.FullName != null) ? Quote(Escape(result.FullName)) : "null"); if (result.Flags != DkmEvaluationResultFlags.None) { builder.Append(", "); builder.Append(FormatEnumValue(result.Flags)); } if (result.Category != DkmEvaluationResultCategory.Other) { builder.Append(", "); builder.Append(FormatEnumValue(result.Category)); } if (result.Access != DkmEvaluationResultAccessType.None) { builder.Append(", "); builder.Append(FormatEnumValue(result.Access)); } if (result.EditableValue != null) { builder.Append(", "); builder.Append(Quote(result.EditableValue)); } builder.Append(")"); return pooledBuilder.ToStringAndFree(); } private static string ToString(DkmIntermediateEvaluationResult result) { var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append("IntermediateEvalResult("); builder.Append(Quote(result.Name)); builder.Append(", "); builder.Append(Quote(result.Expression)); if (result.Type != null) { builder.Append(", "); builder.Append(Quote(result.Type)); } if (result.FullName != null) { builder.Append(", "); builder.Append(Quote(Escape(result.FullName))); } if (result.Flags != DkmEvaluationResultFlags.None) { builder.Append(", "); builder.Append(FormatEnumValue(result.Flags)); } builder.Append(")"); return pooledBuilder.ToStringAndFree(); } private static string ToString(DkmFailedEvaluationResult result) { var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append("EvalFailedResult("); builder.Append(Quote(result.Name)); builder.Append(", "); builder.Append(Quote(result.ErrorMessage)); if (result.Type != null) { builder.Append(", "); builder.Append(Quote(result.Type)); } if (result.FullName != null) { builder.Append(", "); builder.Append(Quote(Escape(result.FullName))); } if (result.Flags != DkmEvaluationResultFlags.None) { builder.Append(", "); builder.Append(FormatEnumValue(result.Flags)); } builder.Append(")"); return pooledBuilder.ToStringAndFree(); } private static string Escape(string str) { return str.Replace("\"", "\\\""); } private static string Quote(string str) { return '"' + str + '"'; } private static string FormatEnumValue(Enum e) { var parts = e.ToString().Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries); var enumTypeName = e.GetType().Name; return string.Join(" | ", parts.Select(p => enumTypeName + "." + p)); } internal static void Verify(DkmEvaluationResult actual, DkmEvaluationResult expected) { Assert.Equal(expected.Name, actual.Name); Assert.Equal(expected.FullName, actual.FullName); var expectedSuccess = expected as DkmSuccessEvaluationResult; var expectedIntermediate = expected as DkmIntermediateEvaluationResult; if (expectedSuccess != null) { var actualSuccess = (DkmSuccessEvaluationResult)actual; Assert.Equal(expectedSuccess.Value, actualSuccess.Value); Assert.Equal(expectedSuccess.Type, actualSuccess.Type); Assert.Equal(expectedSuccess.Flags, actualSuccess.Flags); if (expectedSuccess.Category != UnspecifiedCategory) { Assert.Equal(expectedSuccess.Category, actualSuccess.Category); } if (expectedSuccess.Access != UnspecifiedAccessType) { Assert.Equal(expectedSuccess.Access, actualSuccess.Access); } Assert.Equal(expectedSuccess.EditableValue, actualSuccess.EditableValue); Assert.True( (expectedSuccess.CustomUIVisualizers == actualSuccess.CustomUIVisualizers) || (expectedSuccess.CustomUIVisualizers != null && actualSuccess.CustomUIVisualizers != null && expectedSuccess.CustomUIVisualizers.SequenceEqual(actualSuccess.CustomUIVisualizers, CustomUIVisualizerInfoComparer.Instance))); } else if (expectedIntermediate != null) { var actualIntermediate = (DkmIntermediateEvaluationResult)actual; Assert.Equal(expectedIntermediate.Expression, actualIntermediate.Expression); Assert.Equal(expectedIntermediate.IntermediateLanguage.Id.LanguageId, actualIntermediate.IntermediateLanguage.Id.LanguageId); Assert.Equal(expectedIntermediate.IntermediateLanguage.Id.VendorId, actualIntermediate.IntermediateLanguage.Id.VendorId); } else { var actualFailed = (DkmFailedEvaluationResult)actual; var expectedFailed = (DkmFailedEvaluationResult)expected; Assert.Equal(expectedFailed.ErrorMessage, actualFailed.ErrorMessage); Assert.Equal(expectedFailed.Type, actualFailed.Type); Assert.Equal(expectedFailed.Flags, actualFailed.Flags); } } #endregion private sealed class CustomUIVisualizerInfoComparer : IEqualityComparer<DkmCustomUIVisualizerInfo> { internal static readonly CustomUIVisualizerInfoComparer Instance = new CustomUIVisualizerInfoComparer(); bool IEqualityComparer<DkmCustomUIVisualizerInfo>.Equals(DkmCustomUIVisualizerInfo x, DkmCustomUIVisualizerInfo y) { return x == y || (x != null && y != null && x.Id == y.Id && x.MenuName == y.MenuName && x.Description == y.Description && x.Metric == y.Metric && x.UISideVisualizerTypeName == y.UISideVisualizerTypeName && x.UISideVisualizerAssemblyName == y.UISideVisualizerAssemblyName && x.UISideVisualizerAssemblyLocation == y.UISideVisualizerAssemblyLocation && x.DebuggeeSideVisualizerTypeName == y.DebuggeeSideVisualizerTypeName && x.DebuggeeSideVisualizerAssemblyName == y.DebuggeeSideVisualizerAssemblyName); } int IEqualityComparer<DkmCustomUIVisualizerInfo>.GetHashCode(DkmCustomUIVisualizerInfo obj) { throw new NotImplementedException(); } } } }
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Xml; using System.Xml.Xsl; using System.Xml.XPath; using System.Diagnostics; using System.Threading; namespace Hydra.Framework.XmlSerialization.Common.Xsl { // //********************************************************************** /// <summary> /// <para>XslReader provides an efficient way to read results of an XSL /// transformation via an <see cref="XmlReader"/> API. Due to /// architectural and performance reasons the <see cref="XslCompiledTransform"/> /// class doesn't support transforming to an <see cref="XmlReader"/> as obsolete /// <see cref="XslTransform"/> class did and XslReader's goal is to /// supplement such functionality.</para> /// <para>XslReader has been developed and contributed to the Hydra.Framework.XmlSerialization project /// by Sergey Dubinets (Microsoft XML Team).</para> /// </summary> /// <remarks> /// <para>XslReader can work in a singlethreaded (fully buffering) or a /// multithreaded mode.</para> /// <para>In a multithreaded mode XslReader runs an XSL transformation /// in a separate dedicated thread. XSLT output is being recorded into a buffer /// and once the buffer is full, transformation thread gets suspended. In a main /// thread XslReader reads recorded XSLT output from a buffer as a client calls /// XslReader methods. Whenever the buffer is read, the transformation thread /// is resumed to produce next portion of an XSLT output.<br/> /// In effect that means that an XSL transformation happens on demand portion by /// portion as a client calls XslReader methods. In terms of memory footprint /// that means that at any time at most buffer size of XSLT output is buffered.</para> /// <para>In a singlethreaded mode XslReader runs an XSL transformation /// to the end and records full XSLT output into a buffer (using effective /// binary representation though). After that it reads the buffer when a client /// calls XslReader methods. So in this mode before first call to the /// XslReader.Read() method returns, XSL transformation is over and XSLT output /// is buffered internally as a whole. /// </para> /// <para>By default XslReader works in a multithreaded mode. You can choose the mode /// and the buffer size using <c>multiThread</c> and <c>initialBufferSize</c> arguments /// when instantiating XslReader object. On small XSLT outputs XslReader performs /// better in a singlethreaded mode, but on medium and big outputs multithreaded /// mode is preferrable. You are adviced to measure performance in both modes to /// find out which suites better for your particular scenario.</para> /// <para>XslReader designed to be reused. Just provide another inoput XML or XSLT /// stylesheet, start transformation and read the output. If the <c>StartTransform()</c> /// method is called when previous /// transformation isn't over yet, it will be aborted, the buffer cleaned and /// the XslReader object will be reset to an initial state automatically.</para> /// <para>XslReader is not thread safe, keep separate instances of the XslReader /// for each thread.</para> /// </remarks> /// <example> /// <para>Here is an example of using XslReader class. First you need to create /// an <see cref="XslCompiledTransform"/> object and load XSLT stylesheet you want to /// execute. Then prepare XML input as <see cref="XmlInput"/> object providing /// XML source in a form of URI, <see cref="Stream"/>, <see cref="TextReader"/>, /// <see cref="XmlReader"/> or <see cref="IXPathNavigable"/> along with an optional /// <see cref="XmlResolver"/> object, which will be used to resolve URIs for /// the XSLT document() function calls.<br/> /// After that create XslReader instance optionally choosing multithreaded or /// singlethreaded mode and initial buffer size.<br/> /// Finally start transformation by calling <c>StartTransform()</c> method and then /// you can read transformation output via XslReader object, which implements /// <see cref="XmlReader"/> API. /// </para> /// <para> /// Basic XslReader usage sample: /// <code> /// //Prepare XslCompiledTransform /// XslCompiledTransform xslt = new XslCompiledTransform(); /// xslt.Load("catalog.xslt"); /// //Prepare input XML /// XmlInput input = new XmlInput("books.xml"); /// //Create XslReader /// XslReader xslReader = new XslReader(xslt); /// //Initiate transformation /// xslReader.StartTransform(input, null); /// //Now read XSLT output from the reader /// XPathDocument results = new XPathDocument(xslReader); /// </code> /// A more advanced sample: /// <code> /// //Prepare XslCompiledTransform /// XslCompiledTransform xslt = new XslCompiledTransform(); /// xslt.Load("../../catalog.xslt"); /// //Prepare XmlResolver to be used by the document() function /// XmlResolver resolver = new XmlUrlResolver(); /// resolver.Credentials = new NetworkCredential("user42", "god"); /// //Prepare input XML /// XmlInput input = new XmlInput("../../books.xml", resolver); /// //Create XslReader, multithreaded mode, initial buffer for 32 nodes /// XslReader xslReader = new XslReader(xslt, true, 32); /// //XSLT parameters /// XsltArgumentList prms = new XsltArgumentList(); /// prms.AddParam("param2", "", "red"); /// //Initiate transformation /// xslReader.StartTransform(input, prms); /// //Now read XSLT output from the reader /// XPathDocument results = new XPathDocument(xslReader); /// </code> /// </para> /// </example> //********************************************************************** // public class XslReader : XmlReader { static string NsXml = "http://www.w3.org/XML/1998/namespace"; static string NsXmlNs = "http://www.w3.org/2000/xmlns/"; static int defaultBufferSize = 256; XmlNameTable nameTable; TokenPipe pipe; BufferWriter writer; ScopeManager scope; Thread thread; XslCompiledTransform xslCompiledTransform; bool multiThread = false; int initialBufferSize; private static XmlReaderSettings ReaderSettings; static XslReader() { ReaderSettings = new XmlReaderSettings(); ReaderSettings.ProhibitDtd = true; } // // Transform Parameters // XmlInput defaulDocument; XsltArgumentList args; // //********************************************************************** /// <summary> /// Creates new XslReader instance with given <see cref="XslCompiledTransform"/>, /// mode (multithreaded/singlethreaded) and initial buffer size. The buffer will be /// expanded if necessary to be able to store any element start tag with all its /// attributes. /// </summary> /// <param name="xslTransform">Loaded <see cref="XslCompiledTransform"/> object</param> /// <param name="multiThread">Defines in which mode (multithreaded or singlethreaded) /// this instance of XslReader will operate</param> /// <param name="initialBufferSize">Initial buffer size (number of nodes, not bytes)</param> //********************************************************************** // public XslReader(XslCompiledTransform xslTransform, bool multiThread, int initialBufferSize) { this.xslCompiledTransform = xslTransform; this.multiThread = multiThread; this.initialBufferSize = initialBufferSize; nameTable = new NameTable(); pipe = this.multiThread ? new TokenPipeMultiThread(initialBufferSize) : new TokenPipe(initialBufferSize); writer = new BufferWriter(pipe, nameTable); scope = new ScopeManager(nameTable); SetUndefinedState(ReadState.Initial); } // //********************************************************************** /// <summary> /// Creates new XslReader instance with given <see cref="XslCompiledTransform"/>, /// operating in a multithreaded mode and having default initial buffer size. /// </summary> /// <param name="xslTransform">Loaded <see cref="XslCompiledTransform"/> object</param> //********************************************************************** // public XslReader(XslCompiledTransform xslTransform) : this(xslTransform, true, defaultBufferSize) { } // //********************************************************************** /// <summary> /// Starts XSL transformation of given <see cref="XmlInput"/> object with /// specified <see cref="XsltArgumentList"/>. After this method returns /// you can read the transformation output out of XslReader object via /// standard <see cref="XmlReader"/> methods such as Read() or MoveXXX(). /// </summary> /// <remarks>If the <c>StartTransform()</c> method is called when previous /// transformation isn't over yet, it will be aborted, buffer cleaned and /// XslReader object reset to an initial state automatically.</remarks> /// <param name="input">An input XML to be transformed</param> /// <param name="args">A collection of global parameter values and /// extension objects.</param> /// <returns></returns> //********************************************************************** // public XmlReader StartTransform(XmlInput input, XsltArgumentList args) { this.defaulDocument = input; this.args = args; Start(); return this; } private void Start() { if (thread != null && thread.IsAlive) { // // We can also reuse this thread or use ThreadPool. For simplicity we create new thread each time. // Some problem with TreadPool will be the need to notify transformation thread when user calls new Start() befor previous transformation completed // thread.Abort(); thread.Join(); } this.writer.Reset(); this.scope.Reset(); this.pipe.Reset(); this.depth = 0; SetUndefinedState(ReadState.Initial); if (multiThread) { this.thread = new Thread(new ThreadStart(this.StartTransform)); this.thread.Start(); } else { StartTransform(); } } private void StartTransform() { try { while (true) { XmlReader xmlReader = defaulDocument.source as XmlReader; if (xmlReader != null) { xslCompiledTransform.Transform(xmlReader, args, writer, defaulDocument.resolver); break; } IXPathNavigable nav = defaulDocument.source as IXPathNavigable; if (nav != null) { xslCompiledTransform.Transform(nav, args, writer); break; } string str = defaulDocument.source as string; if (str != null) { using (XmlReader reader = XmlReader.Create(str, ReaderSettings)) { xslCompiledTransform.Transform(reader, args, writer, defaulDocument.resolver); } break; } Stream strm = defaulDocument.source as Stream; if (strm != null) { using (XmlReader reader = XmlReader.Create(strm, ReaderSettings)) { xslCompiledTransform.Transform(reader, args, writer, defaulDocument.resolver); } break; } TextReader txtReader = defaulDocument.source as TextReader; if (txtReader != null) { using (XmlReader reader = XmlReader.Create(txtReader, ReaderSettings)) { xslCompiledTransform.Transform(reader, args, writer, defaulDocument.resolver); } break; } throw new Exception("Unexpected XmlInput"); } writer.Close(); } catch (Exception e) { if (multiThread) { // // we need this exception on main thread. So pass it through pipe. // pipe.WriteException(e); } else { throw; } } } // //********************************************************************** /// <summary> /// Loaded <see cref="XslCompiledTransform"/> object, which is used /// to run XSL transformations. You can reuse XslReader for running /// another transformation by replacing <see cref="XslCompiledTransform"/> /// object. /// </summary> //********************************************************************** // public XslCompiledTransform XslCompiledTransform { get { return this.xslCompiledTransform; } set { this.xslCompiledTransform = value; } } // //********************************************************************** /// <summary> /// Initial buffer size. The buffer will be /// expanded if necessary to be able to store any element start tag with /// all its attributes. /// </summary> //********************************************************************** // public int InitialBufferSize { get { return initialBufferSize; } set { initialBufferSize = value; } } #region XmlReader Implementation int attOffset = 0; // 0 - means reader is positioned on element, when reader potitionrd on the first attribute attOffset == 1 int attCount; int depth; XmlNodeType nodeType = XmlNodeType.None; ReadState readState = ReadState.Initial; QName qname; string value; void SetUndefinedState(ReadState readState) { this.qname = writer.QNameEmpty; this.value = string.Empty; this.nodeType = XmlNodeType.None; this.attCount = 0; this.readState = readState; } bool IsWhitespace(string s) { // // Because our xml is presumably valid only and all ws chars <= ' ' // foreach (char c in s) { if (' ' < c) { return false; } } return true; } // //********************************************************************** /// <summary> /// See <see cref="XmlReader.Read()"/>. /// </summary> //********************************************************************** // public override bool Read() { // // Leave Current node // switch (nodeType) { case XmlNodeType.None: if (readState == ReadState.EndOfFile || readState == ReadState.Closed) { return false; } readState = ReadState.Interactive; break; case XmlNodeType.Attribute: attOffset = 0; depth--; goto case XmlNodeType.Element; case XmlNodeType.Element: pipe.FreeTokens(1 + attCount); depth++; break; case XmlNodeType.EndElement: scope.PopScope(); pipe.FreeTokens(1); break; case XmlNodeType.Text: if (attOffset != 0) { // // We are on text node inside of the attribute // attOffset = 0; depth -= 2; goto case XmlNodeType.Element; } pipe.FreeTokens(1); break; case XmlNodeType.ProcessingInstruction: case XmlNodeType.Comment: case XmlNodeType.SignificantWhitespace: case XmlNodeType.Whitespace: pipe.FreeTokens(1); break; default: throw new InvalidProgramException("Internal Error: unexpected node type"); } Debug.Assert(attOffset == 0); Debug.Assert(readState == ReadState.Interactive); attCount = 0; // // Step on next node // pipe.Read(out nodeType, out qname, out value); if (nodeType == XmlNodeType.None) { SetUndefinedState(ReadState.EndOfFile); return false; } switch (nodeType) { case XmlNodeType.Element: for (attCount = 0; true; attCount++) { XmlNodeType attType; QName attName; string attText; pipe.Read(out attType, out attName, out attText); if (attType != XmlNodeType.Attribute) { break; // We are done with attributes for this element } if (RefEquals(attName.Prefix, "xmlns")) { scope.AddNamespace(attName.Local, attText); } else if (RefEquals(attName, writer.QNameXmlNs)) { scope.AddNamespace(attName.Prefix, attText); } // prefix is atomized empty string else if (RefEquals(attName, writer.QNameXmlLang)) { scope.AddLang(attText); } else if (RefEquals(attName, writer.QNameXmlSpace)) { scope.AddSpace(attText); } } scope.PushScope(qname); break; case XmlNodeType.EndElement: qname = scope.Name; depth--; break; case XmlNodeType.Comment: case XmlNodeType.ProcessingInstruction: break; case XmlNodeType.Text: if (IsWhitespace(value)) { nodeType = XmlSpace == XmlSpace.Preserve ? XmlNodeType.SignificantWhitespace : XmlNodeType.Whitespace; } break; default: throw new InvalidProgramException("Internal Error: unexpected node type"); } return true; } // //********************************************************************** /// <summary>See <see cref="XmlReader.AttributeCount"/>.</summary> //********************************************************************** // public override int AttributeCount { get { return attCount; } } // issue: What should be BaseURI in XslReader? xslCompiledTransform.BaseURI ? /// <summary>See <see cref="XmlReader.BaseURI"/>.</summary> public override string BaseURI { get { return string.Empty; } } // //********************************************************************** /// <summary>See <see cref="XmlReader.NameTable"/>.</summary> //********************************************************************** // public override XmlNameTable NameTable { get { return nameTable; } } /// <summary>See <see cref="XmlReader.Depth"/>.</summary> public override int Depth { get { return depth; } } // //********************************************************************** /// <summary>See <see cref="XmlReader.EOF"/>.</summary> //********************************************************************** // public override bool EOF { get { return ReadState == ReadState.EndOfFile; } } /// <summary>See <see cref="XmlReader.HasValue"/>.</summary> public override bool HasValue { get { return 0 != (/*HasValueBitmap:*/0x2659C & (1 << (int)nodeType)); } } // //********************************************************************** /// <summary>See <see cref="XmlReader.NodeType"/>.</summary> //********************************************************************** // public override XmlNodeType NodeType { get { return nodeType; } } // issue: We may want return true if element doesn't have content. Iteresting to know what /// <summary>See <see cref="XmlReader.IsEmptyElement"/>.</summary> public override bool IsEmptyElement { get { return false; } } // //********************************************************************** /// <summary>See <see cref="XmlReader.LocalName"/>.</summary> //********************************************************************** // public override string LocalName { get { return qname.Local; } } /// <summary>See <see cref="XmlReader.NamespaceURI"/>.</summary> public override string NamespaceURI { get { return qname.NsUri; } } // //********************************************************************** /// <summary>See <see cref="XmlReader.Prefix"/>.</summary> //********************************************************************** // public override string Prefix { get { return qname.Prefix; } } /// <summary>See <see cref="XmlReader.Value"/>.</summary> public override string Value { get { return value; } } // //********************************************************************** /// <summary>See <see cref="XmlReader.ReadState"/>.</summary> //********************************************************************** // public override ReadState ReadState { get { return readState; } } // //********************************************************************** /// <summary>See <see cref="XmlReader.Close()"/>.</summary> //********************************************************************** // public override void Close() { SetUndefinedState(ReadState.Closed); } // //********************************************************************** /// <summary>See <see cref="XmlReader.GetAttribute(int)"/>.</summary> //********************************************************************** // public override string GetAttribute(int i) { if (IsInsideElement()) { if (0 <= i && i < attCount) { QName attName; string attValue; pipe.GetToken(i + 1, out attName, out attValue); return value; } } throw new ArgumentOutOfRangeException("i"); } static char[] qnameSeparator = new char[] { ':' }; private int FindAttribute(string name) { if (IsInsideElement()) { string prefix, local; string[] strings = name.Split(qnameSeparator, StringSplitOptions.None); switch (strings.Length) { case 1: prefix = string.Empty; local = name; break; case 2: if (strings[0].Length == 0) { return 0; // ":local-name" } prefix = strings[0]; local = strings[1]; break; default: return 0; } for (int i = 1; i <= attCount; i++) { QName attName; string attValue; pipe.GetToken(i, out attName, out attValue); if (attName.Local == local && attName.Prefix == prefix) { return i; } } } return 0; } // //********************************************************************** /// <summary>See <see cref="XmlReader.GetAttribute(string)"/>.</summary> //********************************************************************** // public override string GetAttribute(string name) { int attNum = FindAttribute(name); if (attNum != 0) { return GetAttribute(attNum - 1); } return null; } // //********************************************************************** /// <summary>See <see cref="XmlReader.GetAttribute(string, string)"/>.</summary> //********************************************************************** // public override string GetAttribute(string name, string ns) { if (IsInsideElement()) { for (int i = 1; i <= attCount; i++) { QName attName; string attValue; pipe.GetToken(i, out attName, out attValue); if (attName.Local == name && attName.NsUri == ns) { return attValue; } } } return null; } // //********************************************************************** /// <summary>See <see cref="XmlReader.LookupNamespace(string)"/>.</summary> //********************************************************************** // public override string LookupNamespace(string prefix) { return scope.LookupNamespace(prefix); } /// <summary>See <see cref="XmlReader.Close()"/>.</summary> public override bool MoveToAttribute(string name) { int attNum = FindAttribute(name); if (attNum != 0) { MoveToAttribute(attNum - 1); return true; } return false; } // //********************************************************************** /// <summary>See <see cref="XmlReader.MoveToAttribute(int)"/>.</summary> //********************************************************************** // public override void MoveToAttribute(int i) { if (IsInsideElement()) { if (0 <= i && i < attCount) { ChangeDepthToElement(); attOffset = i + 1; depth++; pipe.GetToken(attOffset, out qname, out value); nodeType = XmlNodeType.Attribute; } } throw new ArgumentOutOfRangeException("i"); } // //********************************************************************** /// <summary>See <see cref="XmlReader.MoveToAttribute(string, string)"/>.</summary> //********************************************************************** // public override bool MoveToAttribute(string name, string ns) { if (IsInsideElement()) { for (int i = 1; i <= attCount; i++) { QName attName; string attValue; pipe.GetToken(i, out attName, out attValue); if (attName.Local == name && attName.NsUri == ns) { ChangeDepthToElement(); nodeType = XmlNodeType.Attribute; attOffset = i; qname = attName; depth++; value = attValue; } } } return false; } private bool IsInsideElement() { return ( nodeType == XmlNodeType.Element || nodeType == XmlNodeType.Attribute || nodeType == XmlNodeType.Text && attOffset != 0 ); } private void ChangeDepthToElement() { switch (nodeType) { case XmlNodeType.Attribute: depth--; break; case XmlNodeType.Text: if (attOffset != 0) { depth -= 2; } break; } } // //********************************************************************** /// <summary>See <see cref="XmlReader.MoveToElement()"/>.</summary> //********************************************************************** // public override bool MoveToElement() { if ( nodeType == XmlNodeType.Attribute || nodeType == XmlNodeType.Text && attOffset != 0 ) { ChangeDepthToElement(); nodeType = XmlNodeType.Element; attOffset = 0; pipe.GetToken(0, out qname, out value); return true; } return false; } // //********************************************************************** /// <summary>See <see cref="XmlReader.MoveToFirstAttribute()"/>.</summary> //********************************************************************** // public override bool MoveToFirstAttribute() { ChangeDepthToElement(); attOffset = 0; return MoveToNextAttribute(); } // //********************************************************************** /// <summary>See <see cref="XmlReader.MoveToNextAttribute()"/>.</summary> //********************************************************************** // public override bool MoveToNextAttribute() { if (attOffset < attCount) { ChangeDepthToElement(); depth++; attOffset++; pipe.GetToken(attOffset, out qname, out value); nodeType = XmlNodeType.Attribute; return true; } return false; } // //********************************************************************** /// <summary>See <see cref="XmlReader.ReadAttributeValue()"/>.</summary> //********************************************************************** // public override bool ReadAttributeValue() { if (nodeType == XmlNodeType.Attribute) { nodeType = XmlNodeType.Text; depth++; return true; } return false; } // //********************************************************************** /// <summary>See <see cref="XmlReader.ResolveEntity()"/>.</summary> //********************************************************************** // public override void ResolveEntity() { throw new InvalidOperationException(); } // //********************************************************************** /// <summary>See <see cref="XmlReader.XmlLang"/>.</summary> //********************************************************************** // public override string XmlLang { get { return scope.Lang; } } /// <summary>See <see cref="XmlReader.XmlSpace"/>.</summary> public override XmlSpace XmlSpace { get { return scope.Space; } } #endregion // XmlReader Implementation #region ------------------------------- Supporting classes ------------------------------ private static bool RefEquals(string strA, string strB) { Debug.Assert( ((object)strA == (object)strB) || !String.Equals(strA, strB), "String atomization Failure: '" + strA + "'" ); return (object)strA == (object)strB; } private static bool RefEquals(QName qnA, QName qnB) { Debug.Assert( ((object)qnA == (object)qnB) || qnA.Local != qnB.Local || qnA.NsUri != qnB.NsUri || qnA.Prefix != qnB.Prefix, "QName atomization Failure: '" + qnA.ToString() + "'" ); return (object)qnA == (object)qnB; } // // QName is imutable. // private class QName { string local; string nsUri; string prefix; public QName(string local, string nsUri, string prefix) { this.local = local; this.nsUri = nsUri; this.prefix = prefix; } public string Local { get { return this.local; } } public string NsUri { get { return this.nsUri; } } public string Prefix { get { return this.prefix; } } public override string ToString() { return (Prefix != null && Prefix.Length != 0) ? (Prefix + ':' + Local) : Local; } } // // BufferWriter records information written to it in sequence of WriterEvents: // [DebuggerDisplay("{NodeType}: name={StateName}, Value={Value}")] private struct XmlToken { public XmlNodeType NodeType; public QName Name; public string Value; // // it seams that it faster to set fields of structure in one call. // This trick is workaround of the C# limitation of declaring variable as ref to a struct. // public static void Set(ref XmlToken evnt, XmlNodeType nodeType, QName name, string value) { evnt.NodeType = nodeType; evnt.Name = name; evnt.Value = value; } public static void Get(ref XmlToken evnt, out XmlNodeType nodeType, out QName name, out string value) { nodeType = evnt.NodeType; name = evnt.Name; value = evnt.Value; } } private class BufferWriter : XmlWriter { QNameTable qnameTable; TokenPipe pipe; string firstText; StringBuilder sbuilder; QName curAttribute; public QName QNameXmlSpace; public QName QNameXmlLang; public QName QNameEmpty; public QName QNameXmlNs; public BufferWriter(TokenPipe pipe, XmlNameTable nameTable) { this.pipe = pipe; this.qnameTable = new QNameTable(nameTable); this.sbuilder = new StringBuilder(); QNameXmlSpace = qnameTable.GetQName("space", NsXml, "xml"); // xml:space QNameXmlLang = qnameTable.GetQName("lang", NsXml, "xml"); // xml:lang QNameXmlNs = qnameTable.GetQName("xmlns", NsXmlNs, ""); // xmlsn="" QNameEmpty = qnameTable.GetQName("", "", ""); } public void Reset() { this.firstText = null; this.sbuilder.Length = 0; } private void AppendText(string text) { if (firstText == null) { Debug.Assert(sbuilder.Length == 0); firstText = text; } else if (sbuilder.Length == 0) { sbuilder.Append(firstText); } sbuilder.Append(text); } private string MergeText() { if (firstText == null) { return string.Empty; // There was no text ouptuted } if (sbuilder.Length != 0) { // // merge content of sbuilder into firstText // Debug.Assert(firstText != null); firstText = sbuilder.ToString(); sbuilder.Length = 0; } string result = firstText; firstText = null; return result; } private void FinishTextNode() { string text = MergeText(); if (text.Length != 0) { pipe.Write(XmlNodeType.Text, QNameEmpty, text); } } public override void WriteComment(string text) { FinishTextNode(); pipe.Write(XmlNodeType.Comment, QNameEmpty, text); } public override void WriteProcessingInstruction(string name, string text) { FinishTextNode(); pipe.Write(XmlNodeType.ProcessingInstruction, qnameTable.GetQName(name, string.Empty, string.Empty), text); } public override void WriteStartElement(string prefix, string name, string ns) { FinishTextNode(); pipe.Write(XmlNodeType.Element, qnameTable.GetQName(name, ns, prefix), ""); } public override void WriteEndElement() { FinishTextNode(); pipe.Write(XmlNodeType.EndElement, QNameEmpty, ""); } public override void WriteStartAttribute(string prefix, string name, string ns) { curAttribute = qnameTable.GetQName(name, ns, prefix); } public override void WriteEndAttribute() { pipe.Write(XmlNodeType.Attribute, curAttribute, MergeText()); } public override void WriteString(string text) { AppendText(text); } public override void WriteFullEndElement() { WriteEndElement(); } public override void WriteRaw(string data) { WriteString(data); // In XslReader output we ignore disable-output-escaping } public override void Close() { FinishTextNode(); pipe.Close(); } public override void Flush() { } // // XsltCompiledTransform never calls these methods and properties: // public override void WriteStartDocument() { throw new NotSupportedException(); } public override void WriteStartDocument(bool standalone) { throw new NotSupportedException(); } public override void WriteEndDocument() { throw new NotSupportedException(); } public override void WriteDocType(string name, string pubid, string sysid, string subset) { throw new NotSupportedException(); } public override void WriteEntityRef(string name) { throw new NotSupportedException(); } public override void WriteCharEntity(char ch) { throw new NotSupportedException(); } public override void WriteSurrogateCharEntity(char lowChar, char highChar) { throw new NotSupportedException(); } public override void WriteWhitespace(string ws) { throw new NotSupportedException(); } public override void WriteChars(char[] buffer, int index, int count) { throw new NotSupportedException(); } public override void WriteRaw(char[] buffer, int index, int count) { throw new NotSupportedException(); } public override void WriteBase64(byte[] buffer, int index, int count) { throw new NotSupportedException(); } public override void WriteCData(string text) { throw new NotSupportedException(); } public override string LookupPrefix(string ns) { throw new NotSupportedException(); } public override WriteState WriteState { get { throw new NotSupportedException(); } } public override XmlSpace XmlSpace { get { throw new NotSupportedException(); } } public override string XmlLang { get { throw new NotSupportedException(); } } private class QNameTable { // // This class atomizes QNames. // XmlNameTable nameTable; Dictionary<string, List<QName>> qnames = new Dictionary<string, List<QName>>(); public QNameTable(XmlNameTable nameTable) { this.nameTable = nameTable; } public QName GetQName(string local, string nsUri, string prefix) { nsUri = nameTable.Add(nsUri); prefix = nameTable.Add(prefix); List<QName> list; if (!qnames.TryGetValue(local, out list)) { list = new List<QName>(); qnames.Add(local, list); } else { foreach (QName qn in list) { Debug.Assert(qn.Local == local, "Atomization Failure: '" + local + "'"); if (RefEquals(qn.Prefix, prefix) && RefEquals(qn.NsUri, nsUri)) { return qn; } } } QName qname = new QName(nameTable.Add(local), nsUri, prefix); list.Add(qname); return qname; } private static string Atomize(string s, Dictionary<string, string> dic) { string atom; if (dic.TryGetValue(s, out atom)) { return atom; } else { dic.Add(s, s); return s; } } } } private class ScopeManager { // // We need the scope for the following reasons: // 1. Report QName on EndElement (local, nsUri, prefix ) // 2. Keep scope of Namespaces (null , nsUri, prefix ) // 3. Keep scope of xml:lang (null , lang , "lang" ) // 4. Keep scope of xml:space (null , space, "space") // On each StartElement we adding record(s) to the scope, // Its convinient to add QName last becuase in this case it will be directly available for EndElement // static string atomLang = new String("lang".ToCharArray()); static string atomSpace = new String("space".ToCharArray()); XmlNameTable nameTable; string stringEmpty; QName[] records = new QName[32]; int lastRecord; XmlSpace currentSpace; string currentLang; public ScopeManager(XmlNameTable nameTable) { this.nameTable = nameTable; this.stringEmpty = nameTable.Add(string.Empty); this.currentLang = this.stringEmpty; this.currentSpace = XmlSpace.None; Reset(); } public void Reset() { lastRecord = 0; records[lastRecord++] = new QName(null, nameTable.Add(NsXml), nameTable.Add("xml")); // xmlns:xml="http://www.w3.org/XML/1998/namespace" records[lastRecord++] = new QName(null, stringEmpty, stringEmpty); // xml="" records[lastRecord++] = new QName(stringEmpty, stringEmpty, stringEmpty); // -- lookup barier } public void PushScope(QName qname) { Debug.Assert(qname.Local != null, "Scope is Element StateName"); AddRecord(qname); } public void PopScope() { Debug.Assert(records[lastRecord - 1].Local != null, "LastRecord in each scope is expected to be ElementName"); do { lastRecord--; Debug.Assert(0 < lastRecord, "Push/Pop balance error"); QName record = records[lastRecord - 1]; if (record.Local != null) { break; // this record is Element QName } if (RefEquals(record.Prefix, atomLang)) { currentLang = record.NsUri; } else if (RefEquals(record.Prefix, atomSpace)) { currentSpace = Str2Space(record.NsUri); } } while (true); } private void AddRecord(QName qname) { if (lastRecord == records.Length) { QName[] temp = new QName[records.Length * 2]; records.CopyTo(temp, 0); records = temp; } records[lastRecord++] = qname; } public void AddNamespace(string prefix, string uri) { Debug.Assert(prefix != null); Debug.Assert(uri != null); Debug.Assert(prefix == nameTable.Add(prefix), "prefixes are expected to be already atomized in this NameTable"); uri = nameTable.Add(uri); Debug.Assert( !RefEquals(prefix, atomLang) && !RefEquals(prefix, atomSpace) , "This assumption is important to distinct NsDecl from xml:space and xml:lang" ); AddRecord(new QName(null, uri, prefix)); } public void AddLang(string lang) { Debug.Assert(lang != null); lang = nameTable.Add(lang); if (RefEquals(lang, currentLang)) { return; } AddRecord(new QName(null, currentLang, atomLang)); currentLang = lang; } public void AddSpace(string space) { Debug.Assert(space != null); XmlSpace xmlSpace = Str2Space(space); if (xmlSpace == XmlSpace.None) { throw new Exception("Unexpected value for xml:space attribute"); } if (xmlSpace == currentSpace) { return; } AddRecord(new QName(null, Space2Str(currentSpace), atomSpace)); currentSpace = xmlSpace; } private string Space2Str(XmlSpace space) { switch (space) { case XmlSpace.Preserve: return "preserve"; case XmlSpace.Default: return "default"; default: return "none"; } } private XmlSpace Str2Space(string space) { switch (space) { case "preserve": return XmlSpace.Preserve; case "default": return XmlSpace.Default; default: return XmlSpace.None; } } public string LookupNamespace(string prefix) { Debug.Assert(prefix != null); prefix = nameTable.Get(prefix); for (int i = lastRecord - 2; 0 <= i; i--) { QName record = records[i]; if (record.Local == null && RefEquals(record.Prefix, prefix)) { return record.NsUri; } } return null; } public string Lang { get { return currentLang; } } public XmlSpace Space { get { return currentSpace; } } public QName Name { get { Debug.Assert(records[lastRecord - 1].Local != null, "Element StateName is expected"); return records[lastRecord - 1]; } } } private class TokenPipe { protected XmlToken[] buffer; protected int writePos; // position after last wrote token protected int readStartPos; // protected int readEndPos; // protected int mask; // used in TokenPipeMultiThread public TokenPipe(int bufferSize) { /*BuildMask*/ { if (bufferSize < 2) { bufferSize = defaultBufferSize; } // // To make or round buffer work bufferSize should be == 2 power N and mask == bufferSize - 1 // bufferSize--; mask = bufferSize; while ((bufferSize = bufferSize >> 1) != 0) { mask |= bufferSize; } } this.buffer = new XmlToken[mask + 1]; } public virtual void Reset() { readStartPos = readEndPos = writePos = 0; } public virtual void Write(XmlNodeType nodeType, QName name, string value) { Debug.Assert(writePos <= buffer.Length); if (writePos == buffer.Length) { XmlToken[] temp = new XmlToken[buffer.Length * 2]; buffer.CopyTo(temp, 0); buffer = temp; } Debug.Assert(writePos < buffer.Length); XmlToken.Set(ref buffer[writePos], nodeType, name, value); writePos++; } public virtual void WriteException(Exception e) { throw e; } public virtual void Read(out XmlNodeType nodeType, out QName name, out string value) { Debug.Assert(readEndPos < buffer.Length); XmlToken.Get(ref buffer[readEndPos], out nodeType, out name, out value); readEndPos++; } public virtual void FreeTokens(int num) { readStartPos += num; readEndPos = readStartPos; } public virtual void Close() { Write(XmlNodeType.None, null, null); } public virtual void GetToken(int attNum, out QName name, out string value) { Debug.Assert(0 <= attNum && attNum < readEndPos - readStartPos - 1); XmlNodeType nodeType; XmlToken.Get(ref buffer[readStartPos + attNum], out nodeType, out name, out value); Debug.Assert(nodeType == (attNum == 0 ? XmlNodeType.Element : XmlNodeType.Attribute), "We use GetToken() only to access parts of start element tag."); } } private class TokenPipeMultiThread : TokenPipe { Exception exception; public TokenPipeMultiThread(int bufferSize) : base(bufferSize) { } public override void Reset() { base.Reset(); exception = null; } private void ExpandBuffer() { // // Buffer is too smal for this amount of attributes. // Debug.Assert(writePos == readStartPos + buffer.Length, "no space to write next token"); Debug.Assert(writePos == readEndPos, "all tokens ware read"); int newMask = (mask << 1) | 1; XmlToken[] newBuffer = new XmlToken[newMask + 1]; for (int i = readStartPos; i < writePos; i++) { newBuffer[i & newMask] = buffer[i & mask]; } buffer = newBuffer; mask = newMask; Debug.Assert(writePos < readStartPos + buffer.Length, "we should have now space to next write token"); } public override void Write(XmlNodeType nodeType, QName name, string value) { lock (this) { Debug.Assert(readEndPos <= writePos && writePos <= readStartPos + buffer.Length); if (writePos == readStartPos + buffer.Length) { if (writePos == readEndPos) { ExpandBuffer(); } else { Monitor.Wait(this); } } Debug.Assert(writePos < readStartPos + buffer.Length); XmlToken.Set(ref buffer[writePos & mask], nodeType, name, value); writePos++; if (readStartPos + buffer.Length <= writePos) { // // This "if" is some heuristics, it may wrk or may not: // To minimize task switching we wakeup reader ony if we wrote enouph tokens. // So if reader already waits, let it sleep before we fill up the buffer. // Monitor.Pulse(this); } } } public override void WriteException(Exception e) { lock (this) { exception = e; Monitor.Pulse(this); } } public override void Read(out XmlNodeType nodeType, out QName name, out string value) { lock (this) { Debug.Assert(readEndPos <= writePos && writePos <= readStartPos + buffer.Length); if (readEndPos == writePos) { if (readEndPos == readStartPos + buffer.Length) { ExpandBuffer(); Monitor.Pulse(this); } Monitor.Wait(this); } if (exception != null) { throw new XsltException("Exception happened during transformation. See inner exception for details:\n", exception); } } Debug.Assert(readEndPos < writePos); XmlToken.Get(ref buffer[readEndPos & mask], out nodeType, out name, out value); readEndPos++; } public override void FreeTokens(int num) { lock (this) { readStartPos += num; readEndPos = readStartPos; Monitor.Pulse(this); } } public override void Close() { Write(XmlNodeType.None, null, null); lock (this) { Monitor.Pulse(this); } } public override void GetToken(int attNum, out QName name, out string value) { Debug.Assert(0 <= attNum && attNum < readEndPos - readStartPos - 1); XmlNodeType nodeType; XmlToken.Get(ref buffer[(readStartPos + attNum) & mask], out nodeType, out name, out value); Debug.Assert(nodeType == (attNum == 0 ? XmlNodeType.Element : XmlNodeType.Attribute), "We use GetToken() only to access parts of start element tag."); } } #endregion ------------------------------- Supporting classes ------------------------------ } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; namespace XenAPI { /// <summary> /// The metrics associated with a virtual network device /// First published in XenServer 4.0. /// </summary> public partial class VIF_metrics : XenObject<VIF_metrics> { public VIF_metrics() { } public VIF_metrics(string uuid, double io_read_kbs, double io_write_kbs, DateTime last_updated, Dictionary<string, string> other_config) { this.uuid = uuid; this.io_read_kbs = io_read_kbs; this.io_write_kbs = io_write_kbs; this.last_updated = last_updated; this.other_config = other_config; } /// <summary> /// Creates a new VIF_metrics from a Proxy_VIF_metrics. /// </summary> /// <param name="proxy"></param> public VIF_metrics(Proxy_VIF_metrics proxy) { this.UpdateFromProxy(proxy); } public override void UpdateFrom(VIF_metrics update) { uuid = update.uuid; io_read_kbs = update.io_read_kbs; io_write_kbs = update.io_write_kbs; last_updated = update.last_updated; other_config = update.other_config; } internal void UpdateFromProxy(Proxy_VIF_metrics proxy) { uuid = proxy.uuid == null ? null : (string)proxy.uuid; io_read_kbs = Convert.ToDouble(proxy.io_read_kbs); io_write_kbs = Convert.ToDouble(proxy.io_write_kbs); last_updated = proxy.last_updated; other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); } public Proxy_VIF_metrics ToProxy() { Proxy_VIF_metrics result_ = new Proxy_VIF_metrics(); result_.uuid = uuid ?? ""; result_.io_read_kbs = io_read_kbs; result_.io_write_kbs = io_write_kbs; result_.last_updated = last_updated; result_.other_config = Maps.convert_to_proxy_string_string(other_config); return result_; } /// <summary> /// Creates a new VIF_metrics from a Hashtable. /// </summary> /// <param name="table"></param> public VIF_metrics(Hashtable table) { uuid = Marshalling.ParseString(table, "uuid"); io_read_kbs = Marshalling.ParseDouble(table, "io_read_kbs"); io_write_kbs = Marshalling.ParseDouble(table, "io_write_kbs"); last_updated = Marshalling.ParseDateTime(table, "last_updated"); other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(VIF_metrics other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._io_read_kbs, other._io_read_kbs) && Helper.AreEqual2(this._io_write_kbs, other._io_write_kbs) && Helper.AreEqual2(this._last_updated, other._last_updated) && Helper.AreEqual2(this._other_config, other._other_config); } public override string SaveChanges(Session session, string opaqueRef, VIF_metrics server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { if (!Helper.AreEqual2(_other_config, server._other_config)) { VIF_metrics.set_other_config(session, opaqueRef, _other_config); } return null; } } /// <summary> /// Get a record containing the current state of the given VIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vif_metrics">The opaque_ref of the given vif_metrics</param> public static VIF_metrics get_record(Session session, string _vif_metrics) { return new VIF_metrics((Proxy_VIF_metrics)session.proxy.vif_metrics_get_record(session.uuid, _vif_metrics ?? "").parse()); } /// <summary> /// Get a reference to the VIF_metrics instance with the specified UUID. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<VIF_metrics> get_by_uuid(Session session, string _uuid) { return XenRef<VIF_metrics>.Create(session.proxy.vif_metrics_get_by_uuid(session.uuid, _uuid ?? "").parse()); } /// <summary> /// Get the uuid field of the given VIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vif_metrics">The opaque_ref of the given vif_metrics</param> public static string get_uuid(Session session, string _vif_metrics) { return (string)session.proxy.vif_metrics_get_uuid(session.uuid, _vif_metrics ?? "").parse(); } /// <summary> /// Get the io/read_kbs field of the given VIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vif_metrics">The opaque_ref of the given vif_metrics</param> public static double get_io_read_kbs(Session session, string _vif_metrics) { return Convert.ToDouble(session.proxy.vif_metrics_get_io_read_kbs(session.uuid, _vif_metrics ?? "").parse()); } /// <summary> /// Get the io/write_kbs field of the given VIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vif_metrics">The opaque_ref of the given vif_metrics</param> public static double get_io_write_kbs(Session session, string _vif_metrics) { return Convert.ToDouble(session.proxy.vif_metrics_get_io_write_kbs(session.uuid, _vif_metrics ?? "").parse()); } /// <summary> /// Get the last_updated field of the given VIF_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vif_metrics">The opaque_ref of the given vif_metrics</param> public static DateTime get_last_updated(Session session, string _vif_metrics) { return session.proxy.vif_metrics_get_last_updated(session.uuid, _vif_metrics ?? "").parse(); } /// <summary> /// Get the other_config field of the given VIF_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vif_metrics">The opaque_ref of the given vif_metrics</param> public static Dictionary<string, string> get_other_config(Session session, string _vif_metrics) { return Maps.convert_from_proxy_string_string(session.proxy.vif_metrics_get_other_config(session.uuid, _vif_metrics ?? "").parse()); } /// <summary> /// Set the other_config field of the given VIF_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vif_metrics">The opaque_ref of the given vif_metrics</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _vif_metrics, Dictionary<string, string> _other_config) { session.proxy.vif_metrics_set_other_config(session.uuid, _vif_metrics ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given VIF_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vif_metrics">The opaque_ref of the given vif_metrics</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_other_config(Session session, string _vif_metrics, string _key, string _value) { session.proxy.vif_metrics_add_to_other_config(session.uuid, _vif_metrics ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given VIF_metrics. If the key is not in that Map, then do nothing. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vif_metrics">The opaque_ref of the given vif_metrics</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _vif_metrics, string _key) { session.proxy.vif_metrics_remove_from_other_config(session.uuid, _vif_metrics ?? "", _key ?? "").parse(); } /// <summary> /// Return a list of all the VIF_metrics instances known to the system. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static List<XenRef<VIF_metrics>> get_all(Session session) { return XenRef<VIF_metrics>.Create(session.proxy.vif_metrics_get_all(session.uuid).parse()); } /// <summary> /// Get all the VIF_metrics Records at once, in a single XML RPC call /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<VIF_metrics>, VIF_metrics> get_all_records(Session session) { return XenRef<VIF_metrics>.Create<Proxy_VIF_metrics>(session.proxy.vif_metrics_get_all_records(session.uuid).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid; /// <summary> /// Read bandwidth (KiB/s) /// </summary> public virtual double io_read_kbs { get { return _io_read_kbs; } set { if (!Helper.AreEqual(value, _io_read_kbs)) { _io_read_kbs = value; Changed = true; NotifyPropertyChanged("io_read_kbs"); } } } private double _io_read_kbs; /// <summary> /// Write bandwidth (KiB/s) /// </summary> public virtual double io_write_kbs { get { return _io_write_kbs; } set { if (!Helper.AreEqual(value, _io_write_kbs)) { _io_write_kbs = value; Changed = true; NotifyPropertyChanged("io_write_kbs"); } } } private double _io_write_kbs; /// <summary> /// Time at which this information was last updated /// </summary> public virtual DateTime last_updated { get { return _last_updated; } set { if (!Helper.AreEqual(value, _last_updated)) { _last_updated = value; Changed = true; NotifyPropertyChanged("last_updated"); } } } private DateTime _last_updated; /// <summary> /// additional configuration /// First published in XenServer 5.0. /// </summary> public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; Changed = true; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config; } }
/* Copyright (c) 2006 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #region Using directives #define USE_TRACING using System; using System.Security.Cryptography; using System.Net; using System.Text; using System.Globalization; using System.Collections.Generic; #endregion ////////////////////////////////////////////////////////////////////// // Contains AuthSubUtil, a helper class for authsub communications ////////////////////////////////////////////////////////////////////// namespace Google.GData.Client { ////////////////////////////////////////////////////////////////////// /// <summary>helper class for communications between a 3rd party site and Google using the AuthSub protocol /// </summary> ////////////////////////////////////////////////////////////////////// public sealed class AuthSubUtil { private static string DEFAULT_PROTOCOL = "https"; private static string DEFAULT_DOMAIN = "www.google.com"; private static string DEFAULT_HANDLER = "/accounts/AuthSubRequest"; // to prevent the compiler from creating a default public one. private AuthSubUtil() { } ////////////////////////////////////////////////////////////////////// /// <summary>Creates the request URL to be used to retrieve an AuthSub /// token. On success, the user will be redirected to the continue URL /// with the AuthSub token appended to the URL. /// Use getTokenFromReply(String) to retrieve the token from the reply. /// </summary> /// <param name="continueUrl">the URL to redirect to on successful /// token retrieval</param> /// <param name="scope">the scope of the requested AuthSub token</param> /// <param name="secure">if the token will be used securely</param> /// <param name="session"> if the token will be exchanged for a /// session cookie</param> /// <returns>the URL to be used to retrieve the AuthSub token</returns> ////////////////////////////////////////////////////////////////////// public static string getRequestUrl(string continueUrl, string scope, bool secure, bool session) { return getRequestUrl(DEFAULT_PROTOCOL, DEFAULT_DOMAIN, continueUrl, scope, secure, session); } ////////////////////////////////////////////////////////////////////// /// <summary>Creates the request URL to be used to retrieve an AuthSub /// token. On success, the user will be redirected to the continue URL /// with the AuthSub token appended to the URL. /// Use getTokenFromReply(String) to retrieve the token from the reply. /// </summary> /// <param name="hostedDomain">the name of the hosted domain, /// like www.myexample.com</param> /// <param name="continueUrl">the URL to redirect to on successful /// token retrieval</param> /// <param name="scope">the scope of the requested AuthSub token</param> /// <param name="secure">if the token will be used securely</param> /// <param name="session"> if the token will be exchanged for a /// session cookie</param> /// <returns>the URL to be used to retrieve the AuthSub token</returns> ////////////////////////////////////////////////////////////////////// public static string getRequestUrl(string hostedDomain, string continueUrl, string scope, bool secure, bool session) { return getRequestUrl(hostedDomain, DEFAULT_PROTOCOL, DEFAULT_DOMAIN, DEFAULT_HANDLER, continueUrl, scope, secure, session); } ////////////////////////////////////////////////////////////////////// /// <summary>Creates the request URL to be used to retrieve an AuthSub /// token. On success, the user will be redirected to the continue URL /// with the AuthSub token appended to the URL. /// Use getTokenFromReply(String) to retrieve the token from the reply. /// </summary> /// <param name="protocol">the protocol to use to communicate with the /// server</param> /// <param name="authenticationDomain">the domain at which the authentication server /// exists</param> /// <param name="continueUrl">the URL to redirect to on successful /// token retrieval</param> /// <param name="scope">the scope of the requested AuthSub token</param> /// <param name="secure">if the token will be used securely</param> /// <param name="session"> if the token will be exchanged for a /// session cookie</param> /// <returns>the URL to be used to retrieve the AuthSub token</returns> ////////////////////////////////////////////////////////////////////// public static string getRequestUrl(string protocol, string authenticationDomain, string continueUrl, string scope, bool secure, bool session) { return getRequestUrl(null, protocol, authenticationDomain, DEFAULT_HANDLER, continueUrl, scope, secure, session); } ////////////////////////////////////////////////////////////////////// /// <summary>Creates the request URL to be used to retrieve an AuthSub /// token. On success, the user will be redirected to the continue URL /// with the AuthSub token appended to the URL. /// Use getTokenFromReply(String) to retrieve the token from the reply. /// </summary> /// <param name="protocol">the protocol to use to communicate with the /// server</param> /// <param name="authenticationDomain">the domain at which the authentication server /// exists</param> /// <param name="handler">the location of the authentication handler /// (defaults to "/accounts/AuthSubRequest".</param> /// <param name="continueUrl">the URL to redirect to on successful /// token retrieval</param> /// <param name="scope">the scope of the requested AuthSub token</param> /// <param name="secure">if the token will be used securely</param> /// <param name="session"> if the token will be exchanged for a /// session cookie</param> /// <returns>the URL to be used to retrieve the AuthSub token</returns> ////////////////////////////////////////////////////////////////////// public static string getRequestUrl(string protocol, string authenticationDomain, string handler, string continueUrl, string scope, bool secure, bool session) { return getRequestUrl(null, protocol, authenticationDomain, handler, continueUrl, scope, secure, session); } ////////////////////////////////////////////////////////////////////// /// <summary>Creates the request URL to be used to retrieve an AuthSub /// token. On success, the user will be redirected to the continue URL /// with the AuthSub token appended to the URL. /// Use getTokenFromReply(String) to retrieve the token from the reply. /// </summary> /// <param name="hostedDomain">the name of the hosted domain, /// like www.myexample.com</param> /// <param name="protocol">the protocol to use to communicate with the /// server</param> /// <param name="authenticationDomain">the domain at which the authentication server /// exists</param> /// <param name="handler">the location of the authentication handler /// (defaults to "/accounts/AuthSubRequest".</param> /// <param name="continueUrl">the URL to redirect to on successful /// token retrieval</param> /// <param name="scope">the scope of the requested AuthSub token</param> /// <param name="secure">if the token will be used securely</param> /// <param name="session"> if the token will be exchanged for a /// session cookie</param> /// <returns>the URL to be used to retrieve the AuthSub token</returns> ////////////////////////////////////////////////////////////////////// public static string getRequestUrl(string hostedDomain, string protocol, string authenticationDomain, string handler, string continueUrl, string scope, bool secure, bool session) { StringBuilder url = new StringBuilder(protocol); url.Append("://"); url.Append(authenticationDomain); url.Append(handler); url.Append("?"); addParameter(url, "next", continueUrl); url.Append("&"); addParameter(url, "scope", scope); url.Append("&"); addParameter(url, "secure", secure ? "1" : "0"); url.Append("&"); addParameter(url, "session", session ? "1" : "0"); if (hostedDomain != null) { url.Append("&"); addParameter(url, "hd", hostedDomain); } return url.ToString(); } ////////////////////////////////////////////////////////////////////// /// <summary> /// Adds the query parameter with the given name and value to the URL. /// </summary> ////////////////////////////////////////////////////////////////////// private static void addParameter(StringBuilder url, string name, string value) { // encode them name = Utilities.UriEncodeReserved(name); value = Utilities.UriEncodeReserved(value); // Append the name/value pair url.Append(name); url.Append('='); url.Append(value); } ////////////////////////////////////////////////////////////////////// /// <summary> /// Returns the URL to use to exchange the one-time-use token for /// a session token. /// </summary> /// <returns>the URL to exchange for the session token</returns> ////////////////////////////////////////////////////////////////////// public static string getSessionTokenUrl() { return getSessionTokenUrl(DEFAULT_PROTOCOL, DEFAULT_DOMAIN); } //end of public static string getSessionTokenUrl() ////////////////////////////////////////////////////////////////////// /// <summary> /// Returns the URL to use to exchange the one-time-use token for /// a session token. /// </summary> /// <param name="protocol">the protocol to use to communicate with /// the server</param> /// <param name="domain">the domain at which the authentication server /// exists</param> /// <returns>the URL to exchange for the session token</returns> ////////////////////////////////////////////////////////////////////// public static string getSessionTokenUrl(string protocol, string domain) { return protocol + "://" + domain + "/accounts/AuthSubSessionToken"; } //end of public static string getSessionTokenUrl() ////////////////////////////////////////////////////////////////////// /// <summary> /// Returns the URL that handles token revocation, using the default /// domain and the default protocol /// </summary> /// <returns>the URL to exchange for the session token</returns> ////////////////////////////////////////////////////////////////////// public static string getRevokeTokenUrl() { return getRevokeTokenUrl(DEFAULT_PROTOCOL, DEFAULT_DOMAIN); } ////////////////////////////////////////////////////////////////////// /// <summary> /// Returns the URL that handles token revocation. /// </summary> /// <param name="protocol">the protocol to use to communicate with /// the server</param> /// <param name="domain">the domain at which the authentication server /// exists</param> /// <returns>the URL to exchange for the session token</returns> ////////////////////////////////////////////////////////////////////// public static string getRevokeTokenUrl(string protocol, string domain) { return protocol + "://" + domain + "/accounts/AuthSubRevokeToken"; } ////////////////////////////////////////////////////////////////////// /// <summary> /// Parses and returns the AuthSub token returned by Google on a successful /// AuthSub login request. The token will be appended as a query parameter /// to the continue URL specified while making the AuthSub request. /// </summary> /// <param name="uri">The reply URI to parse </param> /// <returns>the token value of the URI, or null if none </returns> ////////////////////////////////////////////////////////////////////// public static string getTokenFromReply(Uri uri) { if (uri == null) { throw new ArgumentNullException("uri"); } char [] deli = {'?','&'}; TokenCollection tokens = new TokenCollection(uri.Query, deli); foreach (String token in tokens ) { if (token.Length > 0) { char [] otherDeli = {'='}; String [] parameters = token.Split(otherDeli,2); if (parameters[0] == "token") { return parameters[1]; } } } return null; } //end of public static string getTokenFromReply(URL url) ////////////////////////////////////////////////////////////////////// /// <summary> /// Exchanges the one time use token returned in the URL for a session /// token. If the key is non-null, the token will be used securely, /// and the request will be signed /// </summary> /// <param name="onetimeUseToken">the token send by google in the URL</param> /// <param name="key">the private key used to sign</param> /// <returns>the session token</returns> ////////////////////////////////////////////////////////////////////// public static String exchangeForSessionToken(String onetimeUseToken, AsymmetricAlgorithm key) { return exchangeForSessionToken(DEFAULT_PROTOCOL, DEFAULT_DOMAIN, onetimeUseToken, key); } //end of public static String exchangeForSessionToken(String onetimeUseToken, PrivateKey key) ////////////////////////////////////////////////////////////////////// /// <summary> /// Exchanges the one time use token returned in the URL for a session /// token. If the key is non-null, the token will be used securely, /// and the request will be signed /// </summary> /// <param name="protocol">the protocol to use to communicate with the /// server</param> /// <param name="domain">the domain at which the authentication server /// exists</param> /// <param name="onetimeUseToken">the token send by google in the URL</param> /// <param name="key">the private key used to sign</param> /// <returns>the session token</returns> ////////////////////////////////////////////////////////////////////// public static string exchangeForSessionToken(string protocol, string domain, string onetimeUseToken, AsymmetricAlgorithm key) { HttpWebResponse response = null; string authSubToken = null; try { string sessionUrl = getSessionTokenUrl(protocol, domain); Uri uri = new Uri(sessionUrl); HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest; string header = formAuthorizationHeader(onetimeUseToken, key, uri, "GET"); request.Headers.Add(header); response = request.GetResponse() as HttpWebResponse; } catch (WebException e) { Tracing.TraceMsg("exchangeForSessionToken failed " + e.Status); throw new GDataRequestException("Execution of exchangeForSessionToken", e); } if (response != null) { int code= (int)response.StatusCode; if (code != 200) { throw new GDataRequestException("Execution of exchangeForSessionToken request returned unexpected result: " +code, response); } // get the body and parse it authSubToken = Utilities.ParseValueFormStream(response.GetResponseStream(), GoogleAuthentication.AuthSubToken); } Tracing.Assert(authSubToken != null, "did not find an auth token in exchangeForSessionToken"); return authSubToken; } //end of public static String exchangeForSessionToken(String onetimeUseToken, PrivateKey key) /// <summary> /// Revokes the specified token. If the <code>key</code> is non-null, /// the token will be used securely and the request to revoke the /// token will be signed. /// </summary> /// <param name="token">the AuthSub token to revoke</param> /// <param name="key">the private key to sign the request</param> public static void revokeToken(string token, AsymmetricAlgorithm key) { revokeToken(DEFAULT_PROTOCOL, DEFAULT_DOMAIN, token, key); } /// <summary> /// Revokes the specified token. If the <code>key</code> is non-null, /// the token will be used securely and the request to revoke the /// token will be signed. /// </summary> /// <param name="protocol"></param> /// <param name="domain"></param> /// <param name="token">the AuthSub token to revoke</param> /// <param name="key">the private key to sign the request</param> public static void revokeToken(String protocol, String domain, String token, AsymmetricAlgorithm key) { HttpWebResponse response = null; try { string revokeUrl = getRevokeTokenUrl(protocol, domain); Uri uri = new Uri(revokeUrl); HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest; string header = formAuthorizationHeader(token, key, uri, "GET"); request.Headers.Add(header); response = request.GetResponse() as HttpWebResponse; } catch (WebException e) { Tracing.TraceMsg("revokeToken failed " + e.Status); throw new GDataRequestException("Execution of revokeToken", e); } if (response != null) { int code= (int)response.StatusCode; if (code != 200) { throw new GDataRequestException("Execution of revokeToken request returned unexpected result: " +code, response); } } } ////////////////////////////////////////////////////////////////////// /// <summary>Forms the AuthSub authorization header. /// if key is null, the token will be in insecure mode, otherwise /// the token will be used securely and the header contains /// a signature /// </summary> /// <param name="token">the AuthSub token to use </param> /// <param name="key">the private key to used </param> /// <param name="requestUri">the request uri to use </param> /// <param name="requestMethod">the HTTP method to use </param> /// <returns>the authorization header </returns> ////////////////////////////////////////////////////////////////////// public static string formAuthorizationHeader(string token, AsymmetricAlgorithm key, Uri requestUri, string requestMethod) { if (key == null) { return String.Format(CultureInfo.InvariantCulture, "Authorization: AuthSub token=\"{0}\"", token); } else { if (requestUri == null) { throw new ArgumentNullException("requestUri"); } // Form signature for secure mode TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1)); int timestamp = (int)t.TotalSeconds; string nounce = generateULONGRnd(); string dataToSign = String.Format(CultureInfo.InvariantCulture, "{0} {1} {2} {3}", requestMethod, requestUri.AbsoluteUri, timestamp.ToString(CultureInfo.InvariantCulture), nounce); byte[] signature = sign(dataToSign, key); string encodedSignature = Convert.ToBase64String(signature); string algorithmName = key is DSACryptoServiceProvider ? "dsa-sha1" : "rsa-sha1"; return String.Format(CultureInfo.InvariantCulture, "Authorization: AuthSub token=\"{0}\" data=\"{1}\" sig=\"{2}\" sigalg=\"{3}\"", token, dataToSign, encodedSignature, algorithmName); } } //end of public static string formAuthorizationHeader(string token, p key, Uri requestUri, string requestMethod) ////////////////////////////////////////////////////////////////////// /// <summary>Retrieves information about the AuthSub token. /// If the <code>key</code> is non-null, the token will be used securely /// and the request to revoke the token will be signed. /// </summary> /// <param name="token">tthe AuthSub token for which to receive information </param> /// <param name="key">the private key to sign the request</param> /// <returns>the token information in the form of a Dictionary from the name of the /// attribute to the value of the attribute</returns> ////////////////////////////////////////////////////////////////////// public static Dictionary<String, String> GetTokenInfo(String token, AsymmetricAlgorithm key) { return GetTokenInfo(DEFAULT_PROTOCOL, DEFAULT_DOMAIN, token, key); } ////////////////////////////////////////////////////////////////////// /// <summary>Retrieves information about the AuthSub token. /// If the <code>key</code> is non-null, the token will be used securely /// and the request to revoke the token will be signed. /// </summary> /// <param name="protocol">the protocol to use to communicate with the server</param> /// <param name="domain">the domain at which the authentication server exists</param> /// <param name="token">tthe AuthSub token for which to receive information </param> /// <param name="key">the private key to sign the request</param> /// <returns>the token information in the form of a Dictionary from the name of the /// attribute to the value of the attribute</returns> ////////////////////////////////////////////////////////////////////// public static Dictionary<String, String> GetTokenInfo(String protocol, String domain, String token, AsymmetricAlgorithm key) { HttpWebResponse response; try { string tokenInfoUrl = GetTokenInfoUrl(protocol, domain); Uri uri = new Uri(tokenInfoUrl); HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest; string header = formAuthorizationHeader(token, key, uri, "GET"); request.Headers.Add(header); response = request.GetResponse() as HttpWebResponse; } catch (WebException e) { Tracing.TraceMsg("GetTokenInfo failed " + e.Status); throw new GDataRequestException("Execution of GetTokenInfo", e); } if (response != null) { int code= (int)response.StatusCode; if (code != 200) { throw new GDataRequestException("Execution of revokeToken request returned unexpected result: " +code, response); } TokenCollection tokens = Utilities.ParseStreamInTokenCollection(response.GetResponseStream()); if (tokens != null) { return tokens.CreateDictionary(); } } return null; } ////////////////////////////////////////////////////////////////////// /// <summary>creates a max 20 character long string of random numbers</summary> /// <returns> the string containing random numbers</returns> ////////////////////////////////////////////////////////////////////// private static string generateULONGRnd() { byte[] randomNumber = new byte[20]; // Create a new instance of the RNGCryptoServiceProvider. RNGCryptoServiceProvider Gen = new RNGCryptoServiceProvider(); // Fill the array with a random value. Gen.GetBytes(randomNumber); StringBuilder x = new StringBuilder(20); for (int i = 0; i < 20; i++) { if (randomNumber[i] == 0 && x.Length == 0) { continue; } x.Append(Convert.ToInt16(randomNumber[i], CultureInfo.InvariantCulture).ToString()[0]); } return x.ToString(); } //end of private static string generateULONGRnd() ////////////////////////////////////////////////////////////////////// /// <summary>signs the data with the given key</summary> /// <param name="dataToSign">the data to sign </param> /// <param name="key">the private key to used </param> /// <returns> the signed data</returns> ////////////////////////////////////////////////////////////////////// private static byte[] sign(string dataToSign, AsymmetricAlgorithm key) { byte[] data = new ASCIIEncoding().GetBytes(dataToSign); try { RSACryptoServiceProvider providerRSA = key as RSACryptoServiceProvider; if (providerRSA != null) { return providerRSA.SignData(data, new SHA1CryptoServiceProvider()); } DSACryptoServiceProvider providerDSA = key as DSACryptoServiceProvider; if (providerDSA != null) { return providerDSA.SignData(data); } } catch (CryptographicException e) { Tracing.TraceMsg(e.Message); } return null; } ////////////////////////////////////////////////////////////////////// /// <summary>Returns the URL that handles token information call.</summary> /// <param name="protocol">the protocol to use to communicate with the server</param> /// <param name="domain">the domain at which the authentication server exists</param> /// <returns> the URL that handles token information call.</returns> ////////////////////////////////////////////////////////////////////// private static String GetTokenInfoUrl(String protocol, String domain) { return protocol + "://" + domain + "/accounts/AuthSubTokenInfo"; } } //end of public class AuthSubUtil } /////////////////////////////////////////////////////////////////////////////
namespace Epi.Windows.MakeView.Dialogs.CheckCodeCommandDialogs { /// <summary> /// The Variable Definition dialog /// </summary> partial class VariableDefinitionDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(VariableDefinitionDialog)); this.gbxScope = new System.Windows.Forms.GroupBox(); this.rbPermanent = new System.Windows.Forms.RadioButton(); this.rbGlobal = new System.Windows.Forms.RadioButton(); this.rbStandard = new System.Windows.Forms.RadioButton(); this.lblVarName = new System.Windows.Forms.Label(); this.txtVariableName = new System.Windows.Forms.TextBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.cmbVarType = new Epi.Windows.Controls.LocalizedComboBox(); this.lblVarType = new System.Windows.Forms.Label(); this.btnHelp = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.btnOK = new System.Windows.Forms.Button(); this.btnClear = new System.Windows.Forms.Button(); this.gbxScope.SuspendLayout(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // baseImageList // this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream"))); this.baseImageList.Images.SetKeyName(0, ""); this.baseImageList.Images.SetKeyName(1, ""); this.baseImageList.Images.SetKeyName(2, ""); this.baseImageList.Images.SetKeyName(3, ""); this.baseImageList.Images.SetKeyName(4, ""); this.baseImageList.Images.SetKeyName(5, ""); this.baseImageList.Images.SetKeyName(6, ""); this.baseImageList.Images.SetKeyName(7, ""); this.baseImageList.Images.SetKeyName(8, ""); this.baseImageList.Images.SetKeyName(9, ""); this.baseImageList.Images.SetKeyName(10, ""); this.baseImageList.Images.SetKeyName(11, ""); this.baseImageList.Images.SetKeyName(12, ""); this.baseImageList.Images.SetKeyName(13, ""); this.baseImageList.Images.SetKeyName(14, ""); this.baseImageList.Images.SetKeyName(15, ""); this.baseImageList.Images.SetKeyName(16, ""); this.baseImageList.Images.SetKeyName(17, ""); this.baseImageList.Images.SetKeyName(18, ""); this.baseImageList.Images.SetKeyName(19, ""); this.baseImageList.Images.SetKeyName(20, ""); this.baseImageList.Images.SetKeyName(21, ""); this.baseImageList.Images.SetKeyName(22, ""); this.baseImageList.Images.SetKeyName(23, ""); this.baseImageList.Images.SetKeyName(24, ""); this.baseImageList.Images.SetKeyName(25, ""); this.baseImageList.Images.SetKeyName(26, ""); this.baseImageList.Images.SetKeyName(27, ""); this.baseImageList.Images.SetKeyName(28, ""); this.baseImageList.Images.SetKeyName(29, ""); this.baseImageList.Images.SetKeyName(30, ""); this.baseImageList.Images.SetKeyName(31, ""); this.baseImageList.Images.SetKeyName(32, ""); this.baseImageList.Images.SetKeyName(33, ""); this.baseImageList.Images.SetKeyName(34, ""); this.baseImageList.Images.SetKeyName(35, ""); this.baseImageList.Images.SetKeyName(36, ""); this.baseImageList.Images.SetKeyName(37, ""); this.baseImageList.Images.SetKeyName(38, ""); this.baseImageList.Images.SetKeyName(39, ""); this.baseImageList.Images.SetKeyName(40, ""); this.baseImageList.Images.SetKeyName(41, ""); this.baseImageList.Images.SetKeyName(42, ""); this.baseImageList.Images.SetKeyName(43, ""); this.baseImageList.Images.SetKeyName(44, ""); this.baseImageList.Images.SetKeyName(45, ""); this.baseImageList.Images.SetKeyName(46, ""); this.baseImageList.Images.SetKeyName(47, ""); this.baseImageList.Images.SetKeyName(48, ""); this.baseImageList.Images.SetKeyName(49, ""); this.baseImageList.Images.SetKeyName(50, ""); this.baseImageList.Images.SetKeyName(51, ""); this.baseImageList.Images.SetKeyName(52, ""); this.baseImageList.Images.SetKeyName(53, ""); this.baseImageList.Images.SetKeyName(54, ""); this.baseImageList.Images.SetKeyName(55, ""); this.baseImageList.Images.SetKeyName(56, ""); this.baseImageList.Images.SetKeyName(57, ""); this.baseImageList.Images.SetKeyName(58, ""); this.baseImageList.Images.SetKeyName(59, ""); this.baseImageList.Images.SetKeyName(60, ""); this.baseImageList.Images.SetKeyName(61, ""); this.baseImageList.Images.SetKeyName(62, ""); this.baseImageList.Images.SetKeyName(63, ""); this.baseImageList.Images.SetKeyName(64, ""); this.baseImageList.Images.SetKeyName(65, ""); this.baseImageList.Images.SetKeyName(66, ""); this.baseImageList.Images.SetKeyName(67, ""); this.baseImageList.Images.SetKeyName(68, ""); this.baseImageList.Images.SetKeyName(69, ""); // // gbxScope // resources.ApplyResources(this.gbxScope, "gbxScope"); this.gbxScope.Controls.Add(this.rbPermanent); this.gbxScope.Controls.Add(this.rbGlobal); this.gbxScope.Controls.Add(this.rbStandard); this.gbxScope.FlatStyle = System.Windows.Forms.FlatStyle.System; this.gbxScope.Name = "gbxScope"; this.gbxScope.TabStop = false; this.gbxScope.Enter += new System.EventHandler(this.gbxScope_Enter); // // rbPermanent // resources.ApplyResources(this.rbPermanent, "rbPermanent"); this.rbPermanent.Name = "rbPermanent"; this.rbPermanent.Tag = "PERMANENT"; // // rbGlobal // resources.ApplyResources(this.rbGlobal, "rbGlobal"); this.rbGlobal.Name = "rbGlobal"; this.rbGlobal.Tag = "GLOBAL"; // // rbStandard // this.rbStandard.Checked = true; resources.ApplyResources(this.rbStandard, "rbStandard"); this.rbStandard.Name = "rbStandard"; this.rbStandard.TabStop = true; this.rbStandard.Tag = "STANDARD"; // // lblVarName // this.lblVarName.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.lblVarName, "lblVarName"); this.lblVarName.Name = "lblVarName"; // // txtVariableName // resources.ApplyResources(this.txtVariableName, "txtVariableName"); this.txtVariableName.Name = "txtVariableName"; this.txtVariableName.TextChanged += new System.EventHandler(this.txtVariableName_TextChanged); this.txtVariableName.Leave += new System.EventHandler(this.txtVariableName_Leave); // // groupBox1 // this.groupBox1.Controls.Add(this.cmbVarType); this.groupBox1.Controls.Add(this.lblVarType); resources.ApplyResources(this.groupBox1, "groupBox1"); this.groupBox1.Name = "groupBox1"; this.groupBox1.TabStop = false; // // cmbVarType // this.cmbVarType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; resources.ApplyResources(this.cmbVarType, "cmbVarType"); this.cmbVarType.Name = "cmbVarType"; this.cmbVarType.SkipTranslation = false; // // lblVarType // this.lblVarType.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.lblVarType, "lblVarType"); this.lblVarType.Name = "lblVarType"; // // btnHelp // resources.ApplyResources(this.btnHelp, "btnHelp"); this.btnHelp.Name = "btnHelp"; // // btnCancel // this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; resources.ApplyResources(this.btnCancel, "btnCancel"); this.btnCancel.Name = "btnCancel"; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // btnOK // resources.ApplyResources(this.btnOK, "btnOK"); this.btnOK.Name = "btnOK"; this.btnOK.Click += new System.EventHandler(this.btnOK_Click); // // btnClear // resources.ApplyResources(this.btnClear, "btnClear"); this.btnClear.Name = "btnClear"; this.btnClear.Click += new System.EventHandler(this.btnClear_Click); // // VariableDefinitionDialog // resources.ApplyResources(this, "$this"); this.Controls.Add(this.gbxScope); this.Controls.Add(this.lblVarName); this.Controls.Add(this.txtVariableName); this.Controls.Add(this.groupBox1); this.Controls.Add(this.btnHelp); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOK); this.Controls.Add(this.btnClear); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "VariableDefinitionDialog"; this.ShowIcon = false; this.ShowInTaskbar = false; this.gbxScope.ResumeLayout(false); this.groupBox1.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label lblVarName; private System.Windows.Forms.TextBox txtVariableName; private System.Windows.Forms.GroupBox groupBox1; private Epi.Windows.Controls.LocalizedComboBox cmbVarType; private System.Windows.Forms.Label lblVarType; private System.Windows.Forms.Button btnHelp; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Button btnClear; private System.Windows.Forms.GroupBox gbxScope; private System.Windows.Forms.RadioButton rbPermanent; private System.Windows.Forms.RadioButton rbGlobal; private System.Windows.Forms.RadioButton rbStandard; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Globalization { public abstract class EastAsianLunisolarCalendar : Calendar { private const int LeapMonth = 0; private const int Jan1Month = 1; private const int Jan1Date = 2; private const int nDaysPerMonth = 3; // # of days so far in the solar year private static readonly int[] s_daysToMonth365 = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; private static readonly int[] s_daysToMonth366 = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 }; public override CalendarAlgorithmType AlgorithmType => CalendarAlgorithmType.LunisolarCalendar; /// <summary> /// Return the year number in the 60-year cycle. /// </summary> public virtual int GetSexagenaryYear(DateTime time) { CheckTicksRange(time.Ticks); TimeToLunar(time, out int year, out _, out _); return ((year - 4) % 60) + 1; } /// <summary> /// Return the celestial year from the 60-year cycle. /// The returned value is from 1 ~ 10. /// </summary> public int GetCelestialStem(int sexagenaryYear) { if (sexagenaryYear < 1 || sexagenaryYear > 60) { throw new ArgumentOutOfRangeException( nameof(sexagenaryYear), sexagenaryYear, SR.Format(SR.ArgumentOutOfRange_Range, 1, 60)); } return ((sexagenaryYear - 1) % 10) + 1; } /// <summary> /// Return the Terrestial Branch from the 60-year cycle. /// The returned value is from 1 ~ 12. /// </summary> public int GetTerrestrialBranch(int sexagenaryYear) { if (sexagenaryYear < 1 || sexagenaryYear > 60) { throw new ArgumentOutOfRangeException( nameof(sexagenaryYear), sexagenaryYear, SR.Format(SR.ArgumentOutOfRange_Range, 1, 60)); } return ((sexagenaryYear - 1) % 12) + 1; } internal abstract int GetYearInfo(int LunarYear, int Index); internal abstract int GetYear(int year, DateTime time); internal abstract int GetGregorianYear(int year, int era); internal abstract int MinCalendarYear { get; } internal abstract int MaxCalendarYear { get; } internal abstract EraInfo[]? CalEraInfo { get; } internal abstract DateTime MinDate { get; } internal abstract DateTime MaxDate { get; } internal const int MaxCalendarMonth = 13; internal const int MaxCalendarDay = 30; internal int MinEraCalendarYear(int era) { EraInfo[]? eraInfo = CalEraInfo; if (eraInfo == null) { return MinCalendarYear; } if (era == Calendar.CurrentEra) { era = CurrentEraValue; } // Era has to be in the supported range otherwise we will throw exception in CheckEraRange() if (era == GetEra(MinDate)) { return GetYear(MinCalendarYear, MinDate); } for (int i = 0; i < eraInfo.Length; i++) { if (era == eraInfo[i].era) { return eraInfo[i].minEraYear; } } throw new ArgumentOutOfRangeException(nameof(era), era, SR.ArgumentOutOfRange_InvalidEraValue); } internal int MaxEraCalendarYear(int era) { EraInfo[]? eraInfo = CalEraInfo; if (eraInfo == null) { return MaxCalendarYear; } if (era == Calendar.CurrentEra) { era = CurrentEraValue; } // Era has to be in the supported range otherwise we will throw exception in CheckEraRange() if (era == GetEra(MaxDate)) { return GetYear(MaxCalendarYear, MaxDate); } for (int i = 0; i < eraInfo.Length; i++) { if (era == eraInfo[i].era) { return eraInfo[i].maxEraYear; } } throw new ArgumentOutOfRangeException(nameof(era), era, SR.ArgumentOutOfRange_InvalidEraValue); } internal EastAsianLunisolarCalendar() { } internal void CheckTicksRange(long ticks) { if (ticks < MinSupportedDateTime.Ticks || ticks > MaxSupportedDateTime.Ticks) { throw new ArgumentOutOfRangeException( "time", ticks, SR.Format(CultureInfo.InvariantCulture, SR.ArgumentOutOfRange_CalendarRange, MinSupportedDateTime, MaxSupportedDateTime)); } } internal void CheckEraRange(int era) { if (era == Calendar.CurrentEra) { era = CurrentEraValue; } if (era < GetEra(MinDate) || era > GetEra(MaxDate)) { throw new ArgumentOutOfRangeException(nameof(era), era, SR.ArgumentOutOfRange_InvalidEraValue); } } internal int CheckYearRange(int year, int era) { CheckEraRange(era); year = GetGregorianYear(year, era); if (year < MinCalendarYear || year > MaxCalendarYear) { throw new ArgumentOutOfRangeException( nameof(year), year, SR.Format(SR.ArgumentOutOfRange_Range, MinEraCalendarYear(era), MaxEraCalendarYear(era))); } return year; } internal int CheckYearMonthRange(int year, int month, int era) { year = CheckYearRange(year, era); if (month == 13) { // Reject if there is no leap month this year if (GetYearInfo(year, LeapMonth) == 0) { throw new ArgumentOutOfRangeException(nameof(month), month, SR.ArgumentOutOfRange_Month); } } if (month < 1 || month > 13) { throw new ArgumentOutOfRangeException(nameof(month), month, SR.ArgumentOutOfRange_Month); } return year; } internal int InternalGetDaysInMonth(int year, int month) { int mask = 0x8000; // convert the lunar day into a lunar month/date mask >>= (month - 1); if ((GetYearInfo(year, nDaysPerMonth) & mask) == 0) { return 29; } return 30; } /// <summary> /// Returns the number of days in the month given by the year and /// month arguments. /// </summary> public override int GetDaysInMonth(int year, int month, int era) { year = CheckYearMonthRange(year, month, era); return InternalGetDaysInMonth(year, month); } private static bool GregorianIsLeapYear(int y) { if ((y % 4) != 0) { return false; } if ((y % 100) != 0) { return true; } return (y % 400) == 0; } /// <summary> /// Returns the date and time converted to a DateTime value. /// Throws an exception if the n-tuple is invalid. /// </summary> public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { year = CheckYearMonthRange(year, month, era); int daysInMonth = InternalGetDaysInMonth(year, month); if (day < 1 || day > daysInMonth) { throw new ArgumentOutOfRangeException( nameof(day), day, SR.Format(SR.ArgumentOutOfRange_Day, daysInMonth, month)); } if (!LunarToGregorian(year, month, day, out int gy, out int gm, out int gd)) { throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay); } return new DateTime(gy, gm, gd, hour, minute, second, millisecond); } /// <summary> /// Calculates lunar calendar info for the given gregorian year, month, date. /// The input date should be validated before calling this method. /// </summary> private void GregorianToLunar(int solarYear, int solarMonth, int solarDate, out int lunarYear, out int lunarMonth, out int lunarDate) { bool isLeapYear = GregorianIsLeapYear(solarYear); int jan1Month; int jan1Date; // Calculate the day number in the solar year. int solarDay = isLeapYear ? s_daysToMonth366[solarMonth - 1] : s_daysToMonth365[solarMonth - 1]; solarDay += solarDate; // Calculate the day number in the lunar year. int lunarDay = solarDay; lunarYear = solarYear; if (lunarYear == (MaxCalendarYear + 1)) { lunarYear--; lunarDay += (GregorianIsLeapYear(lunarYear) ? 366 : 365); jan1Month = GetYearInfo(lunarYear, Jan1Month); jan1Date = GetYearInfo(lunarYear, Jan1Date); } else { jan1Month = GetYearInfo(lunarYear, Jan1Month); jan1Date = GetYearInfo(lunarYear, Jan1Date); // check if this solar date is actually part of the previous // lunar year if ((solarMonth < jan1Month) || (solarMonth == jan1Month && solarDate < jan1Date)) { // the corresponding lunar day is actually part of the previous // lunar year lunarYear--; // add a solar year to the lunar day # lunarDay += (GregorianIsLeapYear(lunarYear) ? 366 : 365); // update the new start of year jan1Month = GetYearInfo(lunarYear, Jan1Month); jan1Date = GetYearInfo(lunarYear, Jan1Date); } } // convert solar day into lunar day. // subtract off the beginning part of the solar year which is not // part of the lunar year. since this part is always in Jan or Feb, // we don't need to handle Leap Year (LY only affects March // and later). lunarDay -= s_daysToMonth365[jan1Month - 1]; lunarDay -= (jan1Date - 1); // convert the lunar day into a lunar month/date int mask = 0x8000; int yearInfo = GetYearInfo(lunarYear, nDaysPerMonth); int days = ((yearInfo & mask) != 0) ? 30 : 29; lunarMonth = 1; while (lunarDay > days) { lunarDay -= days; lunarMonth++; mask >>= 1; days = ((yearInfo & mask) != 0) ? 30 : 29; } lunarDate = lunarDay; } /// <summary> /// Convert from Lunar to Gregorian /// </summary> /// <remarks> /// Highly inefficient, but it works based on the forward conversion /// </remarks> private bool LunarToGregorian(int lunarYear, int lunarMonth, int lunarDate, out int solarYear, out int solarMonth, out int solarDay) { if (lunarDate < 1 || lunarDate > 30) { solarYear = 0; solarMonth = 0; solarDay = 0; return false; } int numLunarDays = lunarDate - 1; // Add previous months days to form the total num of days from the first of the month. for (int i = 1; i < lunarMonth; i++) { numLunarDays += InternalGetDaysInMonth(lunarYear, i); } // Get Gregorian First of year int jan1Month = GetYearInfo(lunarYear, Jan1Month); int jan1Date = GetYearInfo(lunarYear, Jan1Date); // calc the solar day of year of 1 Lunar day bool isLeapYear = GregorianIsLeapYear(lunarYear); int[] days = isLeapYear ? s_daysToMonth366 : s_daysToMonth365; solarDay = jan1Date; if (jan1Month > 1) { solarDay += days[jan1Month - 1]; } // Add the actual lunar day to get the solar day we want solarDay += numLunarDays; if (solarDay > (365 + (isLeapYear ? 1 : 0))) { solarYear = lunarYear + 1; solarDay -= (365 + (isLeapYear ? 1 : 0)); } else { solarYear = lunarYear; } for (solarMonth = 1; solarMonth < 12; solarMonth++) { if (days[solarMonth] >= solarDay) { break; } } solarDay -= days[solarMonth - 1]; return true; } private DateTime LunarToTime(DateTime time, int year, int month, int day) { LunarToGregorian(year, month, day, out int gy, out int gm, out int gd); return GregorianCalendar.GetDefaultInstance().ToDateTime(gy, gm, gd, time.Hour, time.Minute, time.Second, time.Millisecond); } private void TimeToLunar(DateTime time, out int year, out int month, out int day) { Calendar gregorianCalendar = GregorianCalendar.GetDefaultInstance(); int gy = gregorianCalendar.GetYear(time); int gm = gregorianCalendar.GetMonth(time); int gd = gregorianCalendar.GetDayOfMonth(time); GregorianToLunar(gy, gm, gd, out year, out month, out day); } /// <summary> /// Returns the DateTime resulting from adding the given number of /// months to the specified DateTime. The result is computed by incrementing /// (or decrementing) the year and month parts of the specified DateTime by /// value months, and, if required, adjusting the day part of the /// resulting date downwards to the last day of the resulting month in the /// resulting year. The time-of-day part of the result is the same as the /// time-of-day part of the specified DateTime. /// </summary> public override DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException( nameof(months), months, SR.Format(SR.ArgumentOutOfRange_Range, -120000, 120000)); } CheckTicksRange(time.Ticks); TimeToLunar(time, out int y, out int m, out int d); int i = m + months; if (i > 0) { int monthsInYear = InternalIsLeapYear(y) ? 13 : 12; while (i - monthsInYear > 0) { i -= monthsInYear; y++; monthsInYear = InternalIsLeapYear(y) ? 13 : 12; } m = i; } else { int monthsInYear; while (i <= 0) { monthsInYear = InternalIsLeapYear(y - 1) ? 13 : 12; i += monthsInYear; y--; } m = i; } int days = InternalGetDaysInMonth(y, m); if (d > days) { d = days; } DateTime dt = LunarToTime(time, y, m, d); CheckAddResult(dt.Ticks, MinSupportedDateTime, MaxSupportedDateTime); return dt; } public override DateTime AddYears(DateTime time, int years) { CheckTicksRange(time.Ticks); TimeToLunar(time, out int y, out int m, out int d); y += years; if (m == 13 && !InternalIsLeapYear(y)) { m = 12; d = InternalGetDaysInMonth(y, m); } int daysInMonths = InternalGetDaysInMonth(y, m); if (d > daysInMonths) { d = daysInMonths; } DateTime dt = LunarToTime(time, y, m, d); CheckAddResult(dt.Ticks, MinSupportedDateTime, MaxSupportedDateTime); return dt; } /// <summary> /// Returns the day-of-year part of the specified DateTime. The returned value /// is an integer between 1 and [354|355 |383|384]. /// </summary> public override int GetDayOfYear(DateTime time) { CheckTicksRange(time.Ticks); TimeToLunar(time, out int y, out int m, out int d); for (int i = 1; i < m; i++) { d += InternalGetDaysInMonth(y, i); } return d; } /// <summary> /// Returns the day-of-month part of the specified DateTime. The returned /// value is an integer between 1 and 29 or 30. /// </summary> public override int GetDayOfMonth(DateTime time) { CheckTicksRange(time.Ticks); TimeToLunar(time, out _, out _, out int d); return d; } /// <summary> /// Returns the number of days in the year given by the year argument for the current era. /// </summary> public override int GetDaysInYear(int year, int era) { year = CheckYearRange(year, era); int days = 0; int monthsInYear = InternalIsLeapYear(year) ? 13 : 12; while (monthsInYear != 0) { days += InternalGetDaysInMonth(year, monthsInYear--); } return days; } /// <summary> /// Returns the month part of the specified DateTime. /// The returned value is an integer between 1 and 13. /// </summary> public override int GetMonth(DateTime time) { CheckTicksRange(time.Ticks); TimeToLunar(time, out _, out int m, out _); return m; } /// <summary> /// Returns the year part of the specified DateTime. /// The returned value is an integer between 1 and MaxCalendarYear. /// </summary> public override int GetYear(DateTime time) { CheckTicksRange(time.Ticks); TimeToLunar(time, out int y, out _, out _); return GetYear(y, time); } /// <summary> /// Returns the day-of-week part of the specified DateTime. The returned value /// is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates /// Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates /// Thursday, 5 indicates Friday, and 6 indicates Saturday. /// </summary> public override DayOfWeek GetDayOfWeek(DateTime time) { CheckTicksRange(time.Ticks); return (DayOfWeek)((int)(time.Ticks / Calendar.TicksPerDay + 1) % 7); } /// <summary> /// Returns the number of months in the specified year and era. /// </summary> public override int GetMonthsInYear(int year, int era) { year = CheckYearRange(year, era); return InternalIsLeapYear(year) ? 13 : 12; } /// <summary> /// Checks whether a given day in the specified era is a leap day. /// This method returns true if the date is a leap day, or false if not. /// </summary> public override bool IsLeapDay(int year, int month, int day, int era) { year = CheckYearMonthRange(year, month, era); int daysInMonth = InternalGetDaysInMonth(year, month); if (day < 1 || day > daysInMonth) { throw new ArgumentOutOfRangeException( nameof(day), day, SR.Format(SR.ArgumentOutOfRange_Day, daysInMonth, month)); } int m = GetYearInfo(year, LeapMonth); return (m != 0) && (month == (m + 1)); } /// <summary> /// Checks whether a given month in the specified era is a leap month. /// This method returns true if month is a leap month, or false if not. /// </summary> public override bool IsLeapMonth(int year, int month, int era) { year = CheckYearMonthRange(year, month, era); int m = GetYearInfo(year, LeapMonth); return (m != 0) && (month == (m + 1)); } /// <summary> /// Returns the leap month in a calendar year of the specified era. This method returns 0 /// if this year is not a leap year. /// </summary> public override int GetLeapMonth(int year, int era) { year = CheckYearRange(year, era); int month = GetYearInfo(year, LeapMonth); return month > 0 ? month + 1 : 0; } internal bool InternalIsLeapYear(int year) { return GetYearInfo(year, LeapMonth) != 0; } /// <summary> /// Checks whether a given year in the specified era is a leap year. /// This method returns true if year is a leap year, or false if not. /// </summary> public override bool IsLeapYear(int year, int era) { year = CheckYearRange(year, era); return InternalIsLeapYear(year); } private const int DefaultGregorianTwoDigitYearMax = 2029; public override int TwoDigitYearMax { get { if (_twoDigitYearMax == -1) { _twoDigitYearMax = GetSystemTwoDigitYearSetting(BaseCalendarID, GetYear(new DateTime(DefaultGregorianTwoDigitYearMax, 1, 1))); } return _twoDigitYearMax; } set { VerifyWritable(); if (value < 99 || value > MaxCalendarYear) { throw new ArgumentOutOfRangeException( nameof(value), value, SR.Format(SR.ArgumentOutOfRange_Range, 99, MaxCalendarYear)); } _twoDigitYearMax = value; } } public override int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException( nameof(year), year, SR.ArgumentOutOfRange_NeedNonNegNum); } year = base.ToFourDigitYear(year); CheckYearRange(year, CurrentEra); return year; } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using SDKTemplate; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Windows.ApplicationModel.Resources; using Windows.ApplicationModel.Resources.Core; using Windows.Foundation; using Windows.Globalization; using Windows.Media.SpeechRecognition; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace SDKTemplate { public sealed partial class Scenario_ListConstraint : Page { /// <summary> /// This HResult represents the scenario where a user is prompted to allow in-app speech, but /// declines. This should only happen on a Phone device, where speech is enabled for the entire device, /// not per-app. /// </summary> private static uint HResultPrivacyStatementDeclined = 0x80045509; /// <summary> /// the HResult 0x8004503a typically represents the case where a recognizer for a particular language cannot /// be found. This may occur if the language is installed, but the speech pack for that language is not. /// See Settings -> Time & Language -> Region & Language -> *Language* -> Options -> Speech Language Options. /// </summary> private static uint HResultRecognizerNotFound = 0x8004503a; private SpeechRecognizer speechRecognizer; private ResourceContext speechContext; private ResourceMap speechResourceMap; private bool isPopulatingLanguages = false; private IAsyncOperation<SpeechRecognitionResult> recognitionOperation; public Scenario_ListConstraint() { InitializeComponent(); } /// <summary> /// When activating the scenario, ensure we have permission from the user to access their microphone, and /// provide an appropriate path for the user to enable access to the microphone if they haven't /// given explicit permission for it. /// </summary> /// <param name="e">The navigation event details</param> protected async override void OnNavigatedTo(NavigationEventArgs e) { bool permissionGained = await AudioCapturePermissions.RequestMicrophonePermission(); if (permissionGained) { // Enable the recognition buttons. btnRecognizeWithUI.IsEnabled = true; btnRecognizeWithoutUI.IsEnabled = true; Language speechLanguage = SpeechRecognizer.SystemSpeechLanguage; string langTag = speechLanguage.LanguageTag; speechContext = ResourceContext.GetForCurrentView(); speechContext.Languages = new string[] { langTag }; speechResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("LocalizationSpeechResources"); PopulateLanguageDropdown(); await InitializeRecognizer(SpeechRecognizer.SystemSpeechLanguage); } else { resultTextBlock.Visibility = Visibility.Visible; resultTextBlock.Text = "Permission to access capture resources was not given by the user; please set the application setting in Settings->Privacy->Microphone."; btnRecognizeWithUI.IsEnabled = false; btnRecognizeWithoutUI.IsEnabled = false; cbLanguageSelection.IsEnabled = false; } } /// <summary> /// Look up the supported languages for this speech recognition scenario, /// that are installed on this machine, and populate a dropdown with a list. /// </summary> private void PopulateLanguageDropdown() { // disable the callback so we don't accidentally trigger initialization of the recognizer // while initialization is already in progress. isPopulatingLanguages = true; Language defaultLanguage = SpeechRecognizer.SystemSpeechLanguage; IEnumerable<Language> supportedLanguages = SpeechRecognizer.SupportedGrammarLanguages; foreach(Language lang in supportedLanguages) { ComboBoxItem item = new ComboBoxItem(); item.Tag = lang; item.Content = lang.DisplayName; cbLanguageSelection.Items.Add(item); if(lang.LanguageTag == defaultLanguage.LanguageTag) { item.IsSelected = true; cbLanguageSelection.SelectedItem = item; } } isPopulatingLanguages = false; } /// <summary> /// When a user changes the speech recognition language, trigger re-initialization of the /// speech engine with that language, and change any speech-specific UI assets. /// </summary> /// <param name="sender">Ignored</param> /// <param name="e">Ignored</param> private async void cbLanguageSelection_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (isPopulatingLanguages) { return; } ComboBoxItem item = (ComboBoxItem)(cbLanguageSelection.SelectedItem); Language newLanguage = (Language)item.Tag; if (speechRecognizer != null) { if (speechRecognizer.CurrentLanguage == newLanguage) { return; } } // trigger cleanup and re-initialization of speech. try { // update the context for resource lookup speechContext.Languages = new string[] { newLanguage.LanguageTag }; await InitializeRecognizer(newLanguage); } catch (Exception exception) { var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception"); await messageDialog.ShowAsync(); } } /// <summary> /// Ensure that we clean up any state tracking event handlers created in OnNavigatedTo to prevent leaks, /// dipose the speech recognizer, and clean up to ensure the scenario is not still attempting to recognize /// speech while not in view. /// </summary> /// <param name="e">Details about the navigation event</param> protected override void OnNavigatedFrom(NavigationEventArgs e) { base.OnNavigatedFrom(e); if (speechRecognizer != null) { if (speechRecognizer.State != SpeechRecognizerState.Idle) { if (recognitionOperation != null) { recognitionOperation.Cancel(); recognitionOperation = null; } } speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged; this.speechRecognizer.Dispose(); this.speechRecognizer = null; } } /// <summary> /// Initialize Speech Recognizer and compile constraints. /// </summary> /// <param name="recognizerLanguage">Language to use for the speech recognizer</param> /// <returns>Awaitable task.</returns> private async Task InitializeRecognizer(Language recognizerLanguage) { if(speechRecognizer != null) { // cleanup prior to re-initializing this scenario. speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged; this.speechRecognizer.Dispose(); this.speechRecognizer = null; } try { // Create an instance of SpeechRecognizer. speechRecognizer = new SpeechRecognizer(recognizerLanguage); // Provide feedback to the user about the state of the recognizer. speechRecognizer.StateChanged += SpeechRecognizer_StateChanged; // Add a list constraint to the recognizer. speechRecognizer.Constraints.Add( new SpeechRecognitionListConstraint( new List<string>() { speechResourceMap.GetValue("ListGrammarGoHome", speechContext).ValueAsString }, "Home")); speechRecognizer.Constraints.Add( new SpeechRecognitionListConstraint( new List<string>() { speechResourceMap.GetValue("ListGrammarGoToContosoStudio", speechContext).ValueAsString }, "GoToContosoStudio")); speechRecognizer.Constraints.Add( new SpeechRecognitionListConstraint( new List<string>() { speechResourceMap.GetValue("ListGrammarShowMessage", speechContext).ValueAsString, speechResourceMap.GetValue("ListGrammarOpenMessage", speechContext).ValueAsString }, "Message")); speechRecognizer.Constraints.Add( new SpeechRecognitionListConstraint( new List<string>() { speechResourceMap.GetValue("ListGrammarSendEmail", speechContext).ValueAsString, speechResourceMap.GetValue("ListGrammarCreateEmail", speechContext).ValueAsString }, "Email")); speechRecognizer.Constraints.Add( new SpeechRecognitionListConstraint( new List<string>() { speechResourceMap.GetValue("ListGrammarCallNitaFarley", speechContext).ValueAsString, speechResourceMap.GetValue("ListGrammarCallNita", speechContext).ValueAsString }, "CallNita")); speechRecognizer.Constraints.Add( new SpeechRecognitionListConstraint( new List<string>() { speechResourceMap.GetValue("ListGrammarCallWayneSigmon", speechContext).ValueAsString, speechResourceMap.GetValue("ListGrammarCallWayne", speechContext).ValueAsString }, "CallWayne")); // RecognizeWithUIAsync allows developers to customize the prompts. string uiOptionsText = string.Format("Try saying '{0}', '{1}' or '{2}'", speechResourceMap.GetValue("ListGrammarGoHome", speechContext).ValueAsString, speechResourceMap.GetValue("ListGrammarGoToContosoStudio", speechContext).ValueAsString, speechResourceMap.GetValue("ListGrammarShowMessage", speechContext).ValueAsString); speechRecognizer.UIOptions.ExampleText = uiOptionsText; helpTextBlock.Text = string.Format("{0}\n{1}", speechResourceMap.GetValue("ListGrammarHelpText", speechContext).ValueAsString, uiOptionsText); // Compile the constraint. SpeechRecognitionCompilationResult compilationResult = await speechRecognizer.CompileConstraintsAsync(); // Check to make sure that the constraints were in a proper format and the recognizer was able to compile it. if (compilationResult.Status != SpeechRecognitionResultStatus.Success) { // Disable the recognition buttons. btnRecognizeWithUI.IsEnabled = false; btnRecognizeWithoutUI.IsEnabled = false; // Let the user know that the grammar didn't compile properly. resultTextBlock.Visibility = Visibility.Visible; resultTextBlock.Text = "Unable to compile grammar."; } else { btnRecognizeWithUI.IsEnabled = true; btnRecognizeWithoutUI.IsEnabled = true; resultTextBlock.Visibility = Visibility.Collapsed; } } catch(Exception ex) { if((uint)ex.HResult == HResultRecognizerNotFound) { btnRecognizeWithUI.IsEnabled = false; btnRecognizeWithoutUI.IsEnabled = false; resultTextBlock.Visibility = Visibility.Visible; resultTextBlock.Text = "Speech Language pack for selected language not installed."; } else { var messageDialog = new Windows.UI.Popups.MessageDialog(ex.Message, "Exception"); await messageDialog.ShowAsync(); } } } /// <summary> /// Handle SpeechRecognizer state changed events by updating a UI component. /// </summary> /// <param name="sender">Speech recognizer that generated this status event</param> /// <param name="args">The recognizer's status</param> private async void SpeechRecognizer_StateChanged(SpeechRecognizer sender, SpeechRecognizerStateChangedEventArgs args) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { MainPage.Current.NotifyUser("Speech recognizer state: " + args.State.ToString(), NotifyType.StatusMessage); }); } /// <summary> /// Uses the recognizer constructed earlier to listen for speech from the user before displaying /// it back on the screen. Uses the built-in speech recognition UI. /// </summary> /// <param name="sender">Button that triggered this event</param> /// <param name="e">State information about the routed event</param> private async void RecognizeWithUIListConstraint_Click(object sender, RoutedEventArgs e) { heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Collapsed; // Start recognition. try { recognitionOperation = speechRecognizer.RecognizeWithUIAsync(); SpeechRecognitionResult speechRecognitionResult = await recognitionOperation; // If successful, display the recognition result. if (speechRecognitionResult.Status == SpeechRecognitionResultStatus.Success) { string tag = "unknown"; if(speechRecognitionResult.Constraint != null) { // Only attempt to retreive the tag if we didn't hit the garbage rule. tag = speechRecognitionResult.Constraint.Tag; } heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Visible; resultTextBlock.Text = string.Format("Heard: '{0}', (Tag: '{1}', Confidence: {2})", speechRecognitionResult.Text, tag, speechRecognitionResult.Confidence.ToString()); } else { resultTextBlock.Visibility = Visibility.Visible; resultTextBlock.Text = string.Format("Speech Recognition Failed, Status: {0}", speechRecognitionResult.Status.ToString() ); } } catch (TaskCanceledException exception) { // TaskCanceledException will be thrown if you exit the scenario while the recognizer is actively // processing speech. Since this happens here when we navigate out of the scenario, don't try to // show a message dialog for this exception. System.Diagnostics.Debug.WriteLine("TaskCanceledException caught while recognition in progress (can be ignored):"); System.Diagnostics.Debug.WriteLine(exception.ToString()); } catch (Exception exception) { // Handle the speech privacy policy error. if ((uint)exception.HResult == HResultPrivacyStatementDeclined) { resultTextBlock.Visibility = Visibility.Visible; resultTextBlock.Text = "The privacy statement was declined."; } else { var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception"); await messageDialog.ShowAsync(); } } } /// <summary> /// Uses the recognizer constructed earlier to listen for speech from the user before displaying /// it back on the screen. Uses developer-provided UI for user feedback. /// </summary> /// <param name="sender">Button that triggered this event</param> /// <param name="e">State information about the routed event</param> private async void RecognizeWithoutUIListConstraint_Click(object sender, RoutedEventArgs e) { heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Collapsed; // Disable the UI while recognition is occurring, and provide feedback to the user about current state. btnRecognizeWithUI.IsEnabled = false; btnRecognizeWithoutUI.IsEnabled = false; cbLanguageSelection.IsEnabled = false; listenWithoutUIButtonText.Text = " listening for speech..."; // Start recognition. try { // Save the recognition operation so we can cancel it (as it does not provide a blocking // UI, unlike RecognizeWithAsync() recognitionOperation = speechRecognizer.RecognizeAsync(); SpeechRecognitionResult speechRecognitionResult = await recognitionOperation; // If successful, display the recognition result. A cancelled task should do nothing. if (speechRecognitionResult.Status == SpeechRecognitionResultStatus.Success) { string tag = "unknown"; if (speechRecognitionResult.Constraint != null) { // Only attempt to retreive the tag if we didn't hit the garbage rule. tag = speechRecognitionResult.Constraint.Tag; } heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Visible; resultTextBlock.Text = string.Format("Heard: '{0}', (Tag: '{1}', Confidence: {2})", speechRecognitionResult.Text, tag, speechRecognitionResult.Confidence.ToString()); } else { resultTextBlock.Visibility = Visibility.Visible; resultTextBlock.Text = string.Format("Speech Recognition Failed, Status: {0}", speechRecognitionResult.Status.ToString()); } } catch (TaskCanceledException exception) { // TaskCanceledException will be thrown if you exit the scenario while the recognizer is actively // processing speech. Since this happens here when we navigate out of the scenario, don't try to // show a message dialog for this exception. System.Diagnostics.Debug.WriteLine("TaskCanceledException caught while recognition in progress (can be ignored):"); System.Diagnostics.Debug.WriteLine(exception.ToString()); } catch (Exception exception) { // Handle the speech privacy policy error. if ((uint)exception.HResult == HResultPrivacyStatementDeclined) { resultTextBlock.Visibility = Visibility.Visible; resultTextBlock.Text = "The privacy statement was declined."; } else { var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception"); await messageDialog.ShowAsync(); } } // Reset UI state. listenWithoutUIButtonText.Text = " without UI"; cbLanguageSelection.IsEnabled = true; btnRecognizeWithUI.IsEnabled = true; btnRecognizeWithoutUI.IsEnabled = true; } } }
// Copyright 2016 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using UnityEngine; using System.Collections; using System.Collections.Generic; using System; using UnityEngine.VR.WSA.Persistence; using UnityEngine.VR.WSA; using UnityEngine.Events; [Serializable] public class TrackableLocation : MonoBehaviour { public string id; private WorldAnchorStore store; public GameObject pointStandin; public GameObject anchorStandin; public Transform offset; [SerializeField] private bool m_visualizeTrackingPoints = false; public bool visualizeTrackingPoints { get { return m_visualizeTrackingPoints; } set { m_visualizeTrackingPoints = value; foreach(Transform t in m_trackingPoints) { if (t.childCount == 0) { var instance = (GameObject)GameObject.Instantiate(pointStandin, t, false); } for (int i = 0; i < t.childCount; i++) t.GetChild(i).gameObject.SetActive(value); } } } [SerializeField] private bool m_visualizeAnchorPoints = false; public bool visualizeAnchorPoints { get { return m_visualizeAnchorPoints; } set { m_visualizeAnchorPoints = value; foreach (GameObject anchor in m_anchors) { if (anchor.transform.childCount == 0) { var instance = (GameObject)GameObject.Instantiate(anchorStandin, anchor.transform, false); } for (int i = 0; i < anchor.transform.childCount; i++) anchor.transform.GetChild(i).gameObject.SetActive(value); } } } [SerializeField] private List<Transform> m_trackingPoints = new List<Transform>(); private List<GameObject> m_anchors = new List<GameObject>(); public bool anchored = true; public List<Transform> TrackingPoints { get { return m_trackingPoints; } //set { m_trackingPoints = value; } } public List<GameObject> Anchors { get { return m_anchors; } } public Vector3 forward { get { if (TrackingPoints.Count == 0) return Vector3.zero; return TrackingPoints[TrackingPoints.Count - 1].transform.position - TrackingPoints[0].transform.position; } } public Vector3 up { get { if (TrackingPoints.Count < 3) return Vector3.up; Vector3[] points = new Vector3[TrackingPoints.Count]; for (int i = 0; i < points.Length; i++) points[i] = TrackingPoints[i].transform.position; return MathUtil.getAverageNormal(points); } } public Vector3 right { get { return Vector3.Cross(up, forward); } } public Vector3 center { get { Vector3[] points = new Vector3[TrackingPoints.Count]; for (int i = 0; i < points.Length; i++) points[i] = TrackingPoints[i].transform.position; return MathUtil.getCenter(points); } } public float[] distances { get { Vector3[] points = new Vector3[TrackingPoints.Count]; for (int i = 0; i < points.Length; i++) points[i] = TrackingPoints[i].transform.position; return MathUtil.getDistances(points); } } void OnDrawGizmos() { //show the points foreach (Transform point in m_trackingPoints) { Gizmos.color = new Color(1, 0, 0, 0.5F); Gizmos.DrawCube(point.transform.position, new Vector3(.01f, .01f, .01f)); } //Draw lines connecting the points for (int i = 1; i < m_trackingPoints.Count; i++) { Gizmos.color = new Color(1, 0, 0, 0.5F); Gizmos.DrawLine(m_trackingPoints[i].transform.position, m_trackingPoints[i - 1].transform.position); } //last line if (m_trackingPoints.Count > 2) { Gizmos.color = new Color(1, 0, 0, 0.5F); Gizmos.DrawLine(m_trackingPoints[m_trackingPoints.Count - 1].transform.position, m_trackingPoints[0].transform.position); } //points center Gizmos.color = new Color(0, 0, 1, 0.5F); Vector3[] points = new Vector3[m_trackingPoints.Count]; for (int i = 0; i < points.Length; i++) points[i] = m_trackingPoints[i].transform.position; Vector3 center = MathUtil.getCenter(points); Gizmos.DrawCube(center, new Vector3(.01f, .01f, .01f)); //points normal Gizmos.color = new Color(0, 1, 0, 0.5F); Gizmos.DrawLine(center, center + up); //points pseudo-forward Gizmos.color = new Color(0, 0, 1, 0.5F); Gizmos.DrawLine(center, center + forward); //points pseudo-right Gizmos.color = new Color(1, 0, 0, 0.5F); Gizmos.DrawLine(center, center + right); //transform center Gizmos.color = new Color(0, 1, 0, 0.5F); Gizmos.DrawCube(transform.position, new Vector3(.01f, .01f, .01f)); } void Start() { //retrieve the WorldAnchorStore and load previous calibration values WorldAnchorStore.GetAsync(StoreLoaded); visualizeTrackingPoints = visualizeTrackingPoints; visualizeAnchorPoints = visualizeAnchorPoints; } void Update() { //TODO: Only do this when anchors position change if(anchored) AlignToAnchors(); } public void LoadSavedLocation() { for(int i = 0; i < m_trackingPoints.Count; i++) { if (i >= Anchors.Count) { m_anchors.Add(new GameObject("WAnchor_" + i)); //default location to where the workspace currently is m_anchors[i].transform.position = m_trackingPoints[i].position; } string sub_id = id + "_" + i; if (store.Load(sub_id, m_anchors[i].gameObject)) Debug.Log("Loaded anchor for " + sub_id); else { Debug.Log("Failed to load anchor for " + sub_id+ ", creating new one"); m_anchors[i].gameObject.AddComponent<WorldAnchor>(); } } if (offset) { Vector3 lPos, lRot; lPos.x = PlayerPrefs.GetFloat(gameObject.name + "PX", 0); lPos.y = PlayerPrefs.GetFloat(gameObject.name + "PY", 0); lPos.z = PlayerPrefs.GetFloat(gameObject.name + "PZ", 0); lRot.x = PlayerPrefs.GetFloat(gameObject.name + "RX", 0); lRot.y = PlayerPrefs.GetFloat(gameObject.name + "RY", 0); lRot.z = PlayerPrefs.GetFloat(gameObject.name + "RZ", 0); offset.localPosition = lPos; offset.localRotation = Quaternion.Euler(lRot); } } private void AlignToAnchors() { if (m_anchors.Count == m_trackingPoints.Count) { Vector3 trackingPointsCenter, anchorsGlobalCenter; //transform.rotation = Quaternion.identity; Vector3[] anchorPoints = new Vector3[m_anchors.Count]; for(int i = 0; i < m_anchors.Count; i++) { //points[i] = m_anchors[i].transform.position; anchorPoints[i] = m_anchors[i].transform.position; } //global center anchorsGlobalCenter = MathUtil.getCenter(anchorPoints); Vector3[] localTrackingPoints = new Vector3[m_trackingPoints.Count]; for (int i = 0; i < m_trackingPoints.Count; i++) { //Get the tracking points position relative to the TrackableLocation space localTrackingPoints[i] = this.transform.InverseTransformPoint(m_trackingPoints[i].transform.position); } Vector3 localTrackingPointsNormal = MathUtil.getAverageNormal(localTrackingPoints); Vector3 localForward = localTrackingPoints[localTrackingPoints.Length - 1] - localTrackingPoints[0]; Quaternion originalLookRotation = Quaternion.LookRotation(localForward, localTrackingPointsNormal); // Anchor's normal Vector3 anchorsNormal = MathUtil.getAverageNormal(anchorPoints); Vector3 anchorsForward = anchorPoints[anchorPoints.Length - 1] - anchorPoints[0]; Quaternion anchorsLookRotation = Quaternion.LookRotation(anchorsForward, anchorsNormal);// Quaternion deltaRotation = anchorsLookRotation * Quaternion.Inverse(originalLookRotation); transform.rotation = deltaRotation; trackingPointsCenter = this.center; Vector3 deltaPosition = anchorsGlobalCenter - trackingPointsCenter; transform.position += deltaPosition; if(offset) { transform.rotation = offset.localRotation * transform.rotation; transform.position += offset.localPosition; } } } public void SaveLocation() { if (store != null) { for (int i = 0; i < m_anchors.Count; i++) { WorldAnchor anchor = m_anchors[i].gameObject.GetComponent<WorldAnchor>(); if (anchor == null) anchor = m_anchors[i].gameObject.AddComponent<WorldAnchor>(); string sub_id = id + "_" + i; if (store.Delete(sub_id)) { Debug.Log("Deleted anchor for " + sub_id); } else { Debug.Log("Failed to delete anchor for " + sub_id); } if (store.Save(sub_id, anchor)) Debug.Log("Saved anchor for " + sub_id); else Debug.Log("Failed to save anchor for " + sub_id); } SaveOffset(); } else Debug.Log("Unable to save location, store not loaded"); } public void SaveOffset() { if (offset) { PlayerPrefs.SetFloat(gameObject.name + "PX", offset.localPosition.x); PlayerPrefs.SetFloat(gameObject.name + "PY", offset.localPosition.y); PlayerPrefs.SetFloat(gameObject.name + "PZ", offset.localPosition.z); var lAngle = offset.localRotation.eulerAngles; PlayerPrefs.SetFloat(gameObject.name + "RX", lAngle.x); PlayerPrefs.SetFloat(gameObject.name + "RY", lAngle.y); PlayerPrefs.SetFloat(gameObject.name + "RZ", lAngle.z); PlayerPrefs.Save(); } } private void OnApplicationPause(bool pause) { if (pause) SaveOffset(); } private void StoreLoaded(WorldAnchorStore store) { this.store = store; LoadSavedLocation(); } public void ResetOffset() { if(offset) { offset.localPosition = Vector3.zero; offset.localRotation = Quaternion.identity; } } }
using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Abp.Application.Editions; using Abp.Application.Features; using Abp.Authorization.Roles; using Abp.Authorization.Users; using Abp.Collections.Extensions; using Abp.Domain.Repositories; using Abp.Domain.Services; using Abp.Domain.Uow; using Abp.Events.Bus.Entities; using Abp.Events.Bus.Handlers; using Abp.IdentityFramework; using Abp.Localization; using Abp.Runtime.Caching; using Abp.Zero; using Microsoft.AspNet.Identity; namespace Abp.MultiTenancy { /// <summary> /// Tenant manager. /// Implements domain logic for <see cref="AbpTenant{TTenant,TUser}"/>. /// </summary> /// <typeparam name="TTenant">Type of the application Tenant</typeparam> /// <typeparam name="TRole">Type of the application Role</typeparam> /// <typeparam name="TUser">Type of the application User</typeparam> public abstract class AbpTenantManager<TTenant, TRole, TUser> : IDomainService, IEventHandler<EntityChangedEventData<TTenant>>, IEventHandler<EntityDeletedEventData<Edition>> where TTenant : AbpTenant<TTenant, TUser> where TRole : AbpRole<TTenant, TUser> where TUser : AbpUser<TTenant, TUser> { public AbpEditionManager EditionManager { get; set; } public ILocalizationManager LocalizationManager { get; set; } public ICacheManager CacheManager { get; set; } public IRepository<TTenant> TenantRepository { get; set; } public IRepository<TenantFeatureSetting, long> TenantFeatureRepository { get; set; } public IFeatureManager FeatureManager { get; set; } protected AbpTenantManager(AbpEditionManager editionManager) { EditionManager = editionManager; LocalizationManager = NullLocalizationManager.Instance; } public virtual IQueryable<TTenant> Tenants { get { return TenantRepository.GetAll(); } } public virtual async Task<IdentityResult> CreateAsync(TTenant tenant) { if (await TenantRepository.FirstOrDefaultAsync(t => t.TenancyName == tenant.TenancyName) != null) { return AbpIdentityResult.Failed(string.Format(L("TenancyNameIsAlreadyTaken"), tenant.TenancyName)); } var validationResult = await ValidateTenantAsync(tenant); if (!validationResult.Succeeded) { return validationResult; } await TenantRepository.InsertAsync(tenant); return IdentityResult.Success; } public async Task<IdentityResult> UpdateAsync(TTenant tenant) { if (await TenantRepository.FirstOrDefaultAsync(t => t.TenancyName == tenant.TenancyName && t.Id != tenant.Id) != null) { return AbpIdentityResult.Failed(string.Format(L("TenancyNameIsAlreadyTaken"), tenant.TenancyName)); } await TenantRepository.UpdateAsync(tenant); return IdentityResult.Success; } public virtual async Task<TTenant> FindByIdAsync(int id) { return await TenantRepository.FirstOrDefaultAsync(id); } public virtual async Task<TTenant> GetByIdAsync(int id) { var tenant = await FindByIdAsync(id); if (tenant == null) { throw new AbpException("There is no tenant with id: " + id); } return tenant; } public virtual Task<TTenant> FindByTenancyNameAsync(string tenancyName) { return TenantRepository.FirstOrDefaultAsync(t => t.TenancyName == tenancyName); } public virtual async Task<IdentityResult> DeleteAsync(TTenant tenant) { await TenantRepository.DeleteAsync(tenant); return IdentityResult.Success; } public async Task<string> GetFeatureValueOrNullAsync(int tenantId, string featureName) { var cacheItem = await GetTenantFeatureCacheItemAsync(tenantId); var value = cacheItem.FeatureValues.GetOrDefault(featureName); if (value != null) { return value; } if (cacheItem.EditionId.HasValue) { value = await EditionManager.GetFeatureValueOrNullAsync(cacheItem.EditionId.Value, featureName); if (value != null) { return value; } } return null; } public virtual async Task<IReadOnlyList<NameValue>> GetFeatureValuesAsync(int tenantId) { var values = new List<NameValue>(); foreach (var feature in FeatureManager.GetAll()) { values.Add(new NameValue(feature.Name, await GetFeatureValueOrNullAsync(tenantId, feature.Name) ?? feature.DefaultValue)); } return values; } public virtual async Task SetFeatureValuesAsync(int tenantId, params NameValue[] values) { if (values.IsNullOrEmpty()) { return; } foreach (var value in values) { await SetFeatureValueAsync(tenantId, value.Name, value.Value); } } [UnitOfWork] public virtual async Task SetFeatureValueAsync(int tenantId, string featureName, string value) { await SetFeatureValueAsync(await GetByIdAsync(tenantId), featureName, value); } [UnitOfWork] public virtual async Task SetFeatureValueAsync(TTenant tenant, string featureName, string value) { //No need to change if it's already equals to the current value if (await GetFeatureValueOrNullAsync(tenant.Id, featureName) == value) { return; } //Get the current feature setting var currentSetting = await TenantFeatureRepository.FirstOrDefaultAsync(f => f.TenantId == tenant.Id && f.Name == featureName); //Get the feature var feature = FeatureManager.GetOrNull(featureName); if (feature == null) { if (currentSetting != null) { await TenantFeatureRepository.DeleteAsync(currentSetting); } return; } //Determine default value var defaultValue = tenant.EditionId.HasValue ? (await EditionManager.GetFeatureValueOrNullAsync(tenant.EditionId.Value, featureName) ?? feature.DefaultValue) : feature.DefaultValue; //No need to store value if it's default if (value == defaultValue) { if (currentSetting != null) { await TenantFeatureRepository.DeleteAsync(currentSetting); } return; } //Insert/update the feature value if (currentSetting == null) { await TenantFeatureRepository.InsertAsync(new TenantFeatureSetting(tenant.Id, featureName, value)); } else { currentSetting.Value = value; } } /// <summary> /// Resets all custom feature settings for a tenant. /// Tenant will have features according to it's edition. /// </summary> /// <param name="tenantId">Tenant Id</param> public async Task ResetAllFeaturesAsync(int tenantId) { await TenantFeatureRepository.DeleteAsync(f => f.TenantId == tenantId); } private async Task<TenantFeatureCacheItem> GetTenantFeatureCacheItemAsync(int tenantId) { return await CacheManager.GetTenantFeatureCache().GetAsync(tenantId, async () => { var tenant = await GetByIdAsync(tenantId); var newCacheItem = new TenantFeatureCacheItem { EditionId = tenant.EditionId }; var featureSettings = await TenantFeatureRepository.GetAllListAsync(f => f.TenantId == tenantId); foreach (var featureSetting in featureSettings) { newCacheItem.FeatureValues[featureSetting.Name] = featureSetting.Value; } return newCacheItem; }); } protected virtual async Task<IdentityResult> ValidateTenantAsync(TTenant tenant) { var nameValidationResult = await ValidateTenancyNameAsync(tenant.TenancyName); if (!nameValidationResult.Succeeded) { return nameValidationResult; } return IdentityResult.Success; } protected virtual async Task<IdentityResult> ValidateTenancyNameAsync(string tenancyName) { if (!Regex.IsMatch(tenancyName, AbpTenant<TTenant, TUser>.TenancyNameRegex)) { return AbpIdentityResult.Failed(L("InvalidTenancyName")); } return IdentityResult.Success; } private string L(string name) { return LocalizationManager.GetString(AbpZeroConsts.LocalizationSourceName, name); } public void HandleEvent(EntityChangedEventData<TTenant> eventData) { if (eventData.Entity.IsTransient()) { return; } CacheManager.GetTenantFeatureCache().Remove(eventData.Entity.Id); } [UnitOfWork] public virtual void HandleEvent(EntityDeletedEventData<Edition> eventData) { var relatedTenants = TenantRepository.GetAllList(t => t.EditionId == eventData.Entity.Id); foreach (var relatedTenant in relatedTenants) { relatedTenant.EditionId = null; } } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using osu.Framework.Development; using osu.Framework.Graphics.Batches; using osu.Framework.Graphics.Primitives; using osuTK.Graphics.ES30; using osu.Framework.Statistics; using osu.Framework.Graphics.Colour; using osu.Framework.Graphics.OpenGL.Vertices; using osu.Framework.Graphics.Textures; using osu.Framework.Lists; using osu.Framework.Platform; using osuTK; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Advanced; using SixLabors.ImageSharp.PixelFormats; namespace osu.Framework.Graphics.OpenGL.Textures { internal class TextureGLSingle : TextureGL { /// <summary> /// Contains all currently-active <see cref="TextureGLSingle"/>es. /// </summary> private static readonly LockedWeakList<TextureGLSingle> all_textures = new LockedWeakList<TextureGLSingle>(); public const int MAX_MIPMAP_LEVELS = 3; private static readonly Action<TexturedVertex2D> default_quad_action = new QuadBatch<TexturedVertex2D>(100, 1000).AddAction; private readonly Queue<ITextureUpload> uploadQueue = new Queue<ITextureUpload>(); /// <summary> /// Invoked when a new <see cref="TextureGLAtlas"/> is created. /// </summary> /// <remarks> /// Invocation from the draw or update thread cannot be assumed. /// </remarks> public static event Action<TextureGLSingle> TextureCreated; private int internalWidth; private int internalHeight; private readonly All filteringMode; /// <summary> /// The total amount of times this <see cref="TextureGLSingle"/> was bound. /// </summary> public ulong BindCount { get; protected set; } // ReSharper disable once InconsistentlySynchronizedField (no need to lock here. we don't really care if the value is stale). public override bool Loaded => textureId > 0 || uploadQueue.Count > 0; public override RectangleI Bounds => new RectangleI(0, 0, Width, Height); /// <summary> /// Creates a new <see cref="TextureGLSingle"/>. /// </summary> /// <param name="width">The width of the texture.</param> /// <param name="height">The height of the texture.</param> /// <param name="manualMipmaps">Whether manual mipmaps will be uploaded to the texture. If false, the texture will compute mipmaps automatically.</param> /// <param name="filteringMode">The filtering mode.</param> /// <param name="wrapModeS">The texture wrap mode in horizontal direction.</param> /// <param name="wrapModeT">The texture wrap mode in vertical direction.</param> public TextureGLSingle(int width, int height, bool manualMipmaps = false, All filteringMode = All.Linear, WrapMode wrapModeS = WrapMode.None, WrapMode wrapModeT = WrapMode.None) : base(wrapModeS, wrapModeT) { Width = width; Height = height; this.manualMipmaps = manualMipmaps; this.filteringMode = filteringMode; all_textures.Add(this); TextureCreated?.Invoke(this); } /// <summary> /// Retrieves all currently-active <see cref="TextureGLSingle"/>s. /// </summary> public static TextureGLSingle[] GetAllTextures() => all_textures.ToArray(); #region Disposal protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); all_textures.Remove(this); while (tryGetNextUpload(out var upload)) upload.Dispose(); GLWrapper.ScheduleDisposal(unload); } /// <summary> /// Removes texture from GL memory. /// </summary> private void unload() { int disposableId = textureId; if (disposableId <= 0) return; GL.DeleteTextures(1, new[] { disposableId }); memoryLease?.Dispose(); textureId = 0; } #endregion #region Memory Tracking private List<long> levelMemoryUsage = new List<long>(); private NativeMemoryTracker.NativeMemoryLease memoryLease; private void updateMemoryUsage(int level, long newUsage) { levelMemoryUsage ??= new List<long>(); while (level >= levelMemoryUsage.Count) levelMemoryUsage.Add(0); levelMemoryUsage[level] = newUsage; memoryLease?.Dispose(); memoryLease = NativeMemoryTracker.AddMemory(this, getMemoryUsage()); } private long getMemoryUsage() { long usage = 0; for (int i = 0; i < levelMemoryUsage.Count; i++) usage += levelMemoryUsage[i]; return usage; } #endregion private int height; public override TextureGL Native => this; public override int Height { get => height; set => height = value; } private int width; public override int Width { get => width; set => width = value; } private int textureId; public override int TextureId { get { if (!Available) throw new ObjectDisposedException(ToString(), "Can not obtain ID of a disposed texture."); if (textureId == 0) throw new InvalidOperationException("Can not obtain ID of a texture before uploading it."); return textureId; } } /// <summary> /// Retrieves the size of this texture in bytes. /// </summary> public virtual int GetByteSize() => Width * Height * 4; private static void rotateVector(ref Vector2 toRotate, float sin, float cos) { float oldX = toRotate.X; toRotate.X = toRotate.X * cos - toRotate.Y * sin; toRotate.Y = oldX * sin + toRotate.Y * cos; } public override RectangleF GetTextureRect(RectangleF? textureRect) { RectangleF texRect = textureRect != null ? new RectangleF(textureRect.Value.X, textureRect.Value.Y, textureRect.Value.Width, textureRect.Value.Height) : new RectangleF(0, 0, Width, Height); texRect.X /= width; texRect.Y /= height; texRect.Width /= width; texRect.Height /= height; return texRect; } public const int VERTICES_PER_TRIANGLE = 4; internal override void DrawTriangle(Triangle vertexTriangle, ColourInfo drawColour, RectangleF? textureRect = null, Action<TexturedVertex2D> vertexAction = null, Vector2? inflationPercentage = null, RectangleF? textureCoords = null) { if (!Available) throw new ObjectDisposedException(ToString(), "Can not draw a triangle with a disposed texture."); RectangleF texRect = GetTextureRect(textureRect); Vector2 inflationAmount = inflationPercentage.HasValue ? new Vector2(inflationPercentage.Value.X * texRect.Width, inflationPercentage.Value.Y * texRect.Height) : Vector2.Zero; // If clamp to edge is active, allow the texture coordinates to penetrate by half the repeated atlas margin width if (GLWrapper.CurrentWrapModeS == WrapMode.ClampToEdge || GLWrapper.CurrentWrapModeT == WrapMode.ClampToEdge) { Vector2 inflationVector = Vector2.Zero; const int mipmap_padding_requirement = (1 << MAX_MIPMAP_LEVELS) / 2; if (GLWrapper.CurrentWrapModeS == WrapMode.ClampToEdge) inflationVector.X = mipmap_padding_requirement / (float)width; if (GLWrapper.CurrentWrapModeT == WrapMode.ClampToEdge) inflationVector.Y = mipmap_padding_requirement / (float)height; texRect = texRect.Inflate(inflationVector); } RectangleF coordRect = GetTextureRect(textureCoords ?? textureRect); RectangleF inflatedCoordRect = coordRect.Inflate(inflationAmount); vertexAction ??= default_quad_action; // We split the triangle into two, such that we can obtain smooth edges with our // texture coordinate trick. We might want to revert this to drawing a single // triangle in case we ever need proper texturing, or if the additional vertices // end up becoming an overhead (unlikely). SRGBColour topColour = (drawColour.TopLeft + drawColour.TopRight) / 2; SRGBColour bottomColour = (drawColour.BottomLeft + drawColour.BottomRight) / 2; vertexAction(new TexturedVertex2D { Position = vertexTriangle.P0, TexturePosition = new Vector2((inflatedCoordRect.Left + inflatedCoordRect.Right) / 2, inflatedCoordRect.Top), TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom), BlendRange = inflationAmount, Colour = topColour.Linear, }); vertexAction(new TexturedVertex2D { Position = vertexTriangle.P1, TexturePosition = new Vector2(inflatedCoordRect.Left, inflatedCoordRect.Bottom), TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom), BlendRange = inflationAmount, Colour = drawColour.BottomLeft.Linear, }); vertexAction(new TexturedVertex2D { Position = (vertexTriangle.P1 + vertexTriangle.P2) / 2, TexturePosition = new Vector2((inflatedCoordRect.Left + inflatedCoordRect.Right) / 2, inflatedCoordRect.Bottom), TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom), BlendRange = inflationAmount, Colour = bottomColour.Linear, }); vertexAction(new TexturedVertex2D { Position = vertexTriangle.P2, TexturePosition = new Vector2(inflatedCoordRect.Right, inflatedCoordRect.Bottom), TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom), BlendRange = inflationAmount, Colour = drawColour.BottomRight.Linear, }); FrameStatistics.Add(StatisticsCounterType.Pixels, (long)vertexTriangle.Area); } public const int VERTICES_PER_QUAD = 4; internal override void DrawQuad(Quad vertexQuad, ColourInfo drawColour, RectangleF? textureRect = null, Action<TexturedVertex2D> vertexAction = null, Vector2? inflationPercentage = null, Vector2? blendRangeOverride = null, RectangleF? textureCoords = null) { if (!Available) throw new ObjectDisposedException(ToString(), "Can not draw a quad with a disposed texture."); RectangleF texRect = GetTextureRect(textureRect); Vector2 inflationAmount = inflationPercentage.HasValue ? new Vector2(inflationPercentage.Value.X * texRect.Width, inflationPercentage.Value.Y * texRect.Height) : Vector2.Zero; // If clamp to edge is active, allow the texture coordinates to penetrate by half the repeated atlas margin width if (GLWrapper.CurrentWrapModeS == WrapMode.ClampToEdge || GLWrapper.CurrentWrapModeT == WrapMode.ClampToEdge) { Vector2 inflationVector = Vector2.Zero; const int mipmap_padding_requirement = (1 << MAX_MIPMAP_LEVELS) / 2; if (GLWrapper.CurrentWrapModeS == WrapMode.ClampToEdge) inflationVector.X = mipmap_padding_requirement / (float)width; if (GLWrapper.CurrentWrapModeT == WrapMode.ClampToEdge) inflationVector.Y = mipmap_padding_requirement / (float)height; texRect = texRect.Inflate(inflationVector); } RectangleF coordRect = GetTextureRect(textureCoords ?? textureRect); RectangleF inflatedCoordRect = coordRect.Inflate(inflationAmount); Vector2 blendRange = blendRangeOverride ?? inflationAmount; vertexAction ??= default_quad_action; vertexAction(new TexturedVertex2D { Position = vertexQuad.BottomLeft, TexturePosition = new Vector2(inflatedCoordRect.Left, inflatedCoordRect.Bottom), TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom), BlendRange = blendRange, Colour = drawColour.BottomLeft.Linear, }); vertexAction(new TexturedVertex2D { Position = vertexQuad.BottomRight, TexturePosition = new Vector2(inflatedCoordRect.Right, inflatedCoordRect.Bottom), TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom), BlendRange = blendRange, Colour = drawColour.BottomRight.Linear, }); vertexAction(new TexturedVertex2D { Position = vertexQuad.TopRight, TexturePosition = new Vector2(inflatedCoordRect.Right, inflatedCoordRect.Top), TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom), BlendRange = blendRange, Colour = drawColour.TopRight.Linear, }); vertexAction(new TexturedVertex2D { Position = vertexQuad.TopLeft, TexturePosition = new Vector2(inflatedCoordRect.Left, inflatedCoordRect.Top), TextureRect = new Vector4(texRect.Left, texRect.Top, texRect.Right, texRect.Bottom), BlendRange = blendRange, Colour = drawColour.TopLeft.Linear, }); FrameStatistics.Add(StatisticsCounterType.Pixels, (long)vertexQuad.Area); } internal override void SetData(ITextureUpload upload, WrapMode wrapModeS, WrapMode wrapModeT, Opacity? uploadOpacity) { if (!Available) throw new ObjectDisposedException(ToString(), "Can not set data of a disposed texture."); if (upload.Bounds.IsEmpty && upload.Data.Length > 0) { upload.Bounds = Bounds; if (width * height > upload.Data.Length) throw new InvalidOperationException($"Size of texture upload ({width}x{height}) does not contain enough data ({upload.Data.Length} < {width * height})"); } UpdateOpacity(upload, ref uploadOpacity); lock (uploadQueue) { bool requireUpload = uploadQueue.Count == 0; uploadQueue.Enqueue(upload); if (requireUpload && !BypassTextureUploadQueueing) GLWrapper.EnqueueTextureUpload(this); } } internal override bool Bind(TextureUnit unit, WrapMode wrapModeS, WrapMode wrapModeT) { if (!Available) throw new ObjectDisposedException(ToString(), "Can not bind a disposed texture."); Upload(); if (textureId <= 0) return false; if (GLWrapper.BindTexture(this, unit, wrapModeS, wrapModeT)) BindCount++; return true; } private bool manualMipmaps; internal override unsafe bool Upload() { if (!Available) return false; // We should never run raw OGL calls on another thread than the main thread due to race conditions. ThreadSafety.EnsureDrawThread(); bool didUpload = false; while (tryGetNextUpload(out ITextureUpload upload)) { using (upload) { fixed (Rgba32* ptr = upload.Data) DoUpload(upload, (IntPtr)ptr); didUpload = true; } } if (didUpload && !manualMipmaps) { GL.Hint(HintTarget.GenerateMipmapHint, HintMode.Nicest); GL.GenerateMipmap(TextureTarget.Texture2D); } return didUpload; } internal override void FlushUploads() { while (tryGetNextUpload(out var upload)) upload.Dispose(); } private bool tryGetNextUpload(out ITextureUpload upload) { lock (uploadQueue) { if (uploadQueue.Count == 0) { upload = null; return false; } upload = uploadQueue.Dequeue(); return true; } } protected virtual void DoUpload(ITextureUpload upload, IntPtr dataPointer) { // Do we need to generate a new texture? if (textureId <= 0 || internalWidth != width || internalHeight != height) { internalWidth = width; internalHeight = height; // We only need to generate a new texture if we don't have one already. Otherwise just re-use the current one. if (textureId <= 0) { int[] textures = new int[1]; GL.GenTextures(1, textures); textureId = textures[0]; GLWrapper.BindTexture(this); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureBaseLevel, 0); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMaxLevel, MAX_MIPMAP_LEVELS); // These shouldn't be required, but on some older Intel drivers the MAX_LOD chosen by the shader isn't clamped to the MAX_LEVEL from above, resulting in disappearing textures. GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinLod, 0); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMaxLod, MAX_MIPMAP_LEVELS); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)(manualMipmaps ? filteringMode : filteringMode == All.Linear ? All.LinearMipmapLinear : All.Nearest)); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)filteringMode); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge); } else GLWrapper.BindTexture(this); if (width == upload.Bounds.Width && height == upload.Bounds.Height || dataPointer == IntPtr.Zero) { updateMemoryUsage(upload.Level, (long)width * height * 4); GL.TexImage2D(TextureTarget2d.Texture2D, upload.Level, TextureComponentCount.Srgb8Alpha8, width, height, 0, upload.Format, PixelType.UnsignedByte, dataPointer); } else { initializeLevel(upload.Level, width, height); GL.TexSubImage2D(TextureTarget2d.Texture2D, upload.Level, upload.Bounds.X, upload.Bounds.Y, upload.Bounds.Width, upload.Bounds.Height, upload.Format, PixelType.UnsignedByte, dataPointer); } } // Just update content of the current texture else if (dataPointer != IntPtr.Zero) { GLWrapper.BindTexture(this); if (!manualMipmaps && upload.Level > 0) { //allocate mipmap levels int level = 1; int d = 2; while (width / d > 0) { initializeLevel(level, width / d, height / d); level++; d *= 2; } manualMipmaps = true; } int div = (int)Math.Pow(2, upload.Level); GL.TexSubImage2D(TextureTarget2d.Texture2D, upload.Level, upload.Bounds.X / div, upload.Bounds.Y / div, upload.Bounds.Width / div, upload.Bounds.Height / div, upload.Format, PixelType.UnsignedByte, dataPointer); } } private unsafe void initializeLevel(int level, int width, int height) { using (var image = new Image<Rgba32>(width, height)) { fixed (void* buffer = &MemoryMarshal.GetReference(image.GetPixelSpan())) { updateMemoryUsage(level, (long)width * height * 4); GL.TexImage2D(TextureTarget2d.Texture2D, level, TextureComponentCount.Srgb8Alpha8, width, height, 0, PixelFormat.Rgba, PixelType.UnsignedByte, (IntPtr)buffer); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel.Composition.Primitives; using System.Linq; using System.Reflection; using Microsoft.Internal; using Xunit; namespace System.ComponentModel.Composition.ReflectionModel { public class ReflectionComposablePartDefinitionTests { private ReflectionComposablePartDefinition CreateReflectionPartDefinition( Lazy<Type> partType, bool requiresDisposal, Func<IEnumerable<ImportDefinition>> imports, Func<IEnumerable<ExportDefinition>>exports, IDictionary<string, object> metadata, ICompositionElement origin) { return (ReflectionComposablePartDefinition)ReflectionModelServices.CreatePartDefinition(partType, requiresDisposal, new Lazy<IEnumerable<ImportDefinition>>(imports, false), new Lazy<IEnumerable<ExportDefinition>>(exports, false), metadata.AsLazy(), origin); } [Fact] public void Constructor() { Type expectedType = typeof(TestPart); Lazy<Type> expectedLazyType = expectedType.AsLazy(); IDictionary<string, object> expectedMetadata = new Dictionary<string, object>(); expectedMetadata["Key1"] = 1; expectedMetadata["Key2"] = "Value2"; IEnumerable<ImportDefinition> expectedImports = CreateImports(expectedType); IEnumerable<ExportDefinition> expectedExports = CreateExports(expectedType); ICompositionElement expectedOrigin = new MockOrigin(); ReflectionComposablePartDefinition definition = CreateReflectionPartDefinition( expectedLazyType, false, () => expectedImports, () => expectedExports, expectedMetadata, expectedOrigin); Assert.Same(expectedType, definition.GetPartType()); Assert.True(definition.Metadata.Keys.SequenceEqual(expectedMetadata.Keys)); Assert.True(definition.Metadata.Values.SequenceEqual(expectedMetadata.Values)); Assert.True(definition.ExportDefinitions.SequenceEqual(expectedExports.Cast<ExportDefinition>())); Assert.True(definition.ImportDefinitions.SequenceEqual(expectedImports.Cast<ImportDefinition>())); Assert.Same(expectedOrigin, ((ICompositionElement)definition).Origin); Assert.NotNull(((ICompositionElement)definition).DisplayName); Assert.False(definition.IsDisposalRequired); } [Fact] public void Constructor_DisposablePart() { Type expectedType = typeof(TestPart); Lazy<Type> expectedLazyType = expectedType.AsLazy(); IDictionary<string, object> expectedMetadata = new Dictionary<string, object>(); expectedMetadata["Key1"] = 1; expectedMetadata["Key2"] = "Value2"; IEnumerable<ImportDefinition> expectedImports = CreateImports(expectedType); IEnumerable<ExportDefinition> expectedExports = CreateExports(expectedType); ICompositionElement expectedOrigin = new MockOrigin(); ReflectionComposablePartDefinition definition = CreateReflectionPartDefinition( expectedLazyType, true, () => expectedImports, () => expectedExports, expectedMetadata, expectedOrigin); Assert.Same(expectedType, definition.GetPartType()); Assert.True(definition.Metadata.Keys.SequenceEqual(expectedMetadata.Keys)); Assert.True(definition.Metadata.Values.SequenceEqual(expectedMetadata.Values)); Assert.True(definition.ExportDefinitions.SequenceEqual(expectedExports.Cast<ExportDefinition>())); Assert.True(definition.ImportDefinitions.SequenceEqual(expectedImports.Cast<ImportDefinition>())); Assert.Same(expectedOrigin, ((ICompositionElement)definition).Origin); Assert.NotNull(((ICompositionElement)definition).DisplayName); Assert.True(definition.IsDisposalRequired); } [Fact] public void CreatePart() { Type expectedType = typeof(TestPart); Lazy<Type> expectedLazyType = expectedType.AsLazy(); IDictionary<string, object> expectedMetadata = new Dictionary<string, object>(); expectedMetadata["Key1"] = 1; expectedMetadata["Key2"] = "Value2"; IEnumerable<ImportDefinition> expectedImports = CreateImports(expectedType); IEnumerable<ExportDefinition> expectedExports = CreateExports(expectedType); ICompositionElement expectedOrigin = new MockOrigin(); ReflectionComposablePartDefinition definition = CreateReflectionPartDefinition( expectedLazyType, false, () => expectedImports, () => expectedExports, expectedMetadata, expectedOrigin); var part = definition.CreatePart(); Assert.NotNull(part); Assert.False(part is IDisposable); } [Fact] public void CreatePart_Disposable() { Type expectedType = typeof(TestPart); Lazy<Type> expectedLazyType = expectedType.AsLazy(); IDictionary<string, object> expectedMetadata = new Dictionary<string, object>(); expectedMetadata["Key1"] = 1; expectedMetadata["Key2"] = "Value2"; IEnumerable<ImportDefinition> expectedImports = CreateImports(expectedType); IEnumerable<ExportDefinition> expectedExports = CreateExports(expectedType); ICompositionElement expectedOrigin = new MockOrigin(); ReflectionComposablePartDefinition definition = CreateReflectionPartDefinition( expectedLazyType, true, () => expectedImports, () => expectedExports, expectedMetadata, expectedOrigin); var part = definition.CreatePart(); Assert.NotNull(part); Assert.True(part is IDisposable); } [Fact] public void CreatePart_DoesntLoadType() { Type expectedType = typeof(TestPart); Lazy<Type> expectedLazyType = new Lazy<Type>(() => { throw new NotImplementedException(); /*"Part should not be loaded" */ }); IDictionary<string, object> expectedMetadata = new Dictionary<string, object>(); expectedMetadata["Key1"] = 1; expectedMetadata["Key2"] = "Value2"; IEnumerable<ImportDefinition> expectedImports = CreateImports(expectedType); IEnumerable<ExportDefinition> expectedExports = CreateExports(expectedType); ICompositionElement expectedOrigin = new MockOrigin(); ReflectionComposablePartDefinition definition = CreateReflectionPartDefinition( expectedLazyType, true, () => expectedImports, () => expectedExports, expectedMetadata, expectedOrigin); var part = definition.CreatePart(); Assert.NotNull(part); Assert.True(part is IDisposable); } [Fact] public void Constructor_NullMetadata_ShouldSetMetadataPropertyToEmpty() { ReflectionComposablePartDefinition definition = CreateEmptyDefinition(typeof(object), typeof(object).GetConstructors().First(), null, new MockOrigin()); Assert.NotNull(definition.Metadata); Assert.Equal(0, definition.Metadata.Count); } [Fact] public void Constructor_NullOrigin_ShouldSetOriginPropertyToNull() { ReflectionComposablePartDefinition definition = CreateEmptyDefinition(typeof(object), typeof(object).GetConstructors().First(), MetadataServices.EmptyMetadata, null); Assert.NotNull(((ICompositionElement)definition).DisplayName); Assert.Null(((ICompositionElement)definition).Origin); } [Fact] public void ImportaAndExports_CreatorsShouldBeCalledLazilyAndOnce() { Type expectedType = typeof(TestPart); IEnumerable<ImportDefinition> expectedImports = CreateImports(expectedType); IEnumerable<ExportDefinition> expectedExports = CreateExports(expectedType); bool importsCreatorCalled = false; Func<IEnumerable<ImportDefinition>> importsCreator = () => { Assert.False(importsCreatorCalled); importsCreatorCalled = true; return expectedImports.Cast<ImportDefinition>(); }; bool exportsCreatorCalled = false; Func<IEnumerable<ExportDefinition>> exportsCreator = () => { Assert.False(exportsCreatorCalled); exportsCreatorCalled = true; return expectedExports.Cast<ExportDefinition>(); }; ReflectionComposablePartDefinition definition = CreateReflectionPartDefinition( expectedType.AsLazy(), false, importsCreator, exportsCreator, null, null); IEnumerable<ExportDefinition> exports; Assert.False(exportsCreatorCalled); exports = definition.ExportDefinitions; Assert.True(exportsCreatorCalled); exports = definition.ExportDefinitions; IEnumerable<ImportDefinition> imports; Assert.False(importsCreatorCalled); imports = definition.ImportDefinitions; Assert.True(importsCreatorCalled); imports = definition.ImportDefinitions; } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. public void ICompositionElementDisplayName_ShouldReturnTypeDisplayName() { var expectations = Expectations.GetAttributedTypes(); foreach (var e in expectations) { var definition = (ICompositionElement)CreateEmptyDefinition(e, null, null, null); Assert.Equal(e.GetDisplayName(), definition.DisplayName); } } private ReflectionComposablePartDefinition CreateEmptyDefinition(Type type, ConstructorInfo constructor, IDictionary<string, object> metadata, ICompositionElement origin) { return (ReflectionComposablePartDefinition)ReflectionModelServices.CreatePartDefinition( (type != null) ? type.AsLazy() : null, false, Enumerable.Empty<ImportDefinition>().AsLazy(), Enumerable.Empty<ExportDefinition>().AsLazy(), metadata.AsLazy(), origin); } private static List<ImportDefinition> CreateImports(Type type) { List<ImportDefinition> imports = new List<ImportDefinition>(); foreach (PropertyInfo property in type.GetProperties()) { imports.Add(new ReflectionMemberImportDefinition(new LazyMemberInfo(property), "Contract", (string)null, new KeyValuePair<string, Type>[] { new KeyValuePair<string, Type>("Key1", typeof(object)) }, ImportCardinality.ZeroOrOne, true, false, CreationPolicy.Any, MetadataServices.EmptyMetadata, new TypeOrigin(type))); } return imports; } private static List<ExportDefinition> CreateExports(Type type) { List<ExportDefinition> exports = new List<ExportDefinition>(); foreach (PropertyInfo property in type.GetProperties()) { exports.Add(ReflectionModelServices.CreateExportDefinition(new LazyMemberInfo(property), "Contract", new Lazy<IDictionary<string, object>>(() => null, false), new TypeOrigin(type))); } return exports; } public class TestPart { public int field1; public string field2; public int Property1 { get; set; } public string Property2 { get; set; } } private class TypeOrigin : ICompositionElement { private readonly Type _type; private readonly ICompositionElement _orgin; public TypeOrigin(Type type) : this(type, null) { } public TypeOrigin(Type type, ICompositionElement origin) { this._type = type; this._orgin = origin; } public string DisplayName { get { return this._type.GetDisplayName(); } } public ICompositionElement Origin { get { return this._orgin; } } } private class MockOrigin : ICompositionElement { public string DisplayName { get { throw new NotImplementedException(); } } public ICompositionElement Origin { get { throw new NotImplementedException(); } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace CocosSharp { [Obsolete("Use CCLabel instead.")] public class CCLabelBMFont : CCNode, ICCTextContainer { public const int AutomaticWidth = -1; internal static Dictionary<string, CCBMFontConfiguration> fontConfigurations = new Dictionary<string, CCBMFontConfiguration>(); protected bool lineBreakWithoutSpaces; protected CCTextAlignment horzAlignment = CCTextAlignment.Center; protected CCVerticalTextAlignment vertAlignment = CCVerticalTextAlignment.Top; internal CCBMFontConfiguration FontConfiguration { get; set; } protected string fntConfigFile; protected string labelInitialText; protected string labelText = string.Empty; protected CCPoint ImageOffset { get; set; } protected CCSize labelDimensions; protected bool IsDirty { get; set; } protected bool isColorModifiedByOpacity = false; // Static properties public static float DefaultTexelToContentSizeRatio { set { DefaultTexelToContentSizeRatios = new CCSize(value, value); } } public static CCSize DefaultTexelToContentSizeRatios { get; set; } // Instance properties public CCTextureAtlas TextureAtlas { get ; private set; } public CCBlendFunc BlendFunc { get; set; } protected int LineHeight { get; set; } public override CCPoint AnchorPoint { get { return base.AnchorPoint; } set { if (!AnchorPoint.Equals(value)) { base.AnchorPoint = value; IsDirty = true; } } } public override float Scale { set { if (!value.Equals(base.ScaleX) || !value.Equals(base.ScaleY)) { base.Scale = value; IsDirty = true; } } } public override float ScaleX { get { return base.ScaleX; } set { if (!value.Equals(base.ScaleX)) { base.ScaleX = value; IsDirty = true; } } } public override float ScaleY { get { return base.ScaleY; } set { if (!value.Equals(base.ScaleY)) { base.ScaleY = value; IsDirty = true; } } } public CCTextAlignment HorizontalAlignment { get { return horzAlignment; } set { if (horzAlignment != value) { horzAlignment = value; IsDirty = true; } } } public CCVerticalTextAlignment VerticalAlignment { get { return vertAlignment; } set { if (vertAlignment != value) { vertAlignment = value; IsDirty = true; } } } public override CCPoint Position { get { return base.Position; } set { if (base.Position != value) { base.Position = value; IsDirty = true; } } } public override float PositionX { get { return base.PositionX; } set { if (base.PositionX != value) { base.PositionX = value; IsDirty = true; } } } public override float PositionY { get { return base.PositionY; } set { if (base.PositionY != value) { base.PositionY = value; IsDirty = true; } } } public override CCSize ContentSize { get { return base.ContentSize; } set { if (ContentSize != value) { base.ContentSize = value; IsDirty = true; } } } public CCSize Dimensions { get { return labelDimensions; } set { if (labelDimensions != value) { labelDimensions = value; IsDirty = true; } } } public bool LineBreakWithoutSpace { get { return lineBreakWithoutSpaces; } set { lineBreakWithoutSpaces = value; IsDirty = true; } } public string FntFile { get { return fntConfigFile; } set { if (value != null && fntConfigFile != value) { CCBMFontConfiguration newConf = FNTConfigLoadFile(value); Debug.Assert(newConf != null, "CCLabelBMFont: Impossible to create font. Please check file"); fntConfigFile = value; FontConfiguration = newConf; TextureAtlas.Texture = CCTextureCache.SharedTextureCache.AddImage(FontConfiguration.AtlasName); IsDirty = true; } } } public virtual string Text { get { return labelInitialText; } set { if (labelInitialText != value) { labelInitialText = value; IsDirty = true; } } } public static void PurgeCachedData() { if (fontConfigurations != null) { fontConfigurations.Clear(); } } #region Constructors static CCLabelBMFont() { DefaultTexelToContentSizeRatios = CCSize.One; } public CCLabelBMFont() : this("", "") { } public CCLabelBMFont(string str, string fntFile) : this(str, fntFile, 0.0f) { } public CCLabelBMFont(string str, string fntFile, float width) : this(str, fntFile, width, CCTextAlignment.Left) { } public CCLabelBMFont(string str, string fntFile, float width, CCTextAlignment alignment) : this(str, fntFile, width, alignment, CCPoint.Zero) { } public CCLabelBMFont(string str, string fntFile, float width, CCTextAlignment alignment, CCPoint imageOffset) : this(str, fntFile, width, alignment, imageOffset, null) { } public CCLabelBMFont(string str, string fntFile, float width, CCTextAlignment alignment, CCPoint imageOffset, CCTexture2D texture) : this(str, fntFile, width, alignment, CCVerticalTextAlignment.Top, imageOffset, null) { } public CCLabelBMFont(string str, string fntFile, float width, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment, CCPoint imageOffset, CCTexture2D texture) : this(str, fntFile, new CCSize(width, 0), hAlignment, vAlignment, imageOffset, texture) { } public CCLabelBMFont(string str, string fntFile, CCSize dimensions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment, CCPoint imageOffset, CCTexture2D texture) { InitCCLabelBMFont(str, fntFile, dimensions, hAlignment, vAlignment, imageOffset, texture); } protected void InitCCLabelBMFont(string theString, string fntFile, CCSize dimensions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment, CCPoint imageOffset, CCTexture2D texture) { Debug.Assert(FontConfiguration == null, "re-init is no longer supported"); Debug.Assert((theString == null && fntFile == null) || (theString != null && fntFile != null), "Invalid params for CCLabelBMFont"); if (!String.IsNullOrEmpty(fntFile)) { CCBMFontConfiguration newConf = FNTConfigLoadFile(fntFile); if (newConf == null) { CCLog.Log("CCLabelBMFont: Impossible to create font. Please check file: '{0}'", fntFile); return; } FontConfiguration = newConf; fntConfigFile = fntFile; if (texture == null) { try { texture = CCTextureCache.SharedTextureCache.AddImage(FontConfiguration.AtlasName); } catch (Exception) { // Try the 'images' ref location just in case. try { texture = CCTextureCache.SharedTextureCache.AddImage(System.IO.Path.Combine("images", FontConfiguration .AtlasName)); } catch (Exception) { // Lastly, try <font_path>/images/<font_name> string dir = System.IO.Path.GetDirectoryName(FontConfiguration.AtlasName); string fname = System.IO.Path.GetFileName(FontConfiguration.AtlasName); string newName = System.IO.Path.Combine(System.IO.Path.Combine(dir, "images"), fname); texture = CCTextureCache.SharedTextureCache.AddImage(newName); } } } } else { texture = new CCTexture2D(); } if (String.IsNullOrEmpty(theString)) { theString = String.Empty; } TextureAtlas = new CCTextureAtlas(texture, theString.Length); this.labelDimensions = dimensions; horzAlignment = hAlignment; vertAlignment = vAlignment; IsOpacityCascaded = true; ContentSize = CCSize.Zero; IsColorModifiedByOpacity = TextureAtlas.Texture.HasPremultipliedAlpha; AnchorPoint = CCPoint.AnchorMiddle; ImageOffset = imageOffset; SetString(theString, true); } #endregion Constructors #region Scene handling protected override void AddedToScene() { base.AddedToScene(); if (Scene != null) { CreateFontChars(); } } #endregion Scene handling public override void UpdateColor() { base.UpdateColor(); if (Children != null) { for (int i = 0, count = Children.Count; i < count; i++) { ((CCSprite)Children.Elements[i]).UpdateDisplayedColor(DisplayedColor); } } } public override bool IsColorModifiedByOpacity { get { return isColorModifiedByOpacity; } set { if (isColorModifiedByOpacity != value) { isColorModifiedByOpacity = value; if (Children != null) { for (int i = 0, count = Children.Count; i < count; i++) { Children.Elements[i].IsColorModifiedByOpacity = isColorModifiedByOpacity; } } UpdateColor(); } } } private int KerningAmountForFirst(int first, int second) { int ret = 0; int key = (first << 16) | (second & 0xffff); if (FontConfiguration.GlyphKernings != null) { CCBMFontConfiguration.CCKerningHashElement element; if (FontConfiguration.GlyphKernings.TryGetValue(key, out element)) { ret = element.Amount; } } return ret; } public void CreateFontChars() { int nextFontPositionX = 0; int nextFontPositionY = 0; char prev = (char)255; int kerningAmount = 0; CCSize tmpSize = CCSize.Zero; int longestLine = 0; int totalHeight = 0; int quantityOfLines = 1; if (String.IsNullOrEmpty(labelText)) { return; } int stringLen = labelText.Length; var charSet = FontConfiguration.CharacterSet; if (charSet.Count == 0) { throw (new InvalidOperationException( "Can not compute the size of the font because the character set is empty.")); } for (int i = 0; i < stringLen - 1; ++i) { if (labelText[i] == '\n') { quantityOfLines++; } } LineHeight = FontConfiguration.CommonHeight; totalHeight = LineHeight * quantityOfLines; nextFontPositionY = 0 - (LineHeight - LineHeight * quantityOfLines); CCBMFontConfiguration.CCBMGlyphDef fontDef = null; CCRect fontCharTextureRect; CCSize fontCharContentSize; for (int i = 0; i < stringLen; i++) { char c = labelText[i]; if (c == '\n') { nextFontPositionX = 0; nextFontPositionY -= LineHeight; continue; } if (charSet.IndexOf(c) == -1) { CCLog.Log("CocosSharp: CCLabelBMFont: Attempted to use character not defined in this bitmap: {0}", (int)c); continue; } kerningAmount = this.KerningAmountForFirst(prev, c); // unichar is a short, and an int is needed on HASH_FIND_INT if (!FontConfiguration.Glyphs.TryGetValue(c, out fontDef)) { CCLog.Log("CocosSharp: CCLabelBMFont: character not found {0}", (int)c); continue; } fontCharTextureRect = fontDef.Subrect; fontCharTextureRect.Origin.X += ImageOffset.X; fontCharTextureRect.Origin.Y += ImageOffset.Y; fontCharContentSize = fontCharTextureRect.Size / DefaultTexelToContentSizeRatios; CCSprite fontChar; //bool hasSprite = true; fontChar = (CCSprite)(this[i]); if (fontChar != null) { // Reusing previous Sprite fontChar.Visible = true; // updating previous sprite fontChar.IsTextureRectRotated = false; fontChar.ContentSize = fontCharContentSize; fontChar.TextureRectInPixels = fontCharTextureRect; } else { // New Sprite ? Set correct color, opacity, etc... //if( false ) //{ // /* WIP: Doesn't support many features yet. // But this code is super fast. It doesn't create any sprite. // Ideal for big labels. // */ // fontChar = m_pReusedChar; // fontChar.BatchNode = null; // hasSprite = false; //} //else { fontChar = new CCSprite(TextureAtlas.Texture, fontCharTextureRect); fontChar.ContentSize = fontCharContentSize; AddChild(fontChar, i, i); } // Apply label properties fontChar.IsColorModifiedByOpacity = IsColorModifiedByOpacity; // Color MUST be set before opacity, since opacity might change color if OpacityModifyRGB is on fontChar.UpdateDisplayedColor(DisplayedColor); fontChar.UpdateDisplayedOpacity(DisplayedOpacity); } // See issue 1343. cast( signed short + unsigned integer ) == unsigned integer (sign is lost!) int yOffset = FontConfiguration.CommonHeight - fontDef.YOffset; var fontPos = new CCPoint( (float)nextFontPositionX + fontDef.XOffset + fontDef.Subrect.Size.Width * 0.5f + kerningAmount, (float)nextFontPositionY + yOffset - fontCharTextureRect.Size.Height * 0.5f); fontChar.Position = fontPos; // update kerning nextFontPositionX += fontDef.XAdvance + kerningAmount; prev = c; if (longestLine < nextFontPositionX) { longestLine = nextFontPositionX; } } // If the last character processed has an xAdvance which is less that the width of the characters image, then we need // to adjust the width of the string to take this into account, or the character will overlap the end of the bounding // box if (fontDef != null && fontDef.XAdvance < fontDef.Subrect.Size.Width) { tmpSize.Width = longestLine + fontDef.Subrect.Size.Width - fontDef.XAdvance; } else { tmpSize.Width = longestLine; } tmpSize.Height = totalHeight; var tmpDimensions = labelDimensions; labelDimensions = new CCSize( labelDimensions.Width > 0 ? labelDimensions.Width : tmpSize.Width, labelDimensions.Height > 0 ? labelDimensions.Height : tmpSize.Height ); ContentSize = labelDimensions; labelDimensions = tmpDimensions; } public virtual void SetString(string newString, bool needUpdateLabel) { if (!needUpdateLabel) { labelText = newString; } else { labelInitialText = newString; } UpdateString(needUpdateLabel); } private void UpdateString(bool needUpdateLabel) { if (Children != null && Children.Count != 0) { CCNode[] elements = Children.Elements; for (int i = 0, count = Children.Count; i < count; i++) { elements[i].Visible = false; } } CreateFontChars(); if (needUpdateLabel) { UpdateLabel(); } } protected void UpdateLabel() { SetString(labelInitialText, false); if (string.IsNullOrEmpty(labelText)) { return; } if (labelDimensions.Width > 0) { // Step 1: Make multiline string str_whole = labelText; int stringLength = str_whole.Length; var multiline_string = new StringBuilder(stringLength); var last_word = new StringBuilder(stringLength); int line = 1, i = 0; bool start_line = false, start_word = false; float startOfLine = -1, startOfWord = -1; int skip = 0; CCRawList<CCNode> children = Children; for (int j = 0; j < children.Count; j++) { CCSprite characterSprite; int justSkipped = 0; while ((characterSprite = (CCSprite)this[(j + skip + justSkipped)]) == null) { justSkipped++; } skip += justSkipped; if (!characterSprite.Visible) { continue; } if (i >= stringLength) { break; } char character = str_whole[i]; if (!start_word) { startOfWord = GetLetterPosXLeft(characterSprite); start_word = true; } if (!start_line) { startOfLine = startOfWord; start_line = true; } // Newline. if (character == '\n') { int len = last_word.Length; while (len > 0 && Char.IsWhiteSpace(last_word[len - 1])) { len--; last_word.Remove(len, 1); } multiline_string.Append(last_word); multiline_string.Append('\n'); last_word.Clear(); start_word = false; start_line = false; startOfWord = -1; startOfLine = -1; i += justSkipped; line++; if (i >= stringLength) break; character = str_whole[i]; if (startOfWord == 0) { startOfWord = GetLetterPosXLeft(characterSprite); start_word = true; } if (startOfLine == 0) { startOfLine = startOfWord; start_line = true; } } // Whitespace. if (Char.IsWhiteSpace(character)) { last_word.Append(character); multiline_string.Append(last_word); last_word.Clear(); start_word = false; startOfWord = -1; i++; continue; } // Out of bounds. if (GetLetterPosXRight(characterSprite) - startOfLine > labelDimensions.Width) { if (!lineBreakWithoutSpaces) { last_word.Append(character); int len = multiline_string.Length; while (len > 0 && Char.IsWhiteSpace(multiline_string[len - 1])) { len--; multiline_string.Remove(len, 1); } if (multiline_string.Length > 0) { multiline_string.Append('\n'); } line++; start_line = false; startOfLine = -1; i++; } else { int len = last_word.Length; while (len > 0 && Char.IsWhiteSpace(last_word[len - 1])) { len--; last_word.Remove(len, 1); } multiline_string.Append(last_word); multiline_string.Append('\n'); last_word.Clear(); start_word = false; start_line = false; startOfWord = -1; startOfLine = -1; line++; if (i >= stringLength) break; if (startOfWord == 0) { startOfWord = GetLetterPosXLeft(characterSprite); start_word = true; } if (startOfLine == 0) { startOfLine = startOfWord; start_line = true; } j--; } continue; } else { // Character is normal. last_word.Append(character); i++; continue; } } multiline_string.Append(last_word); SetString(multiline_string.ToString(), false); } // Step 2: Make alignment if (horzAlignment != CCTextAlignment.Left) { int i = 0; int lineNumber = 0; int str_len = labelText.Length; var last_line = new CCRawList<char>(); // If label dim is 0, then we need to use the content size width instead float maxLabelWidth = labelDimensions.Width > 0 ? labelDimensions.Width : ContentSize.Width; for (int ctr = 0; ctr <= str_len; ++ctr) { if (ctr == str_len || labelText[ctr] == '\n') { float lineWidth = 0.0f; int line_length = last_line.Count; // if last line is empty we must just increase lineNumber and work with next line if (line_length == 0) { lineNumber++; continue; } int index = i + line_length - 1 + lineNumber; if (index < 0) continue; var lastChar = (CCSprite)this[index]; if (lastChar == null) continue; lineWidth = lastChar.Position.X + lastChar.ContentSize.Width; var shift = maxLabelWidth - lineWidth; if (horzAlignment == CCTextAlignment.Center) shift /= 2; for (int j = 0; j < line_length; j++) { index = i + j + lineNumber; if (index < 0) continue; var characterSprite = this[index]; characterSprite.PositionX += shift; } i += line_length; lineNumber++; last_line.Clear(); continue; } last_line.Add(labelText[ctr]); } } if (vertAlignment != CCVerticalTextAlignment.Bottom && labelDimensions.Height > 0) { int lineNumber = 1; int str_len = labelText.Length; for (int ctr = 0; ctr < str_len; ++ctr) { if (labelText[ctr] == '\n') { lineNumber++; } } float yOffset = labelDimensions.Height - FontConfiguration.CommonHeight * lineNumber; if (vertAlignment == CCVerticalTextAlignment.Center) { yOffset /= 2f; } for (int i = 0; i < str_len; i++) { var characterSprite = this[i] as CCSprite; if (characterSprite != null && characterSprite.Visible) characterSprite.PositionY += yOffset; } } } private float GetLetterPosXLeft(CCSprite sp) { return sp.Position.X * ScaleX; } private float GetLetterPosXRight(CCSprite sp) { return (sp.Position.X + sp.ContentSize.Width) * ScaleX; } private static CCBMFontConfiguration FNTConfigLoadFile(string file) { CCBMFontConfiguration pRet; if (!fontConfigurations.TryGetValue(file, out pRet)) { pRet = CCBMFontConfiguration.FontConfigurationWithFile(file); fontConfigurations.Add(file, pRet); } return pRet; } protected override void VisitRenderer(ref CCAffineTransform worldTransform) { Renderer.AddCommand(new CCCustomCommand(worldTransform.Tz, worldTransform, RenderLabel)); } void RenderLabel() { if (IsDirty) { UpdateLabel(); IsDirty = false; } } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the MamExamenFisico class. /// </summary> [Serializable] public partial class MamExamenFisicoCollection : ActiveList<MamExamenFisico, MamExamenFisicoCollection> { public MamExamenFisicoCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>MamExamenFisicoCollection</returns> public MamExamenFisicoCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { MamExamenFisico o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the MAM_ExamenFisico table. /// </summary> [Serializable] public partial class MamExamenFisico : ActiveRecord<MamExamenFisico>, IActiveRecord { #region .ctors and Default Settings public MamExamenFisico() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public MamExamenFisico(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public MamExamenFisico(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public MamExamenFisico(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("MAM_ExamenFisico", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdExamenFisico = new TableSchema.TableColumn(schema); colvarIdExamenFisico.ColumnName = "idExamenFisico"; colvarIdExamenFisico.DataType = DbType.Int32; colvarIdExamenFisico.MaxLength = 0; colvarIdExamenFisico.AutoIncrement = true; colvarIdExamenFisico.IsNullable = false; colvarIdExamenFisico.IsPrimaryKey = true; colvarIdExamenFisico.IsForeignKey = false; colvarIdExamenFisico.IsReadOnly = false; colvarIdExamenFisico.DefaultSetting = @""; colvarIdExamenFisico.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdExamenFisico); TableSchema.TableColumn colvarIdPaciente = new TableSchema.TableColumn(schema); colvarIdPaciente.ColumnName = "idPaciente"; colvarIdPaciente.DataType = DbType.Int32; colvarIdPaciente.MaxLength = 0; colvarIdPaciente.AutoIncrement = false; colvarIdPaciente.IsNullable = false; colvarIdPaciente.IsPrimaryKey = false; colvarIdPaciente.IsForeignKey = false; colvarIdPaciente.IsReadOnly = false; colvarIdPaciente.DefaultSetting = @"((0))"; colvarIdPaciente.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdPaciente); TableSchema.TableColumn colvarFecha = new TableSchema.TableColumn(schema); colvarFecha.ColumnName = "fecha"; colvarFecha.DataType = DbType.DateTime; colvarFecha.MaxLength = 0; colvarFecha.AutoIncrement = false; colvarFecha.IsNullable = false; colvarFecha.IsPrimaryKey = false; colvarFecha.IsForeignKey = false; colvarFecha.IsReadOnly = false; colvarFecha.DefaultSetting = @""; colvarFecha.ForeignKeyTableName = ""; schema.Columns.Add(colvarFecha); TableSchema.TableColumn colvarEdadActual = new TableSchema.TableColumn(schema); colvarEdadActual.ColumnName = "edadActual"; colvarEdadActual.DataType = DbType.Int32; colvarEdadActual.MaxLength = 0; colvarEdadActual.AutoIncrement = false; colvarEdadActual.IsNullable = false; colvarEdadActual.IsPrimaryKey = false; colvarEdadActual.IsForeignKey = false; colvarEdadActual.IsReadOnly = false; colvarEdadActual.DefaultSetting = @"((0))"; colvarEdadActual.ForeignKeyTableName = ""; schema.Columns.Add(colvarEdadActual); TableSchema.TableColumn colvarIdMotivoConsulta = new TableSchema.TableColumn(schema); colvarIdMotivoConsulta.ColumnName = "idMotivoConsulta"; colvarIdMotivoConsulta.DataType = DbType.Int32; colvarIdMotivoConsulta.MaxLength = 0; colvarIdMotivoConsulta.AutoIncrement = false; colvarIdMotivoConsulta.IsNullable = false; colvarIdMotivoConsulta.IsPrimaryKey = false; colvarIdMotivoConsulta.IsForeignKey = true; colvarIdMotivoConsulta.IsReadOnly = false; colvarIdMotivoConsulta.DefaultSetting = @"((0))"; colvarIdMotivoConsulta.ForeignKeyTableName = "MAM_MotivoConsulta"; schema.Columns.Add(colvarIdMotivoConsulta); TableSchema.TableColumn colvarIdResultadoExFisico = new TableSchema.TableColumn(schema); colvarIdResultadoExFisico.ColumnName = "idResultadoExFisico"; colvarIdResultadoExFisico.DataType = DbType.Int32; colvarIdResultadoExFisico.MaxLength = 0; colvarIdResultadoExFisico.AutoIncrement = false; colvarIdResultadoExFisico.IsNullable = false; colvarIdResultadoExFisico.IsPrimaryKey = false; colvarIdResultadoExFisico.IsForeignKey = true; colvarIdResultadoExFisico.IsReadOnly = false; colvarIdResultadoExFisico.DefaultSetting = @"((0))"; colvarIdResultadoExFisico.ForeignKeyTableName = "MAM_ResultadoExFisico"; schema.Columns.Add(colvarIdResultadoExFisico); TableSchema.TableColumn colvarIdResponsableExamen = new TableSchema.TableColumn(schema); colvarIdResponsableExamen.ColumnName = "idResponsableExamen"; colvarIdResponsableExamen.DataType = DbType.Int32; colvarIdResponsableExamen.MaxLength = 0; colvarIdResponsableExamen.AutoIncrement = false; colvarIdResponsableExamen.IsNullable = false; colvarIdResponsableExamen.IsPrimaryKey = false; colvarIdResponsableExamen.IsForeignKey = true; colvarIdResponsableExamen.IsReadOnly = false; colvarIdResponsableExamen.DefaultSetting = @"((0))"; colvarIdResponsableExamen.ForeignKeyTableName = "Sys_Profesional"; schema.Columns.Add(colvarIdResponsableExamen); TableSchema.TableColumn colvarIdCentroSalud = new TableSchema.TableColumn(schema); colvarIdCentroSalud.ColumnName = "idCentroSalud"; colvarIdCentroSalud.DataType = DbType.Int32; colvarIdCentroSalud.MaxLength = 0; colvarIdCentroSalud.AutoIncrement = false; colvarIdCentroSalud.IsNullable = false; colvarIdCentroSalud.IsPrimaryKey = false; colvarIdCentroSalud.IsForeignKey = true; colvarIdCentroSalud.IsReadOnly = false; colvarIdCentroSalud.DefaultSetting = @"((0))"; colvarIdCentroSalud.ForeignKeyTableName = "Sys_Efector"; schema.Columns.Add(colvarIdCentroSalud); TableSchema.TableColumn colvarActivo = new TableSchema.TableColumn(schema); colvarActivo.ColumnName = "activo"; colvarActivo.DataType = DbType.Boolean; colvarActivo.MaxLength = 0; colvarActivo.AutoIncrement = false; colvarActivo.IsNullable = false; colvarActivo.IsPrimaryKey = false; colvarActivo.IsForeignKey = false; colvarActivo.IsReadOnly = false; colvarActivo.DefaultSetting = @"((1))"; colvarActivo.ForeignKeyTableName = ""; schema.Columns.Add(colvarActivo); TableSchema.TableColumn colvarCreatedBy = new TableSchema.TableColumn(schema); colvarCreatedBy.ColumnName = "CreatedBy"; colvarCreatedBy.DataType = DbType.String; colvarCreatedBy.MaxLength = 50; colvarCreatedBy.AutoIncrement = false; colvarCreatedBy.IsNullable = false; colvarCreatedBy.IsPrimaryKey = false; colvarCreatedBy.IsForeignKey = false; colvarCreatedBy.IsReadOnly = false; colvarCreatedBy.DefaultSetting = @"('')"; colvarCreatedBy.ForeignKeyTableName = ""; schema.Columns.Add(colvarCreatedBy); TableSchema.TableColumn colvarCreatedOn = new TableSchema.TableColumn(schema); colvarCreatedOn.ColumnName = "CreatedOn"; colvarCreatedOn.DataType = DbType.DateTime; colvarCreatedOn.MaxLength = 0; colvarCreatedOn.AutoIncrement = false; colvarCreatedOn.IsNullable = false; colvarCreatedOn.IsPrimaryKey = false; colvarCreatedOn.IsForeignKey = false; colvarCreatedOn.IsReadOnly = false; colvarCreatedOn.DefaultSetting = @"(((1)/(1))/(1900))"; colvarCreatedOn.ForeignKeyTableName = ""; schema.Columns.Add(colvarCreatedOn); TableSchema.TableColumn colvarModifiedBy = new TableSchema.TableColumn(schema); colvarModifiedBy.ColumnName = "ModifiedBy"; colvarModifiedBy.DataType = DbType.String; colvarModifiedBy.MaxLength = 50; colvarModifiedBy.AutoIncrement = false; colvarModifiedBy.IsNullable = false; colvarModifiedBy.IsPrimaryKey = false; colvarModifiedBy.IsForeignKey = false; colvarModifiedBy.IsReadOnly = false; colvarModifiedBy.DefaultSetting = @"('')"; colvarModifiedBy.ForeignKeyTableName = ""; schema.Columns.Add(colvarModifiedBy); TableSchema.TableColumn colvarModifiedOn = new TableSchema.TableColumn(schema); colvarModifiedOn.ColumnName = "ModifiedOn"; colvarModifiedOn.DataType = DbType.DateTime; colvarModifiedOn.MaxLength = 0; colvarModifiedOn.AutoIncrement = false; colvarModifiedOn.IsNullable = false; colvarModifiedOn.IsPrimaryKey = false; colvarModifiedOn.IsForeignKey = false; colvarModifiedOn.IsReadOnly = false; colvarModifiedOn.DefaultSetting = @"(((1)/(1))/(1900))"; colvarModifiedOn.ForeignKeyTableName = ""; schema.Columns.Add(colvarModifiedOn); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("MAM_ExamenFisico",schema); } } #endregion #region Props [XmlAttribute("IdExamenFisico")] [Bindable(true)] public int IdExamenFisico { get { return GetColumnValue<int>(Columns.IdExamenFisico); } set { SetColumnValue(Columns.IdExamenFisico, value); } } [XmlAttribute("IdPaciente")] [Bindable(true)] public int IdPaciente { get { return GetColumnValue<int>(Columns.IdPaciente); } set { SetColumnValue(Columns.IdPaciente, value); } } [XmlAttribute("Fecha")] [Bindable(true)] public DateTime Fecha { get { return GetColumnValue<DateTime>(Columns.Fecha); } set { SetColumnValue(Columns.Fecha, value); } } [XmlAttribute("EdadActual")] [Bindable(true)] public int EdadActual { get { return GetColumnValue<int>(Columns.EdadActual); } set { SetColumnValue(Columns.EdadActual, value); } } [XmlAttribute("IdMotivoConsulta")] [Bindable(true)] public int IdMotivoConsulta { get { return GetColumnValue<int>(Columns.IdMotivoConsulta); } set { SetColumnValue(Columns.IdMotivoConsulta, value); } } [XmlAttribute("IdResultadoExFisico")] [Bindable(true)] public int IdResultadoExFisico { get { return GetColumnValue<int>(Columns.IdResultadoExFisico); } set { SetColumnValue(Columns.IdResultadoExFisico, value); } } [XmlAttribute("IdResponsableExamen")] [Bindable(true)] public int IdResponsableExamen { get { return GetColumnValue<int>(Columns.IdResponsableExamen); } set { SetColumnValue(Columns.IdResponsableExamen, value); } } [XmlAttribute("IdCentroSalud")] [Bindable(true)] public int IdCentroSalud { get { return GetColumnValue<int>(Columns.IdCentroSalud); } set { SetColumnValue(Columns.IdCentroSalud, value); } } [XmlAttribute("Activo")] [Bindable(true)] public bool Activo { get { return GetColumnValue<bool>(Columns.Activo); } set { SetColumnValue(Columns.Activo, value); } } [XmlAttribute("CreatedBy")] [Bindable(true)] public string CreatedBy { get { return GetColumnValue<string>(Columns.CreatedBy); } set { SetColumnValue(Columns.CreatedBy, value); } } [XmlAttribute("CreatedOn")] [Bindable(true)] public DateTime CreatedOn { get { return GetColumnValue<DateTime>(Columns.CreatedOn); } set { SetColumnValue(Columns.CreatedOn, value); } } [XmlAttribute("ModifiedBy")] [Bindable(true)] public string ModifiedBy { get { return GetColumnValue<string>(Columns.ModifiedBy); } set { SetColumnValue(Columns.ModifiedBy, value); } } [XmlAttribute("ModifiedOn")] [Bindable(true)] public DateTime ModifiedOn { get { return GetColumnValue<DateTime>(Columns.ModifiedOn); } set { SetColumnValue(Columns.ModifiedOn, value); } } #endregion #region ForeignKey Properties /// <summary> /// Returns a SysEfector ActiveRecord object related to this MamExamenFisico /// /// </summary> public DalSic.SysEfector SysEfector { get { return DalSic.SysEfector.FetchByID(this.IdCentroSalud); } set { SetColumnValue("idCentroSalud", value.IdEfector); } } /// <summary> /// Returns a MamResultadoExFisico ActiveRecord object related to this MamExamenFisico /// /// </summary> public DalSic.MamResultadoExFisico MamResultadoExFisico { get { return DalSic.MamResultadoExFisico.FetchByID(this.IdResultadoExFisico); } set { SetColumnValue("idResultadoExFisico", value.IdResultadoExFisico); } } /// <summary> /// Returns a MamMotivoConsultum ActiveRecord object related to this MamExamenFisico /// /// </summary> public DalSic.MamMotivoConsultum MamMotivoConsultum { get { return DalSic.MamMotivoConsultum.FetchByID(this.IdMotivoConsulta); } set { SetColumnValue("idMotivoConsulta", value.IdMotivoConsulta); } } /// <summary> /// Returns a SysProfesional ActiveRecord object related to this MamExamenFisico /// /// </summary> public DalSic.SysProfesional SysProfesional { get { return DalSic.SysProfesional.FetchByID(this.IdResponsableExamen); } set { SetColumnValue("idResponsableExamen", value.IdProfesional); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdPaciente,DateTime varFecha,int varEdadActual,int varIdMotivoConsulta,int varIdResultadoExFisico,int varIdResponsableExamen,int varIdCentroSalud,bool varActivo,string varCreatedBy,DateTime varCreatedOn,string varModifiedBy,DateTime varModifiedOn) { MamExamenFisico item = new MamExamenFisico(); item.IdPaciente = varIdPaciente; item.Fecha = varFecha; item.EdadActual = varEdadActual; item.IdMotivoConsulta = varIdMotivoConsulta; item.IdResultadoExFisico = varIdResultadoExFisico; item.IdResponsableExamen = varIdResponsableExamen; item.IdCentroSalud = varIdCentroSalud; item.Activo = varActivo; item.CreatedBy = varCreatedBy; item.CreatedOn = varCreatedOn; item.ModifiedBy = varModifiedBy; item.ModifiedOn = varModifiedOn; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdExamenFisico,int varIdPaciente,DateTime varFecha,int varEdadActual,int varIdMotivoConsulta,int varIdResultadoExFisico,int varIdResponsableExamen,int varIdCentroSalud,bool varActivo,string varCreatedBy,DateTime varCreatedOn,string varModifiedBy,DateTime varModifiedOn) { MamExamenFisico item = new MamExamenFisico(); item.IdExamenFisico = varIdExamenFisico; item.IdPaciente = varIdPaciente; item.Fecha = varFecha; item.EdadActual = varEdadActual; item.IdMotivoConsulta = varIdMotivoConsulta; item.IdResultadoExFisico = varIdResultadoExFisico; item.IdResponsableExamen = varIdResponsableExamen; item.IdCentroSalud = varIdCentroSalud; item.Activo = varActivo; item.CreatedBy = varCreatedBy; item.CreatedOn = varCreatedOn; item.ModifiedBy = varModifiedBy; item.ModifiedOn = varModifiedOn; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdExamenFisicoColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdPacienteColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn FechaColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn EdadActualColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn IdMotivoConsultaColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn IdResultadoExFisicoColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn IdResponsableExamenColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn IdCentroSaludColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn ActivoColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn CreatedByColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn CreatedOnColumn { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn ModifiedByColumn { get { return Schema.Columns[11]; } } public static TableSchema.TableColumn ModifiedOnColumn { get { return Schema.Columns[12]; } } #endregion #region Columns Struct public struct Columns { public static string IdExamenFisico = @"idExamenFisico"; public static string IdPaciente = @"idPaciente"; public static string Fecha = @"fecha"; public static string EdadActual = @"edadActual"; public static string IdMotivoConsulta = @"idMotivoConsulta"; public static string IdResultadoExFisico = @"idResultadoExFisico"; public static string IdResponsableExamen = @"idResponsableExamen"; public static string IdCentroSalud = @"idCentroSalud"; public static string Activo = @"activo"; public static string CreatedBy = @"CreatedBy"; public static string CreatedOn = @"CreatedOn"; public static string ModifiedBy = @"ModifiedBy"; public static string ModifiedOn = @"ModifiedOn"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
using System.Collections.Generic; namespace Lucene.Net.Search { using System; /* * 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 AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using RamUsageEstimator = Lucene.Net.Util.RamUsageEstimator; /// <summary> /// Caches all docs, and optionally also scores, coming from /// a search, and is then able to replay them to another /// collector. You specify the max RAM this class may use. /// Once the collection is done, call <seealso cref="#isCached"/>. If /// this returns true, you can use <seealso cref="#replay(Collector)"/> /// against a new collector. If it returns false, this means /// too much RAM was required and you must instead re-run the /// original search. /// /// <p><b>NOTE</b>: this class consumes 4 (or 8 bytes, if /// scoring is cached) per collected document. If the result /// set is large this can easily be a very substantial amount /// of RAM! /// /// <p><b>NOTE</b>: this class caches at least 128 documents /// before checking RAM limits. /// /// <p>See the Lucene <tt>modules/grouping</tt> module for more /// details including a full code example.</p> /// /// @lucene.experimental /// </summary> public abstract class CachingCollector : Collector { // Max out at 512K arrays private const int MAX_ARRAY_SIZE = 512 * 1024; private const int INITIAL_ARRAY_SIZE = 128; private static readonly int[] EMPTY_INT_ARRAY = new int[0]; private class SegStart { public readonly AtomicReaderContext ReaderContext; public readonly int End; public SegStart(AtomicReaderContext readerContext, int end) { this.ReaderContext = readerContext; this.End = end; } } private sealed class CachedScorer : Scorer { // NOTE: these members are package-private b/c that way accessing them from // the outer class does not incur access check by the JVM. The same // situation would be if they were defined in the outer class as private // members. internal int Doc; internal float Score_Renamed; internal CachedScorer() : base(null) { } public override float Score() { return Score_Renamed; } public override int Advance(int target) { throw new System.NotSupportedException(); } public override int DocID() { return Doc; } public override int Freq() { throw new System.NotSupportedException(); } public override int NextDoc() { throw new System.NotSupportedException(); } public override long Cost() { return 1; } } // A CachingCollector which caches scores private sealed class ScoreCachingCollector : CachingCollector { internal readonly CachedScorer CachedScorer; internal readonly IList<float[]> CachedScores; internal Scorer Scorer_Renamed; internal float[] CurScores; internal ScoreCachingCollector(Collector other, double maxRAMMB) : base(other, maxRAMMB, true) { CachedScorer = new CachedScorer(); CachedScores = new List<float[]>(); CurScores = new float[INITIAL_ARRAY_SIZE]; CachedScores.Add(CurScores); } internal ScoreCachingCollector(Collector other, int maxDocsToCache) : base(other, maxDocsToCache) { CachedScorer = new CachedScorer(); CachedScores = new List<float[]>(); CurScores = new float[INITIAL_ARRAY_SIZE]; CachedScores.Add(CurScores); } public override void Collect(int doc) { if (CurDocs == null) { // Cache was too large CachedScorer.Score_Renamed = Scorer_Renamed.Score(); CachedScorer.Doc = doc; Other.Collect(doc); return; } // Allocate a bigger array or abort caching if (Upto == CurDocs.Length) { @base += Upto; // Compute next array length - don't allocate too big arrays int nextLength = 8 * CurDocs.Length; if (nextLength > MAX_ARRAY_SIZE) { nextLength = MAX_ARRAY_SIZE; } if (@base + nextLength > MaxDocsToCache) { // try to allocate a smaller array nextLength = MaxDocsToCache - @base; if (nextLength <= 0) { // Too many docs to collect -- clear cache CurDocs = null; CurScores = null; CachedSegs.Clear(); CachedDocs.Clear(); CachedScores.Clear(); CachedScorer.Score_Renamed = Scorer_Renamed.Score(); CachedScorer.Doc = doc; Other.Collect(doc); return; } } CurDocs = new int[nextLength]; CachedDocs.Add(CurDocs); CurScores = new float[nextLength]; CachedScores.Add(CurScores); Upto = 0; } CurDocs[Upto] = doc; CachedScorer.Score_Renamed = CurScores[Upto] = Scorer_Renamed.Score(); Upto++; CachedScorer.Doc = doc; Other.Collect(doc); } public override void Replay(Collector other) { ReplayInit(other); int curUpto = 0; int curBase = 0; int chunkUpto = 0; CurDocs = EMPTY_INT_ARRAY; foreach (SegStart seg in CachedSegs) { other.NextReader = seg.ReaderContext; other.Scorer = CachedScorer; while (curBase + curUpto < seg.End) { if (curUpto == CurDocs.Length) { curBase += CurDocs.Length; CurDocs = CachedDocs[chunkUpto]; CurScores = CachedScores[chunkUpto]; chunkUpto++; curUpto = 0; } CachedScorer.Score_Renamed = CurScores[curUpto]; CachedScorer.Doc = CurDocs[curUpto]; other.Collect(CurDocs[curUpto++]); } } } public override Scorer Scorer { set { this.Scorer_Renamed = value; Other.Scorer = CachedScorer; } } public override string ToString() { if (Cached) { return "CachingCollector (" + (@base + Upto) + " docs & scores cached)"; } else { return "CachingCollector (cache was cleared)"; } } } // A CachingCollector which does not cache scores private sealed class NoScoreCachingCollector : CachingCollector { internal NoScoreCachingCollector(Collector other, double maxRAMMB) : base(other, maxRAMMB, false) { } internal NoScoreCachingCollector(Collector other, int maxDocsToCache) : base(other, maxDocsToCache) { } public override void Collect(int doc) { if (CurDocs == null) { // Cache was too large Other.Collect(doc); return; } // Allocate a bigger array or abort caching if (Upto == CurDocs.Length) { @base += Upto; // Compute next array length - don't allocate too big arrays int nextLength = 8 * CurDocs.Length; if (nextLength > MAX_ARRAY_SIZE) { nextLength = MAX_ARRAY_SIZE; } if (@base + nextLength > MaxDocsToCache) { // try to allocate a smaller array nextLength = MaxDocsToCache - @base; if (nextLength <= 0) { // Too many docs to collect -- clear cache CurDocs = null; CachedSegs.Clear(); CachedDocs.Clear(); Other.Collect(doc); return; } } CurDocs = new int[nextLength]; CachedDocs.Add(CurDocs); Upto = 0; } CurDocs[Upto] = doc; Upto++; Other.Collect(doc); } public override void Replay(Collector other) { ReplayInit(other); int curUpto = 0; int curbase = 0; int chunkUpto = 0; CurDocs = EMPTY_INT_ARRAY; foreach (SegStart seg in CachedSegs) { other.NextReader = seg.ReaderContext; while (curbase + curUpto < seg.End) { if (curUpto == CurDocs.Length) { curbase += CurDocs.Length; CurDocs = CachedDocs[chunkUpto]; chunkUpto++; curUpto = 0; } other.Collect(CurDocs[curUpto++]); } } } public override Scorer Scorer { set { Other.Scorer = value; } } public override string ToString() { if (Cached) { return "CachingCollector (" + (@base + Upto) + " docs cached)"; } else { return "CachingCollector (cache was cleared)"; } } } // TODO: would be nice if a collector defined a // needsScores() method so we can specialize / do checks // up front. this is only relevant for the ScoreCaching // version -- if the wrapped Collector does not need // scores, it can avoid cachedScorer entirely. protected readonly Collector Other; protected readonly int MaxDocsToCache; private readonly IList<SegStart> CachedSegs = new List<SegStart>(); protected readonly IList<int[]> CachedDocs; private AtomicReaderContext LastReaderContext; protected int[] CurDocs; protected int Upto; protected int @base; protected int LastDocBase; /// <summary> /// Creates a <seealso cref="CachingCollector"/> which does not wrap another collector. /// The cached documents and scores can later be {@link #replay(Collector) /// replayed}. /// </summary> /// <param name="acceptDocsOutOfOrder"> /// whether documents are allowed to be collected out-of-order </param> public static CachingCollector Create(bool acceptDocsOutOfOrder, bool cacheScores, double maxRAMMB) { Collector other = new CollectorAnonymousInnerClassHelper(acceptDocsOutOfOrder); return Create(other, cacheScores, maxRAMMB); } private class CollectorAnonymousInnerClassHelper : Collector { private bool AcceptDocsOutOfOrder; public CollectorAnonymousInnerClassHelper(bool acceptDocsOutOfOrder) { this.AcceptDocsOutOfOrder = acceptDocsOutOfOrder; } public override bool AcceptsDocsOutOfOrder() { return AcceptDocsOutOfOrder; } public override Scorer Scorer { set { } } public override void Collect(int doc) { } public override AtomicReaderContext NextReader { set { } } } /// <summary> /// Create a new <seealso cref="CachingCollector"/> that wraps the given collector and /// caches documents and scores up to the specified RAM threshold. /// </summary> /// <param name="other"> /// the Collector to wrap and delegate calls to. </param> /// <param name="cacheScores"> /// whether to cache scores in addition to document IDs. Note that /// this increases the RAM consumed per doc </param> /// <param name="maxRAMMB"> /// the maximum RAM in MB to consume for caching the documents and /// scores. If the collector exceeds the threshold, no documents and /// scores are cached. </param> public static CachingCollector Create(Collector other, bool cacheScores, double maxRAMMB) { return cacheScores ? (CachingCollector)new ScoreCachingCollector(other, maxRAMMB) : new NoScoreCachingCollector(other, maxRAMMB); } /// <summary> /// Create a new <seealso cref="CachingCollector"/> that wraps the given collector and /// caches documents and scores up to the specified max docs threshold. /// </summary> /// <param name="other"> /// the Collector to wrap and delegate calls to. </param> /// <param name="cacheScores"> /// whether to cache scores in addition to document IDs. Note that /// this increases the RAM consumed per doc </param> /// <param name="maxDocsToCache"> /// the maximum number of documents for caching the documents and /// possible the scores. If the collector exceeds the threshold, /// no documents and scores are cached. </param> public static CachingCollector Create(Collector other, bool cacheScores, int maxDocsToCache) { return cacheScores ? (CachingCollector)new ScoreCachingCollector(other, maxDocsToCache) : new NoScoreCachingCollector(other, maxDocsToCache); } // Prevent extension from non-internal classes private CachingCollector(Collector other, double maxRAMMB, bool cacheScores) { this.Other = other; CachedDocs = new List<int[]>(); CurDocs = new int[INITIAL_ARRAY_SIZE]; CachedDocs.Add(CurDocs); int bytesPerDoc = RamUsageEstimator.NUM_BYTES_INT; if (cacheScores) { bytesPerDoc += RamUsageEstimator.NUM_BYTES_FLOAT; } MaxDocsToCache = (int)((maxRAMMB * 1024 * 1024) / bytesPerDoc); } private CachingCollector(Collector other, int maxDocsToCache) { this.Other = other; CachedDocs = new List<int[]>(); CurDocs = new int[INITIAL_ARRAY_SIZE]; CachedDocs.Add(CurDocs); this.MaxDocsToCache = maxDocsToCache; } public override bool AcceptsDocsOutOfOrder() { return Other.AcceptsDocsOutOfOrder(); } public virtual bool Cached { get { return CurDocs != null; } } public override AtomicReaderContext NextReader { set { Other.NextReader = value; if (LastReaderContext != null) { CachedSegs.Add(new SegStart(LastReaderContext, @base + Upto)); } LastReaderContext = value; } } /// <summary> /// Reused by the specialized inner classes. </summary> internal virtual void ReplayInit(Collector other) { if (!Cached) { throw new InvalidOperationException("cannot replay: cache was cleared because too much RAM was required"); } if (!other.AcceptsDocsOutOfOrder() && this.Other.AcceptsDocsOutOfOrder()) { throw new System.ArgumentException("cannot replay: given collector does not support " + "out-of-order collection, while the wrapped collector does. " + "Therefore cached documents may be out-of-order."); } //System.out.println("CC: replay totHits=" + (upto + base)); if (LastReaderContext != null) { CachedSegs.Add(new SegStart(LastReaderContext, @base + Upto)); LastReaderContext = null; } } /// <summary> /// Replays the cached doc IDs (and scores) to the given Collector. If this /// instance does not cache scores, then Scorer is not set on /// {@code other.setScorer} as well as scores are not replayed. /// </summary> /// <exception cref="InvalidOperationException"> /// if this collector is not cached (i.e., if the RAM limits were too /// low for the number of documents + scores to cache). </exception> /// <exception cref="IllegalArgumentException"> /// if the given Collect's does not support out-of-order collection, /// while the collector passed to the ctor does. </exception> public abstract void Replay(Collector other); } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using log4net; using OpenSim.Framework; using OpenSim.Region.PhysicsModule.BulletS; using OpenSim.Region.PhysicsModules.SharedBase; using OpenSim.Tests.Common; using OpenMetaverse; namespace OpenSim.Region.PhysicsModule.BulletS.Tests { [TestFixture] public class HullCreation : OpenSimTestCase { // Documentation on attributes: http://www.nunit.org/index.php?p=attributes&r=2.6.1 // Documentation on assertions: http://www.nunit.org/index.php?p=assertions&r=2.6.1 BSScene PhysicsScene { get; set; } Vector3 ObjectInitPosition; [TestFixtureSetUp] public void Init() { } [TestFixtureTearDown] public void TearDown() { if (PhysicsScene != null) { // The Dispose() will also free any physical objects in the scene PhysicsScene.Dispose(); PhysicsScene = null; } } [TestCase(7, 2, 5f, 5f, 32, 0f)] /* default hull parameters */ public void GeomHullConvexDecomp( int maxDepthSplit, int maxDepthSplitForSimpleShapes, float concavityThresholdPercent, float volumeConservationThresholdPercent, int maxVertices, float maxSkinWidth) { // Setup the physics engine to use the C# version of convex decomp Dictionary<string, string> engineParams = new Dictionary<string, string>(); engineParams.Add("MeshSculptedPrim", "true"); // ShouldMeshSculptedPrim engineParams.Add("ForceSimplePrimMeshing", "false"); // ShouldForceSimplePrimMeshing engineParams.Add("UseHullsForPhysicalObjects", "true"); // ShouldUseHullsForPhysicalObjects engineParams.Add("ShouldRemoveZeroWidthTriangles", "true"); engineParams.Add("ShouldUseBulletHACD", "false"); engineParams.Add("ShouldUseSingleConvexHullForPrims", "true"); engineParams.Add("ShouldUseGImpactShapeForPrims", "false"); engineParams.Add("ShouldUseAssetHulls", "true"); engineParams.Add("CSHullMaxDepthSplit", maxDepthSplit.ToString()); engineParams.Add("CSHullMaxDepthSplitForSimpleShapes", maxDepthSplitForSimpleShapes.ToString()); engineParams.Add("CSHullConcavityThresholdPercent", concavityThresholdPercent.ToString()); engineParams.Add("CSHullVolumeConservationThresholdPercent", volumeConservationThresholdPercent.ToString()); engineParams.Add("CSHullMaxVertices", maxVertices.ToString()); engineParams.Add("CSHullMaxSkinWidth", maxSkinWidth.ToString()); PhysicsScene = BulletSimTestsUtil.CreateBasicPhysicsEngine(engineParams); PrimitiveBaseShape pbs; Vector3 pos; Vector3 size; Quaternion rot; bool isPhys; // Cylinder pbs = PrimitiveBaseShape.CreateCylinder(); pos = new Vector3(100.0f, 100.0f, 0f); pos.Z = PhysicsScene.TerrainManager.GetTerrainHeightAtXYZ(pos) + 10f; ObjectInitPosition = pos; size = new Vector3(2f, 2f, 2f); pbs.Scale = size; rot = Quaternion.Identity; isPhys = true; uint cylinderLocalID = 123; PhysicsScene.AddPrimShape("testCylinder", pbs, pos, size, rot, isPhys, cylinderLocalID); BSPrim primTypeCylinder = (BSPrim)PhysicsScene.PhysObjects[cylinderLocalID]; // Hollow Cylinder pbs = PrimitiveBaseShape.CreateCylinder(); pbs.ProfileHollow = (ushort)(0.70f * 50000); pos = new Vector3(110.0f, 110.0f, 0f); pos.Z = PhysicsScene.TerrainManager.GetTerrainHeightAtXYZ(pos) + 10f; ObjectInitPosition = pos; size = new Vector3(2f, 2f, 2f); pbs.Scale = size; rot = Quaternion.Identity; isPhys = true; uint hollowCylinderLocalID = 124; PhysicsScene.AddPrimShape("testHollowCylinder", pbs, pos, size, rot, isPhys, hollowCylinderLocalID); BSPrim primTypeHollowCylinder = (BSPrim)PhysicsScene.PhysObjects[hollowCylinderLocalID]; // Torus // ProfileCurve = Circle, PathCurve = Curve1 pbs = PrimitiveBaseShape.CreateSphere(); pbs.ProfileShape = (byte)ProfileShape.Circle; pbs.PathCurve = (byte)Extrusion.Curve1; pbs.PathScaleX = 100; // default hollow info as set in the viewer pbs.PathScaleY = (int)(.25f / 0.01f) + 200; pos = new Vector3(120.0f, 120.0f, 0f); pos.Z = PhysicsScene.TerrainManager.GetTerrainHeightAtXYZ(pos) + 10f; ObjectInitPosition = pos; size = new Vector3(2f, 4f, 4f); pbs.Scale = size; rot = Quaternion.Identity; isPhys = true; uint torusLocalID = 125; PhysicsScene.AddPrimShape("testTorus", pbs, pos, size, rot, isPhys, torusLocalID); BSPrim primTypeTorus = (BSPrim)PhysicsScene.PhysObjects[torusLocalID]; // The actual prim shape creation happens at taint time PhysicsScene.ProcessTaints(); // Check out the created hull shapes and report their characteristics ReportShapeGeom(primTypeCylinder); ReportShapeGeom(primTypeHollowCylinder); ReportShapeGeom(primTypeTorus); } [TestCase] public void GeomHullBulletHACD() { // Cylinder // Hollow Cylinder // Torus } private void ReportShapeGeom(BSPrim prim) { if (prim != null) { if (prim.PhysShape.HasPhysicalShape) { BSShape physShape = prim.PhysShape; string shapeType = physShape.GetType().ToString(); switch (shapeType) { case "OpenSim.Region.Physics.BulletSPlugin.BSShapeNative": BSShapeNative nShape = physShape as BSShapeNative; prim.PhysScene.DetailLog("{0}, type={1}", prim.Name, shapeType); break; case "OpenSim.Region.Physics.BulletSPlugin.BSShapeMesh": BSShapeMesh mShape = physShape as BSShapeMesh; prim.PhysScene.DetailLog("{0}, mesh, shapeInfo={1}", prim.Name, mShape.shapeInfo); break; case "OpenSim.Region.Physics.BulletSPlugin.BSShapeHull": // BSShapeHull hShape = physShape as BSShapeHull; // prim.PhysScene.DetailLog("{0}, hull, shapeInfo={1}", prim.Name, hShape.shapeInfo); break; case "OpenSim.Region.Physics.BulletSPlugin.BSShapeConvexHull": BSShapeConvexHull chShape = physShape as BSShapeConvexHull; prim.PhysScene.DetailLog("{0}, convexHull, shapeInfo={1}", prim.Name, chShape.shapeInfo); break; case "OpenSim.Region.Physics.BulletSPlugin.BSShapeCompound": BSShapeCompound cShape = physShape as BSShapeCompound; prim.PhysScene.DetailLog("{0}, type={1}", prim.Name, shapeType); break; default: prim.PhysScene.DetailLog("{0}, type={1}", prim.Name, shapeType); break; } } } } } }
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace com.google.zxing.common { /// <summary> <p>Represents a 2D matrix of bits. In function arguments below, and throughout the common /// module, x is the column position, and y is the row position. The ordering is always x, y. /// The origin is at the top-left.</p> /// /// <p>Internally the bits are represented in a 1-D array of 32-bit ints. However, each row begins /// with a new int. This is done intentionally so that we can copy out a row into a BitArray very /// efficiently.</p> /// /// <p>The ordering of bits is row-major. Within each int, the least significant bits are used first, /// meaning they represent lower x values. This is compatible with BitArray's implementation.</p> /// /// </summary> /// <author> Sean Owen /// </author> /// <author> [email protected] (Daniel Switkin) /// </author> /// <author>www.Redivivus.in ([email protected]) - Ported from ZXING Java Source /// </author> public sealed class BitMatrix { /// <returns> The width of the matrix /// </returns> public int Width { get { return width; } } /// <returns> The height of the matrix /// </returns> public int Height { get { return height; } } /// <summary> This method is for compatibility with older code. It's only logical to call if the matrix /// is square, so I'm throwing if that's not the case. /// /// </summary> /// <returns> row/column dimension of this matrix /// </returns> public int Dimension { get { if (width != height) { throw new System.Exception("Can't call getDimension() on a non-square matrix"); } return width; } } // TODO: Just like BitArray, these need to be public so ProGuard can inline them. //UPGRADE_NOTE: Final was removed from the declaration of 'width '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" public int width; //UPGRADE_NOTE: Final was removed from the declaration of 'height '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" public int height; //UPGRADE_NOTE: Final was removed from the declaration of 'rowSize '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" public int rowSize; //UPGRADE_NOTE: Final was removed from the declaration of 'bits '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" public int[] bits; // A helper to construct a square matrix. public BitMatrix(int dimension):this(dimension, dimension) { } public BitMatrix(int width, int height) { if (width < 1 || height < 1) { throw new System.ArgumentException("Both dimensions must be greater than 0"); } this.width = width; this.height = height; int rowSize = width >> 5; if ((width & 0x1f) != 0) { rowSize++; } this.rowSize = rowSize; bits = new int[rowSize * height]; } /// <summary> <p>Gets the requested bit, where true means black.</p> /// /// </summary> /// <param name="x">The horizontal component (i.e. which column) /// </param> /// <param name="y">The vertical component (i.e. which row) /// </param> /// <returns> value of given bit in matrix /// </returns> public bool get_Renamed(int x, int y) { int offset = y * rowSize + (x >> 5); return ((SupportClass.URShift(bits[offset], (x & 0x1f))) & 1) != 0; } /// <summary> <p>Sets the given bit to true.</p> /// /// </summary> /// <param name="x">The horizontal component (i.e. which column) /// </param> /// <param name="y">The vertical component (i.e. which row) /// </param> public void set_Renamed(int x, int y) { int offset = y * rowSize + (x >> 5); bits[offset] |= 1 << (x & 0x1f); } /// <summary> <p>Flips the given bit.</p> /// /// </summary> /// <param name="x">The horizontal component (i.e. which column) /// </param> /// <param name="y">The vertical component (i.e. which row) /// </param> public void flip(int x, int y) { int offset = y * rowSize + (x >> 5); bits[offset] ^= 1 << (x & 0x1f); } /// <summary> Clears all bits (sets to false).</summary> public void clear() { int max = bits.Length; for (int i = 0; i < max; i++) { bits[i] = 0; } } /// <summary> <p>Sets a square region of the bit matrix to true.</p> /// /// </summary> /// <param name="left">The horizontal position to begin at (inclusive) /// </param> /// <param name="top">The vertical position to begin at (inclusive) /// </param> /// <param name="width">The width of the region /// </param> /// <param name="height">The height of the region /// </param> public void setRegion(int left, int top, int width, int height) { if (top < 0 || left < 0) { throw new System.ArgumentException("Left and top must be nonnegative"); } if (height < 1 || width < 1) { throw new System.ArgumentException("Height and width must be at least 1"); } int right = left + width; int bottom = top + height; if (bottom > this.height || right > this.width) { throw new System.ArgumentException("The region must fit inside the matrix"); } for (int y = top; y < bottom; y++) { int offset = y * rowSize; for (int x = left; x < right; x++) { bits[offset + (x >> 5)] |= 1 << (x & 0x1f); } } } /// <summary> A fast method to retrieve one row of data from the matrix as a BitArray. /// /// </summary> /// <param name="y">The row to retrieve /// </param> /// <param name="row">An optional caller-allocated BitArray, will be allocated if null or too small /// </param> /// <returns> The resulting BitArray - this reference should always be used even when passing /// your own row /// </returns> public BitArray getRow(int y, BitArray row) { if (row == null || row.Size < width) { row = new BitArray(width); } int offset = y * rowSize; for (int x = 0; x < rowSize; x++) { row.setBulk(x << 5, bits[offset + x]); } return row; } public override System.String ToString() { System.Text.StringBuilder result = new System.Text.StringBuilder(height * (width + 1)); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { result.Append(get_Renamed(x, y)?"X ":" "); } result.Append('\n'); } return result.ToString(); } } }
// 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.Security; using System.Runtime.Serialization; namespace System.IO { public sealed partial class DirectoryInfo : FileSystemInfo { [System.Security.SecuritySafeCritical] public DirectoryInfo(String path) { if (path == null) throw new ArgumentNullException(nameof(path)); Contract.EndContractBlock(); OriginalPath = PathHelpers.ShouldReviseDirectoryPathToCurrent(path) ? "." : path; FullPath = Path.GetFullPath(path); DisplayPath = GetDisplayName(OriginalPath); } [System.Security.SecuritySafeCritical] internal DirectoryInfo(String fullPath, String originalPath) { Debug.Assert(Path.IsPathRooted(fullPath), "fullPath must be fully qualified!"); // Fast path when we know a DirectoryInfo exists. OriginalPath = originalPath ?? Path.GetFileName(fullPath); FullPath = fullPath; DisplayPath = GetDisplayName(OriginalPath); } public override String Name { get { return GetDirName(FullPath); } } public DirectoryInfo Parent { [System.Security.SecuritySafeCritical] get { string s = FullPath; // FullPath might end in either "parent\child" or "parent\child", and in either case we want // the parent of child, not the child. Trim off an ending directory separator if there is one, // but don't mangle the root. if (!PathHelpers.IsRoot(s)) { s = PathHelpers.TrimEndingDirectorySeparator(s); } string parentName = Path.GetDirectoryName(s); return parentName != null ? new DirectoryInfo(parentName, null) : null; } } [System.Security.SecuritySafeCritical] public DirectoryInfo CreateSubdirectory(String path) { if (path == null) throw new ArgumentNullException(nameof(path)); Contract.EndContractBlock(); return CreateSubdirectoryHelper(path); } [System.Security.SecurityCritical] // auto-generated private DirectoryInfo CreateSubdirectoryHelper(String path) { Debug.Assert(path != null); PathHelpers.ThrowIfEmptyOrRootedPath(path); String newDirs = Path.Combine(FullPath, path); String fullPath = Path.GetFullPath(newDirs); if (0 != String.Compare(FullPath, 0, fullPath, 0, FullPath.Length, PathInternal.StringComparison)) { throw new ArgumentException(SR.Format(SR.Argument_InvalidSubPath, path, DisplayPath), nameof(path)); } FileSystem.Current.CreateDirectory(fullPath); // Check for read permission to directory we hand back by calling this constructor. return new DirectoryInfo(fullPath); } [System.Security.SecurityCritical] public void Create() { FileSystem.Current.CreateDirectory(FullPath); } // Tests if the given path refers to an existing DirectoryInfo on disk. // // Your application must have Read permission to the directory's // contents. // public override bool Exists { [System.Security.SecuritySafeCritical] // auto-generated get { try { return FileSystemObject.Exists; } catch { return false; } } } // Returns an array of Files in the current DirectoryInfo matching the // given search criteria (i.e. "*.txt"). [SecurityCritical] public FileInfo[] GetFiles(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); Contract.EndContractBlock(); return InternalGetFiles(searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of Files in the current DirectoryInfo matching the // given search criteria (i.e. "*.txt"). public FileInfo[] GetFiles(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalGetFiles(searchPattern, searchOption); } // Returns an array of Files in the current DirectoryInfo matching the // given search criteria (i.e. "*.txt"). private FileInfo[] InternalGetFiles(String searchPattern, SearchOption searchOption) { Debug.Assert(searchPattern != null); Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); IEnumerable<FileInfo> enumerable = (IEnumerable<FileInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Files); return EnumerableHelpers.ToArray(enumerable); } // Returns an array of Files in the DirectoryInfo specified by path public FileInfo[] GetFiles() { return InternalGetFiles("*", SearchOption.TopDirectoryOnly); } // Returns an array of Directories in the current directory. public DirectoryInfo[] GetDirectories() { return InternalGetDirectories("*", SearchOption.TopDirectoryOnly); } // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (i.e. "*.txt"). public FileSystemInfo[] GetFileSystemInfos(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); Contract.EndContractBlock(); return InternalGetFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (i.e. "*.txt"). public FileSystemInfo[] GetFileSystemInfos(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalGetFileSystemInfos(searchPattern, searchOption); } // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (i.e. "*.txt"). private FileSystemInfo[] InternalGetFileSystemInfos(String searchPattern, SearchOption searchOption) { Debug.Assert(searchPattern != null); Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); IEnumerable<FileSystemInfo> enumerable = FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Both); return EnumerableHelpers.ToArray(enumerable); } // Returns an array of strongly typed FileSystemInfo entries which will contain a listing // of all the files and directories. public FileSystemInfo[] GetFileSystemInfos() { return InternalGetFileSystemInfos("*", SearchOption.TopDirectoryOnly); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (i.e. "System*" could match the System & System32 // directories). public DirectoryInfo[] GetDirectories(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); Contract.EndContractBlock(); return InternalGetDirectories(searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (i.e. "System*" could match the System & System32 // directories). public DirectoryInfo[] GetDirectories(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalGetDirectories(searchPattern, searchOption); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (i.e. "System*" could match the System & System32 // directories). private DirectoryInfo[] InternalGetDirectories(String searchPattern, SearchOption searchOption) { Debug.Assert(searchPattern != null); Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); IEnumerable<DirectoryInfo> enumerable = (IEnumerable<DirectoryInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Directories); return EnumerableHelpers.ToArray(enumerable); } public IEnumerable<DirectoryInfo> EnumerateDirectories() { return InternalEnumerateDirectories("*", SearchOption.TopDirectoryOnly); } public IEnumerable<DirectoryInfo> EnumerateDirectories(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); Contract.EndContractBlock(); return InternalEnumerateDirectories(searchPattern, SearchOption.TopDirectoryOnly); } public IEnumerable<DirectoryInfo> EnumerateDirectories(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalEnumerateDirectories(searchPattern, searchOption); } private IEnumerable<DirectoryInfo> InternalEnumerateDirectories(String searchPattern, SearchOption searchOption) { Debug.Assert(searchPattern != null); Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return (IEnumerable<DirectoryInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Directories); } public IEnumerable<FileInfo> EnumerateFiles() { return InternalEnumerateFiles("*", SearchOption.TopDirectoryOnly); } public IEnumerable<FileInfo> EnumerateFiles(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); Contract.EndContractBlock(); return InternalEnumerateFiles(searchPattern, SearchOption.TopDirectoryOnly); } public IEnumerable<FileInfo> EnumerateFiles(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalEnumerateFiles(searchPattern, searchOption); } private IEnumerable<FileInfo> InternalEnumerateFiles(String searchPattern, SearchOption searchOption) { Debug.Assert(searchPattern != null); Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return (IEnumerable<FileInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Files); } public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos() { return InternalEnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly); } public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); Contract.EndContractBlock(); return InternalEnumerateFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly); } public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalEnumerateFileSystemInfos(searchPattern, searchOption); } private IEnumerable<FileSystemInfo> InternalEnumerateFileSystemInfos(String searchPattern, SearchOption searchOption) { Debug.Assert(searchPattern != null); Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Both); } // Returns the root portion of the given path. The resulting string // consists of those rightmost characters of the path that constitute the // root of the path. Possible patterns for the resulting string are: An // empty string (a relative path on the current drive), "\" (an absolute // path on the current drive), "X:" (a relative path on a given drive, // where X is the drive letter), "X:\" (an absolute path on a given drive), // and "\\server\share" (a UNC path for a given server and share name). // The resulting string is null if path is null. // public DirectoryInfo Root { [System.Security.SecuritySafeCritical] get { String rootPath = Path.GetPathRoot(FullPath); return new DirectoryInfo(rootPath); } } [System.Security.SecuritySafeCritical] public void MoveTo(string destDirName) { if (destDirName == null) throw new ArgumentNullException(nameof(destDirName)); if (destDirName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destDirName)); Contract.EndContractBlock(); string destination = Path.GetFullPath(destDirName); string destinationWithSeparator = destination; if (destinationWithSeparator[destinationWithSeparator.Length - 1] != Path.DirectorySeparatorChar) destinationWithSeparator = destinationWithSeparator + PathHelpers.DirectorySeparatorCharAsString; string fullSourcePath; if (FullPath.Length > 0 && FullPath[FullPath.Length - 1] == Path.DirectorySeparatorChar) fullSourcePath = FullPath; else fullSourcePath = FullPath + PathHelpers.DirectorySeparatorCharAsString; if (PathInternal.IsDirectoryTooLong(fullSourcePath)) throw new PathTooLongException(SR.IO_PathTooLong); if (PathInternal.IsDirectoryTooLong(destinationWithSeparator)) throw new PathTooLongException(SR.IO_PathTooLong); StringComparison pathComparison = PathInternal.StringComparison; if (string.Equals(fullSourcePath, destinationWithSeparator, pathComparison)) throw new IOException(SR.IO_SourceDestMustBeDifferent); string sourceRoot = Path.GetPathRoot(fullSourcePath); string destinationRoot = Path.GetPathRoot(destinationWithSeparator); if (!string.Equals(sourceRoot, destinationRoot, pathComparison)) throw new IOException(SR.IO_SourceDestMustHaveSameRoot); // Windows will throw if the source file/directory doesn't exist, we preemptively check // to make sure our cross platform behavior matches NetFX behavior. if (!Exists && !FileSystem.Current.FileExists(FullPath)) throw new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, FullPath)); if (FileSystem.Current.DirectoryExists(destinationWithSeparator)) throw new IOException(SR.Format(SR.IO_AlreadyExists_Name, destinationWithSeparator)); FileSystem.Current.MoveDirectory(FullPath, destination); FullPath = destinationWithSeparator; OriginalPath = destDirName; DisplayPath = GetDisplayName(OriginalPath); // Flush any cached information about the directory. Invalidate(); } [System.Security.SecuritySafeCritical] public override void Delete() { FileSystem.Current.RemoveDirectory(FullPath, false); } [System.Security.SecuritySafeCritical] public void Delete(bool recursive) { FileSystem.Current.RemoveDirectory(FullPath, recursive); } /// <summary> /// Returns the original path. Use FullPath or Name properties for the path / directory name. /// </summary> public override String ToString() { return DisplayPath; } private static String GetDisplayName(String originalPath) { Debug.Assert(originalPath != null); // Desktop documents that the path returned by ToString() should be the original path. // For SL/Phone we only gave the directory name regardless of what was passed in. return PathHelpers.ShouldReviseDirectoryPathToCurrent(originalPath) ? "." : originalPath; } private static String GetDirName(String fullPath) { Debug.Assert(fullPath != null); return PathHelpers.IsRoot(fullPath) ? fullPath : Path.GetFileName(PathHelpers.TrimEndingDirectorySeparator(fullPath)); } } }
/* * 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.Reflection; using System.Collections.Generic; using System.Data; using OpenSim.Framework; using OpenSim.Framework.Console; using log4net; using MySql.Data.MySqlClient; using OpenMetaverse; namespace OpenSim.Data.MySQL { public class MySQLFSAssetData : IFSAssetDataPlugin { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected string m_ConnectionString; protected string m_Table; /// <summary> /// Number of days that must pass before we update the access time on an asset when it has been fetched /// Config option to change this is "DaysBetweenAccessTimeUpdates" /// </summary> private int DaysBetweenAccessTimeUpdates = 0; protected virtual Assembly Assembly { get { return GetType().Assembly; } } public MySQLFSAssetData() { } #region IPlugin Members public string Version { get { return "1.0.0.0"; } } // Loads and initialises the MySQL storage plugin and checks for migrations public void Initialise(string connect, string realm, int UpdateAccessTime) { m_ConnectionString = connect; m_Table = realm; DaysBetweenAccessTimeUpdates = UpdateAccessTime; try { using (MySqlConnection conn = new MySqlConnection(m_ConnectionString)) { conn.Open(); Migration m = new Migration(conn, Assembly, "FSAssetStore"); m.Update(); conn.Close(); } } catch (MySqlException e) { m_log.ErrorFormat("[FSASSETS]: Can't connect to database: {0}", e.Message.ToString()); } } public void Initialise() { throw new NotImplementedException(); } public void Dispose() { } public string Name { get { return "MySQL FSAsset storage engine"; } } #endregion private bool ExecuteNonQuery(MySqlCommand cmd) { using (MySqlConnection conn = new MySqlConnection(m_ConnectionString)) { try { conn.Open(); } catch (MySqlException e) { m_log.ErrorFormat("[FSASSETS]: Database open failed with {0}", e.ToString()); return false; } cmd.Connection = conn; try { cmd.ExecuteNonQuery(); } catch (MySqlException e) { cmd.Connection = null; conn.Close(); m_log.ErrorFormat("[FSASSETS]: Query {0} failed with {1}", cmd.CommandText, e.ToString()); return false; } conn.Close(); cmd.Connection = null; } return true; } #region IFSAssetDataPlugin Members public AssetMetadata Get(string id, out string hash) { hash = String.Empty; AssetMetadata meta = new AssetMetadata(); using (MySqlConnection conn = new MySqlConnection(m_ConnectionString)) { try { conn.Open(); } catch (MySqlException e) { m_log.ErrorFormat("[FSASSETS]: Database open failed with {0}", e.ToString()); return null; } using (MySqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = String.Format("select id, name, description, type, hash, create_time, asset_flags, access_time from {0} where id = ?id", m_Table); cmd.Parameters.AddWithValue("?id", id); using (IDataReader reader = cmd.ExecuteReader()) { if (!reader.Read()) return null; hash = reader["hash"].ToString(); meta.ID = id; meta.FullID = new UUID(id); meta.Name = reader["name"].ToString(); meta.Description = reader["description"].ToString(); meta.Type = (sbyte)Convert.ToInt32(reader["type"]); meta.ContentType = SLUtil.SLAssetTypeToContentType(meta.Type); meta.CreationDate = Util.ToDateTime(Convert.ToInt32(reader["create_time"])); meta.Flags = (AssetFlags)Convert.ToInt32(reader["asset_flags"]); int AccessTime = Convert.ToInt32(reader["access_time"]); UpdateAccessTime(id, AccessTime); } } conn.Close(); } return meta; } private void UpdateAccessTime(string AssetID, int AccessTime) { // Reduce DB work by only updating access time if asset hasn't recently been accessed // 0 By Default, Config option is "DaysBetweenAccessTimeUpdates" if (DaysBetweenAccessTimeUpdates > 0 && (DateTime.UtcNow - Utils.UnixTimeToDateTime(AccessTime)).TotalDays < DaysBetweenAccessTimeUpdates) return; using (MySqlConnection conn = new MySqlConnection(m_ConnectionString)) { try { conn.Open(); } catch (MySqlException e) { m_log.ErrorFormat("[FSASSETS]: Database open failed with {0}", e.ToString()); return; } using (MySqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = String.Format("UPDATE {0} SET `access_time` = UNIX_TIMESTAMP() WHERE `id` = ?id", m_Table); cmd.Parameters.AddWithValue("?id", AssetID); cmd.ExecuteNonQuery(); } conn.Close(); } } public bool Store(AssetMetadata meta, string hash) { try { string oldhash; AssetMetadata existingAsset = Get(meta.ID, out oldhash); using (MySqlCommand cmd = new MySqlCommand()) { cmd.Parameters.AddWithValue("?id", meta.ID); cmd.Parameters.AddWithValue("?name", meta.Name); cmd.Parameters.AddWithValue("?description", meta.Description); // cmd.Parameters.AddWithValue("?type", meta.Type.ToString()); cmd.Parameters.AddWithValue("?type", meta.Type); cmd.Parameters.AddWithValue("?hash", hash); cmd.Parameters.AddWithValue("?asset_flags", meta.Flags); if (existingAsset == null) { cmd.CommandText = String.Format("insert into {0} (id, name, description, type, hash, asset_flags, create_time, access_time) values ( ?id, ?name, ?description, ?type, ?hash, ?asset_flags, UNIX_TIMESTAMP(), UNIX_TIMESTAMP())", m_Table); ExecuteNonQuery(cmd); return true; } //cmd.CommandText = String.Format("update {0} set hash = ?hash, access_time = UNIX_TIMESTAMP() where id = ?id", m_Table); //ExecuteNonQuery(cmd); } // return false; // if the asset already exits // assume it was already correctly stored // or regions will keep retry. return true; } catch(Exception e) { m_log.Error("[FSAssets] Failed to store asset with ID " + meta.ID); m_log.Error(e.ToString()); return false; } } /// <summary> /// Check if the assets exist in the database. /// </summary> /// <param name="uuids">The asset UUID's</param> /// <returns>For each asset: true if it exists, false otherwise</returns> public bool[] AssetsExist(UUID[] uuids) { if (uuids.Length == 0) return new bool[0]; bool[] results = new bool[uuids.Length]; for (int i = 0; i < uuids.Length; i++) results[i] = false; HashSet<UUID> exists = new HashSet<UUID>(); string ids = "'" + string.Join("','", uuids) + "'"; string sql = string.Format("select id from {1} where id in ({0})", ids, m_Table); using (MySqlConnection conn = new MySqlConnection(m_ConnectionString)) { try { conn.Open(); } catch (MySqlException e) { m_log.ErrorFormat("[FSASSETS]: Failed to open database: {0}", e.ToString()); return results; } using (MySqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = sql; using (MySqlDataReader dbReader = cmd.ExecuteReader()) { while (dbReader.Read()) { UUID id = DBGuid.FromDB(dbReader["ID"]); exists.Add(id); } } } conn.Close(); } for (int i = 0; i < uuids.Length; i++) results[i] = exists.Contains(uuids[i]); return results; } public int Count() { int count = 0; using (MySqlConnection conn = new MySqlConnection(m_ConnectionString)) { try { conn.Open(); } catch (MySqlException e) { m_log.ErrorFormat("[FSASSETS]: Failed to open database: {0}", e.ToString()); return 0; } using(MySqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = String.Format("select count(*) as count from {0}",m_Table); using (IDataReader reader = cmd.ExecuteReader()) { reader.Read(); count = Convert.ToInt32(reader["count"]); } } conn.Close(); } return count; } public bool Delete(string id) { using(MySqlCommand cmd = new MySqlCommand()) { cmd.CommandText = String.Format("delete from {0} where id = ?id",m_Table); cmd.Parameters.AddWithValue("?id", id); ExecuteNonQuery(cmd); } return true; } public void Import(string conn, string table, int start, int count, bool force, FSStoreDelegate store) { int imported = 0; using (MySqlConnection importConn = new MySqlConnection(conn)) { try { importConn.Open(); } catch (MySqlException e) { m_log.ErrorFormat("[FSASSETS]: Can't connect to database: {0}", e.Message.ToString()); return; } using (MySqlCommand cmd = importConn.CreateCommand()) { string limit = String.Empty; if (count != -1) { limit = String.Format(" limit {0},{1}", start, count); } cmd.CommandText = String.Format("select * from {0}{1}", table, limit); MainConsole.Instance.Output("Querying database"); using (IDataReader reader = cmd.ExecuteReader()) { MainConsole.Instance.Output("Reading data"); while (reader.Read()) { if ((imported % 100) == 0) { MainConsole.Instance.Output(String.Format("{0} assets imported so far", imported)); } AssetBase asset = new AssetBase(); AssetMetadata meta = new AssetMetadata(); meta.ID = reader["id"].ToString(); meta.FullID = new UUID(meta.ID); meta.Name = reader["name"].ToString(); meta.Description = reader["description"].ToString(); meta.Type = (sbyte)Convert.ToInt32(reader["assetType"]); meta.ContentType = SLUtil.SLAssetTypeToContentType(meta.Type); meta.CreationDate = Util.ToDateTime(Convert.ToInt32(reader["create_time"])); asset.Metadata = meta; asset.Data = (byte[])reader["data"]; store(asset, force); imported++; } } } importConn.Close(); } MainConsole.Instance.Output(String.Format("Import done, {0} assets imported", imported)); } #endregion } }
using System; using System.Diagnostics; using u8 = System.Byte; using u32 = System.UInt32; namespace System.Data.SQLite { using sqlite3_value = Sqlite3.Mem; internal partial class Sqlite3 { /* ** 2001 September 15 ** ** 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 C code routines that are called by the parser ** to handle UPDATE statements. ************************************************************************* ** 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-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 ** ************************************************************************* */ //#include "sqliteInt.h" #if !SQLITE_OMIT_VIRTUALTABLE /* Forward declaration */ //static void updateVirtualTable( //Parse pParse, /* The parsing context */ //SrcList pSrc, /* The virtual table to be modified */ //Table pTab, /* The virtual table */ //ExprList pChanges, /* The columns to change in the UPDATE statement */ //Expr pRowidExpr, /* Expression used to recompute the rowid */ //int aXRef, /* Mapping from columns of pTab to entries in pChanges */ //Expr *pWhere, /* WHERE clause of the UPDATE statement */ //int onError /* ON CONFLICT strategy */ //); #endif // * SQLITE_OMIT_VIRTUALTABLE */ /* ** The most recently coded instruction was an OP_Column to retrieve the ** i-th column of table pTab. This routine sets the P4 parameter of the ** OP_Column to the default value, if any. ** ** The default value of a column is specified by a DEFAULT clause in the ** column definition. This was either supplied by the user when the table ** was created, or added later to the table definition by an ALTER TABLE ** command. If the latter, then the row-records in the table btree on disk ** may not contain a value for the column and the default value, taken ** from the P4 parameter of the OP_Column instruction, is returned instead. ** If the former, then all row-records are guaranteed to include a value ** for the column and the P4 value is not required. ** ** Column definitions created by an ALTER TABLE command may only have ** literal default values specified: a number, null or a string. (If a more ** complicated default expression value was provided, it is evaluated ** when the ALTER TABLE is executed and one of the literal values written ** into the sqlite_master table.) ** ** Therefore, the P4 parameter is only required if the default value for ** the column is a literal number, string or null. The sqlite3ValueFromExpr() ** function is capable of transforming these types of expressions into ** sqlite3_value objects. ** ** If parameter iReg is not negative, code an OP_RealAffinity instruction ** on register iReg. This is used when an equivalent integer value is ** stored in place of an 8-byte floating point value in order to save ** space. */ static void sqlite3ColumnDefault(Vdbe v, Table pTab, int i, int iReg) { Debug.Assert(pTab != null); if (null == pTab.pSelect) { sqlite3_value pValue = new sqlite3_value(); int enc = ENC(sqlite3VdbeDb(v)); Column pCol = pTab.aCol[i]; #if SQLITE_DEBUG VdbeComment( v, "%s.%s", pTab.zName, pCol.zName ); #endif Debug.Assert(i < pTab.nCol); sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol.pDflt, enc, pCol.affinity, ref pValue); if (pValue != null) { sqlite3VdbeChangeP4(v, -1, pValue, P4_MEM); } #if !SQLITE_OMIT_FLOATING_POINT if (iReg >= 0 && pTab.aCol[i].affinity == SQLITE_AFF_REAL) { sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg); } #endif } } /* ** Process an UPDATE statement. ** ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL; ** \_______/ \________/ \______/ \________________/ * onError pTabList pChanges pWhere */ static void sqlite3Update( Parse pParse, /* The parser context */ SrcList pTabList, /* The table in which we should change things */ ExprList pChanges, /* Things to be changed */ Expr pWhere, /* The WHERE clause. May be null */ int onError /* How to handle constraint errors */ ) { int i, j; /* Loop counters */ Table pTab; /* The table to be updated */ int addr = 0; /* VDBE instruction address of the start of the loop */ WhereInfo pWInfo; /* Information about the WHERE clause */ Vdbe v; /* The virtual database engine */ Index pIdx; /* For looping over indices */ int nIdx; /* Number of indices that need updating */ int iCur; /* VDBE Cursor number of pTab */ sqlite3 db; /* The database structure */ int[] aRegIdx = null; /* One register assigned to each index to be updated */ int[] aXRef = null; /* aXRef[i] is the index in pChanges.a[] of the ** an expression for the i-th column of the table. ** aXRef[i]==-1 if the i-th column is not changed. */ bool chngRowid; /* True if the record number is being changed */ Expr pRowidExpr = null; /* Expression defining the new record number */ bool openAll = false; /* True if all indices need to be opened */ AuthContext sContext; /* The authorization context */ NameContext sNC; /* The name-context to resolve expressions in */ int iDb; /* Database containing the table being updated */ bool okOnePass; /* True for one-pass algorithm without the FIFO */ bool hasFK; /* True if foreign key processing is required */ #if !SQLITE_OMIT_TRIGGER bool isView; /* True when updating a view (INSTEAD OF trigger) */ Trigger pTrigger; /* List of triggers on pTab, if required */ int tmask = 0; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */ #endif int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */ /* Register Allocations */ int regRowCount = 0; /* A count of rows changed */ int regOldRowid; /* The old rowid */ int regNewRowid; /* The new rowid */ int regNew; int regOld = 0; int regRowSet = 0; /* Rowset of rows to be updated */ sContext = new AuthContext(); //memset( &sContext, 0, sizeof( sContext ) ); db = pParse.db; if (pParse.nErr != 0 /*|| db.mallocFailed != 0 */ ) { goto update_cleanup; } Debug.Assert(pTabList.nSrc == 1); /* Locate the table which we want to update. */ pTab = sqlite3SrcListLookup(pParse, pTabList); if (pTab == null) goto update_cleanup; iDb = sqlite3SchemaToIndex(pParse.db, pTab.pSchema); /* Figure out if we have any triggers and if the table being ** updated is a view. */ #if !SQLITE_OMIT_TRIGGER pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, out tmask); isView = pTab.pSelect != null; Debug.Assert(pTrigger != null || tmask == 0); #else const Trigger pTrigger = null;//# define pTrigger 0 const int tmask = 0; //# define tmask 0 #endif #if SQLITE_OMIT_TRIGGER || SQLITE_OMIT_VIEW // # undef isView const bool isView = false; //# define isView 0 #endif if (sqlite3ViewGetColumnNames(pParse, pTab) != 0) { goto update_cleanup; } if (sqlite3IsReadOnly(pParse, pTab, tmask)) { goto update_cleanup; } aXRef = new int[pTab.nCol];// sqlite3DbMallocRaw(db, sizeof(int) * pTab.nCol); //if ( aXRef == null ) goto update_cleanup; for (i = 0; i < pTab.nCol; i++) aXRef[i] = -1; /* Allocate a cursors for the main database table and for all indices. ** The index cursors might not be used, but if they are used they ** need to occur right after the database cursor. So go ahead and ** allocate enough space, just in case. */ pTabList.a[0].iCursor = iCur = pParse.nTab++; for (pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext) { pParse.nTab++; } /* Initialize the name-context */ sNC = new NameContext();// memset(&sNC, 0, sNC).Length; sNC.pParse = pParse; sNC.pSrcList = pTabList; /* Resolve the column names in all the expressions of the ** of the UPDATE statement. Also find the column index ** for each column to be updated in the pChanges array. For each ** column to be updated, make sure we have authorization to change ** that column. */ chngRowid = false; for (i = 0; i < pChanges.nExpr; i++) { if (sqlite3ResolveExprNames(sNC, ref pChanges.a[i].pExpr) != 0) { goto update_cleanup; } for (j = 0; j < pTab.nCol; j++) { if (pTab.aCol[j].zName.Equals(pChanges.a[i].zName, StringComparison.InvariantCultureIgnoreCase)) { if (j == pTab.iPKey) { chngRowid = true; pRowidExpr = pChanges.a[i].pExpr; } aXRef[j] = i; break; } } if (j >= pTab.nCol) { if (sqlite3IsRowid(pChanges.a[i].zName)) { chngRowid = true; pRowidExpr = pChanges.a[i].pExpr; } else { sqlite3ErrorMsg(pParse, "no such column: %s", pChanges.a[i].zName); pParse.checkSchema = 1; goto update_cleanup; } } #if !SQLITE_OMIT_AUTHORIZATION { int rc; rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab.zName, pTab.aCol[j].zName, db.aDb[iDb].zName); if( rc==SQLITE_DENY ){ goto update_cleanup; }else if( rc==SQLITE_IGNORE ){ aXRef[j] = -1; } } #endif } hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid ? 1 : 0) != 0; /* Allocate memory for the array aRegIdx[]. There is one entry in the ** array for each index associated with table being updated. Fill in ** the value with a register number for indices that are to be used ** and with zero for unused indices. */ for (nIdx = 0, pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext, nIdx++) { } if (nIdx > 0) { aRegIdx = new int[nIdx]; // sqlite3DbMallocRaw(db, Index*.Length * nIdx); if (aRegIdx == null) goto update_cleanup; } for (j = 0, pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext, j++) { int reg; if (hasFK || chngRowid) { reg = ++pParse.nMem; } else { reg = 0; for (i = 0; i < pIdx.nColumn; i++) { if (aXRef[pIdx.aiColumn[i]] >= 0) { reg = ++pParse.nMem; break; } } } aRegIdx[j] = reg; } /* Begin generating code. */ v = sqlite3GetVdbe(pParse); if (v == null) goto update_cleanup; if (pParse.nested == 0) sqlite3VdbeCountChanges(v); sqlite3BeginWriteOperation(pParse, 1, iDb); #if !SQLITE_OMIT_VIRTUALTABLE /* Virtual tables must be handled separately */ if (IsVirtual(pTab)) { updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef, pWhere, onError); pWhere = null; pTabList = null; goto update_cleanup; } #endif /* Allocate required registers. */ regOldRowid = regNewRowid = ++pParse.nMem; if (pTrigger != null || hasFK) { regOld = pParse.nMem + 1; pParse.nMem += pTab.nCol; } if (chngRowid || pTrigger != null || hasFK) { regNewRowid = ++pParse.nMem; } regNew = pParse.nMem + 1; pParse.nMem += pTab.nCol; /* Start the view context. */ if (isView) { sqlite3AuthContextPush(pParse, sContext, pTab.zName); } /* If we are trying to update a view, realize that view into ** a ephemeral table. */ #if !(SQLITE_OMIT_VIEW) && !(SQLITE_OMIT_TRIGGER) if (isView) { sqlite3MaterializeView(pParse, pTab, pWhere, iCur); } #endif /* Resolve the column names in all the expressions in the ** WHERE clause. */ if (sqlite3ResolveExprNames(sNC, ref pWhere) != 0) { goto update_cleanup; } /* Begin the database scan */ sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid); ExprList NullOrderby = null; pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, ref NullOrderby, WHERE_ONEPASS_DESIRED); if (pWInfo == null) goto update_cleanup; okOnePass = pWInfo.okOnePass != 0; /* Remember the rowid of every item to be updated. */ sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid); if (!okOnePass) { regRowSet = ++pParse.nMem; sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid); } /* End the database scan loop. */ sqlite3WhereEnd(pWInfo); /* Initialize the count of updated rows */ if ((db.flags & SQLITE_CountRows) != 0 && null == pParse.pTriggerTab) { regRowCount = ++pParse.nMem; sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); } if (!isView) { /* ** Open every index that needs updating. Note that if any ** index could potentially invoke a REPLACE conflict resolution ** action, then we need to open all indices because we might need ** to be deleting some records. */ if (!okOnePass) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); if (onError == OE_Replace) { openAll = true; } else { openAll = false; for (pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext) { if (pIdx.onError == OE_Replace) { openAll = true; break; } } } for (i = 0, pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext, i++) { if (openAll || aRegIdx[i] > 0) { KeyInfo pKey = sqlite3IndexKeyinfo(pParse, pIdx); sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur + i + 1, pIdx.tnum, iDb, pKey, P4_KEYINFO_HANDOFF); Debug.Assert(pParse.nTab > iCur + i + 1); } } } /* Top of the update loop */ if (okOnePass) { int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid); addr = sqlite3VdbeAddOp0(v, OP_Goto); sqlite3VdbeJumpHere(v, a1); } else { addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid); } /* Make cursor iCur point to the record that is being updated. If ** this record does not exist for some reason (deleted by a trigger, ** for example, then jump to the next iteration of the RowSet loop. */ sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid); /* If the record number will change, set register regNewRowid to ** contain the new value. If the record number is not being modified, ** then regNewRowid is the same register as regOldRowid, which is ** already populated. */ Debug.Assert(chngRowid || pTrigger != null || hasFK || regOldRowid == regNewRowid); if (chngRowid) { sqlite3ExprCode(pParse, pRowidExpr, regNewRowid); sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); } /* If there are triggers on this table, populate an array of registers ** with the required old.* column data. */ if (hasFK || pTrigger != null) { u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0); oldmask |= sqlite3TriggerColmask(pParse, pTrigger, pChanges, 0, TRIGGER_BEFORE | TRIGGER_AFTER, pTab, onError ); for (i = 0; i < pTab.nCol; i++) { if (aXRef[i] < 0 || oldmask == 0xffffffff || (i < 32 && 0 != (oldmask & (1 << i)))) { sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld + i); } else { sqlite3VdbeAddOp2(v, OP_Null, 0, regOld + i); } } if (chngRowid == false) { sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid); } } /* Populate the array of registers beginning at regNew with the new ** row data. This array is used to check constaints, create the new ** table and index records, and as the values for any new.* references ** made by triggers. ** ** If there are one or more BEFORE triggers, then do not populate the ** registers associated with columns that are (a) not modified by ** this UPDATE statement and (b) not accessed by new.* references. The ** values for registers not modified by the UPDATE must be reloaded from ** the database after the BEFORE triggers are fired anyway (as the trigger ** may have modified them). So not loading those that are not going to ** be used eliminates some redundant opcodes. */ newmask = (int)sqlite3TriggerColmask( pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError ); for (i = 0; i < pTab.nCol; i++) { if (i == pTab.iPKey) { sqlite3VdbeAddOp2(v, OP_Null, 0, regNew + i); } else { j = aXRef[i]; if (j >= 0) { sqlite3ExprCode(pParse, pChanges.a[j].pExpr, regNew + i); } else if (0 == (tmask & TRIGGER_BEFORE) || i > 31 || (newmask & (1 << i)) != 0) { /* This branch loads the value of a column that will not be changed ** into a register. This is done if there are no BEFORE triggers, or ** if there are one or more BEFORE triggers that use this value via ** a new.* reference in a trigger program. */ testcase(i == 31); testcase(i == 32); sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew + i); sqlite3ColumnDefault(v, pTab, i, regNew + i); } } } /* Fire any BEFORE UPDATE triggers. This happens before constraints are ** verified. One could argue that this is wrong. */ if ((tmask & TRIGGER_BEFORE) != 0) { sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab.nCol); sqlite3TableAffinityStr(v, pTab); sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, TRIGGER_BEFORE, pTab, regOldRowid, onError, addr); /* The row-trigger may have deleted the row being updated. In this ** case, jump to the next row. No updates or AFTER triggers are ** required. This behaviour - what happens when the row being updated ** is deleted or renamed by a BEFORE trigger - is left undefined in the ** documentation. */ sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid); /* If it did not delete it, the row-trigger may still have modified ** some of the columns of the row being updated. Load the values for ** all columns not modified by the update statement into their ** registers in case this has happened. */ for (i = 0; i < pTab.nCol; i++) { if (aXRef[i] < 0 && i != pTab.iPKey) { sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew + i); sqlite3ColumnDefault(v, pTab, i, regNew + i); } } } if (!isView) { int j1; /* Address of jump instruction */ /* Do constraint checks. */ int iDummy; sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid, aRegIdx, (chngRowid ? regOldRowid : 0), true, onError, addr, out iDummy); /* Do FK constraint checks. */ if (hasFK) { sqlite3FkCheck(pParse, pTab, regOldRowid, 0); } /* Delete the index entries associated with the current record. */ j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid); sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx); /* If changing the record number, delete the old record. */ if (hasFK || chngRowid) { sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0); } sqlite3VdbeJumpHere(v, j1); if (hasFK) { sqlite3FkCheck(pParse, pTab, 0, regNewRowid); } /* Insert the new index entries and the new record. */ sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, true, false, false); /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to ** handle rows (possibly in other tables) that refer via a foreign key ** to the row just updated. */ if (hasFK) { sqlite3FkActions(pParse, pTab, pChanges, regOldRowid); } } /* Increment the row counter */ if ((db.flags & SQLITE_CountRows) != 0 && null == pParse.pTriggerTab) { sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); } sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, TRIGGER_AFTER, pTab, regOldRowid, onError, addr); /* Repeat the above with the next record to be updated, until ** all record selected by the WHERE clause have been updated. */ sqlite3VdbeAddOp2(v, OP_Goto, 0, addr); sqlite3VdbeJumpHere(v, addr); /* Close all tables */ for (i = 0, pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext, i++) { if (openAll || aRegIdx[i] > 0) { sqlite3VdbeAddOp2(v, OP_Close, iCur + i + 1, 0); } } sqlite3VdbeAddOp2(v, OP_Close, iCur, 0); /* Update the sqlite_sequence table by storing the content of the ** maximum rowid counter values recorded while inserting into ** autoincrement tables. */ if (pParse.nested == 0 && pParse.pTriggerTab == null) { sqlite3AutoincrementEnd(pParse); } /* ** Return the number of rows that were changed. If this routine is ** generating code because of a call to sqlite3NestedParse(), do not ** invoke the callback function. */ if ((db.flags & SQLITE_CountRows) != 0 && null == pParse.pTriggerTab && 0 == pParse.nested) { sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1); sqlite3VdbeSetNumCols(v, 1); sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC); } update_cleanup: #if !SQLITE_OMIT_AUTHORIZATION sqlite3AuthContextPop(sContext); #endif sqlite3DbFree(db, ref aRegIdx); sqlite3DbFree(db, ref aXRef); sqlite3SrcListDelete(db, ref pTabList); sqlite3ExprListDelete(db, ref pChanges); sqlite3ExprDelete(db, ref pWhere); return; } /* Make sure "isView" and other macros defined above are undefined. Otherwise ** thely may interfere with compilation of other functions in this file ** (or in another file, if this file becomes part of the amalgamation). */ //#if isView // #undef isView //#endif //#if pTrigger // #undef pTrigger //#endif #if !SQLITE_OMIT_VIRTUALTABLE /* ** Generate code for an UPDATE of a virtual table. ** ** The strategy is that we create an ephemerial table that contains ** for each row to be changed: ** ** (A) The original rowid of that row. ** (B) The revised rowid for the row. (note1) ** (C) The content of every column in the row. ** ** Then we loop over this ephemeral table and for each row in ** the ephermeral table call VUpdate. ** ** When finished, drop the ephemeral table. ** ** (note1) Actually, if we know in advance that (A) is always the same ** as (B) we only store (A), then duplicate (A) when pulling ** it out of the ephemeral table before calling VUpdate. */ static void updateVirtualTable( Parse pParse, /* The parsing context */ SrcList pSrc, /* The virtual table to be modified */ Table pTab, /* The virtual table */ ExprList pChanges, /* The columns to change in the UPDATE statement */ Expr pRowid, /* Expression used to recompute the rowid */ int[] aXRef, /* Mapping from columns of pTab to entries in pChanges */ Expr pWhere, /* WHERE clause of the UPDATE statement */ int onError /* ON CONFLICT strategy */ ) { Vdbe v = pParse.pVdbe; /* Virtual machine under construction */ ExprList pEList = null; /* The result set of the SELECT statement */ Select pSelect = null; /* The SELECT statement */ Expr pExpr; /* Temporary expression */ int ephemTab; /* Table holding the result of the SELECT */ int i; /* Loop counter */ int addr; /* Address of top of loop */ int iReg; /* First register in set passed to OP_VUpdate */ sqlite3 db = pParse.db; /* Database connection */ VTable pVTab = sqlite3GetVTable(db, pTab); SelectDest dest = new SelectDest(); /* Construct the SELECT statement that will find the new values for ** all updated rows. */ pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_")); if (pRowid != null) { pEList = sqlite3ExprListAppend(pParse, pEList, sqlite3ExprDup(db, pRowid, 0)); } Debug.Assert(pTab.iPKey < 0); for (i = 0; i < pTab.nCol; i++) { if (aXRef[i] >= 0) { pExpr = sqlite3ExprDup(db, pChanges.a[aXRef[i]].pExpr, 0); } else { pExpr = sqlite3Expr(db, TK_ID, pTab.aCol[i].zName); } pEList = sqlite3ExprListAppend(pParse, pEList, pExpr); } pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, null, null, null, 0, null, null); /* Create the ephemeral table into which the update results will ** be stored. */ Debug.Assert(v != null); ephemTab = pParse.nTab++; sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab.nCol + 1 + ((pRowid != null) ? 1 : 0)); sqlite3VdbeChangeP5(v, BTREE_UNORDERED); /* fill the ephemeral table */ sqlite3SelectDestInit(dest, SRT_Table, ephemTab); sqlite3Select(pParse, pSelect, ref dest); /* Generate code to scan the ephemeral table and call VUpdate. */ iReg = ++pParse.nMem; pParse.nMem += pTab.nCol + 1; addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0); sqlite3VdbeAddOp3(v, OP_Column, ephemTab, 0, iReg); sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid != null ? 1 : 0), iReg + 1); for (i = 0; i < pTab.nCol; i++) { sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i + 1 + ((pRowid != null) ? 1 : 0), iReg + 2 + i); } sqlite3VtabMakeWritable(pParse, pTab); sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab.nCol + 2, iReg, pVTab, P4_VTAB); sqlite3VdbeChangeP5(v, (byte)(onError == OE_Default ? OE_Abort : onError)); sqlite3MayAbort(pParse); sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr + 1); sqlite3VdbeJumpHere(v, addr); sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0); /* Cleanup */ sqlite3SelectDelete(db, ref pSelect); } #endif // * SQLITE_OMIT_VIRTUALTABLE */ } }
using System; using System.Globalization; using AllReady.DataAccess; using AllReady.Hangfire; using AllReady.Models; using AllReady.Security; using Autofac; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.PlatformAbstractions; using Newtonsoft.Json.Serialization; using Hangfire; using AllReady.ModelBinding; using Microsoft.AspNetCore.Localization; using AllReady.Configuration; namespace AllReady { public class Startup { public Startup(IHostingEnvironment env) { // Setup configuration sources. var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("version.json") .AddJsonFile("config.json") .AddJsonFile($"config.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); if (env.IsDevelopment()) { // This reads the configuration keys from the secret store. // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709 builder.AddUserSecrets(); // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately. //builder.AddApplicationInsightsSettings(developerMode: true); builder.AddApplicationInsightsSettings(developerMode: false); } else if (env.IsStaging() || env.IsProduction()) { // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately. builder.AddApplicationInsightsSettings(developerMode: false); } Configuration = builder.Build(); Configuration["version"] = new ApplicationEnvironment().ApplicationVersion; // version in project.json } public IConfiguration Configuration { get; set; } // This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { //Add CORS support. // Must be first to avoid OPTIONS issues when calling from Angular/Browser services.AddCors(options => { options.AddPolicy("allReady", AllReadyCorsPolicyFactory.BuildAllReadyOpenCorsPolicy()); }); // Add Application Insights data collection services to the services container. services.AddApplicationInsightsTelemetry(Configuration); // Add Entity Framework services to the services container. services.AddDbContext<AllReadyContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])); Options.LoadConfigurationOptions(services, Configuration); // Add Identity services to the services container. services.AddIdentity<ApplicationUser, IdentityRole>(options => { options.Password.RequiredLength = 10; options.Password.RequireNonAlphanumeric = false; options.Password.RequireDigit = true; options.Password.RequireUppercase = false; options.Cookies.ApplicationCookie.AccessDeniedPath = new PathString("/Home/AccessDenied"); }) .AddEntityFrameworkStores<AllReadyContext>() .AddDefaultTokenProviders(); // Add Authorization rules for the app services.AddAuthorization(options => { options.AddPolicy("OrgAdmin", b => b.RequireClaim(Security.ClaimTypes.UserType, "OrgAdmin", "SiteAdmin")); options.AddPolicy("SiteAdmin", b => b.RequireClaim(Security.ClaimTypes.UserType, "SiteAdmin")); }); services.AddLocalization(); //Currently AllReady only supports en-US culture. This forces datetime and number formats to the en-US culture regardless of local culture var usCulture = new CultureInfo("en-US"); var supportedCultures = new[] { usCulture }; services.Configure<RequestLocalizationOptions>(options => { options.DefaultRequestCulture = new RequestCulture(usCulture, usCulture); options.SupportedCultures = supportedCultures; options.SupportedUICultures = supportedCultures; }); // Add MVC services to the services container. // config add to get passed Angular failing on Options request when logging in. services.AddMvc(config => { config.ModelBinderProviders.Insert(0, new AdjustToTimezoneModelBinderProvider()); }) .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver()); //Hangfire services.AddHangfire(configuration => configuration.UseSqlServerStorage(Configuration["Data:HangfireConnection:ConnectionString"])); // configure IoC support var container = AllReady.Configuration.Services.CreateIoCContainer(services, Configuration); return container.Resolve<IServiceProvider>(); } // Configure is called after ConfigureServices is called. public async void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SampleDataGenerator sampleData, AllReadyContext context, IConfiguration configuration) { // Put first to avoid issues with OPTIONS when calling from Angular/Browser. app.UseCors("allReady"); // todo: in RC update we can read from a logging.json config file loggerFactory.AddConsole((category, level) => { if (category.StartsWith("Microsoft.")) { return level >= LogLevel.Information; } return true; }); if (env.IsDevelopment()) { // this will go to the VS output window loggerFactory.AddDebug((category, level) => { if (category.StartsWith("Microsoft.")) { return level >= LogLevel.Information; } return true; }); } // Add Application Insights to the request pipeline to track HTTP request telemetry data. app.UseApplicationInsightsRequestTelemetry(); // Add the following to the request pipeline only in development environment. if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else if (env.IsStaging()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { // Add Error handling middleware which catches all application specific errors and // sends the request to the following path or controller action. app.UseExceptionHandler("/Home/Error"); } // Track data about exceptions from the application. Should be configured after all error handling middleware in the request pipeline. app.UseApplicationInsightsExceptionTelemetry(); // Add static files to the request pipeline. app.UseStaticFiles(); app.UseRequestLocalization(); Authentication.ConfigureAuthentication(app, Configuration); //call Migrate here to force the creation of the AllReady database so Hangfire can create its schema under it if (!env.IsProduction()) { context.Database.Migrate(); } //Hangfire app.UseHangfireDashboard("/hangfire", new DashboardOptions { Authorization = new[] { new HangireDashboardAuthorizationFilter() } }); app.UseHangfireServer(); // Add MVC to the request pipeline. app.UseMvc(routes => { routes.MapRoute(name: "areaRoute", template: "{area:exists}/{controller}/{action=Index}/{id?}"); routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); // Add sample data and test admin accounts if specified in Config.Json. // for production applications, this should either be set to false or deleted. if (Configuration["SampleData:InsertSampleData"] == "true") { sampleData.InsertTestData(); } if (Configuration["SampleData:InsertTestUsers"] == "true") { await sampleData.CreateAdminUser(); } } } }
#region License /* * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion using System; using System.Reflection; using System.Threading; using log4net; using NUnit.Framework; using Spring.Threading; namespace Spring.Services.WindowsService.Common { class StoppingHelper { private readonly ServiceSupport serviceSupport; private readonly ISync stopping; private readonly ISync stopped; public bool wasStopped = false; public StoppingHelper (ServiceSupport serviceSupport, ISync stopping, ISync stopped) { this.stopping = stopping; this.stopped = stopped; this.serviceSupport = serviceSupport; } public void Stop () { ServiceSupportTest.Log ("stopping ..."); stopping.Release(); ServiceSupportTest.Log ("stopping sync released ..."); serviceSupport.Stop(true); wasStopped = true; ServiceSupportTest.Log ("releasing stopped sync ..."); stopped.Release(); ServiceSupportTest.Log ("stopped ..."); } } class BlockWhileStartingExecutor : IExecutor { private readonly ISync started; private readonly ISync starting; MyServiceSupport serviceSupport; public bool wasStarted = false; public BlockWhileStartingExecutor (ISync starting, ISync started) { this.starting = starting; this.started = started; } public MyServiceSupport ServiceSupport { get { return serviceSupport; } set { serviceSupport = value; } } public void Start () { serviceSupport.Start(true); } public void Execute (IRunnable runnable) { if (runnable == serviceSupport.StartedCommand) { ServiceSupportTest.Log ("waiting to start ..."); starting.Acquire(); ServiceSupportTest.Log ("starting ..."); runnable.Run(); wasStarted = true; ServiceSupportTest.Log ("releasing started sync ..."); started.Release(); ServiceSupportTest.Log ("started ..."); } else { ServiceSupportTest.Log ("unexpected runnable: " + runnable); runnable.Run(); } } } class MyServiceSupport : ServiceSupport { public MyServiceSupport(IExecutor executor, IServiceable serviceable) : base(executor, serviceable) { } public IRunnable StartedCommand { get { return base.startedCommand; } } } class MyService : ServiceSupport.IServiceable { ISync _sync1; ISync _sync2; public MyService (ISync sync1, ISync sync2) { this._sync1 = sync1; this._sync2 = sync2; } public void PerformStart () { } public void PerformStop () { } public void Dispose () { lock (this) { _sync1.Release(); _sync2.Acquire(); } } } [TestFixture] public class ServiceSupportTest { MyService serviceable; ServiceSupport serviceSupport; ISync sync1; ISync sync2; static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); [SetUp] public void SetUp () { sync1 = new Semaphore(0); sync2 = new Semaphore(0); serviceable = new MyService(sync1, sync2); serviceSupport = new ServiceSupport(serviceable); } [Test(Description="Bugfix")] public void DoesNotLockTheServiceableWhenQueryingForStatus() { new Thread(new ThreadStart(serviceable.Dispose)).Start(); sync1.Acquire(); Assert.IsFalse(serviceSupport.StopRequested); sync2.Release(); } [Test] public void WaitForStartedBeforeStopping() { MyService serviceable = new MyService(sync1, sync2); ISync starting = new Latch(); ISync started = new Latch(); BlockWhileStartingExecutor executor = new BlockWhileStartingExecutor(starting, started); MyServiceSupport support = new MyServiceSupport(executor, serviceable); executor.ServiceSupport = support; Thread startThread = new Thread(new ThreadStart(executor.Start)); startThread.Name = "start"; startThread.Start(); Log ("start thread started"); Latch stopping = new Latch(); Latch stopped = new Latch(); StoppingHelper helper = new StoppingHelper(support, stopping, stopped); Thread stopThread = new Thread(new ThreadStart(helper.Stop)); stopThread.Name = "stop"; stopThread.Start(); Log ("stop thread started: waiting for stopping ..."); stopping.Acquire(); Log ("stopping in progress ..."); Assert.IsFalse(executor.wasStarted); Assert.IsFalse(helper.wasStopped, "helper could stop before expected"); Log ("allow to start ..."); starting.Release(); Log ("waiting for started ..."); started.Acquire(); Assert.IsTrue(executor.wasStarted); stopped.Acquire(); Log ("waiting for stop ..."); Assert.IsTrue(helper.wasStopped); Log ("stopped ..."); } public static void Log (string msg) { Thread currentThread = Thread.CurrentThread; string message = String.Format("thread [#{1}-{2}], msg = {0}", msg, currentThread.GetHashCode(), currentThread.Name); log.Debug(message); Console.Out.WriteLine (message); } } }
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. using System; using System.Threading.Tasks; using NUnit.Framework; using Scriban.Parsing; using Scriban.Runtime; using Scriban.Syntax; namespace Scriban.Tests { public class TestIncludes { public class Loader : ITemplateLoader { public string GetPath(TemplateContext context, SourceSpan callerSpan, string templateName) { return templateName == "test" ? "test" : "nested"; } public string Load(TemplateContext context, SourceSpan callerSpan, string templatePath) { return templatePath == "test" ? "AA\r\nBB\r\nCC\r\n {{include 'nested'}}{{include 'nested'}}" : "DD\r\nEE\r\nFF\r\n"; } public ValueTask<string> LoadAsync(TemplateContext context, SourceSpan callerSpan, string templatePath) { throw new System.NotImplementedException(); } } [Test] public void TestIndentedNestedIncludes() { var context = new TemplateContext { TemplateLoader = new Loader(), IndentWithInclude = true }; var template = Template.Parse(@"Test {{include 'test' ~}} {{include 'test' ~}} "); var result = template.Render(context).Replace("\r\n", "\n"); TextAssert.AreEqual(@"Test AA BB CC DD EE FF DD EE FF AA BB CC DD EE FF DD EE FF ".Replace("\r\n", "\n"), result); } [Test] public void TestIndentedIncludes2() { var template = Template.Parse(@"Test {{ include 'header' }} "); var context = new TemplateContext(); context.TemplateLoader = new CustomTemplateLoader(); context.IndentWithInclude = true; var text = template.Render(context).Replace("\r\n", "\n"); var expected = @"Test This is a header ".Replace("\r\n", "\n"); TextAssert.AreEqual(expected, text); } [Test] public void TestIndentedIncludes() { var template = Template.Parse(@" {{ include 'header' }} {{ include 'multilines' }} Test1 {{ include 'nested_templates_with_indent' }} Test2 "); var context = new TemplateContext(); context.TemplateLoader = new CustomTemplateLoader(); context.IndentWithInclude = true; var text = template.Render(context).Replace("\r\n", "\n"); var expectedText = @" This is a header Line 1 Line 2 Line 3 Test1 Line 1 Line 2 Line 3 Test2 ".Replace("\r\n", "\n"); TextAssert.AreEqual(expectedText, text); } [Test] public void TestJekyllInclude() { var input = "{% include /this/is/a/test.htm %}"; var template = Template.ParseLiquid(input, lexerOptions: new LexerOptions() { EnableIncludeImplicitString = true, Lang = ScriptLang.Liquid }); var context = new TemplateContext { TemplateLoader = new LiquidCustomTemplateLoader() }; var result = template.Render(context); TextAssert.AreEqual("/this/is/a/test.htm", result); } [Test] public void TestTemplateLoaderNoArgs() { var template = Template.Parse("Test with a include {{ include }}"); var context = new TemplateContext(); var exception = Assert.Throws<ScriptRuntimeException>(() => template.Render(context)); var expectedString = "Invalid number of arguments"; Assert.True(exception.Message.Contains(expectedString), $"The message `{exception.Message}` does not contain the string `{expectedString}`"); } [Test] public void TestTemplateLoaderNotSetup() { var template = Template.Parse("Test with a include {{ include 'yoyo' }}"); var context = new TemplateContext(); var exception = Assert.Throws<ScriptRuntimeException>(() => template.Render(context)); var expectedString = "No TemplateLoader registered"; Assert.True(exception.Message.Contains(expectedString), $"The message `{exception.Message}` does not contain the string `{expectedString}`"); } [Test] public void TestTemplateLoaderNotNull() { var template = Template.Parse("Test with a include {{ include null }}"); var context = new TemplateContext(); var exception = Assert.Throws<ScriptRuntimeException>(() => template.Render(context)); var expectedString = "Include template name cannot be null or empty"; Assert.True(exception.Message.Contains(expectedString), $"The message `{exception.Message}` does not contain the string `${expectedString}`"); } [Test] public void TestSimple() { TestParser.AssertTemplate("Test with a include yoyo", "Test with a include {{ include 'yoyo' }}"); } [Test] public void TestArguments() { TestParser.AssertTemplate("1 + 2", "{{ include 'arguments' 1 2 }}"); } [Test] public void TestProduct() { TestParser.AssertTemplate("product: Orange", "{{ include 'product' }}"); } [Test] public void TestNested() { TestParser.AssertTemplate("This is a header body This is a body_detail This is a footer", "{{ include 'nested_templates' }}"); } [Test] public void TestRecursiveNested() { TestParser.AssertTemplate("56789", "{{ include 'recursive_nested_templates' 5 }}"); } [Test] public void TestLiquidNull() { TestParser.AssertTemplate("", "{% include a %}", ScriptLang.Liquid); } [Test] public void TestLiquidWith() { TestParser.AssertTemplate("with_product: Orange", "{% include 'with_product' with product %}", ScriptLang.Liquid); } [Test] public void TestLiquidFor() { TestParser.AssertTemplate("for_product: Orange for_product: Banana for_product: Apple for_product: Computer for_product: Mobile Phone for_product: Table for_product: Sofa ", "{% include 'for_product' for products %}", ScriptLang.Liquid); } [Test] public void TestLiquidArguments() { TestParser.AssertTemplate("1 + yoyo", "{% include 'arguments' var1: 1, var2: 'yoyo' %}", ScriptLang.Liquid); } [Test] public void TestLiquidWithAndArguments() { TestParser.AssertTemplate("tada : 1 + yoyo", "{% include 'with_arguments' with 'tada' var1: 1, var2: 'yoyo' %}", ScriptLang.Liquid); } [Test] public void TestTemplateLoaderIncludeWithParsingErrors() { var template = Template.Parse("Test with a include {{ include 'invalid' }}"); var context = new TemplateContext() { TemplateLoader = new CustomTemplateLoader() }; var exception = Assert.Throws<ScriptParserRuntimeException>(() => template.Render(context)); Console.WriteLine(exception); var expectedString = "Error while parsing template"; Assert.True(exception.Message.Contains(expectedString), $"The message `{exception.Message}` does not contain the string `${expectedString}`"); } [Test] public void TestTemplateLoaderIncludeWithLexerErrors() { var template = Template.Parse("Test with a include {{ include 'invalid2' }}"); var context = new TemplateContext() { TemplateLoader = new CustomTemplateLoader() }; var exception = Assert.Throws<ScriptRuntimeException>(() => template.Render(context)); Console.WriteLine(exception); var expectedString = "The result of including"; Assert.True(exception.Message.Contains(expectedString), $"The message `{exception.Message}` does not contain the string `${expectedString}`"); } [Test] public void TestTemplateLoaderIncludeWithNullGetPath() { var template = Template.Parse("{{ include 'null' }}"); var context = new TemplateContext() { TemplateLoader = new CustomTemplateLoader() }; var exception = Assert.Throws<ScriptRuntimeException>(() => template.Render(context)); Console.WriteLine(exception); var expectedString = "Include template path is null"; Assert.True(exception.Message.Contains(expectedString), $"The message `{exception.Message}` does not contain the string `${expectedString}`"); } } }
// // 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.Resources; namespace Microsoft.Azure.Management.Resources { public partial class AuthorizationClient : ServiceClient<AuthorizationClient>, IAuthorizationClient { 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 IManagementLockOperations _managementLocks; /// <summary> /// Operations for managing locks. /// </summary> public virtual IManagementLockOperations ManagementLocks { get { return this._managementLocks; } } /// <summary> /// Initializes a new instance of the AuthorizationClient class. /// </summary> public AuthorizationClient() : base() { this._managementLocks = new ManagementLockOperations(this); this._apiVersion = "2015-01-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the AuthorizationClient 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 AuthorizationClient(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 AuthorizationClient 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 AuthorizationClient(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 AuthorizationClient class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> public AuthorizationClient(HttpClient httpClient) : base(httpClient) { this._managementLocks = new ManagementLockOperations(this); this._apiVersion = "2015-01-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the AuthorizationClient 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 AuthorizationClient(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 AuthorizationClient 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 AuthorizationClient(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 /// AuthorizationClient instance /// </summary> /// <param name='client'> /// Instance of AuthorizationClient to clone to /// </param> protected override void Clone(ServiceClient<AuthorizationClient> client) { base.Clone(client); if (client is AuthorizationClient) { AuthorizationClient clonedClient = ((AuthorizationClient)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); } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Windows.Media.Media3D.Point3DCollection.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows.Media.Media3D { sealed public partial class Point3DCollection : System.Windows.Freezable, IFormattable, System.Collections.IList, System.Collections.ICollection, IList<Point3D>, ICollection<Point3D>, IEnumerable<Point3D>, System.Collections.IEnumerable { #region Methods and constructors public void Add(Point3D value) { } public void Clear() { } public Point3DCollection Clone() { return default(Point3DCollection); } protected override void CloneCore(System.Windows.Freezable source) { } public Point3DCollection CloneCurrentValue() { return default(Point3DCollection); } protected override void CloneCurrentValueCore(System.Windows.Freezable source) { } public bool Contains(Point3D value) { return default(bool); } public void CopyTo(Point3D[] array, int index) { } protected override System.Windows.Freezable CreateInstanceCore() { return default(System.Windows.Freezable); } protected override void GetAsFrozenCore(System.Windows.Freezable source) { } protected override void GetCurrentValueAsFrozenCore(System.Windows.Freezable source) { } public Point3DCollection.Enumerator GetEnumerator() { return default(Point3DCollection.Enumerator); } public int IndexOf(Point3D value) { return default(int); } public void Insert(int index, Point3D value) { } public static Point3DCollection Parse(string source) { return default(Point3DCollection); } public Point3DCollection(IEnumerable<Point3D> collection) { } public Point3DCollection() { } public Point3DCollection(int capacity) { } public bool Remove(Point3D value) { return default(bool); } public void RemoveAt(int index) { } IEnumerator<Point3D> System.Collections.Generic.IEnumerable<System.Windows.Media.Media3D.Point3D>.GetEnumerator() { return default(IEnumerator<Point3D>); } void System.Collections.ICollection.CopyTo(Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } int System.Collections.IList.Add(Object value) { return default(int); } bool System.Collections.IList.Contains(Object value) { return default(bool); } int System.Collections.IList.IndexOf(Object value) { return default(int); } void System.Collections.IList.Insert(int index, Object value) { } void System.Collections.IList.Remove(Object value) { } string System.IFormattable.ToString(string format, IFormatProvider provider) { return default(string); } public string ToString(IFormatProvider provider) { return default(string); } #endregion #region Properties and indexers public int Count { get { return default(int); } } public Point3D this [int index] { get { return default(Point3D); } set { } } bool System.Collections.Generic.ICollection<System.Windows.Media.Media3D.Point3D>.IsReadOnly { get { return default(bool); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } Object System.Collections.ICollection.SyncRoot { get { return default(Object); } } bool System.Collections.IList.IsFixedSize { get { return default(bool); } } bool System.Collections.IList.IsReadOnly { get { return default(bool); } } Object System.Collections.IList.this [int index] { get { return default(Object); } set { } } #endregion } }