context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Management.Automation.Host; using Dbg = System.Management.Automation.Diagnostics; namespace Microsoft.PowerShell { /// <summary> /// ProgressPane is a class that represents the "window" in which outstanding activities for which the host has received /// progress updates are shown. /// ///</summary> internal class ProgressPane { /// <summary> /// Constructs a new instance. /// </summary> /// <param name="ui"> /// An implementation of the PSHostRawUserInterface with which the pane will be shown and hidden. /// </param> internal ProgressPane(ConsoleHostUserInterface ui) { if (ui == null) throw new ArgumentNullException("ui"); _ui = ui; _rawui = ui.RawUI; } /// <summary> /// Indicates whether the pane is visible on the screen buffer or not. /// </summary> /// <value> /// true if the pane is visible, false if not. /// ///</value> internal bool IsShowing { get { return (_savedRegion != null); } } /// <summary> /// Shows the pane in the screen buffer. Saves off the content of the region of the buffer that will be overwritten so /// that it can be restored again. /// </summary> internal void Show() { if (!IsShowing) { // Get temporary reference to the progress region since it can be // changed at any time by a call to WriteProgress. BufferCell[,] tempProgressRegion = _progressRegion; if (tempProgressRegion == null) { return; } // The location where we show ourselves is always relative to the screen buffer's current window position. int rows = tempProgressRegion.GetLength(0); int cols = tempProgressRegion.GetLength(1); _savedCursor = _rawui.CursorPosition; _location.X = 0; #if UNIX _location.Y = _rawui.CursorPosition.Y; // if cursor is not on left edge already move down one line if (_rawui.CursorPosition.X != 0) { _location.Y++; _rawui.CursorPosition = _location; } // if the cursor is at the bottom, create screen buffer space by scrolling int scrollRows = rows - ((_rawui.BufferSize.Height - 1) - _location.Y); if (scrollRows > 0) { // Scroll the console screen up by 'scrollRows' var bottomLocation = _location; bottomLocation.Y = _rawui.BufferSize.Height; _rawui.CursorPosition = bottomLocation; for (int i = 0; i < scrollRows; i++) { Console.Out.Write('\n'); } _location.Y -= scrollRows; _savedCursor.Y -= scrollRows; } // create cleared region to clear progress bar later _savedRegion = tempProgressRegion; for(int row = 0; row < rows; row++) { for(int col = 0; col < cols; col++) { _savedRegion[row, col].Character = ' '; } } // put cursor back to where output should be _rawui.CursorPosition = _location; #else _location = _rawui.WindowPosition; // We have to show the progress pane in the first column, as the screen buffer at any point might contain // a CJK double-cell characters, which makes it impractical to try to find a position where the pane would // not slice a character. Column 0 is the only place where we know for sure we can place the pane. _location.Y = Math.Min(_location.Y + 2, _bufSize.Height); // Save off the current contents of the screen buffer in the region that we will occupy _savedRegion = _rawui.GetBufferContents( new Rectangle(_location.X, _location.Y, _location.X + cols - 1, _location.Y + rows - 1)); #endif // replace the saved region in the screen buffer with our progress display _rawui.SetBufferContents(_location, tempProgressRegion); } } /// <summary> /// Hides the pane by restoring the saved contents of the region of the buffer that the pane occupies. If the pane is /// not showing, then does nothing. /// </summary> internal void Hide() { if (IsShowing) { // It would be nice if we knew that the saved region could be kept for the next time Show is called, but alas, // we have no way of knowing if the screen buffer has changed since we were hidden. By "no good way" I mean that // detecting a change would be at least as expensive as chucking the savedRegion and rebuilding it. And it would // be very complicated. _rawui.SetBufferContents(_location, _savedRegion); _savedRegion = null; _rawui.CursorPosition = _savedCursor; } } /// <summary> /// Updates the pane with the rendering of the supplied PendingProgress, and shows it. /// </summary> /// <param name="pendingProgress"> /// A PendingProgress instance that represents the outstanding activities that should be shown. /// </param> internal void Show(PendingProgress pendingProgress) { Dbg.Assert(pendingProgress != null, "pendingProgress may not be null"); _bufSize = _rawui.BufferSize; // In order to keep from slicing any CJK double-cell characters that might be present in the screen buffer, // we use the full width of the buffer. int maxWidth = _bufSize.Width; int maxHeight = Math.Max(5, _rawui.WindowSize.Height / 3); string[] contents = pendingProgress.Render(maxWidth, maxHeight, _rawui); if (contents == null) { // There's nothing to show. Hide(); _progressRegion = null; return; } // NTRAID#Windows OS Bugs-1061752-2004/12/15-sburns should read a skin setting here... BufferCell[,] newRegion = _rawui.NewBufferCellArray(contents, _ui.ProgressForegroundColor, _ui.ProgressBackgroundColor); Dbg.Assert(newRegion != null, "NewBufferCellArray has failed!"); if (_progressRegion == null) { // we've never shown this pane before. _progressRegion = newRegion; Show(); } else { // We have shown the pane before. We have to be smart about when we restore the saved region to minimize // flicker. We need to decide if the new contents will change the dimensions of the progress pane // currently being shown. If it will, then restore the saved region, and show the new one. Otherwise, // just blast the new one on top of the last one shown. // We're only checking size, not content, as we assume that the content will always change upon receipt // of a new ProgressRecord. That's not guaranteed, of course, but it's a good bet. So checking content // would usually result in detection of a change, so why bother? bool sizeChanged = (newRegion.GetLength(0) != _progressRegion.GetLength(0)) || (newRegion.GetLength(1) != _progressRegion.GetLength(1)) ? true : false; _progressRegion = newRegion; if (sizeChanged) { if (IsShowing) { Hide(); } Show(); } else { _rawui.SetBufferContents(_location, _progressRegion); } } } private Coordinates _location = new Coordinates(0, 0); private Coordinates _savedCursor; private Size _bufSize; private BufferCell[,] _savedRegion; private BufferCell[,] _progressRegion; private PSHostRawUserInterface _rawui; private ConsoleHostUserInterface _ui; } } // namespace
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Reflection; using Xunit; namespace System.Linq.Expressions.Tests { public class SwitchTests { [Theory] [ClassData(typeof(CompilationTypes))] public void IntSwitch1(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(int)); ParameterExpression p1 = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Assign(p1, Expression.Constant("default")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant(1)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("two")), Expression.Constant(2)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant(1))); BlockExpression block = Expression.Block(new ParameterExpression[] { p1 }, s, p1); Func<int, string> f = Expression.Lambda<Func<int, string>>(block, p).Compile(useInterpreter); Assert.Equal("hello", f(1)); Assert.Equal("two", f(2)); Assert.Equal("default", f(3)); } [Theory] [ClassData(typeof(CompilationTypes))] public void NullableIntSwitch1(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(int?)); ParameterExpression p1 = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Assign(p1, Expression.Constant("default")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant((int?)1, typeof(int?))), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("two")), Expression.Constant((int?)2, typeof(int?))), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant((int?)1, typeof(int?)))); BlockExpression block = Expression.Block(new ParameterExpression[] { p1 }, s, p1); Func<int?, string> f = Expression.Lambda<Func<int?, string>>(block, p).Compile(useInterpreter); Assert.Equal("hello", f(1)); Assert.Equal("two", f(2)); Assert.Equal("default", f(null)); Assert.Equal("default", f(3)); } [Theory, ClassData(typeof(CompilationTypes))] public void SwitchToGotos(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(int)); ParameterExpression p1 = Expression.Parameter(typeof(string)); LabelTarget end = Expression.Label(); LabelTarget lala = Expression.Label(); LabelTarget hello = Expression.Label(); BlockExpression block =Expression.Block( new [] { p1 }, Expression.Switch( p, Expression.Block( Expression.Assign(p1, Expression.Constant("default")), Expression.Goto(end) ), Expression.SwitchCase(Expression.Goto(hello), Expression.Constant(1)), Expression.SwitchCase(Expression.Block( Expression.Assign(p1, Expression.Constant("two")), Expression.Goto(end) ), Expression.Constant(2)), Expression.SwitchCase(Expression.Goto(lala), Expression.Constant(4)) ), Expression.Label(hello), Expression.Assign(p1, Expression.Constant("hello")), Expression.Goto(end), Expression.Label(lala), Expression.Assign(p1, Expression.Constant("lala")), Expression.Label(end), p1 ); Func<int, string> f = Expression.Lambda<Func<int, string>>(block, p).Compile(useInterpreter); Assert.Equal("hello", f(1)); Assert.Equal("two", f(2)); Assert.Equal("default", f(3)); Assert.Equal("lala", f(4)); } [Theory, ClassData(typeof(CompilationTypes))] public void SwitchToGotosOutOfTry(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(char)); ParameterExpression p1 = Expression.Parameter(typeof(string)); LabelTarget end = Expression.Label(); LabelTarget lala = Expression.Label(); LabelTarget hello = Expression.Label(); BlockExpression block = Expression.Block( new[] { p1 }, Expression.TryFinally( Expression.Switch( p, Expression.Block( Expression.Assign(p1, Expression.Constant("default")), Expression.Goto(end) ), Expression.SwitchCase(Expression.Goto(hello), Expression.Constant('a')), Expression.SwitchCase(Expression.Block( Expression.Assign(p1, Expression.Constant("two")), Expression.Goto(end) ), Expression.Constant('b')), Expression.SwitchCase(Expression.Goto(lala), Expression.Constant('d')) ), Expression.Empty() ), Expression.Label(hello), Expression.Assign(p1, Expression.Constant("hello")), Expression.Goto(end), Expression.Label(lala), Expression.Assign(p1, Expression.Constant("lala")), Expression.Label(end), p1 ); Func<char, string> f = Expression.Lambda<Func<char, string>>(block, p).Compile(useInterpreter); Assert.Equal("hello", f('a')); Assert.Equal("two", f('b')); Assert.Equal("default", f('c')); Assert.Equal("lala", f('d')); } [Theory] [ClassData(typeof(CompilationTypes))] public void NullableIntSwitch2(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(int?)); ParameterExpression p1 = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Assign(p1, Expression.Constant("default")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant((int?)1, typeof(int?))), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("two")), Expression.Constant((int?)2, typeof(int?))), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("null")), Expression.Constant((int?)null, typeof(int?))), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant((int?)1, typeof(int?)))); BlockExpression block = Expression.Block(new ParameterExpression[] { p1 }, s, p1); Func<int?, string> f = Expression.Lambda<Func<int?, string>>(block, p).Compile(useInterpreter); Assert.Equal("hello", f(1)); Assert.Equal("two", f(2)); Assert.Equal("null", f(null)); Assert.Equal("default", f(3)); } [Theory] [ClassData(typeof(CompilationTypes))] public void IntSwitch2(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(byte)); ParameterExpression p1 = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Assign(p1, Expression.Constant("default")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant((byte)1)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("two")), Expression.Constant((byte)2)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant((byte)1))); BlockExpression block = Expression.Block(new ParameterExpression[] { p1 }, s, p1); Func<byte, string> f = Expression.Lambda<Func<byte, string>>(block, p).Compile(useInterpreter); Assert.Equal("hello", f(1)); Assert.Equal("two", f(2)); Assert.Equal("default", f(3)); } [Theory] [ClassData(typeof(CompilationTypes))] public void IntSwitch3(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(uint)); ParameterExpression p1 = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Assign(p1, Expression.Constant("default")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant((uint)1)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("two")), Expression.Constant((uint)2)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant((uint)1)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("wow")), Expression.Constant(uint.MaxValue))); BlockExpression block = Expression.Block(new ParameterExpression[] { p1 }, s, p1); Func<uint, string> f = Expression.Lambda<Func<uint, string>>(block, p).Compile(useInterpreter); Assert.Equal("hello", f(1)); Assert.Equal("wow", f(uint.MaxValue)); Assert.Equal("two", f(2)); Assert.Equal("default", f(3)); } [Theory] [ClassData(typeof(CompilationTypes))] public void LongSwitch(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(long)); ParameterExpression p1 = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Assign(p1, Expression.Constant("default")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant(1L)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("two")), Expression.Constant(2L)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant(1L)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("wow")), Expression.Constant(long.MaxValue))); BlockExpression block = Expression.Block(new [] { p1 }, s, p1); Func<long, string> f = Expression.Lambda<Func<long, string>>(block, p).Compile(useInterpreter); Assert.Equal("hello", f(1)); Assert.Equal("wow", f(long.MaxValue)); Assert.Equal("two", f(2)); Assert.Equal("default", f(3)); } [Theory] [ClassData(typeof(CompilationTypes))] public void ULongSwitch(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(ulong)); ParameterExpression p1 = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Assign(p1, Expression.Constant("default")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant(1UL)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("two")), Expression.Constant(2UL)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant(1UL)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("wow")), Expression.Constant(ulong.MaxValue))); BlockExpression block = Expression.Block(new [] { p1 }, s, p1); Func<ulong, string> f = Expression.Lambda<Func<ulong, string>>(block, p).Compile(useInterpreter); Assert.Equal("hello", f(1)); Assert.Equal("wow", f(ulong.MaxValue)); Assert.Equal("two", f(2)); Assert.Equal("default", f(3)); } [Theory] [ClassData(typeof(CompilationTypes))] public void SparseULongSwitch(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(ulong)); ParameterExpression p1 = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Assign(p1, Expression.Constant("default")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant(1UL)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("two")), Expression.Constant(2UL)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("three")), Expression.Constant(203212UL)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("four")), Expression.Constant(10212UL)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("five")), Expression.Constant(5021029121UL)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("six")), Expression.Constant(690219291UL)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant(1UL)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("wow")), Expression.Constant(ulong.MaxValue))); BlockExpression block = Expression.Block(new[] { p1 }, s, p1); Func<ulong, string> f = Expression.Lambda<Func<ulong, string>>(block, p).Compile(useInterpreter); Assert.Equal("hello", f(1)); Assert.Equal("three", f(203212UL)); Assert.Equal("two", f(2)); Assert.Equal("default", f(3)); } [Theory] [ClassData(typeof(CompilationTypes))] public void SparseLongSwitch(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(long)); ParameterExpression p1 = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Assign(p1, Expression.Constant("default")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant(1L)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("two")), Expression.Constant(2L)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("three")), Expression.Constant(203212L)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("four")), Expression.Constant(10212L)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("five")), Expression.Constant(5021029121L)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("six")), Expression.Constant(690219291L)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant(1L)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("wow")), Expression.Constant(long.MaxValue))); BlockExpression block = Expression.Block(new[] { p1 }, s, p1); Func<long, string> f = Expression.Lambda<Func<long, string>>(block, p).Compile(useInterpreter); Assert.Equal("hello", f(1)); Assert.Equal("three", f(203212L)); Assert.Equal("two", f(2)); Assert.Equal("default", f(3)); } [Theory] [ClassData(typeof(CompilationTypes))] public void StringSwitch(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Constant("default"), Expression.SwitchCase(Expression.Constant("hello"), Expression.Constant("hi")), Expression.SwitchCase(Expression.Constant("lala"), Expression.Constant("bye"))); Func<string, string> f = Expression.Lambda<Func<string, string>>(s, p).Compile(useInterpreter); Assert.Equal("hello", f("hi")); Assert.Equal("lala", f("bye")); Assert.Equal("default", f("hi2")); Assert.Equal("default", f(null)); } [Theory] [ClassData(typeof(CompilationTypes))] public void StringSwitchTailCall(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Constant("default"), Expression.SwitchCase(Expression.Constant("hello"), Expression.Constant("hi")), Expression.SwitchCase(Expression.Constant("lala"), Expression.Constant("bye"))); Func<string, string> f = Expression.Lambda<Func<string, string>>(s, true, p).Compile(useInterpreter); Assert.Equal("hello", f("hi")); Assert.Equal("lala", f("bye")); Assert.Equal("default", f("hi2")); Assert.Equal("default", f(null)); } [Theory] [ClassData(typeof(CompilationTypes))] public void StringSwitchTailCallButNotLast(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Constant("default"), Expression.SwitchCase(Expression.Constant("hello"), Expression.Constant("hi")), Expression.SwitchCase(Expression.Constant("lala"), Expression.Constant("bye"))); BlockExpression block = Expression.Block(s, Expression.Constant("Not from the switch")); Func<string, string> f = Expression.Lambda<Func<string, string>>(block, true, p).Compile(useInterpreter); Assert.Equal("Not from the switch", f("hi")); Assert.Equal("Not from the switch", f("bye")); Assert.Equal("Not from the switch", f("hi2")); Assert.Equal("Not from the switch", f(null)); } [Theory] [ClassData(typeof(CompilationTypes))] public void StringSwitch1(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(string)); ParameterExpression p1 = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Assign(p1, Expression.Constant("default")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant("hi")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("null")), Expression.Constant(null, typeof(string))), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant("bye"))); BlockExpression block = Expression.Block(new ParameterExpression[] { p1 }, s, p1); Func<string, string> f = Expression.Lambda<Func<string, string>>(block, p).Compile(useInterpreter); Assert.Equal("hello", f("hi")); Assert.Equal("lala", f("bye")); Assert.Equal("default", f("hi2")); Assert.Equal("null", f(null)); } [Theory] [ClassData(typeof(CompilationTypes))] public void StringSwitchNotConstant(bool useInterpreter) { Expression<Func<string>> expr1 = () => new string('a', 5); Expression<Func<string>> expr2 = () => new string('q', 5); ParameterExpression p = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Constant("default"), Expression.SwitchCase(Expression.Invoke(expr1), Expression.Invoke(expr2)), Expression.SwitchCase(Expression.Constant("lala"), Expression.Constant("bye"))); Func<string, string> f = Expression.Lambda<Func<string, string>>(s, p).Compile(useInterpreter); Assert.Equal("aaaaa", f("qqqqq")); Assert.Equal("lala", f("bye")); Assert.Equal("default", f("hi2")); Assert.Equal("default", f(null)); } [Theory] [ClassData(typeof(CompilationTypes))] public void ObjectSwitch1(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(object)); ParameterExpression p1 = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Assign(p1, Expression.Constant("default")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant("hi")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("null")), Expression.Constant(null, typeof(string))), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant("bye")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lalala")), Expression.Constant("hi"))); BlockExpression block = Expression.Block(new ParameterExpression[] { p1 }, s, p1); Func<object, string> f = Expression.Lambda<Func<object, string>>(block, p).Compile(useInterpreter); Assert.Equal("hello", f("hi")); Assert.Equal("lala", f("bye")); Assert.Equal("default", f("hi2")); Assert.Equal("default", f("HI")); Assert.Equal("null", f(null)); } [Theory] [ClassData(typeof(CompilationTypes))] public void DefaultOnlySwitch(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(int)); SwitchExpression s = Expression.Switch(p, Expression.Constant(42)); Func<int, int> fInt32Int32 = Expression.Lambda<Func<int, int>>(s, p).Compile(useInterpreter); Assert.Equal(42, fInt32Int32(0)); Assert.Equal(42, fInt32Int32(1)); Assert.Equal(42, fInt32Int32(-1)); s = Expression.Switch(typeof(object), p, Expression.Constant("A test string"), null); Func<int, object> fInt32Object = Expression.Lambda<Func<int, object>>(s, p).Compile(useInterpreter); Assert.Equal("A test string", fInt32Object(0)); Assert.Equal("A test string", fInt32Object(1)); Assert.Equal("A test string", fInt32Object(-1)); p = Expression.Parameter(typeof(string)); s = Expression.Switch(p, Expression.Constant("foo")); Func<string, string> fStringString = Expression.Lambda<Func<string, string>>(s, p).Compile(useInterpreter); Assert.Equal("foo", fStringString("bar")); Assert.Equal("foo", fStringString(null)); Assert.Equal("foo", fStringString("foo")); } [Theory] [ClassData(typeof(CompilationTypes))] public void NoDefaultOrCasesSwitch(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(int)); SwitchExpression s = Expression.Switch(p); Action<int> f = Expression.Lambda<Action<int>>(s, p).Compile(useInterpreter); f(0); Assert.Equal(s.Type, typeof(void)); } [Fact] public void TypedNoDefaultOrCasesSwitch() { ParameterExpression p = Expression.Parameter(typeof(int)); // A SwitchExpression with neither a defaultBody nor any cases can not be any type except void. AssertExtensions.Throws<ArgumentException>("defaultBody", () => Expression.Switch(typeof(int), p, null, null)); } private delegate int RefSettingDelegate(ref bool changed); private delegate void JustRefSettingDelegate(ref bool changed); public static int QuestionMeaning(ref bool changed) { changed = true; return 42; } [Theory] [ClassData(typeof(CompilationTypes))] public void DefaultOnlySwitchWithSideEffect(bool useInterpreter) { bool changed = false; ParameterExpression pOut = Expression.Parameter(typeof(bool).MakeByRefType(), "changed"); MethodCallExpression switchValue = Expression.Call(typeof(SwitchTests).GetMethod(nameof(QuestionMeaning)), pOut); SwitchExpression s = Expression.Switch(switchValue, Expression.Constant(42)); RefSettingDelegate fInt32Int32 = Expression.Lambda<RefSettingDelegate>(s, pOut).Compile(useInterpreter); Assert.False(changed); Assert.Equal(42, fInt32Int32(ref changed)); Assert.True(changed); changed = false; Assert.Equal(42, fInt32Int32(ref changed)); Assert.True(changed); } [Theory] [ClassData(typeof(CompilationTypes))] public void NoDefaultOrCasesSwitchWithSideEffect(bool useInterpreter) { bool changed = false; ParameterExpression pOut = Expression.Parameter(typeof(bool).MakeByRefType(), "changed"); MethodCallExpression switchValue = Expression.Call(typeof(SwitchTests).GetMethod(nameof(QuestionMeaning)), pOut); SwitchExpression s = Expression.Switch(switchValue, (Expression)null); JustRefSettingDelegate f = Expression.Lambda<JustRefSettingDelegate>(s, pOut).Compile(useInterpreter); Assert.False(changed); f(ref changed); Assert.True(changed); } public class TestComparers { public static bool CaseInsensitiveStringCompare(string s1, string s2) { return StringComparer.OrdinalIgnoreCase.Equals(s1, s2); } } [Theory] [ClassData(typeof(CompilationTypes))] public void SwitchWithComparison(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(string)); ParameterExpression p1 = Expression.Parameter(typeof(string)); SwitchExpression s = Expression.Switch(p, Expression.Assign(p1, Expression.Constant("default")), typeof(TestComparers).GetMethod(nameof(TestComparers.CaseInsensitiveStringCompare)), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("hello")), Expression.Constant("hi")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("null")), Expression.Constant(null, typeof(string))), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lala")), Expression.Constant("bye")), Expression.SwitchCase(Expression.Assign(p1, Expression.Constant("lalala")), Expression.Constant("hi"))); BlockExpression block = Expression.Block(new ParameterExpression[] { p1 }, s, p1); Func<string, string> f = Expression.Lambda<Func<string, string>>(block, p).Compile(useInterpreter); Assert.Equal("hello", f("hi")); Assert.Equal("lala", f("bYe")); Assert.Equal("default", f("hi2")); Assert.Equal("hello", f("HI")); Assert.Equal("null", f(null)); } [Fact] public void NullSwitchValue() { AssertExtensions.Throws<ArgumentNullException>("switchValue", () => Expression.Switch(null)); AssertExtensions.Throws<ArgumentNullException>("switchValue", () => Expression.Switch(null, Expression.Empty())); AssertExtensions.Throws<ArgumentNullException>("switchValue", () => Expression.Switch(null, Expression.Empty(), default(MethodInfo))); AssertExtensions.Throws<ArgumentNullException>("switchValue", () => Expression.Switch(null, Expression.Empty(), default(MethodInfo), Enumerable.Empty<SwitchCase>())); AssertExtensions.Throws<ArgumentNullException>("switchValue", () => Expression.Switch(typeof(int), null, Expression.Constant(1), default(MethodInfo))); AssertExtensions.Throws<ArgumentNullException>("switchValue", () => Expression.Switch(typeof(int), null, Expression.Constant(1), default(MethodInfo), Enumerable.Empty<SwitchCase>())); } [Fact] public void VoidSwitchValue() { AssertExtensions.Throws<ArgumentException>("switchValue", () => Expression.Switch(Expression.Empty())); AssertExtensions.Throws<ArgumentException>("switchValue", () => Expression.Switch(Expression.Empty(), Expression.Empty())); AssertExtensions.Throws<ArgumentException>("switchValue", () => Expression.Switch(Expression.Empty(), Expression.Empty(), default(MethodInfo))); AssertExtensions.Throws<ArgumentException>("switchValue", () => Expression.Switch(Expression.Empty(), Expression.Empty(), default(MethodInfo), Enumerable.Empty<SwitchCase>())); AssertExtensions.Throws<ArgumentException>("switchValue", () => Expression.Switch(typeof(int), Expression.Empty(), Expression.Constant(1), default(MethodInfo))); AssertExtensions.Throws<ArgumentException>("switchValue", () => Expression.Switch(typeof(int), Expression.Empty(), Expression.Constant(1), default(MethodInfo), Enumerable.Empty<SwitchCase>())); } private static IEnumerable<object[]> ComparisonsWithInvalidParmeterCounts() { Func<bool> nullary = () => true; yield return new object[] { nullary.GetMethodInfo() }; Func<int, bool> unary = x => x % 2 == 0; yield return new object[] { unary.GetMethodInfo() }; Func<int, int, int, bool> ternary = (x, y, z) => (x == y) == (y == z); yield return new object[] { ternary.GetMethodInfo() }; Func<int, int, int, int, bool> quaternary = (a, b, c, d) => (a == b) == (c == d); yield return new object[] { quaternary.GetMethodInfo() }; } [Theory, MemberData(nameof(ComparisonsWithInvalidParmeterCounts))] public void InvalidComparisonMethodParameterCount(MethodInfo comparison) { AssertExtensions.Throws<ArgumentException>("comparison", () => Expression.Switch(Expression.Constant(0), Expression.Empty(), comparison)); AssertExtensions.Throws<ArgumentException>("comparison", () => Expression.Switch(Expression.Constant(0), Expression.Empty(), comparison, Enumerable.Empty<SwitchCase>())); AssertExtensions.Throws<ArgumentException>("comparison", () => Expression.Switch(typeof(int), Expression.Constant(0), Expression.Constant(1), comparison)); AssertExtensions.Throws<ArgumentException>("comparison", () => Expression.Switch(typeof(int), Expression.Constant(0), Expression.Constant(1), comparison, Enumerable.Empty<SwitchCase>())); } [Fact] public void ComparisonLeftParameterIncorrect() { Func<string, int, bool> isLength = (x, y) => (x?.Length).GetValueOrDefault() == y; MethodInfo comparer = isLength.GetMethodInfo(); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Switch(Expression.Constant(0), Expression.Empty(), comparer)); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Switch(Expression.Constant(0), Expression.Empty(), comparer, Enumerable.Empty<SwitchCase>())); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Switch(typeof(int), Expression.Constant(0), Expression.Constant(1), comparer)); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Switch(typeof(int), Expression.Constant(0), Expression.Constant(1), comparer, Enumerable.Empty<SwitchCase>())); } [Fact] public void ComparisonRightParameterIncorrect() { Func<int, string, bool> isLength = (x, y) => (y?.Length).GetValueOrDefault() == x; MethodInfo comparer = isLength.GetMethodInfo(); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Switch(Expression.Constant(0), Expression.Empty(), comparer, Expression.SwitchCase(Expression.Empty(), Expression.Constant(0)))); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Switch(Expression.Constant(0), Expression.Empty(), comparer, Enumerable.Repeat(Expression.SwitchCase(Expression.Empty(), Expression.Constant(0)), 1))); AssertExtensions.Throws<ArgumentException>("cases", () => Expression.Switch(typeof(int), Expression.Constant(0), Expression.Constant(1), comparer, Expression.SwitchCase(Expression.Empty(), Expression.Constant(0)))); AssertExtensions.Throws<ArgumentException>("cases", () => Expression.Switch(typeof(int), Expression.Constant(0), Expression.Constant(1), comparer, Enumerable.Repeat(Expression.SwitchCase(Expression.Empty(), Expression.Constant(0)), 1))); } private class GenClass<T> { public static bool WithinTwo(int x, int y) => Math.Abs(x - y) < 2; } [Theory, ClassData(typeof(CompilationTypes))] public void OpenGenericMethodDeclarer(bool useInterpreter) { Expression switchVal = Expression.Constant(30); Expression defaultExp = Expression.Constant(0); SwitchCase switchCase = Expression.SwitchCase(Expression.Constant(1), Expression.Constant(2)); MethodInfo method = typeof(GenClass<>).GetMethod(nameof(GenClass<int>.WithinTwo), BindingFlags.Static | BindingFlags.Public); AssertExtensions.Throws<ArgumentException>( "comparison", () => Expression.Switch(switchVal, defaultExp, method, switchCase)); } static bool WithinTen(int x, int y) => Math.Abs(x - y) < 10; [Theory, ClassData(typeof(CompilationTypes))] public void LiftedCall(bool useInterpreter) { Func<int> f = Expression.Lambda<Func<int>>( Expression.Switch( Expression.Constant(30, typeof(int?)), Expression.Constant(0), typeof(SwitchTests).GetMethod(nameof(WithinTen), BindingFlags.Static | BindingFlags.NonPublic), Expression.SwitchCase(Expression.Constant(1), Expression.Constant(2, typeof(int?))), Expression.SwitchCase(Expression.Constant(2), Expression.Constant(9, typeof(int?)), Expression.Constant(28, typeof(int?))), Expression.SwitchCase(Expression.Constant(3), Expression.Constant(49, typeof(int?))) ) ).Compile(useInterpreter); Assert.Equal(2, f()); } [Fact] public void LeftLiftedCall() { AssertExtensions.Throws<ArgumentException>(null, () => Expression.Switch( Expression.Constant(30, typeof(int?)), Expression.Constant(0), typeof(SwitchTests).GetMethod(nameof(WithinTen), BindingFlags.Static | BindingFlags.NonPublic), Expression.SwitchCase(Expression.Constant(1), Expression.Constant(2)) ) ); } [Fact] public void CaseTypeMisMatch() { AssertExtensions.Throws<ArgumentException>("cases", () => Expression.Switch( Expression.Constant(30), Expression.SwitchCase(Expression.Constant(1), Expression.Constant(0)), Expression.SwitchCase(Expression.Constant(2), Expression.Constant("Foo")) ) ); AssertExtensions.Throws<ArgumentException>("cases", () => Expression.Switch( Expression.Constant(30), Expression.SwitchCase(Expression.Constant(1), Expression.Constant(0), Expression.Constant("Foo")) ) ); } static int NonBooleanMethod(int x, int y) => x + y; [Fact] public void NonBooleanComparer() { MethodInfo comparer = typeof(SwitchTests).GetMethod(nameof(NonBooleanMethod), BindingFlags.Static | BindingFlags.NonPublic); AssertExtensions.Throws<ArgumentException>("comparison", () => Expression.Switch(Expression.Constant(0), Expression.Empty(), comparer, Expression.SwitchCase(Expression.Empty(), Expression.Constant(0)))); AssertExtensions.Throws<ArgumentException>("comparison", () => Expression.Switch(Expression.Constant(0), Expression.Empty(), comparer, Enumerable.Repeat(Expression.SwitchCase(Expression.Empty(), Expression.Constant(0)), 1))); AssertExtensions.Throws<ArgumentException>("cases", () => Expression.Switch(typeof(int), Expression.Constant(0), Expression.Constant(1), comparer, Expression.SwitchCase(Expression.Empty(), Expression.Constant(0)))); AssertExtensions.Throws<ArgumentException>("cases", () => Expression.Switch(typeof(int), Expression.Constant(0), Expression.Constant(1), comparer, Enumerable.Repeat(Expression.SwitchCase(Expression.Empty(), Expression.Constant(0)), 1))); } [Fact] public void MismatchingCasesAndType() { AssertExtensions.Throws<ArgumentException>("cases", () => Expression.Switch(Expression.Constant(2), Expression.SwitchCase(Expression.Constant("Foo"), Expression.Constant(0)), Expression.SwitchCase(Expression.Constant(3), Expression.Constant(9)))); } [Fact] public void MismatchingCasesAndExpclitType() { AssertExtensions.Throws<ArgumentException>("cases", () => Expression.Switch(typeof(int), Expression.Constant(0), null, null, Expression.SwitchCase(Expression.Constant("Foo"), Expression.Constant(0)))); } [Fact] public void MismatchingDefaultAndExpclitType() { AssertExtensions.Throws<ArgumentException>("defaultBody", () => Expression.Switch(typeof(int), Expression.Constant(0), Expression.Constant("Foo"), null)); } [Theory, ClassData(typeof(CompilationTypes))] public void MismatchingAllowedIfExplicitlyVoidIntgralValueType(bool useInterpreter) { Expression.Lambda<Action>( Expression.Switch( typeof(void), Expression.Constant(0), Expression.Constant(1), null, Expression.SwitchCase(Expression.Constant("Foo"), Expression.Constant(2)), Expression.SwitchCase(Expression.Constant(DateTime.MinValue), Expression.Constant(3)) ) ).Compile(useInterpreter)(); } [Theory, ClassData(typeof(CompilationTypes))] public void MismatchingAllowedIfExplicitlyVoidStringValueType(bool useInterpreter) { Expression.Lambda<Action>( Expression.Switch( typeof(void), Expression.Constant("Foo"), Expression.Constant(1), null, Expression.SwitchCase(Expression.Constant("Foo"), Expression.Constant("Bar")), Expression.SwitchCase(Expression.Constant(DateTime.MinValue), Expression.Constant("Foo")) ) ).Compile(useInterpreter)(); } [Theory, ClassData(typeof(CompilationTypes))] public void MismatchingAllowedIfExplicitlyVoidDateTimeValueType(bool useInterpreter) { Expression.Lambda<Action>( Expression.Switch( typeof(void), Expression.Constant(DateTime.MinValue), Expression.Constant(1), null, Expression.SwitchCase(Expression.Constant("Foo"), Expression.Constant(DateTime.MinValue)), Expression.SwitchCase(Expression.Constant(DateTime.MinValue), Expression.Constant(DateTime.MaxValue)) ) ).Compile(useInterpreter)(); } [Fact] public void SwitchCaseUpdateSameToSame() { Expression[] tests = {Expression.Constant(0), Expression.Constant(2)}; SwitchCase sc = Expression.SwitchCase(Expression.Constant(1), tests); Assert.Same(sc, sc.Update(tests, sc.Body)); Assert.Same(sc, sc.Update(sc.TestValues, sc.Body)); } [Fact] public void SwitchCaseUpdateNullTestsToSame() { SwitchCase sc = Expression.SwitchCase(Expression.Constant(0), Expression.Constant(1)); AssertExtensions.Throws<ArgumentException>("testValues", () => sc.Update(null, sc.Body)); AssertExtensions.Throws<ArgumentNullException>("body", () => sc.Update(sc.TestValues, null)); } [Fact] public void SwitchCaseDifferentBodyToDifferent() { SwitchCase sc = Expression.SwitchCase(Expression.Constant(1), Expression.Constant(0), Expression.Constant(2)); Assert.NotSame(sc, sc.Update(sc.TestValues, Expression.Constant(1))); } [Fact] public void SwitchCaseDifferentTestsToDifferent() { SwitchCase sc = Expression.SwitchCase(Expression.Constant(1), Expression.Constant(0), Expression.Constant(2)); Assert.NotSame(sc, sc.Update(new[] { Expression.Constant(0), Expression.Constant(2) }, sc.Body)); } [Fact] public void SwitchCaseUpdateDoesntRepeatEnumeration() { SwitchCase sc = Expression.SwitchCase(Expression.Constant(1), Expression.Constant(0), Expression.Constant(2)); Assert.NotSame(sc, sc.Update(new RunOnceEnumerable<Expression>(new[] { Expression.Constant(0), Expression.Constant(2) }), sc.Body)); } [Fact] public void SwitchUpdateSameToSame() { SwitchCase[] cases = { Expression.SwitchCase(Expression.Constant(1), Expression.Constant(1)), Expression.SwitchCase(Expression.Constant(2), Expression.Constant(2)) }; SwitchExpression sw = Expression.Switch( Expression.Constant(0), Expression.Constant(0), cases ); Assert.Same(sw, sw.Update(sw.SwitchValue, cases.Skip(0), sw.DefaultBody)); Assert.Same(sw, sw.Update(sw.SwitchValue, cases, sw.DefaultBody)); Assert.Same(sw, NoOpVisitor.Instance.Visit(sw)); } [Fact] public void SwitchUpdateDifferentDefaultToDifferent() { SwitchExpression sw = Expression.Switch( Expression.Constant(0), Expression.Constant(0), Expression.SwitchCase(Expression.Constant(1), Expression.Constant(1)), Expression.SwitchCase(Expression.Constant(2), Expression.Constant(2)) ); Assert.NotSame(sw, sw.Update(sw.SwitchValue, sw.Cases, Expression.Constant(0))); } [Fact] public void SwitchUpdateDifferentValueToDifferent() { SwitchExpression sw = Expression.Switch( Expression.Constant(0), Expression.Constant(0), Expression.SwitchCase(Expression.Constant(1), Expression.Constant(1)), Expression.SwitchCase(Expression.Constant(2), Expression.Constant(2)) ); Assert.NotSame(sw, sw.Update(Expression.Constant(0), sw.Cases, sw.DefaultBody)); } [Fact] public void SwitchUpdateDifferentCasesToDifferent() { SwitchExpression sw = Expression.Switch( Expression.Constant(0), Expression.Constant(0), Expression.SwitchCase(Expression.Constant(1), Expression.Constant(1)), Expression.SwitchCase(Expression.Constant(2), Expression.Constant(2)) ); SwitchCase[] newCases = new[] { Expression.SwitchCase(Expression.Constant(1), Expression.Constant(1)), Expression.SwitchCase(Expression.Constant(2), Expression.Constant(2)) }; Assert.NotSame(sw, sw.Update(sw.SwitchValue, newCases, sw.DefaultBody)); } [Fact] public void SwitchUpdateDoesntRepeatEnumeration() { SwitchExpression sw = Expression.Switch( Expression.Constant(0), Expression.Constant(0), Expression.SwitchCase(Expression.Constant(1), Expression.Constant(1)), Expression.SwitchCase(Expression.Constant(2), Expression.Constant(2)) ); IEnumerable<SwitchCase> newCases = new RunOnceEnumerable<SwitchCase>( new SwitchCase[] { Expression.SwitchCase(Expression.Constant(1), Expression.Constant(1)), Expression.SwitchCase(Expression.Constant(2), Expression.Constant(2)) }); Assert.NotSame(sw, sw.Update(sw.SwitchValue, newCases, sw.DefaultBody)); } [Fact] public void SingleTestCaseToString() { SwitchCase sc = Expression.SwitchCase(Expression.Constant(1), Expression.Constant(0)); Assert.Equal("case (0): ...", sc.ToString()); } [Fact] public void MultipleTestCaseToString() { SwitchCase sc = Expression.SwitchCase(Expression.Constant(1), Expression.Constant(0), Expression.Constant("A")); Assert.Equal("case (0, \"A\"): ...", sc.ToString()); } [Theory, ClassData(typeof(CompilationTypes))] public void SwitchOnString(bool useInterpreter) { var values = new string[] { "foobar", "foo", "bar", "baz", "qux", "quux", "corge", "grault", "garply", "waldo", "fred", "plugh", "xyzzy", "thud" }; for (var i = 1; i <= values.Length; i++) { SwitchCase[] cases = values.Take(i).Select((s, j) => Expression.SwitchCase(Expression.Constant(j), Expression.Constant(values[j]))).ToArray(); ParameterExpression value = Expression.Parameter(typeof(string)); Expression<Func<string, int>> e = Expression.Lambda<Func<string, int>>(Expression.Switch(value, Expression.Constant(-1), cases), value); Func<string, int> f = e.Compile(useInterpreter); int k = 0; foreach (var str in values.Take(i)) { Assert.Equal(k, f(str)); k++; } foreach (var str in values.Skip(i).Concat(new[] { default(string), "whatever", "FOO" })) { Assert.Equal(-1, f(str)); k++; } } } [Theory, ClassData(typeof(CompilationTypes))] public void SwitchOnStringEqualsMethod(bool useInterpreter) { var values = new string[] { "foobar", "foo", "bar", "baz", "qux", "quux", "corge", "grault", "garply", "waldo", "fred", "plugh", "xyzzy", "thud", null }; for (var i = 1; i <= values.Length; i++) { SwitchCase[] cases = values.Take(i).Select((s, j) => Expression.SwitchCase(Expression.Constant(j), Expression.Constant(values[j], typeof(string)))).ToArray(); ParameterExpression value = Expression.Parameter(typeof(string)); Expression<Func<string, int>> e = Expression.Lambda<Func<string, int>>(Expression.Switch(value, Expression.Constant(-1), typeof(string).GetMethod("Equals", new[] { typeof(string), typeof(string) }), cases), value); Func<string, int> f = e.Compile(useInterpreter); int k = 0; foreach (var str in values.Take(i)) { Assert.Equal(k, f(str)); k++; } foreach (var str in values.Skip(i).Concat(new[] { "whatever", "FOO" })) { Assert.Equal(-1, f(str)); k++; } } } [Fact] public void ToStringTest() { SwitchExpression e1 = Expression.Switch(Expression.Parameter(typeof(int), "x"), Expression.SwitchCase(Expression.Empty(), Expression.Constant(1))); Assert.Equal("switch (x) { ... }", e1.ToString()); SwitchCase e2 = Expression.SwitchCase(Expression.Parameter(typeof(int), "x"), Expression.Constant(1)); Assert.Equal("case (1): ...", e2.ToString()); SwitchCase e3 = Expression.SwitchCase(Expression.Parameter(typeof(int), "x"), Expression.Constant(1), Expression.Constant(2)); Assert.Equal("case (1, 2): ...", e3.ToString()); } private delegate void TwoOutAction(int input, ref int x, ref int y); [Theory, ClassData(typeof(CompilationTypes))] public void JumpBetweenCases(bool useIntepreter) { LabelTarget label = Expression.Label(); ParameterExpression xParam = Expression.Parameter(typeof(int).MakeByRefType()); ParameterExpression yParam = Expression.Parameter(typeof(int).MakeByRefType()); ParameterExpression inpParam = Expression.Parameter(typeof(int)); Expression<TwoOutAction> lambda = Expression.Lambda<TwoOutAction>( Expression.Switch( inpParam, Expression.Empty(), Expression.SwitchCase( Expression.Block(Expression.Assign(xParam, Expression.Constant(1)), Expression.Goto(label), Expression.Empty()), Expression.Constant(0)), Expression.SwitchCase( Expression.Block(Expression.Label(label), Expression.Assign(yParam, Expression.Constant(2)), Expression.Empty()), Expression.Constant(1))), inpParam, xParam, yParam); TwoOutAction act = lambda.Compile(useIntepreter); int x = 0; int y = 0; act(2, ref x, ref y); Assert.Equal(0, x); Assert.Equal(0, y); act(1, ref x, ref y); Assert.Equal(0, x); Assert.Equal(2, y); y = 0; act(0, ref x, ref y); Assert.Equal(1, x); Assert.Equal(2, y); } } }
//----------------------------------------------------------------------- // This file is part of Microsoft Robotics Developer Studio Code Samples. // // Copyright (C) Microsoft Corporation. All rights reserved. // // $File: MicrosoftGpsData.cs $ $Revision: 1 $ //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using W3C.Soap; using Microsoft.Dss.Core.Attributes; using Microsoft.Dss.ServiceModel.Dssp; namespace Microsoft.Robotics.Services.Sensors.Gps { #region Gps State Type /// <summary> /// MicrosoftGps State /// </summary> [DataContract] [Description("The GPS sensor state")] public class GpsState { #region Private data members private bool _connected; private MicrosoftGpsConfig _gpsConfig; private GpGll _gpGll; private GpGga _gpGga; private GpGsa _gpGsa; private GpGsv _gpGsv; private GpRmc _gpRmc; private GpVtg _gpVtg; #endregion /// <summary> /// Is the Gps unit currently connected. /// </summary> [DataMember] [Description("Indicates that the GPS is connected.")] [Browsable(false)] public bool Connected { get { return _connected; } set { _connected = value; } } /// <summary> /// History /// </summary> [DataMember] [Browsable(false)] [Description("Identifies the history of the GPS sensors.")] public List<EarthCoordinates> History = new List<EarthCoordinates>(); /// <summary> /// Serial Port Configuration /// </summary> [DataMember(IsRequired = true)] [Description("Specifies the serial port where the GPS is connected.")] public MicrosoftGpsConfig MicrosoftGpsConfig { get { return this._gpsConfig; } set { this._gpsConfig = value; } } /// <summary> /// Altitude and backup position /// </summary> [DataMember(IsRequired = false)] [Browsable(false)] [Description("Indicates altitude and backup position.")] public GpGga GpGga { get { return _gpGga; } set { _gpGga = value; } } /// <summary> /// Primary Position /// </summary> [DataMember(IsRequired = false)] [Browsable(false)] [Description("Indicates the primary position.")] public GpGll GpGll { get { return this._gpGll; } set { this._gpGll = value; } } /// <summary> /// Precision /// </summary> [DataMember(IsRequired = false)] [Browsable(false)] [Description("Indicates the GPS receiver operating mode, satellites used in the position solution, and DOP values.")] public GpGsa GpGsa { get { return this._gpGsa; } set { this._gpGsa = value; } } /// <summary> /// Satellites /// </summary> [DataMember(IsRequired = false)] [Browsable(false)] [Description("Indicates the number of GPS satellites in view, satellite ID numbers, elevation, azimuth, and SNR values.")] public GpGsv GpGsv { get { return this._gpGsv; } set { this._gpGsv = value; } } /// <summary> /// Backup course, speed, and position /// </summary> [DataMember(IsRequired = false)] [Browsable(false)] [Description("Indicates the time, date, position, course and speed data.")] public GpRmc GpRmc { get { return this._gpRmc; } set { this._gpRmc = value; } } /// <summary> /// Ground Speed and Course /// </summary> [DataMember(IsRequired = false)] [Browsable(false)] [Description("Indicates the course and speed information relative to the ground.")] public GpVtg GpVtg { get { return this._gpVtg; } set { this._gpVtg = value; } } } #endregion #region Gps Configuration /// <summary> /// MicrosoftGps Serial Port Configuration /// </summary> [DataContract] [DisplayName("(User) MicrosoftGps Configuration")] [Description("MicrosoftGps Serial Port Configuration")] public class MicrosoftGpsConfig: ICloneable { #region Private data members private int _commPort; private string _portName; private int _baudRate; private bool _captureHistory; private bool _captureNmea; private bool _retrackNmea; private string _configurationStatus; #endregion /// <summary> /// The Serial Comm Port /// </summary> [DataMember] [Description("Gps COM Port")] public int CommPort { get { return this._commPort; } set { this._commPort = value; } } /// <summary> /// The Serial Port Name or the File name containing Gps readings /// </summary> [DataMember] [Description("The Serial Port Name or the File name containing Gps readings (Default blank)")] public string PortName { get { return this._portName; } set { this._portName = value; } } /// <summary> /// Baud Rate /// </summary> [DataMember] [Description("Gps Baud Rate")] public int BaudRate { get { return this._baudRate; } set { this._baudRate = value; } } /// <summary> /// Capture Gps Coordinate History /// </summary> [DataMember] [Description("Capture Gps Coordinate History")] public bool CaptureHistory { get { return _captureHistory; } set { _captureHistory = value; } } /// <summary> /// Capture Gps Nmea stream /// </summary> [DataMember] [Description("Capture Gps Nmea stream")] public bool CaptureNmea { get { return _captureNmea; } set { _captureNmea = value; } } /// <summary> /// Retrack/Simulate Gps Nmea stream /// </summary> [DataMember] [Description("Retrack Simulate Gps Nmea stream")] public bool RetrackNmea { get { return _retrackNmea; } set { _retrackNmea = value; } } /// <summary> /// Configuration Status /// </summary> [DataMember] [Browsable(false)] [Description("Gps Configuration Status")] public string ConfigurationStatus { get { return _configurationStatus; } set { _configurationStatus = value; } } /// <summary> /// Default Constructor /// </summary> public MicrosoftGpsConfig() { this.BaudRate = 4800; this.CaptureHistory = false; this.CaptureNmea = false; this.RetrackNmea = false; this.CommPort = 0; this.PortName = string.Empty; } #region ICloneable Members /// <summary> /// Clone MicrosoftGpsConfig /// </summary> /// <returns></returns> public object Clone() { MicrosoftGpsConfig config = new MicrosoftGpsConfig(); config.BaudRate = this.BaudRate; config.CaptureHistory = this.CaptureHistory; config.CaptureNmea = this.CaptureNmea; config.RetrackNmea = this.RetrackNmea; config.CommPort = this.CommPort; config.PortName = this.PortName; return config; } #endregion } /// <summary> /// A Microsoft Gps Command /// <remarks>Use with SendMicrosoftGpsCommand()</remarks> /// </summary> [DataContract] [Description("A Microsoft Gps Command")] public class MicrosoftGpsCommand { private string _command; /// <summary> /// Command /// </summary> [DataMember] public string Command { get { return this._command; } set { this._command = value; } } } /// <summary> /// standard subscribe request type /// </summary> [DataContract] [Description("Standard Subscribe request")] public class SubscribeRequest : SubscribeRequestType { /// <summary> /// Which message types to subscribe to /// </summary> [DataMember] public GpsMessageType MessageTypes; /// <summary> /// Only subscribe to messages when IsValid is true /// </summary> [DataMember] public bool ValidOnly; } #endregion #region Gps Data Structures /// <summary> /// Time, position and fix type data /// </summary> [DataContract] public class GpGga { #region Private Members private System.DateTime _utcPosition; private double _latitude; private double _longitude; private PositionFixIndicator _positionFixIndicator; private int _satellitesUsed; private double _horizontalDilutionOfPrecision; private double _AltitudeMeters; private string _altitudeUnits; private string _geoIdSeparation; private string _geoIdSeparationUnits; private string _ageOfDiffCorr; private string _diffRefStationId; private bool _isValid; private System.DateTime _lastUpdate; #endregion /// <summary> /// Is Valid /// </summary> [DataMember] [Description("Indicates the GGA is valid.")] public bool IsValid { get { return this._isValid; } set { this._isValid = value; } } /// <summary> /// Last Update /// </summary> [DataMember] [Description("Indicates the time of the last reading update.")] public System.DateTime LastUpdate { get { return this._lastUpdate; } set { this._lastUpdate = value; } } /// <summary> /// UTC Position /// </summary> [DataMember] [Description("Identifies the UTC time of the reading.")] public System.DateTime UTCPosition { get { return this._utcPosition; } set { this._utcPosition = value; } } /// <summary> /// Latitude /// </summary> [DataMember] [Description("Indicates the latitude.")] public double Latitude { get { return this._latitude; } set { this._latitude = value; } } /// <summary> /// Longitude /// </summary> [DataMember] [Description("Indicates the longitude.")] public double Longitude { get { return this._longitude; } set { this._longitude = value; } } /// <summary> /// Position Fix Indicator /// </summary> [DataMember] [Description("Indicates the position fix indicator.")] public PositionFixIndicator PositionFixIndicator { get { return this._positionFixIndicator; } set { this._positionFixIndicator = value; } } /// <summary> /// Satellites Used /// </summary> [DataMember] [Description("Indicates the number of satellites used.")] public int SatellitesUsed { get { return this._satellitesUsed; } set { this._satellitesUsed = value; } } /// <summary> /// Horizontal Dilution Of Precision /// <remarks>Latitude and Longitude</remarks> /// </summary> [DataMember] [Description("Indicates the Horizontal Dilution Of Precision.")] public double HorizontalDilutionOfPrecision { get { return this._horizontalDilutionOfPrecision; } set { this._horizontalDilutionOfPrecision = value; } } /// <summary> /// Altitude. /// <remarks>No geoid corrections, values are WGS84 ellipsoid heights</remarks></summary> [DataMember] [Description("Indicates the altitude (m).\n(No geoid corrections, values are WGS84 ellipsoid heights.)")] public double AltitudeMeters { get { return this._AltitudeMeters; } set { this._AltitudeMeters = value; } } /// <summary> /// M-Meters /// </summary> [DataMember] [Description("Indicates the altitude units (m = meters).")] public string AltitudeUnits { get { return this._altitudeUnits; } set { this._altitudeUnits = value; } } /// <summary> /// Geo Id Separation /// </summary> [DataMember] [Description("Indicates Geo Id separation.")] public string GeoIdSeparation { get { return this._geoIdSeparation; } set { this._geoIdSeparation = value; } } /// <summary> /// M - Meters /// </summary> [DataMember] [Description("Indicates Geo Id separation units (m = meters).")] public string GeoIdSeparationUnits { get { return this._geoIdSeparationUnits; } set { this._geoIdSeparationUnits = value; } } /// <summary> /// Null when DGPS not used /// </summary> [DataMember] [Description("Indicates Age of Differential Correction.\n(Null when DGPS not used.)")] public string AgeOfDifferentialCorrection { get { return this._ageOfDiffCorr; } set { this._ageOfDiffCorr = value; } } /// <summary> /// Diff Ref Station Id /// </summary> [DataMember] [Description("Indicates Diff Ref Station Id.")] public string DiffRefStationId { get { return this._diffRefStationId; } set { this._diffRefStationId = value; } } } /// <summary> /// Latitude, longitude, UTC time of position fix and status /// </summary> [DataContract] [Description("Indicates latitude, longitude, UTC time of position fix and status.")] public class GpGll { #region Private Members private bool _isValid; private System.DateTime _lastUpdate; private double _latitude; private double _longitude; private string _status; private System.DateTime _gllTime; private string _marginOfError; #endregion /// <summary> /// Status == "A" /// </summary> [DataMember] [Description("Indicates the GLL is valid.")] public bool IsValid { get { return this._isValid; } set { this._isValid = value; } } /// <summary> /// Last Update /// </summary> [DataMember] [Description("Indicates the time of the last reading update.")] public System.DateTime LastUpdate { get { return this._lastUpdate; } set { this._lastUpdate = value; } } /// <summary> /// Latitude /// </summary> [DataMember] [Description("Indicates the latitude.")] public double Latitude { get { return this._latitude; } set { this._latitude = value; } } /// <summary> /// Longitude /// </summary> [DataMember] [Description("Indicates the longitude.")] public double Longitude { get { return this._longitude; } set { this._longitude = value; } } /// <summary> /// Status /// </summary> [DataMember] [Description("Indicates the GLL status.")] public string Status { get { return this._status; } set { this._status = value; } } /// <summary> /// gll Time /// </summary> [DataMember] [Description("Indicates the GLL time.")] public System.DateTime GllTime { get { return this._gllTime; } set { this._gllTime = value; } } /// <summary> /// Margin Of Error /// </summary> [DataMember] [Description("Indicates the Margin of Error.")] public string MarginOfError { get { return this._marginOfError; } set { this._marginOfError = value; } } } /// <summary> /// GPS receiver operating mode, satellites used in the position solution, and DOP values /// </summary> [DataContract] [Description("Indicates GPS receiver operating mode, satellites used in the position solution, and DOP values")] public class GpGsa { #region Private Members private bool _isValid; private System.DateTime _lastUpdate; private string _status; private string _autoManual; private GsaMode _mode; private double _sphericalDilutionOfPrecision; private double _horizontalDilutionOfPrecision; private double _verticalDilutionOfPrecision; internal int[] _satelliteUsed = new int[12]; #endregion /// <summary> /// Gsa Is Valid /// </summary> [DataMember] [Description("Indicates the GSA is valid.")] public bool IsValid { get { return this._isValid; } set { this._isValid = value; } } /// <summary> /// Gsa Last Update /// </summary> [DataMember] [Description("Indicates the time of the last reading update.")] public System.DateTime LastUpdate { get { return this._lastUpdate; } set { this._lastUpdate = value; } } /// <summary> /// Gsa Status /// </summary> [DataMember] [Description("Indicates the GSA status.")] public string Status { get { return this._status; } set { this._status = value; } } /// <summary> /// Gsa Auto Manual /// </summary> [DataMember] [Description("Indicates whether GSA Auto or Manual is set.")] public string AutoManual { get { return this._autoManual; } set { this._autoManual = value; } } /// <summary> /// Gsa Mode /// </summary> [DataMember] [Description("Indicates the GSA mode.")] public GsaMode Mode { get { return this._mode; } set { this._mode = value; } } /// <summary> /// Gsa Spherical Dilution Of Precision /// <remarks>Accuracy of the 3-D coordinates</remarks> /// </summary> [DataMember] [Description("Indicates the GSA Spherical Dilution Of Precision (accuracy of the 3-D coordinates).")] public double SphericalDilutionOfPrecision { get { return this._sphericalDilutionOfPrecision; } set { this._sphericalDilutionOfPrecision = value; } } /// <summary> /// Gsa Horizontal Dilution Of Precision /// <remarks>Latitude and Longitude</remarks> /// </summary> [DataMember] [Description("Indicates the GSA Horizontal Dilution Of Precision (latitude and longitude).")] public double HorizontalDilutionOfPrecision { get { return this._horizontalDilutionOfPrecision; } set { this._horizontalDilutionOfPrecision = value; } } /// <summary> /// Gsa Vertical Dilution Of Precision (Altitude) /// </summary> [DataMember] [Description("Indicates the GSA Vertical Dilution Of Precision (altitude).")] public double VerticalDilutionOfPrecision { get { return this._verticalDilutionOfPrecision; } set { this._verticalDilutionOfPrecision = value; } } /// <summary> /// Satellite Used /// </summary> [DataMember] #if DEBUG [SuppressMessage("Microsoft.Usage", "CA2227")] #endif [Description("Identifies the set of satelites used.")] public List<int> SatelliteUsed { get { return new List<int>(_satelliteUsed); } set { _satelliteUsed = value.ToArray(); } } } /// <summary> /// The number of GPS satellites in view, satellite ID numbers, elevation, azimuth, and SNR values. /// </summary> [DataContract] [Description("Indicates the number of GPS satellites in view, satellite ID numbers, elevation, azimuth, and SNR values.")] public class GpGsv { #region Private Members private System.DateTime _lastUpdate; private bool _isValid; private int _satellitesInView; internal GsvSatellite[] _gsvSatellites; #endregion /// <summary> /// Gsv Is Valid /// </summary> [DataMember] [Description("Indicates the GSV is valid.")] public bool IsValid { get { return this._isValid; } set { this._isValid = value; } } /// <summary> /// Gsv Last Update /// </summary> [DataMember] [Description("Indicates the time of the last reading update.")] public System.DateTime LastUpdate { get { return this._lastUpdate; } set { this._lastUpdate = value; } } /// <summary> /// Number of Gsv Satellites In View /// </summary> [DataMember] [Description("Indicates the number of GSV satellites in view.")] public int SatellitesInView { get { return this._satellitesInView; } set { this._satellitesInView = value; } } /// <summary> /// Satellites in View /// </summary> [DataMember] #if DEBUG [SuppressMessage("Microsoft.Usage", "CA2227", Justification = "DataMember's can not be read-only")] #endif [Description("Identifies the satellites in view.")] public List<GsvSatellite> GsvSatellites { get { return new List<GsvSatellite>(_gsvSatellites); } set { _gsvSatellites = value.ToArray(); } } } /// <summary> /// Info about an individual satellite /// </summary> [DataContract] [Description("Identifies information about an individual satellite.")] public class GsvSatellite { /// <summary> /// Satellite Id /// </summary> [DataMember] [Description("Indicates the satellite Id.")] public int Id; /// <summary> /// Elevation in degrees /// <remarks>Maximum 90</remarks> /// </summary> [DataMember] [Description("Indicates the elevation in degrees (maximum 90).")] public int ElevationDegrees; /// <summary> /// Azimuth in degrees /// <remarks>Range 0-359</remarks> /// </summary> [DataMember] [Description("Indicates the azimuth in degrees (range 0-359).")] public int AzimuthDegrees; /// <summary> /// Signal to Noise Ratio /// <remarks>Range 0-99, -1 when not tracking</remarks> /// </summary> [DataMember] [Description("Indicates the Signal-to-Noise-Ratio (range 0-99, -1 when not tracking).")] public int SignalToNoiseRatio; } /// <summary> /// Time, date, position, course and speed data /// </summary> [DataContract] [Description("Indicates the time, date, position, course and speed data.")] public class GpRmc { #region Private Members private bool _isValid; private System.DateTime _lastUpdate; private System.DateTime _dateTime; private string _status; private double _latitude; private double _longitude; private double _speedMetersPerSecond; private double _courseDegrees; #endregion /// <summary> /// Rmc Is Valid /// </summary> [DataMember] [Description("Indicates the RMC is valid.")] public bool IsValid { get { return this._isValid; } set { this._isValid = value; } } /// <summary> /// Rmc Last Update /// </summary> [DataMember] [Description("Indicates the time of the last reading update.")] public System.DateTime LastUpdate { get { return this._lastUpdate; } set { this._lastUpdate = value; } } /// <summary> /// Rmc Date Time /// </summary> [DataMember] [Description("Indicates the RMC time.")] public System.DateTime DateTime { get { return this._dateTime; } set { this._dateTime = value; } } /// <summary> /// Rmc Status /// </summary> [DataMember] [Description("Indicates the RMC status.")] public string Status { get { return this._status; } set { this._status = value; } } /// <summary> /// Rmc Latitude /// </summary> [DataMember] [Description("Indicates the latitude.")] public double Latitude { get { return this._latitude; } set { this._latitude = value; } } /// <summary> /// Rmc Longitude /// </summary> [DataMember] [Description("Indicates the longitude.")] public double Longitude { get { return this._longitude; } set { this._longitude = value; } } /// <summary> /// Rmc Speed Meters Per Second /// </summary> [DataMember] [Description("Indicates the RMC speed (meters per second).")] public double SpeedMetersPerSecond { get { return this._speedMetersPerSecond; } set { this._speedMetersPerSecond = value; } } /// <summary> /// Rmc Course Degrees /// </summary> [DataMember] [Description("Indicates the RMC course degrees.")] public double CourseDegrees { get { return this._courseDegrees; } set { this._courseDegrees = value; } } } /// <summary> /// Course and speed information relative to the ground /// </summary> [DataContract] [Description("Indicates the course and speed information relative to the ground.")] public class GpVtg { #region Private Members private bool _isValid; private System.DateTime _lastUpdate; private double _speedMetersPerSecond; private double _courseDegrees; #endregion /// <summary> /// Vtg Is Valid /// </summary> [DataMember] [Description("Indicates that the VTG is valid.")] public bool IsValid { get { return this._isValid; } set { this._isValid = value; } } /// <summary> /// Vtg Last Update /// </summary> [DataMember] [Description("Indicates the time of the last reading update.")] public System.DateTime LastUpdate { get { return this._lastUpdate; } set { this._lastUpdate = value; } } /// <summary> /// Speed Meters Per Second /// </summary> [DataMember] [Description("Indicates the speed (meters per second).")] public double SpeedMetersPerSecond { get { return this._speedMetersPerSecond; } set { this._speedMetersPerSecond = value; } } /// <summary> /// Course Degrees /// </summary> [DataMember] [Description("Indicates the course degrees.")] public double CourseDegrees { get { return this._courseDegrees; } set { this._courseDegrees = value; } } } #endregion #region Gps Enums /// <summary> /// Position Fix Indicator (Fix quality) /// 0 = invalid /// 1 = GPS fix (SPS) /// 2 = DGPS fix /// 3 = PPS fix /// 4 = Real Time Kinematic /// 5 = Float RTK /// 6 = estimated (dead reckoning) (2.3 feature) /// 7 = Manual input mode /// 8 = Simulation mode /// </summary> [DataContract] [Description("Identifies the Position Fix Indicator settings.")] public enum PositionFixIndicator { /// <summary> /// Fix Not Available or invalid /// </summary> [DataMember] FixNotAvailable = 0, /// <summary> /// GpsSPS Mode - basic fix available /// </summary> [DataMember] GpsSPSMode = 1, /// <summary> /// Differential GpsSPS Mode - fix available /// </summary> [DataMember] GpsDifferentialSPSMode = 2, /// <summary> /// GpsPPS Mode - fix available /// </summary> [DataMember] GpsPPSMode = 3, /// <summary> /// Real Time Kinematic Mode - fix available /// </summary> [DataMember] GpsRTKMode = 4, /// <summary> /// Float RTK Mode - fix available /// </summary> [DataMember] GpsFloatRTKMode = 5, /// <summary> /// Estimated (dead reckoning) Mode - estimated fix available (2.3 feature) /// </summary> [DataMember] GpsDeadReckoningMode = 6, /// <summary> /// Manual input mode - fix available /// </summary> [DataMember] GpsManualInputMode = 7, /// <summary> /// Simulation Mode - fix available /// </summary> [DataMember] GpsSimulationMode = 8 } /// <summary> /// Gps Message Type /// </summary> [DataContract,Flags] [Description("Identifies the NMEA message types.")] public enum GpsMessageType { /// <summary> /// No message /// </summary> None = 0, /// <summary> /// Altitude and backup position /// </summary> GPGGA = 0x01, /// <summary> /// Primary Position /// </summary> GPGLL = 0x02, /// <summary> /// Precision /// </summary> GPGSA = 0x04, /// <summary> /// Satellites /// </summary> GPGSV = 0x08, /// <summary> /// Backup course, speed, and position /// </summary> GPRMC = 0x10, /// <summary> /// Ground Speed and Course /// </summary> GPVTG = 0x20, /// <summary> /// All message types /// </summary> All = GPGGA | GPGLL | GPGSA | GPGSV | GPRMC | GPVTG } /// <summary> /// Gsa Mode /// </summary> [DataContract] [Description("Identifies the GSA mode.")] public enum GsaMode { /// <summary> /// Default value /// </summary> [DataMember] None = 0, /// <summary> /// No Fix /// </summary> [DataMember] NoFix = 1, /// <summary> /// Fix2D /// </summary> [DataMember] Fix2D = 2, /// <summary> /// Fix3D /// </summary> [DataMember] Fix3D = 3, } #endregion }
// *********************************************************************** // Copyright (c) 2014 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Diagnostics; using System.Reflection; using System.Threading; using System.Globalization; using System.IO; using NUnit.Framework.Constraints; using NUnit.Framework.Internal.Execution; using NUnit.Framework.Interfaces; using System.Security.Principal; #if ASYNC using System.Threading.Tasks; #endif namespace NUnit.Framework.Internal { /// <summary> /// Summary description for TestExecutionContextTests. /// </summary> [TestFixture][Property("Question", "Why?")] public class TestExecutionContextTests { private TestExecutionContext _fixtureContext; private TestExecutionContext _setupContext; private ResultState _fixtureResult; string originalDirectory; #if !NETCOREAPP1_1 CultureInfo originalCulture; CultureInfo originalUICulture; IPrincipal originalPrincipal; #endif readonly DateTime _fixtureCreateTime = DateTime.UtcNow; readonly long _fixtureCreateTicks = Stopwatch.GetTimestamp(); [OneTimeSetUp] public void OneTimeSetUp() { _fixtureContext = TestExecutionContext.CurrentContext; _fixtureResult = _fixtureContext.CurrentResult.ResultState; } [OneTimeTearDown] public void OneTimeTearDown() { // TODO: We put some tests in one time teardown to verify that // the context is still valid. It would be better if these tests // were placed in a second-level test, invoked from this test class. TestExecutionContext ec = TestExecutionContext.CurrentContext; Assert.That(ec.CurrentTest.Name, Is.EqualTo("TestExecutionContextTests")); Assert.That(ec.CurrentTest.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests")); Assert.That(_fixtureContext.CurrentTest.Id, Is.Not.Null.And.Not.Empty); Assert.That(_fixtureContext.CurrentTest.Properties.Get("Question"), Is.EqualTo("Why?")); } [SetUp] public void Initialize() { _setupContext = TestExecutionContext.CurrentContext; originalDirectory = Directory.GetCurrentDirectory(); #if !NETCOREAPP1_1 originalCulture = CultureInfo.CurrentCulture; originalUICulture = CultureInfo.CurrentUICulture; originalPrincipal = Thread.CurrentPrincipal; #endif } [TearDown] public void Cleanup() { Directory.SetCurrentDirectory(originalDirectory); #if !NETCOREAPP1_1 Thread.CurrentThread.CurrentCulture = originalCulture; Thread.CurrentThread.CurrentUICulture = originalUICulture; Thread.CurrentPrincipal = originalPrincipal; #endif Assert.That( TestExecutionContext.CurrentContext.CurrentTest.FullName, Is.EqualTo(_setupContext.CurrentTest.FullName), "Context at TearDown failed to match that saved from SetUp"); Assert.That( TestExecutionContext.CurrentContext.CurrentResult.Name, Is.EqualTo(_setupContext.CurrentResult.Name), "Cannot access CurrentResult in TearDown"); } #region CurrentContext #if ASYNC [Test] public async Task CurrentContextFlowsWithAsyncExecution() { var context = TestExecutionContext.CurrentContext; await YieldAsync(); Assert.AreSame(context, TestExecutionContext.CurrentContext); } [Test] public async Task CurrentContextFlowsWithParallelAsyncExecution() { var expected = TestExecutionContext.CurrentContext; var parallelResult = await WhenAllAsync(YieldAndReturnContext(), YieldAndReturnContext()); Assert.AreSame(expected, TestExecutionContext.CurrentContext); Assert.AreSame(expected, parallelResult[0]); Assert.AreSame(expected, parallelResult[1]); } #endif [Test] public void CurrentContextFlowsToUserCreatedThread() { TestExecutionContext threadContext = null; Thread thread = new Thread(() => { threadContext = TestExecutionContext.CurrentContext; }); thread.Start(); thread.Join(); Assert.That(threadContext, Is.Not.Null.And.SameAs(TestExecutionContext.CurrentContext)); } #endregion #region CurrentTest [Test] public void FixtureSetUpCanAccessFixtureName() { Assert.That(_fixtureContext.CurrentTest.Name, Is.EqualTo("TestExecutionContextTests")); } [Test] public void FixtureSetUpCanAccessFixtureFullName() { Assert.That(_fixtureContext.CurrentTest.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests")); } [Test] public void FixtureSetUpHasNullMethodName() { Assert.That(_fixtureContext.CurrentTest.MethodName, Is.Null); } [Test] public void FixtureSetUpCanAccessFixtureId() { Assert.That(_fixtureContext.CurrentTest.Id, Is.Not.Null.And.Not.Empty); } [Test] public void FixtureSetUpCanAccessFixtureProperties() { Assert.That(_fixtureContext.CurrentTest.Properties.Get("Question"), Is.EqualTo("Why?")); } [Test] public void SetUpCanAccessTestName() { Assert.That(_setupContext.CurrentTest.Name, Is.EqualTo("SetUpCanAccessTestName")); } [Test] public void SetUpCanAccessTestFullName() { Assert.That(_setupContext.CurrentTest.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.SetUpCanAccessTestFullName")); } [Test] public void SetUpCanAccessTestMethodName() { Assert.That(_setupContext.CurrentTest.MethodName, Is.EqualTo("SetUpCanAccessTestMethodName")); } [Test] public void SetUpCanAccessTestId() { Assert.That(_setupContext.CurrentTest.Id, Is.Not.Null.And.Not.Empty); } [Test] [Property("Answer", 42)] public void SetUpCanAccessTestProperties() { Assert.That(_setupContext.CurrentTest.Properties.Get("Answer"), Is.EqualTo(42)); } [Test] public void TestCanAccessItsOwnName() { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Name, Is.EqualTo("TestCanAccessItsOwnName")); } [Test] public void TestCanAccessItsOwnFullName() { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.TestCanAccessItsOwnFullName")); } [Test] public void TestCanAccessItsOwnMethodName() { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.MethodName, Is.EqualTo("TestCanAccessItsOwnMethodName")); } [Test] public void TestCanAccessItsOwnId() { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Id, Is.Not.Null.And.Not.Empty); } [Test] [Property("Answer", 42)] public void TestCanAccessItsOwnProperties() { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Properties.Get("Answer"), Is.EqualTo(42)); } [TestCase(123, "abc")] public void TestCanAccessItsOwnArguments(int i, string s) { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Arguments, Is.EqualTo(new object[] {123, "abc"})); } #if ASYNC [Test] public async Task AsyncTestCanAccessItsOwnName() { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Name, Is.EqualTo("AsyncTestCanAccessItsOwnName")); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Name, Is.EqualTo("AsyncTestCanAccessItsOwnName")); } [Test] public async Task AsyncTestCanAccessItsOwnFullName() { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.AsyncTestCanAccessItsOwnFullName")); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.CurrentTest.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.AsyncTestCanAccessItsOwnFullName")); } [Test] public async Task AsyncTestCanAccessItsOwnMethodName() { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.MethodName, Is.EqualTo("AsyncTestCanAccessItsOwnMethodName")); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.CurrentTest.MethodName, Is.EqualTo("AsyncTestCanAccessItsOwnMethodName")); } [Test] public async Task AsyncTestCanAccessItsOwnId() { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Id, Is.Not.Null.And.Not.Empty); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Id, Is.Not.Null.And.Not.Empty); } [Test] [Property("Answer", 42)] public async Task AsyncTestCanAccessItsOwnProperties() { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Properties.Get("Answer"), Is.EqualTo(42)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Properties.Get("Answer"), Is.EqualTo(42)); } [TestCase(123, "abc")] public async Task AsyncTestCanAccessItsOwnArguments(int i, string s) { Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Arguments, Is.EqualTo(new object[] {123, "abc"})); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Arguments, Is.EqualTo(new object[] {123, "abc"})); } #endif #if PARALLEL [Test] public void TestHasWorkerWhenParallel() { var worker = TestExecutionContext.CurrentContext.TestWorker; var isRunningUnderTestWorker = TestExecutionContext.CurrentContext.Dispatcher is ParallelWorkItemDispatcher; Assert.That(worker != null || !isRunningUnderTestWorker); } #endif #endregion #region CurrentResult [Test] public void CanAccessResultName() { Assert.That(_fixtureContext.CurrentResult.Name, Is.EqualTo("TestExecutionContextTests")); Assert.That(_setupContext.CurrentResult.Name, Is.EqualTo("CanAccessResultName")); Assert.That(TestExecutionContext.CurrentContext.CurrentResult.Name, Is.EqualTo("CanAccessResultName")); } [Test] public void CanAccessResultFullName() { Assert.That(_fixtureContext.CurrentResult.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests")); Assert.That(_setupContext.CurrentResult.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.CanAccessResultFullName")); Assert.That(TestExecutionContext.CurrentContext.CurrentResult.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.CanAccessResultFullName")); } [Test] public void CanAccessResultTest() { Assert.That(_fixtureContext.CurrentResult.Test, Is.SameAs(_fixtureContext.CurrentTest)); Assert.That(_setupContext.CurrentResult.Test, Is.SameAs(_setupContext.CurrentTest)); Assert.That(TestExecutionContext.CurrentContext.CurrentResult.Test, Is.SameAs(TestExecutionContext.CurrentContext.CurrentTest)); } [Test] public void CanAccessResultState() { // This is copied in setup because it can change if any test fails Assert.That(_fixtureResult, Is.EqualTo(ResultState.Success)); Assert.That(_setupContext.CurrentResult.ResultState, Is.EqualTo(ResultState.Inconclusive)); Assert.That(TestExecutionContext.CurrentContext.CurrentResult.ResultState, Is.EqualTo(ResultState.Inconclusive)); } #if ASYNC [Test] public async Task CanAccessResultName_Async() { Assert.That(TestExecutionContext.CurrentContext.CurrentResult.Name, Is.EqualTo("CanAccessResultName_Async")); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.CurrentResult.Name, Is.EqualTo("CanAccessResultName_Async")); } [Test] public async Task CanAccessResultFullName_Async() { Assert.That(TestExecutionContext.CurrentContext.CurrentResult.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.CanAccessResultFullName_Async")); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.CurrentResult.FullName, Is.EqualTo("NUnit.Framework.Internal.TestExecutionContextTests.CanAccessResultFullName_Async")); } [Test] public async Task CanAccessResultTest_Async() { Assert.That(TestExecutionContext.CurrentContext.CurrentResult.Test, Is.SameAs(TestExecutionContext.CurrentContext.CurrentTest)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.CurrentResult.Test, Is.SameAs(TestExecutionContext.CurrentContext.CurrentTest)); } [Test] public async Task CanAccessResultState_Async() { Assert.That(TestExecutionContext.CurrentContext.CurrentResult.ResultState, Is.EqualTo(ResultState.Inconclusive)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.CurrentResult.ResultState, Is.EqualTo(ResultState.Inconclusive)); } #endif #endregion #region StartTime [Test] public void CanAccessStartTime() { Assert.That(_fixtureContext.StartTime, Is.GreaterThan(DateTime.MinValue).And.LessThanOrEqualTo(_fixtureCreateTime)); Assert.That(_setupContext.StartTime, Is.GreaterThanOrEqualTo(_fixtureContext.StartTime)); Assert.That(TestExecutionContext.CurrentContext.StartTime, Is.GreaterThanOrEqualTo(_setupContext.StartTime)); } #if ASYNC [Test] public async Task CanAccessStartTime_Async() { var startTime = TestExecutionContext.CurrentContext.StartTime; Assert.That(startTime, Is.GreaterThanOrEqualTo(_setupContext.StartTime)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.StartTime, Is.EqualTo(startTime)); } #endif #endregion #region StartTicks [Test] public void CanAccessStartTicks() { Assert.That(_fixtureContext.StartTicks, Is.LessThanOrEqualTo(_fixtureCreateTicks)); Assert.That(_setupContext.StartTicks, Is.GreaterThanOrEqualTo(_fixtureContext.StartTicks)); Assert.That(TestExecutionContext.CurrentContext.StartTicks, Is.GreaterThanOrEqualTo(_setupContext.StartTicks)); } #if ASYNC [Test] public async Task AsyncTestCanAccessStartTicks() { var startTicks = TestExecutionContext.CurrentContext.StartTicks; Assert.That(startTicks, Is.GreaterThanOrEqualTo(_setupContext.StartTicks)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.StartTicks, Is.EqualTo(startTicks)); } #endif #endregion #region OutWriter [Test] public void CanAccessOutWriter() { Assert.That(_fixtureContext.OutWriter, Is.Not.Null); Assert.That(_setupContext.OutWriter, Is.Not.Null); Assert.That(TestExecutionContext.CurrentContext.OutWriter, Is.SameAs(_setupContext.OutWriter)); } #if ASYNC [Test] public async Task AsyncTestCanAccessOutWriter() { var outWriter = TestExecutionContext.CurrentContext.OutWriter; Assert.That(outWriter, Is.SameAs(_setupContext.OutWriter)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.OutWriter, Is.SameAs(outWriter)); } #endif #endregion #region TestObject [Test] public void CanAccessTestObject() { Assert.That(_fixtureContext.TestObject, Is.Not.Null.And.TypeOf(GetType())); Assert.That(_setupContext.TestObject, Is.SameAs(_fixtureContext.TestObject)); Assert.That(TestExecutionContext.CurrentContext.TestObject, Is.SameAs(_setupContext.TestObject)); } #if ASYNC [Test] public async Task CanAccessTestObject_Async() { var testObject = TestExecutionContext.CurrentContext.TestObject; Assert.That(testObject, Is.SameAs(_setupContext.TestObject)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.TestObject, Is.SameAs(testObject)); } #endif #endregion #region StopOnError [Test] public void CanAccessStopOnError() { Assert.That(_setupContext.StopOnError, Is.EqualTo(_fixtureContext.StopOnError)); Assert.That(TestExecutionContext.CurrentContext.StopOnError, Is.EqualTo(_setupContext.StopOnError)); } #if ASYNC [Test] public async Task CanAccessStopOnError_Async() { var stop = TestExecutionContext.CurrentContext.StopOnError; Assert.That(stop, Is.EqualTo(_setupContext.StopOnError)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.StopOnError, Is.EqualTo(stop)); } #endif #endregion #region Listener [Test] public void CanAccessListener() { Assert.That(_fixtureContext.Listener, Is.Not.Null); Assert.That(_setupContext.Listener, Is.SameAs(_fixtureContext.Listener)); Assert.That(TestExecutionContext.CurrentContext.Listener, Is.SameAs(_setupContext.Listener)); } #if ASYNC [Test] public async Task CanAccessListener_Async() { var listener = TestExecutionContext.CurrentContext.Listener; Assert.That(listener, Is.SameAs(_setupContext.Listener)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.Listener, Is.SameAs(listener)); } #endif #endregion #region Dispatcher [Test] public void CanAccessDispatcher() { Assert.That(_fixtureContext.RandomGenerator, Is.Not.Null); Assert.That(_setupContext.Dispatcher, Is.SameAs(_fixtureContext.Dispatcher)); Assert.That(TestExecutionContext.CurrentContext.Dispatcher, Is.SameAs(_setupContext.Dispatcher)); } #if ASYNC [Test] public async Task CanAccessDispatcher_Async() { var dispatcher = TestExecutionContext.CurrentContext.Dispatcher; Assert.That(dispatcher, Is.SameAs(_setupContext.Dispatcher)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.Dispatcher, Is.SameAs(dispatcher)); } #endif #endregion #region ParallelScope [Test] public void CanAccessParallelScope() { var scope = _fixtureContext.ParallelScope; Assert.That(_setupContext.ParallelScope, Is.EqualTo(scope)); Assert.That(TestExecutionContext.CurrentContext.ParallelScope, Is.EqualTo(scope)); } #if ASYNC [Test] public async Task CanAccessParallelScope_Async() { var scope = TestExecutionContext.CurrentContext.ParallelScope; Assert.That(scope, Is.EqualTo(_setupContext.ParallelScope)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.ParallelScope, Is.EqualTo(scope)); } #endif #endregion #region TestWorker #if PARALLEL [Test] public void CanAccessTestWorker() { if (TestExecutionContext.CurrentContext.Dispatcher is ParallelWorkItemDispatcher) { Assert.That(_fixtureContext.TestWorker, Is.Not.Null); Assert.That(_setupContext.TestWorker, Is.SameAs(_fixtureContext.TestWorker)); Assert.That(TestExecutionContext.CurrentContext.TestWorker, Is.SameAs(_setupContext.TestWorker)); } } #if ASYNC [Test] public async Task CanAccessTestWorker_Async() { var worker = TestExecutionContext.CurrentContext.TestWorker; Assert.That(worker, Is.SameAs(_setupContext.TestWorker)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.TestWorker, Is.SameAs(worker)); } #endif #endif #endregion #region RandomGenerator [Test] public void CanAccessRandomGenerator() { Assert.That(_fixtureContext.RandomGenerator, Is.Not.Null); Assert.That(_setupContext.RandomGenerator, Is.Not.Null); Assert.That(TestExecutionContext.CurrentContext.RandomGenerator, Is.SameAs(_setupContext.RandomGenerator)); } #if ASYNC [Test] public async Task CanAccessRandomGenerator_Async() { var random = TestExecutionContext.CurrentContext.RandomGenerator; Assert.That(random, Is.SameAs(_setupContext.RandomGenerator)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.RandomGenerator, Is.SameAs(random)); } #endif #endregion #region AssertCount [Test] public void CanAccessAssertCount() { Assert.That(_fixtureContext.AssertCount, Is.EqualTo(0)); Assert.That(_setupContext.AssertCount, Is.EqualTo(1)); Assert.That(TestExecutionContext.CurrentContext.AssertCount, Is.EqualTo(2)); Assert.That(2 + 2, Is.EqualTo(4)); Assert.That(TestExecutionContext.CurrentContext.AssertCount, Is.EqualTo(4)); } #if ASYNC [Test] public async Task CanAccessAssertCount_Async() { Assert.That(2 + 2, Is.EqualTo(4)); Assert.That(TestExecutionContext.CurrentContext.AssertCount, Is.EqualTo(1)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.AssertCount, Is.EqualTo(2)); Assert.That(TestExecutionContext.CurrentContext.AssertCount, Is.EqualTo(3)); } #endif #endregion #region MultipleAssertLevel [Test] public void CanAccessMultipleAssertLevel() { Assert.That(_fixtureContext.MultipleAssertLevel, Is.EqualTo(0)); Assert.That(_setupContext.MultipleAssertLevel, Is.EqualTo(0)); Assert.That(TestExecutionContext.CurrentContext.MultipleAssertLevel, Is.EqualTo(0)); Assert.Multiple(() => { Assert.That(TestExecutionContext.CurrentContext.MultipleAssertLevel, Is.EqualTo(1)); }); } #if ASYNC [Test] public async Task CanAccessMultipleAssertLevel_Async() { Assert.That(TestExecutionContext.CurrentContext.MultipleAssertLevel, Is.EqualTo(0)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.MultipleAssertLevel, Is.EqualTo(0)); Assert.Multiple(() => { Assert.That(TestExecutionContext.CurrentContext.MultipleAssertLevel, Is.EqualTo(1)); }); } #endif #endregion #region TestCaseTimeout [Test] public void CanAccessTestCaseTimeout() { var timeout = _fixtureContext.TestCaseTimeout; Assert.That(_setupContext.TestCaseTimeout, Is.EqualTo(timeout)); Assert.That(TestExecutionContext.CurrentContext.TestCaseTimeout, Is.EqualTo(timeout)); } #if ASYNC [Test] public async Task CanAccessTestCaseTimeout_Async() { var timeout = TestExecutionContext.CurrentContext.TestCaseTimeout; Assert.That(timeout, Is.EqualTo(_setupContext.TestCaseTimeout)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.TestCaseTimeout, Is.EqualTo(timeout)); } #endif #endregion #region UpstreamActions [Test] public void CanAccessUpstreamActions() { var actions = _fixtureContext.UpstreamActions; Assert.That(_setupContext.UpstreamActions, Is.EqualTo(actions)); Assert.That(TestExecutionContext.CurrentContext.UpstreamActions, Is.EqualTo(actions)); } #if ASYNC [Test] public async Task CanAccessUpstreamAcxtions_Async() { var actions = TestExecutionContext.CurrentContext.UpstreamActions; Assert.That(actions, Is.SameAs(_setupContext.UpstreamActions)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.UpstreamActions, Is.SameAs(actions)); } #endif #endregion #region CurrentCulture and CurrentUICulture #if !NETCOREAPP1_1 [Test] public void CanAccessCurrentCulture() { Assert.That(_fixtureContext.CurrentCulture, Is.EqualTo(CultureInfo.CurrentCulture)); Assert.That(_setupContext.CurrentCulture, Is.EqualTo(CultureInfo.CurrentCulture)); Assert.That(TestExecutionContext.CurrentContext.CurrentCulture, Is.EqualTo(CultureInfo.CurrentCulture)); } [Test] public void CanAccessCurrentUICulture() { Assert.That(_fixtureContext.CurrentUICulture, Is.EqualTo(CultureInfo.CurrentUICulture)); Assert.That(_setupContext.CurrentUICulture, Is.EqualTo(CultureInfo.CurrentUICulture)); Assert.That(TestExecutionContext.CurrentContext.CurrentUICulture, Is.EqualTo(CultureInfo.CurrentUICulture)); } #if ASYNC [Test] public async Task CanAccessCurrentCulture_Async() { Assert.That(TestExecutionContext.CurrentContext.CurrentCulture, Is.EqualTo(CultureInfo.CurrentCulture)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.CurrentCulture, Is.EqualTo(CultureInfo.CurrentCulture)); } [Test] public async Task CanAccessCurrentUICulture_Async() { Assert.That(TestExecutionContext.CurrentContext.CurrentUICulture, Is.EqualTo(CultureInfo.CurrentUICulture)); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.CurrentUICulture, Is.EqualTo(CultureInfo.CurrentUICulture)); } #endif [Test] public void SetAndRestoreCurrentCulture() { var context = new TestExecutionContext(_setupContext); try { CultureInfo otherCulture = new CultureInfo(originalCulture.Name == "fr-FR" ? "en-GB" : "fr-FR"); context.CurrentCulture = otherCulture; Assert.AreEqual(otherCulture, CultureInfo.CurrentCulture, "Culture was not set"); Assert.AreEqual(otherCulture, context.CurrentCulture, "Culture not in new context"); Assert.AreEqual(_setupContext.CurrentCulture, originalCulture, "Original context should not change"); } finally { _setupContext.EstablishExecutionEnvironment(); } Assert.AreEqual(CultureInfo.CurrentCulture, originalCulture, "Culture was not restored"); Assert.AreEqual(_setupContext.CurrentCulture, originalCulture, "Culture not in final context"); } [Test] public void SetAndRestoreCurrentUICulture() { var context = new TestExecutionContext(_setupContext); try { CultureInfo otherCulture = new CultureInfo(originalUICulture.Name == "fr-FR" ? "en-GB" : "fr-FR"); context.CurrentUICulture = otherCulture; Assert.AreEqual(otherCulture, CultureInfo.CurrentUICulture, "UICulture was not set"); Assert.AreEqual(otherCulture, context.CurrentUICulture, "UICulture not in new context"); Assert.AreEqual(_setupContext.CurrentUICulture, originalUICulture, "Original context should not change"); } finally { _setupContext.EstablishExecutionEnvironment(); } Assert.AreEqual(CultureInfo.CurrentUICulture, originalUICulture, "UICulture was not restored"); Assert.AreEqual(_setupContext.CurrentUICulture, originalUICulture, "UICulture not in final context"); } #endif #endregion #region CurrentPrincipal #if !NETCOREAPP1_1 [Test] public void CanAccessCurrentPrincipal() { var expectedInstance = Thread.CurrentPrincipal; Assert.That(_fixtureContext.CurrentPrincipal, Is.SameAs(expectedInstance), "Fixture"); Assert.That(_setupContext.CurrentPrincipal, Is.SameAs(expectedInstance), "SetUp"); Assert.That(TestExecutionContext.CurrentContext.CurrentPrincipal, Is.SameAs(expectedInstance), "Test"); } #if ASYNC [Test] public async Task CanAccessCurrentPrincipal_Async() { var expectedInstance = Thread.CurrentPrincipal; Assert.That(TestExecutionContext.CurrentContext.CurrentPrincipal, Is.SameAs(expectedInstance), "Before yield"); await YieldAsync(); Assert.That(TestExecutionContext.CurrentContext.CurrentPrincipal, Is.SameAs(expectedInstance), "After yield"); } #endif [Test] public void SetAndRestoreCurrentPrincipal() { var context = new TestExecutionContext(_setupContext); try { GenericIdentity identity = new GenericIdentity("foo"); context.CurrentPrincipal = new GenericPrincipal(identity, new string[0]); Assert.AreEqual("foo", Thread.CurrentPrincipal.Identity.Name, "Principal was not set"); Assert.AreEqual("foo", context.CurrentPrincipal.Identity.Name, "Principal not in new context"); Assert.AreEqual(_setupContext.CurrentPrincipal, originalPrincipal, "Original context should not change"); } finally { _setupContext.EstablishExecutionEnvironment(); } Assert.AreEqual(Thread.CurrentPrincipal, originalPrincipal, "Principal was not restored"); Assert.AreEqual(_setupContext.CurrentPrincipal, originalPrincipal, "Principal not in final context"); } #endif #endregion #region ValueFormatter [Test] public void SetAndRestoreValueFormatter() { var context = new TestExecutionContext(_setupContext); var originalFormatter = context.CurrentValueFormatter; try { ValueFormatter f = val => "dummy"; context.AddFormatter(next => f); Assert.That(context.CurrentValueFormatter, Is.EqualTo(f)); context.EstablishExecutionEnvironment(); Assert.That(MsgUtils.FormatValue(123), Is.EqualTo("dummy")); } finally { _setupContext.EstablishExecutionEnvironment(); } Assert.That(TestExecutionContext.CurrentContext.CurrentValueFormatter, Is.EqualTo(originalFormatter)); Assert.That(MsgUtils.FormatValue(123), Is.EqualTo("123")); } #endregion #region SingleThreaded [Test] public void SingleThreadedDefaultsToFalse() { Assert.False(new TestExecutionContext().IsSingleThreaded); } [Test] public void SingleThreadedIsInherited() { var parent = new TestExecutionContext(); parent.IsSingleThreaded = true; Assert.True(new TestExecutionContext(parent).IsSingleThreaded); } #endregion #region ExecutionStatus [Test] public void ExecutionStatusIsPushedToHigherContext() { var topContext = new TestExecutionContext(); var bottomContext = new TestExecutionContext(new TestExecutionContext(new TestExecutionContext(topContext))); bottomContext.ExecutionStatus = TestExecutionStatus.StopRequested; Assert.That(topContext.ExecutionStatus, Is.EqualTo(TestExecutionStatus.StopRequested)); } [Test] public void ExecutionStatusIsPulledFromHigherContext() { var topContext = new TestExecutionContext(); var bottomContext = new TestExecutionContext(new TestExecutionContext(new TestExecutionContext(topContext))); topContext.ExecutionStatus = TestExecutionStatus.AbortRequested; Assert.That(bottomContext.ExecutionStatus, Is.EqualTo(TestExecutionStatus.AbortRequested)); } [Test] public void ExecutionStatusIsPromulgatedAcrossBranches() { var topContext = new TestExecutionContext(); var leftContext = new TestExecutionContext(new TestExecutionContext(new TestExecutionContext(topContext))); var rightContext = new TestExecutionContext(new TestExecutionContext(new TestExecutionContext(topContext))); leftContext.ExecutionStatus = TestExecutionStatus.StopRequested; Assert.That(rightContext.ExecutionStatus, Is.EqualTo(TestExecutionStatus.StopRequested)); } #endregion #region Cross-domain Tests #if NET35 || NET40 || NET45 [Test, Platform(Exclude="Mono", Reason="Intermittent failures")] public void CanCreateObjectInAppDomain() { AppDomain domain = AppDomain.CreateDomain( "TestCanCreateAppDomain", AppDomain.CurrentDomain.Evidence, AssemblyHelper.GetDirectoryName(Assembly.GetExecutingAssembly()), null, false); var obj = domain.CreateInstanceAndUnwrap("nunit.framework.tests", "NUnit.Framework.Internal.TestExecutionContextTests+TestClass"); Assert.NotNull(obj); } [Serializable] private class TestClass { } #endif #endregion #region CurrentRepeatCount Tests [Test] public void CanAccessCurrentRepeatCount() { Assert.That(_fixtureContext.CurrentRepeatCount, Is.EqualTo(0), "expected value to default to zero"); _fixtureContext.CurrentRepeatCount++; Assert.That(_fixtureContext.CurrentRepeatCount, Is.EqualTo(1), "expected value to be able to be incremented from the TestExecutionContext"); } #endregion #region Helper Methods #if ASYNC private async Task YieldAsync() { #if NET40 await TaskEx.Yield(); #else await Task.Yield(); #endif } private Task<T[]> WhenAllAsync<T>(params Task<T>[] tasks) { #if NET40 return TaskEx.WhenAll(tasks); #else return Task.WhenAll(tasks); #endif } private async Task<TestExecutionContext> YieldAndReturnContext() { await YieldAsync(); return TestExecutionContext.CurrentContext; } #endif #endregion } #if NET35 || NET40 || NET45 [TestFixture, Platform(Exclude="Mono", Reason="Intermittent failures")] public class TextExecutionContextInAppDomain { private RunsInAppDomain _runsInAppDomain; [SetUp] public void SetUp() { var domain = AppDomain.CreateDomain("TestDomain", null, AppDomain.CurrentDomain.BaseDirectory, AppDomain.CurrentDomain.RelativeSearchPath, false); _runsInAppDomain = domain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, "NUnit.Framework.Internal.RunsInAppDomain") as RunsInAppDomain; Assert.That(_runsInAppDomain, Is.Not.Null); } [Test] [Description("Issue 71 - NUnit swallows console output from AppDomains created within tests")] public void CanWriteToConsoleInAppDomain() { _runsInAppDomain.WriteToConsole(); } [Test] [Description("Issue 210 - TestContext.WriteLine in an AppDomain causes an error")] public void CanWriteToTestContextInAppDomain() { _runsInAppDomain.WriteToTestContext(); } } internal class RunsInAppDomain : MarshalByRefObject { public void WriteToConsole() { Console.WriteLine("RunsInAppDomain.WriteToConsole"); } public void WriteToTestContext() { TestContext.WriteLine("RunsInAppDomain.WriteToTestContext"); } } #endif }
using System.Collections.Generic; using System.Diagnostics; namespace YAF.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. */ /// <summary> /// Access to the Field Info file that describes document fields and whether or /// not they are indexed. Each segment has a separate Field Info file. Objects /// of this class are thread-safe for multiple readers, but only one thread can /// be adding documents at a time, with no other reader or writer threads /// accessing this object. /// </summary> public sealed class FieldInfo { /// <summary> /// Field's name </summary> public string Name { get; private set; } /// <summary> /// Internal field number </summary> public int Number { get; private set; } private bool indexed; private DocValuesType docValueType; // True if any document indexed term vectors private bool storeTermVector; private DocValuesType normType; private bool omitNorms; // omit norms associated with indexed fields private IndexOptions indexOptions; private bool storePayloads; // whether this field stores payloads together with term positions private IDictionary<string, string> attributes; private long dvGen = -1; // the DocValues generation of this field // LUCENENET specific: De-nested the IndexOptions and DocValuesType enums from this class to prevent naming conflicts /// <summary> /// Sole Constructor. /// <para/> /// @lucene.experimental /// </summary> public FieldInfo(string name, bool indexed, int number, bool storeTermVector, bool omitNorms, bool storePayloads, IndexOptions indexOptions, DocValuesType docValues, DocValuesType normsType, IDictionary<string, string> attributes) { this.Name = name; this.indexed = indexed; this.Number = number; this.docValueType = docValues; if (indexed) { this.storeTermVector = storeTermVector; this.storePayloads = storePayloads; this.omitNorms = omitNorms; this.indexOptions = indexOptions; this.normType = !omitNorms ? normsType : DocValuesType.NONE; } // for non-indexed fields, leave defaults else { this.storeTermVector = false; this.storePayloads = false; this.omitNorms = false; this.indexOptions = IndexOptions.NONE; this.normType = DocValuesType.NONE; } this.attributes = attributes; Debug.Assert(CheckConsistency()); } private bool CheckConsistency() { if (!indexed) { Debug.Assert(!storeTermVector); Debug.Assert(!storePayloads); Debug.Assert(!omitNorms); Debug.Assert(normType == DocValuesType.NONE); Debug.Assert(indexOptions == IndexOptions.NONE); } else { Debug.Assert(indexOptions != IndexOptions.NONE); if (omitNorms) { Debug.Assert(normType == DocValuesType.NONE); } // Cannot store payloads unless positions are indexed: Debug.Assert(indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0 || !this.storePayloads); } return true; } internal void Update(IIndexableFieldType ft) { Update(ft.IsIndexed, false, ft.OmitNorms, false, ft.IndexOptions); } // should only be called by FieldInfos#addOrUpdate internal void Update(bool indexed, bool storeTermVector, bool omitNorms, bool storePayloads, IndexOptions indexOptions) { //System.out.println("FI.update field=" + name + " indexed=" + indexed + " omitNorms=" + omitNorms + " this.omitNorms=" + this.omitNorms); if (this.indexed != indexed) { this.indexed = true; // once indexed, always index } if (indexed) // if updated field data is not for indexing, leave the updates out { if (this.storeTermVector != storeTermVector) { this.storeTermVector = true; // once vector, always vector } if (this.storePayloads != storePayloads) { this.storePayloads = true; } if (this.omitNorms != omitNorms) { this.omitNorms = true; // if one require omitNorms at least once, it remains off for life this.normType = DocValuesType.NONE; } if (this.indexOptions != indexOptions) { if (this.indexOptions == IndexOptions.NONE) { this.indexOptions = indexOptions; } else { // downgrade this.indexOptions = this.indexOptions.CompareTo(indexOptions) < 0 ? this.indexOptions : indexOptions; } if (this.indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) < 0) { // cannot store payloads if we don't store positions: this.storePayloads = false; } } } Debug.Assert(CheckConsistency()); } public DocValuesType DocValuesType { internal set { if (docValueType != DocValuesType.NONE && docValueType != value) { throw new System.ArgumentException("cannot change DocValues type from " + docValueType + " to " + value + " for field \"" + Name + "\""); } docValueType = value; Debug.Assert(CheckConsistency()); } get { return docValueType; } } /// <summary> /// Returns <see cref="Index.IndexOptions"/> for the field, or <c>null</c> if the field is not indexed </summary> public IndexOptions IndexOptions { get { return indexOptions; } } /// <summary> /// Returns <c>true</c> if this field has any docValues. /// </summary> public bool HasDocValues { get { return docValueType != DocValuesType.NONE; } } /// <summary> /// Gets or Sets the docValues generation of this field, or -1 if no docValues. </summary> public long DocValuesGen { set { this.dvGen = value; } get { return dvGen; } } /// <summary> /// Returns <see cref="Index.DocValuesType"/> of the norm. This may be <see cref="DocValuesType.NONE"/> if the field has no norms. /// </summary> public DocValuesType NormType { get { return normType; } internal set { if (normType != DocValuesType.NONE && normType != value) { throw new System.ArgumentException("cannot change Norm type from " + normType + " to " + value + " for field \"" + Name + "\""); } normType = value; Debug.Assert(CheckConsistency()); } } internal void SetStoreTermVectors() { storeTermVector = true; Debug.Assert(CheckConsistency()); } internal void SetStorePayloads() { if (indexed && indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0) { storePayloads = true; } Debug.Assert(CheckConsistency()); } /// <summary> /// Returns <c>true</c> if norms are explicitly omitted for this field /// </summary> public bool OmitsNorms { get { return omitNorms; } } /// <summary> /// Returns <c>true</c> if this field actually has any norms. /// </summary> public bool HasNorms { get { return normType != DocValuesType.NONE; } } /// <summary> /// Returns <c>true</c> if this field is indexed. /// </summary> public bool IsIndexed { get { return indexed; } } /// <summary> /// Returns <c>true</c> if any payloads exist for this field. /// </summary> public bool HasPayloads { get { return storePayloads; } } /// <summary> /// Returns <c>true</c> if any term vectors exist for this field. /// </summary> public bool HasVectors { get { return storeTermVector; } } /// <summary> /// Get a codec attribute value, or <c>null</c> if it does not exist /// </summary> public string GetAttribute(string key) { if (attributes == null) { return null; } else { string ret; attributes.TryGetValue(key, out ret); return ret; } } /// <summary> /// Puts a codec attribute value. /// <para/> /// this is a key-value mapping for the field that the codec can use /// to store additional metadata, and will be available to the codec /// when reading the segment via <see cref="GetAttribute(string)"/> /// <para/> /// If a value already exists for the field, it will be replaced with /// the new value. /// </summary> public string PutAttribute(string key, string value) { if (attributes == null) { attributes = new Dictionary<string, string>(); } string ret; // The key was not previously assigned, null will be returned if (!attributes.TryGetValue(key, out ret)) { ret = null; } attributes[key] = value; return ret; } /// <summary> /// Returns internal codec attributes map. May be <c>null</c> if no mappings exist. /// </summary> public IDictionary<string, string> Attributes { get { return attributes; } } } /// <summary> /// Controls how much information is stored in the postings lists. /// <para/> /// @lucene.experimental /// </summary> public enum IndexOptions // LUCENENET specific: de-nested from FieldInfo to prevent naming collisions { // NOTE: order is important here; FieldInfo uses this // order to merge two conflicting IndexOptions (always // "downgrades" by picking the lowest). /// <summary> /// No index options will be used. /// <para/> /// NOTE: This is the same as setting to <c>null</c> in Lucene /// </summary> // LUCENENET specific NONE, /// <summary> /// Only documents are indexed: term frequencies and positions are omitted. /// Phrase and other positional queries on the field will throw an exception, and scoring /// will behave as if any term in the document appears only once. /// </summary> // TODO: maybe rename to just DOCS? DOCS_ONLY, /// <summary> /// Only documents and term frequencies are indexed: positions are omitted. /// this enables normal scoring, except Phrase and other positional queries /// will throw an exception. /// </summary> DOCS_AND_FREQS, /// <summary> /// Indexes documents, frequencies and positions. /// this is a typical default for full-text search: full scoring is enabled /// and positional queries are supported. /// </summary> DOCS_AND_FREQS_AND_POSITIONS, /// <summary> /// Indexes documents, frequencies, positions and offsets. /// Character offsets are encoded alongside the positions. /// </summary> DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS } /// <summary> /// DocValues types. /// Note that DocValues is strongly typed, so a field cannot have different types /// across different documents. /// </summary> public enum DocValuesType // LUCENENET specific: de-nested from FieldInfo to prevent naming collisions { /// <summary> /// No doc values type will be used. /// <para/> /// NOTE: This is the same as setting to <c>null</c> in Lucene /// </summary> // LUCENENET specific NONE, // LUCENENET NOTE: The value of this option is 0, which is the default value for any .NET value type /// <summary> /// A per-document numeric type /// </summary> NUMERIC, /// <summary> /// A per-document <see cref="T:byte[]"/>. Values may be larger than /// 32766 bytes, but different codecs may enforce their own limits. /// </summary> BINARY, /// <summary> /// A pre-sorted <see cref="T:byte[]"/>. Fields with this type only store distinct byte values /// and store an additional offset pointer per document to dereference the shared /// byte[]. The stored byte[] is presorted and allows access via document id, /// ordinal and by-value. Values must be &lt;= 32766 bytes. /// </summary> SORTED, /// <summary> /// A pre-sorted ISet&lt;byte[]&gt;. Fields with this type only store distinct byte values /// and store additional offset pointers per document to dereference the shared /// <see cref="T:byte[]"/>s. The stored <see cref="T:byte[]"/> is presorted and allows access via document id, /// ordinal and by-value. Values must be &lt;= 32766 bytes. /// </summary> SORTED_SET } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using ILCompiler.Compiler.CppCodeGen; using ILCompiler.DependencyAnalysis; using ILCompiler.DependencyAnalysisFramework; using Internal.IL; using Internal.Text; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; namespace ILCompiler.CppCodeGen { internal class CppWriter { private CppCodegenCompilation _compilation; private void SetWellKnownTypeSignatureName(WellKnownType wellKnownType, string mangledSignatureName) { var type = _compilation.TypeSystemContext.GetWellKnownType(wellKnownType); var typeNode = _compilation.NodeFactory.ConstructedTypeSymbol(type); _cppSignatureNames.Add(type, mangledSignatureName); } public CppWriter(CppCodegenCompilation compilation, string outputFilePath) { _compilation = compilation; _out = new StreamWriter(new FileStream(outputFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, 4096, false)); // Unify this list with the one in CppCodegenNodeFactory SetWellKnownTypeSignatureName(WellKnownType.Void, "void"); SetWellKnownTypeSignatureName(WellKnownType.Boolean, "uint8_t"); SetWellKnownTypeSignatureName(WellKnownType.Char, "uint16_t"); SetWellKnownTypeSignatureName(WellKnownType.SByte, "int8_t"); SetWellKnownTypeSignatureName(WellKnownType.Byte, "uint8_t"); SetWellKnownTypeSignatureName(WellKnownType.Int16, "int16_t"); SetWellKnownTypeSignatureName(WellKnownType.UInt16, "uint16_t"); SetWellKnownTypeSignatureName(WellKnownType.Int32, "int32_t"); SetWellKnownTypeSignatureName(WellKnownType.UInt32, "uint32_t"); SetWellKnownTypeSignatureName(WellKnownType.Int64, "int64_t"); SetWellKnownTypeSignatureName(WellKnownType.UInt64, "uint64_t"); SetWellKnownTypeSignatureName(WellKnownType.IntPtr, "intptr_t"); SetWellKnownTypeSignatureName(WellKnownType.UIntPtr, "uintptr_t"); SetWellKnownTypeSignatureName(WellKnownType.Single, "float"); SetWellKnownTypeSignatureName(WellKnownType.Double, "double"); BuildExternCSignatureMap(); } // Mangled type names referenced by the generated code private Dictionary<TypeDesc, string> _mangledNames = new Dictionary<TypeDesc, string>(); private string GetMangledTypeName(TypeDesc type) { string mangledName; if (_mangledNames.TryGetValue(type, out mangledName)) return mangledName; mangledName = _compilation.NameMangler.GetMangledTypeName(type); _mangledNames.Add(type, mangledName); return mangledName; } private Dictionary<TypeDesc, string> _cppSignatureNames = new Dictionary<TypeDesc, string>(); public string GetCppSignatureTypeName(TypeDesc type) { string mangledName; if (_cppSignatureNames.TryGetValue(type, out mangledName)) return mangledName; // TODO: Use friendly names for enums if (type.IsEnum) mangledName = GetCppSignatureTypeName(type.UnderlyingType); else mangledName = GetCppTypeName(type); if (!type.IsValueType && !type.IsByRef && !type.IsPointer) mangledName += "*"; _cppSignatureNames.Add(type, mangledName); return mangledName; } // extern "C" methods are sometimes referenced via different signatures. // _externCSignatureMap contains the canonical signature of the extern "C" import. References // via other signatures are required to use casts. private Dictionary<string, MethodSignature> _externCSignatureMap = new Dictionary<string, MethodSignature>(); private void BuildExternCSignatureMap() { foreach (var nodeAlias in _compilation.NodeFactory.NodeAliases) { var methodNode = (CppMethodCodeNode)nodeAlias.Key; _externCSignatureMap.Add(nodeAlias.Value, methodNode.Method.Signature); } } private IEnumerable<string> GetParameterNamesForMethod(MethodDesc method) { // TODO: The uses of this method need revision. The right way to get to this info is from // a MethodIL. For declarations, we don't need names. method = method.GetTypicalMethodDefinition(); var ecmaMethod = method as EcmaMethod; if (ecmaMethod != null && ecmaMethod.Module.PdbReader != null) { return (new EcmaMethodDebugInformation(ecmaMethod)).GetParameterNames(); } return null; } public void AppendCppMethodDeclaration(CppGenerationBuffer sb, MethodDesc method, bool implementation, string externalMethodName = null, MethodSignature methodSignature = null, string cppMethodName = null) { if (methodSignature == null) methodSignature = method.Signature; if (externalMethodName != null) { sb.Append("extern \"C\" "); } else { if (!implementation) { sb.Append("static "); } } sb.Append(GetCppSignatureTypeName(methodSignature.ReturnType)); sb.Append(" "); if (externalMethodName != null) { sb.Append(externalMethodName); } else { if (implementation) { sb.Append(GetCppMethodDeclarationName(method.OwningType, cppMethodName ?? GetCppMethodName(method))); } else { sb.Append(cppMethodName ?? GetCppMethodName(method)); } } sb.Append("("); bool hasThis = !methodSignature.IsStatic; int argCount = methodSignature.Length; if (hasThis) argCount++; List<string> parameterNames = null; if (method != null) { IEnumerable<string> parameters = GetParameterNamesForMethod(method); if (parameters != null) { parameterNames = new List<string>(parameters); if (parameterNames.Count != 0) { System.Diagnostics.Debug.Assert(parameterNames.Count == argCount); } else { parameterNames = null; } } } for (int i = 0; i < argCount; i++) { if (hasThis) { if (i == 0) { var thisType = method.OwningType; if (thisType.IsValueType) thisType = thisType.MakeByRefType(); sb.Append(GetCppSignatureTypeName(thisType)); } else { sb.Append(GetCppSignatureTypeName(methodSignature[i - 1])); } } else { sb.Append(GetCppSignatureTypeName(methodSignature[i])); } if (implementation) { sb.Append(" "); if (parameterNames != null) { sb.Append(SanitizeCppVarName(parameterNames[i])); } else { sb.Append("_a"); sb.Append(i.ToStringInvariant()); } } if (i != argCount - 1) sb.Append(", "); } sb.Append(")"); if (!implementation) sb.Append(";"); } public void AppendCppMethodCallParamList(CppGenerationBuffer sb, MethodDesc method, bool unbox = false) { var methodSignature = method.Signature; bool hasThis = !methodSignature.IsStatic; int argCount = methodSignature.Length; if (hasThis) argCount++; List<string> parameterNames = null; IEnumerable<string> parameters = GetParameterNamesForMethod(method); if (parameters != null) { parameterNames = new List<string>(parameters); if (parameterNames.Count != 0) { System.Diagnostics.Debug.Assert(parameterNames.Count == argCount); } else { parameterNames = null; } } for (int i = 0; i < argCount; i++) { if(i == 0 && unbox) { // Unboxing stubs only valid for non-static methods on value types System.Diagnostics.Debug.Assert(hasThis); System.Diagnostics.Debug.Assert(method.OwningType.IsValueType); var thisType = method.OwningType.MakeByRefType(); sb.Append("("); sb.Append(GetCppSignatureTypeName(thisType)); sb.Append(")((uint8_t*)("); } if (parameterNames != null) { sb.Append(SanitizeCppVarName(parameterNames[i])); } else { sb.Append("_a"); sb.Append(i.ToStringInvariant()); } if (i == 0 && hasThis && unbox) { sb.Append(")+sizeof(void*))"); } if (i != argCount - 1) sb.Append(", "); } } public string GetCppTypeName(TypeDesc type) { switch (type.Category) { case TypeFlags.ByRef: case TypeFlags.Pointer: return GetCppSignatureTypeName(((ParameterizedType)type).ParameterType) + "*"; default: return GetMangledTypeName(type); } } /// <summary> /// Compute a proper declaration for <param name="methodName"/> defined in <param name="owningType"/>. /// Usually the C++ name for a type is prefixed by "::" but this is not a valid way to declare a method, /// so we need to strip it if present. /// </summary> /// <param name="owningType">Type where <param name="methodName"/> belongs.</param> /// <param name="methodName">Name of method from <param name="owningType"/>.</param> /// <returns>C++ declaration name for <param name="methodName"/>.</returns> public string GetCppMethodDeclarationName(TypeDesc owningType, string methodName, bool isDeclaration = true) { var s = GetMangledTypeName(owningType); if (isDeclaration && s.StartsWith("::")) { // For a Method declaration we do not need the starting :: s = s.Substring(2, s.Length - 2); } return string.Concat(s, "::", methodName); } public string GetCppMethodName(MethodDesc method) { return _compilation.NameMangler.GetMangledMethodName(method).ToString(); } public string GetCppFieldName(FieldDesc field) { return _compilation.NameMangler.GetMangledFieldName(field).ToString(); } public string GetCppStaticFieldName(FieldDesc field) { TypeDesc type = field.OwningType; string typeName = GetCppTypeName(type); return typeName.Replace("::", "__") + "__" + _compilation.NameMangler.GetMangledFieldName(field); } public string SanitizeCppVarName(string varName) { // TODO: name mangling robustness if (varName == "errno" || varName == "environ" || varName == "template" || varName == "typename") // some names collide with CRT headers return "_" + varName + "_"; return _compilation.NameMangler.SanitizeName(varName); } private void CompileExternMethod(CppMethodCodeNode methodCodeNodeNeedingCode, string importName) { MethodDesc method = methodCodeNodeNeedingCode.Method; MethodSignature methodSignature = method.Signature; bool slotCastRequired = false; MethodSignature externCSignature; if (_externCSignatureMap.TryGetValue(importName, out externCSignature)) { slotCastRequired = !externCSignature.Equals(methodSignature); } else { _externCSignatureMap.Add(importName, methodSignature); externCSignature = methodSignature; } var sb = new CppGenerationBuffer(); sb.AppendLine(); AppendCppMethodDeclaration(sb, method, true); sb.AppendLine(); sb.Append("{"); sb.Indent(); if (slotCastRequired) { AppendSlotTypeDef(sb, method); } sb.AppendLine(); if (!method.Signature.ReturnType.IsVoid) { sb.Append("return "); } if (slotCastRequired) sb.Append("((__slot__" + GetCppMethodName(method) + ")"); sb.Append("::"); sb.Append(importName); if (slotCastRequired) sb.Append(")"); sb.Append("("); AppendCppMethodCallParamList(sb, method); sb.Append(");"); sb.Exdent(); sb.AppendLine(); sb.Append("}"); methodCodeNodeNeedingCode.SetCode(sb.ToString(), Array.Empty<Object>()); } public void CompileMethod(CppMethodCodeNode methodCodeNodeNeedingCode) { MethodDesc method = methodCodeNodeNeedingCode.Method; _compilation.Logger.Writer.WriteLine("Compiling " + method.ToString()); if (method.HasCustomAttribute("System.Runtime", "RuntimeImportAttribute")) { CompileExternMethod(methodCodeNodeNeedingCode, ((EcmaMethod)method).GetRuntimeImportName()); return; } if (method.IsRawPInvoke()) { CompileExternMethod(methodCodeNodeNeedingCode, method.GetPInvokeMethodMetadata().Name ?? method.Name); return; } var methodIL = _compilation.GetMethodIL(method); if (methodIL == null) return; try { // TODO: hacky special-case if (method.Name == "_ecvt_s") throw new NotImplementedException(); var ilImporter = new ILImporter(_compilation, this, method, methodIL); CompilerTypeSystemContext typeSystemContext = _compilation.TypeSystemContext; MethodDebugInformation debugInfo = _compilation.GetDebugInfo(methodIL); if (!_compilation.Options.HasOption(CppCodegenConfigProvider.NoLineNumbersString)) { IEnumerable<ILSequencePoint> sequencePoints = debugInfo.GetSequencePoints(); if (sequencePoints != null) ilImporter.SetSequencePoints(sequencePoints); } IEnumerable<ILLocalVariable> localVariables = debugInfo.GetLocalVariables(); if (localVariables != null) ilImporter.SetLocalVariables(localVariables); IEnumerable<string> parameters = GetParameterNamesForMethod(method); if (parameters != null) ilImporter.SetParameterNames(parameters); ilImporter.Compile(methodCodeNodeNeedingCode); } catch (Exception e) { _compilation.Logger.Writer.WriteLine(e.Message + " (" + method + ")"); var sb = new CppGenerationBuffer(); sb.AppendLine(); AppendCppMethodDeclaration(sb, method, true); sb.AppendLine(); sb.Append("{"); sb.Indent(); sb.AppendLine(); sb.Append("throw 0xC000C000;"); sb.Exdent(); sb.AppendLine(); sb.Append("}"); methodCodeNodeNeedingCode.SetCode(sb.ToString(), Array.Empty<Object>()); } } private TextWriter Out { get { return _out; } } private StreamWriter _out; private Dictionary<TypeDesc, List<MethodDesc>> _methodLists; private CppGenerationBuffer _statics; private CppGenerationBuffer _gcStatics; private CppGenerationBuffer _threadStatics; private CppGenerationBuffer _gcThreadStatics; // Base classes and valuetypes has to be emitted before they are used. private HashSet<TypeDesc> _emittedTypes; private TypeDesc GetFieldTypeOrPlaceholder(FieldDesc field) { try { return field.FieldType; } catch { // TODO: For now, catch errors due to missing dependencies return _compilation.TypeSystemContext.GetWellKnownType(WellKnownType.Boolean); } } private void OutputTypeFields(CppGenerationBuffer sb, TypeDesc t) { bool explicitLayout = false; ClassLayoutMetadata classLayoutMetadata = default(ClassLayoutMetadata); if (t.IsValueType) { MetadataType metadataType = (MetadataType)t; if (metadataType.IsExplicitLayout) { explicitLayout = true; classLayoutMetadata = metadataType.GetClassLayout(); } } int instanceFieldIndex = 0; if (explicitLayout) { sb.AppendLine(); sb.Append("union {"); sb.Indent(); } foreach (var field in t.GetFields()) { if (field.IsStatic) { if (field.IsLiteral) continue; TypeDesc fieldType = GetFieldTypeOrPlaceholder(field); CppGenerationBuffer builder; if (!fieldType.IsValueType) { builder = _gcStatics; } else { // TODO: Valuetype statics with GC references builder = _statics; } builder.AppendLine(); builder.Append(GetCppSignatureTypeName(fieldType)); builder.Append(" "); builder.Append(GetCppStaticFieldName(field) + ";"); } else { if (explicitLayout) { sb.AppendLine(); sb.Append("struct {"); sb.Indent(); int offset = classLayoutMetadata.Offsets[instanceFieldIndex].Offset.AsInt; if (offset > 0) { sb.AppendLine(); sb.Append("char __pad" + instanceFieldIndex + "[" + offset + "];"); } } sb.AppendLine(); sb.Append(GetCppSignatureTypeName(GetFieldTypeOrPlaceholder(field)) + " " + GetCppFieldName(field) + ";"); if (explicitLayout) { sb.Exdent(); sb.AppendLine(); sb.Append("};"); } instanceFieldIndex++; } } if (explicitLayout) { if (classLayoutMetadata.Size > 0) { sb.AppendLine(); sb.Append("struct { char __sizePadding[" + classLayoutMetadata.Size + "]; };"); } sb.Exdent(); sb.AppendLine(); sb.Append("};"); } } private void AppendSlotTypeDef(CppGenerationBuffer sb, MethodDesc method) { MethodSignature methodSignature = method.Signature; TypeDesc thisArgument = null; if (!methodSignature.IsStatic) thisArgument = method.OwningType; AppendSignatureTypeDef(sb, "__slot__" + GetCppMethodName(method), methodSignature, thisArgument); } internal void AppendSignatureTypeDef(CppGenerationBuffer sb, string name, MethodSignature methodSignature, TypeDesc thisArgument) { sb.AppendLine(); sb.Append("typedef "); sb.Append(GetCppSignatureTypeName(methodSignature.ReturnType)); sb.Append("(*"); sb.Append(name); sb.Append(")("); int argCount = methodSignature.Length; if (thisArgument != null) argCount++; for (int i = 0; i < argCount; i++) { if (thisArgument != null) { if (i == 0) { sb.Append(GetCppSignatureTypeName(thisArgument)); } else { sb.Append(GetCppSignatureTypeName(methodSignature[i - 1])); } } else { sb.Append(GetCppSignatureTypeName(methodSignature[i])); } if (i != argCount - 1) sb.Append(", "); } sb.Append(");"); } private String GetCodeForDelegate(TypeDesc delegateType) { var sb = new CppGenerationBuffer(); MethodDesc method = delegateType.GetKnownMethod("Invoke", null); AppendSlotTypeDef(sb, method); sb.AppendLine(); sb.Append("static __slot__"); sb.Append(GetCppMethodName(method)); sb.Append(" __invoke__"); sb.Append(GetCppMethodName(method)); sb.Append("(void * pThis)"); sb.AppendLine(); sb.Append("{"); sb.Indent(); sb.AppendLine(); sb.Append("return (__slot__"); sb.Append(GetCppMethodName(method)); sb.Append(")((("); sb.Append(GetCppSignatureTypeName(_compilation.TypeSystemContext.GetWellKnownType(WellKnownType.MulticastDelegate))); sb.Append(")pThis)->m_functionPointer);"); sb.Exdent(); sb.AppendLine(); sb.Append("};"); return sb.ToString(); } private String GetCodeForVirtualMethod(MethodDesc method, int slot) { var sb = new CppGenerationBuffer(); sb.Indent(); if (method.OwningType.IsInterface) { AppendSlotTypeDef(sb, method); sb.Indent(); sb.AppendLine(); sb.Append("static uint16_t"); sb.Append(" __getslot__"); sb.Append(GetCppMethodName(method)); sb.Append("(void * pThis)"); sb.AppendLine(); sb.Append("{"); sb.Indent(); sb.AppendLine(); sb.Append("return "); sb.Append(slot); sb.Append(";"); sb.AppendLine(); } else { AppendSlotTypeDef(sb, method); sb.Indent(); sb.AppendLine(); sb.Append("static __slot__"); sb.Append(GetCppMethodName(method)); sb.Append(" __getslot__"); sb.Append(GetCppMethodName(method)); sb.Append("(void * pThis)"); sb.AppendLine(); sb.Append("{"); sb.Indent(); sb.AppendLine(); sb.Append(" return (__slot__"); sb.Append(GetCppMethodName(method)); sb.Append(")*((void **)(*((RawEEType **)pThis) + 1) + "); sb.Append(slot.ToStringInvariant()); sb.Append(");"); } sb.Exdent(); sb.AppendLine(); sb.Append("};"); sb.Exdent(); return sb.ToString(); } private String GetCodeForObjectNode(ObjectNode node, NodeFactory factory) { // virtual slots var nodeData = node.GetData(factory, false); CppGenerationBuffer nodeCode = new CppGenerationBuffer(); /* Create list of byte data. Used to divide contents between reloc and byte data * First val - isReloc * Second val - size of byte data if first value of tuple is false */ List<NodeDataSection> nodeDataSections = new List<NodeDataSection>(); byte[] actualData = new byte[nodeData.Data.Length]; Relocation[] relocs = nodeData.Relocs; int nextRelocOffset = -1; int nextRelocIndex = -1; int lastByteIndex = 0; if (relocs.Length > 0) { nextRelocOffset = relocs[0].Offset; nextRelocIndex = 0; } int i = 0; int offset = 0; CppGenerationBuffer nodeDataDecl = new CppGenerationBuffer(); if (node is ISymbolDefinitionNode) { offset = (node as ISymbolDefinitionNode).Offset; i = offset; lastByteIndex = offset; } while (i < nodeData.Data.Length) { if (i == nextRelocOffset) { Relocation reloc = relocs[nextRelocIndex]; int size = _compilation.TypeSystemContext.Target.PointerSize; // Make sure we've gotten the correct size for the reloc System.Diagnostics.Debug.Assert(reloc.RelocType == (size == 8 ? RelocType.IMAGE_REL_BASED_DIR64 : RelocType.IMAGE_REL_BASED_HIGHLOW)); // Update nextRelocIndex/Offset if (++nextRelocIndex < relocs.Length) { nextRelocOffset = relocs[nextRelocIndex].Offset; } nodeDataSections.Add(new NodeDataSection(NodeDataSectionType.Relocation, size)); i += size; lastByteIndex = i; } else { i++; if (i + 1 == nextRelocOffset || i + 1 == nodeData.Data.Length) { nodeDataSections.Add(new NodeDataSection(NodeDataSectionType.ByteData, (i + 1) - lastByteIndex)); } } } string pointerType = node is EETypeNode ? "MethodTable * " : "void* "; nodeCode.Append(pointerType); if (node is EETypeNode) { nodeCode.Append(GetCppMethodDeclarationName((node as EETypeNode).Type, "__getMethodTable")); } else { string mangledName = ((ISymbolNode)node).GetMangledName(factory.NameMangler); // Rename generic composition and optional fields nodes to avoid name clash with types bool shouldReplaceNamespaceQualifier = node is GenericCompositionNode || node is EETypeOptionalFieldsNode; nodeCode.Append(shouldReplaceNamespaceQualifier ? mangledName.Replace("::", "_") : mangledName); } nodeCode.Append("()"); nodeCode.AppendLine(); nodeCode.Append("{"); nodeCode.Indent(); nodeCode.AppendLine(); nodeCode.Append("static struct {"); nodeCode.AppendLine(); nodeCode.Append(GetCodeForNodeStruct(nodeDataSections, node)); nodeCode.AppendLine(); nodeCode.Append("} mt = {"); nodeCode.Append(GetCodeForNodeData(nodeDataSections, relocs, nodeData.Data, node, offset, factory)); nodeCode.Append("};"); nodeCode.AppendLine(); nodeCode.Append("return ( "); nodeCode.Append(pointerType); nodeCode.Append(")&mt;"); nodeCode.Exdent(); nodeCode.AppendLine(); nodeCode.Append("}"); nodeCode.AppendLine(); return nodeCode.ToString(); } private String GetCodeForNodeData(List<NodeDataSection> nodeDataSections, Relocation[] relocs, byte[] byteData, DependencyNode node, int offset, NodeFactory factory) { CppGenerationBuffer nodeDataDecl = new CppGenerationBuffer(); int relocCounter = 0; int divisionStartIndex = offset; nodeDataDecl.Indent(); nodeDataDecl.Indent(); nodeDataDecl.AppendLine(); for (int i = 0; i < nodeDataSections.Count; i++) { if (nodeDataSections[i].SectionType == NodeDataSectionType.Relocation) { Relocation reloc = relocs[relocCounter]; nodeDataDecl.Append(GetCodeForReloc(reloc, node, factory)); nodeDataDecl.Append(","); relocCounter++; } else { AppendFormattedByteArray(nodeDataDecl, byteData, divisionStartIndex, divisionStartIndex + nodeDataSections[i].SectionSize); nodeDataDecl.Append(","); } divisionStartIndex += nodeDataSections[i].SectionSize; nodeDataDecl.AppendLine(); } return nodeDataDecl.ToString(); } private String GetCodeForReloc(Relocation reloc, DependencyNode node, NodeFactory factory) { CppGenerationBuffer relocCode = new CppGenerationBuffer(); if (reloc.Target is CppMethodCodeNode) { var method = reloc.Target as CppMethodCodeNode; relocCode.Append("(void*)&"); relocCode.Append(GetCppMethodDeclarationName(method.Method.OwningType, GetCppMethodName(method.Method), false)); } else if (reloc.Target is EETypeNode && node is EETypeNode) { relocCode.Append(GetCppMethodDeclarationName((reloc.Target as EETypeNode).Type, "__getMethodTable", false)); relocCode.Append("()"); } // Node is either an non-emitted type or a generic composition - both are ignored for CPP codegen else if ((reloc.Target is TypeManagerIndirectionNode || reloc.Target is InterfaceDispatchMapNode || reloc.Target is EETypeOptionalFieldsNode || reloc.Target is GenericCompositionNode) && !(reloc.Target as ObjectNode).ShouldSkipEmittingObjectNode(factory)) { string mangledTargetName = reloc.Target.GetMangledName(factory.NameMangler); bool shouldReplaceNamespaceQualifier = reloc.Target is GenericCompositionNode || reloc.Target is EETypeOptionalFieldsNode; relocCode.Append(shouldReplaceNamespaceQualifier ? mangledTargetName.Replace("::", "_") : mangledTargetName); relocCode.Append("()"); } else if (reloc.Target is ObjectAndOffsetSymbolNode && (reloc.Target as ObjectAndOffsetSymbolNode).Target is ArrayOfEmbeddedPointersNode<InterfaceDispatchMapNode>) { relocCode.Append("dispatchMapModule"); } else if(reloc.Target is UnboxingStubNode) { var method = reloc.Target as UnboxingStubNode; relocCode.Append("(void*)&"); relocCode.Append(GetCppMethodDeclarationName(method.Method.OwningType, UnboxingStubNode.GetMangledName(factory.NameMangler, method.Method), false)); } else { relocCode.Append("NULL"); } return relocCode.ToString(); } private String GetCodeForNodeStruct(List<NodeDataSection> nodeDataDivs, DependencyNode node) { CppGenerationBuffer nodeStructDecl = new CppGenerationBuffer(); int relocCounter = 1; int i = 0; nodeStructDecl.Indent(); for (i = 0; i < nodeDataDivs.Count; i++) { NodeDataSection section = nodeDataDivs[i]; if (section.SectionType == NodeDataSectionType.Relocation) { nodeStructDecl.Append("void* reloc"); nodeStructDecl.Append(relocCounter); nodeStructDecl.Append(";"); relocCounter++; } else { nodeStructDecl.Append("unsigned char data"); nodeStructDecl.Append((i + 1) - relocCounter); nodeStructDecl.Append("["); nodeStructDecl.Append(section.SectionSize); nodeStructDecl.Append("];"); } nodeStructDecl.AppendLine(); } nodeStructDecl.Exdent(); return nodeStructDecl.ToString(); } private static void AppendFormattedByteArray(CppGenerationBuffer sb, byte[] array, int startIndex, int endIndex) { sb.Append("{"); sb.Append("0x"); sb.Append(BitConverter.ToString(array, startIndex, endIndex - startIndex).Replace("-", ",0x")); sb.Append("}"); } private void BuildMethodLists(IEnumerable<DependencyNode> nodes) { _methodLists = new Dictionary<TypeDesc, List<MethodDesc>>(); foreach (var node in nodes) { if (node is CppMethodCodeNode) { CppMethodCodeNode methodCodeNode = (CppMethodCodeNode)node; var method = methodCodeNode.Method; var type = method.OwningType; List<MethodDesc> methodList; if (!_methodLists.TryGetValue(type, out methodList)) { GetCppSignatureTypeName(type); methodList = new List<MethodDesc>(); _methodLists.Add(type, methodList); } methodList.Add(method); } else if (node is IEETypeNode) { IEETypeNode eeTypeNode = (IEETypeNode)node; if (eeTypeNode.Type.IsGenericDefinition) { // TODO: CppWriter can't handle generic type definition EETypes } else GetCppSignatureTypeName(eeTypeNode.Type); } } } /// <summary> /// Output C++ code via a given dependency graph /// </summary> /// <param name="nodes">A set of dependency nodes</param> /// <param name="entrypoint">Code entrypoint</param> /// <param name="factory">Associated NodeFactory instance</param> /// <param name="definitions">Text buffer in which the type and method definitions will be written</param> /// <param name="implementation">Text buffer in which the method implementations will be written</param> public void OutputNodes(IEnumerable<DependencyNode> nodes, NodeFactory factory) { CppGenerationBuffer dispatchPointers = new CppGenerationBuffer(); CppGenerationBuffer forwardDefinitions = new CppGenerationBuffer(); CppGenerationBuffer typeDefinitions = new CppGenerationBuffer(); CppGenerationBuffer methodTables = new CppGenerationBuffer(); CppGenerationBuffer additionalNodes = new CppGenerationBuffer(); DependencyNodeIterator nodeIterator = new DependencyNodeIterator(nodes, factory); // Number of InterfaceDispatchMapNodes needs to be declared explicitly for Ubuntu and OSX int dispatchMapCount = 0; dispatchPointers.AppendLine(); dispatchPointers.Indent(); //RTR header needs to be declared after all modules have already been output string rtrHeader = string.Empty; // Iterate through nodes foreach (var node in nodeIterator.GetNodes()) { if (node is EETypeNode) OutputTypeNode(node as EETypeNode, factory, typeDefinitions, methodTables); else if ((node is EETypeOptionalFieldsNode || node is TypeManagerIndirectionNode || node is GenericCompositionNode) && !(node as ObjectNode).ShouldSkipEmittingObjectNode(factory)) additionalNodes.Append(GetCodeForObjectNode(node as ObjectNode, factory)); else if (node is InterfaceDispatchMapNode) { dispatchPointers.Append("(void *)"); dispatchPointers.Append(((ISymbolNode)node).GetMangledName(factory.NameMangler)); dispatchPointers.Append("(),"); dispatchPointers.AppendLine(); dispatchMapCount++; additionalNodes.Append(GetCodeForObjectNode(node as ObjectNode, factory)); } else if (node is ReadyToRunHeaderNode) rtrHeader = GetCodeForReadyToRunHeader(node as ReadyToRunHeaderNode, factory); } dispatchPointers.AppendLine(); dispatchPointers.Exdent(); WriteForwardDefinitions(); Out.Write(typeDefinitions.ToString()); Out.Write(additionalNodes.ToString()); Out.Write(methodTables.ToString()); // Emit pointers to dispatch map nodes, to be used in interface dispatch Out.Write("void * dispatchMapModule["); Out.Write(dispatchMapCount); Out.Write("] = {"); Out.Write(dispatchPointers.ToString()); Out.Write("};"); Out.Write(rtrHeader); } /// <summary> /// Output C++ code for a given codeNode /// </summary> /// <param name="methodCodeNode">The code node to be output</param> /// <param name="methodImplementations">The buffer in which to write out the C++ code</param> private void OutputMethodNode(CppMethodCodeNode methodCodeNode) { Out.WriteLine(); Out.Write(methodCodeNode.CppCode); var alternateName = _compilation.NodeFactory.GetSymbolAlternateName(methodCodeNode); if (alternateName != null) { CppGenerationBuffer sb = new CppGenerationBuffer(); sb.AppendLine(); AppendCppMethodDeclaration(sb, methodCodeNode.Method, true, alternateName); sb.AppendLine(); sb.Append("{"); sb.Indent(); sb.AppendLine(); if (!methodCodeNode.Method.Signature.ReturnType.IsVoid) { sb.Append("return "); } sb.Append(GetCppMethodDeclarationName(methodCodeNode.Method.OwningType, GetCppMethodName(methodCodeNode.Method))); sb.Append("("); AppendCppMethodCallParamList(sb, methodCodeNode.Method); sb.Append(");"); sb.Exdent(); sb.AppendLine(); sb.Append("}"); Out.Write(sb.ToString()); } } /// <summary> /// Write forward definitions for all mangled type names referenced by the generated C++ code. This set is tracked separately from /// the types that need EEType because of the type mangled names are often needed to just get the code to compile but type node is not /// actually required for it. /// </summary> private void WriteForwardDefinitions() { CppGenerationBuffer forwardDefinitions = new CppGenerationBuffer(); string[] mangledNames = _mangledNames.Values.ToArray(); Array.Sort(mangledNames); foreach (string mangledName in mangledNames) { int nesting = 0; int current = 0; for (; ; ) { int sep = mangledName.IndexOf("::", current); if (sep < 0) break; if (sep != 0) { // Case of a name not starting with :: forwardDefinitions.Append("namespace " + mangledName.Substring(current, sep - current) + " { "); nesting++; } current = sep + 2; } forwardDefinitions.Append("class " + mangledName.Substring(current) + ";"); while (nesting > 0) { forwardDefinitions.Append(" }"); nesting--; } forwardDefinitions.AppendLine(); } Out.Write(forwardDefinitions.ToString()); } private void OutputTypeNode(IEETypeNode typeNode, NodeFactory factory, CppGenerationBuffer typeDefinitions, CppGenerationBuffer methodTable) { if (_emittedTypes == null) { _emittedTypes = new HashSet<TypeDesc>(); } TypeDesc nodeType = typeNode.Type; if (_emittedTypes.Contains(nodeType)) return; _emittedTypes.Add(nodeType); // Create Namespaces string mangledName = GetMangledTypeName(nodeType); int nesting = 0; int current = 0; for (;;) { int sep = mangledName.IndexOf("::", current); if (sep < 0) break; if (sep != 0) { // Case of a name not starting with :: typeDefinitions.Append("namespace " + mangledName.Substring(current, sep - current) + " { "); typeDefinitions.Indent(); nesting++; } current = sep + 2; } // type definition typeDefinitions.Append("class " + mangledName.Substring(current)); if (!nodeType.IsValueType) { // Don't emit inheritance if base type has not been marked for emission if (nodeType.BaseType != null && _emittedTypes.Contains(nodeType.BaseType)) { typeDefinitions.Append(" : public " + GetCppTypeName(nodeType.BaseType)); } } typeDefinitions.Append(" {"); typeDefinitions.AppendLine(); typeDefinitions.Append("public:"); typeDefinitions.Indent(); if (typeNode.Marked) { typeDefinitions.AppendLine(); typeDefinitions.Append("static MethodTable * __getMethodTable();"); } if (nodeType.IsDefType && !nodeType.IsGenericDefinition) { OutputTypeFields(typeDefinitions, nodeType); } if (typeNode is ConstructedEETypeNode) { IReadOnlyList<MethodDesc> virtualSlots = _compilation.NodeFactory.VTable(nodeType.GetClosestDefType()).Slots; int baseSlots = 0; var baseType = nodeType.BaseType; while (baseType != null) { IReadOnlyList<MethodDesc> baseVirtualSlots = _compilation.NodeFactory.VTable(baseType).Slots; if (baseVirtualSlots != null) baseSlots += baseVirtualSlots.Count; baseType = baseType.BaseType; } for (int slot = 0; slot < virtualSlots.Count; slot++) { MethodDesc virtualMethod = virtualSlots[slot]; typeDefinitions.AppendLine(); typeDefinitions.Append(GetCodeForVirtualMethod(virtualMethod, baseSlots + slot)); } if (nodeType.IsDelegate) { typeDefinitions.AppendLine(); typeDefinitions.Append(GetCodeForDelegate(nodeType)); } } if (nodeType.HasStaticConstructor) { _statics.AppendLine(); _statics.Append("bool __cctor_" + GetCppTypeName(nodeType).Replace("::", "__") + ";"); } List<MethodDesc> methodList; if (_methodLists.TryGetValue(nodeType, out methodList)) { foreach (var m in methodList) { typeDefinitions.AppendLine(); AppendCppMethodDeclaration(typeDefinitions, m, false); typeDefinitions.AppendLine(); AppendCppMethodDeclaration(typeDefinitions, m, false, null, null, UnboxingStubNode.GetMangledName(factory.NameMangler, m)); } } typeDefinitions.AppendEmptyLine(); typeDefinitions.Append("};"); typeDefinitions.AppendEmptyLine(); typeDefinitions.Exdent(); while (nesting > 0) { typeDefinitions.Append("};"); typeDefinitions.Exdent(); nesting--; } typeDefinitions.AppendEmptyLine(); // declare method table if (typeNode.Marked) { methodTable.Append(GetCodeForObjectNode(typeNode as ObjectNode, factory)); } methodTable.AppendEmptyLine(); } private String GetCodeForReadyToRunHeader(ReadyToRunHeaderNode headerNode, NodeFactory factory) { CppGenerationBuffer rtrHeader = new CppGenerationBuffer(); int pointerSize = _compilation.TypeSystemContext.Target.PointerSize; rtrHeader.Append(GetCodeForObjectNode(headerNode, factory)); rtrHeader.AppendLine(); rtrHeader.Append("void* RtRHeaderWrapper() {"); rtrHeader.Indent(); rtrHeader.AppendLine(); rtrHeader.Append("static struct {"); rtrHeader.AppendLine(); if (pointerSize == 8) rtrHeader.Append("unsigned char leftPadding[8];"); else rtrHeader.Append("unsigned char leftPadding[4];"); rtrHeader.AppendLine(); rtrHeader.Append("void* rtrHeader;"); rtrHeader.AppendLine(); if (pointerSize == 8) rtrHeader.Append("unsigned char rightPadding[8];"); else rtrHeader.Append("unsigned char rightPadding[4];"); rtrHeader.AppendLine(); rtrHeader.Append("} rtrHeaderWrapper = {"); rtrHeader.Indent(); rtrHeader.AppendLine(); if (pointerSize == 8) rtrHeader.Append("{ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },"); else rtrHeader.Append("{ 0x00,0x00,0x00,0x00 },"); rtrHeader.AppendLine(); rtrHeader.Append("(void*)"); rtrHeader.Append(headerNode.GetMangledName(factory.NameMangler)); rtrHeader.Append("(),"); rtrHeader.AppendLine(); if (pointerSize == 8) rtrHeader.Append("{ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }"); else rtrHeader.Append("{ 0x00,0x00,0x00,0x00 },"); rtrHeader.AppendLine(); rtrHeader.Append("};"); rtrHeader.Exdent(); rtrHeader.AppendLine(); rtrHeader.Append("return (void *)&rtrHeaderWrapper;"); rtrHeader.Exdent(); rtrHeader.AppendLine(); rtrHeader.Append("}"); rtrHeader.AppendLine(); return rtrHeader.ToString(); } private void OutputExternCSignatures() { var sb = new CppGenerationBuffer(); foreach (var externC in _externCSignatureMap) { string importName = externC.Key; // TODO: hacky special-case if (importName != "memmove" && importName != "malloc") // some methods are already declared by the CRT headers { sb.AppendLine(); AppendCppMethodDeclaration(sb, null, false, importName, externC.Value); } } Out.Write(sb.ToString()); } /// <summary> /// Output C++ code for a given unboxingStubNode /// </summary> /// <param name="unboxingStubNode">The unboxing stub node to be output</param> /// <param name="methodImplementations">The buffer in which to write out the C++ code</param> private void OutputUnboxingStubNode(UnboxingStubNode unboxingStubNode) { Out.WriteLine(); CppGenerationBuffer sb = new CppGenerationBuffer(); sb.AppendLine(); AppendCppMethodDeclaration(sb, unboxingStubNode.Method, true, null, null, UnboxingStubNode.GetMangledName(_compilation.NameMangler, unboxingStubNode.Method)); sb.AppendLine(); sb.Append("{"); sb.Indent(); sb.AppendLine(); if (!unboxingStubNode.Method.Signature.ReturnType.IsVoid) { sb.Append("return "); } sb.Append(GetCppMethodDeclarationName(unboxingStubNode.Method.OwningType, GetCppMethodName(unboxingStubNode.Method))); sb.Append("("); AppendCppMethodCallParamList(sb, unboxingStubNode.Method, true); sb.Append(");"); sb.Exdent(); sb.AppendLine(); sb.Append("}"); Out.Write(sb.ToString()); } public void OutputCode(IEnumerable<DependencyNode> nodes, NodeFactory factory) { BuildMethodLists(nodes); Out.WriteLine("#include \"common.h\""); Out.WriteLine("#include \"CppCodeGen.h\""); Out.WriteLine(); _statics = new CppGenerationBuffer(); _statics.Indent(); _gcStatics = new CppGenerationBuffer(); _gcStatics.Indent(); _threadStatics = new CppGenerationBuffer(); _threadStatics.Indent(); _gcThreadStatics = new CppGenerationBuffer(); _gcThreadStatics.Indent(); OutputNodes(nodes, factory); Out.Write("struct {"); Out.Write(_statics.ToString()); Out.Write("} __statics;"); Out.Write("struct {"); Out.Write(_gcStatics.ToString()); Out.Write("} __gcStatics;"); Out.Write("struct {"); Out.Write(_gcStatics.ToString()); Out.Write("} __gcThreadStatics;"); OutputExternCSignatures(); foreach (var node in nodes) { if (node is CppMethodCodeNode) OutputMethodNode(node as CppMethodCodeNode); else if (node is UnboxingStubNode) OutputUnboxingStubNode(node as UnboxingStubNode); } Out.Dispose(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Security; namespace System.IO { public sealed partial class DriveInfo { private static string NormalizeDriveName(string driveName) { if (driveName.Contains("\0")) { throw new ArgumentException(SR.Format(SR.Arg_InvalidDriveChars, driveName), "driveName"); } if (driveName.Length == 0) { throw new ArgumentException(SR.Arg_MustBeNonEmptyDriveName, "driveName"); } return driveName; } public DriveType DriveType { [SecuritySafeCritical] get { Interop.libc.statfs data; int errno; if (Interop.libc.TryGetStatFsForDriveName(Name, out data, out errno)) { return GetDriveType(Interop.libc.GetMountPointFsType(data)); } // This is one of the few properties that doesn't throw on failure, // instead returning a value from the enum. switch (errno) { case Interop.Errors.ELOOP: case Interop.Errors.ENAMETOOLONG: case Interop.Errors.ENOENT: case Interop.Errors.ENOTDIR: return DriveType.NoRootDirectory; default: return DriveType.Unknown; } } } public string DriveFormat { [SecuritySafeCritical] get { Interop.libc.statfs data = Interop.libc.GetStatFsForDriveName(Name); return Interop.libc.GetMountPointFsType(data); } } public long AvailableFreeSpace { [SecuritySafeCritical] get { Interop.libc.statfs data = Interop.libc.GetStatFsForDriveName(Name); return (long)data.f_bsize * (long)data.f_bavail; } } public long TotalFreeSpace { [SecuritySafeCritical] get { Interop.libc.statfs data = Interop.libc.GetStatFsForDriveName(Name); return (long)data.f_bsize * (long)data.f_bfree; } } public long TotalSize { [SecuritySafeCritical] get { Interop.libc.statfs data = Interop.libc.GetStatFsForDriveName(Name); return (long)data.f_bsize * (long)data.f_blocks; } } public String VolumeLabel { [SecuritySafeCritical] get { return Name; } [SecuritySafeCritical] set { throw new PlatformNotSupportedException(); } } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- /// <summary>Categorizes a file system name into a drive type.</summary> /// <param name="fileSystemName">The name to categorize.</param> /// <returns>The recognized drive type.</returns> private static DriveType GetDriveType(string fileSystemName) { // This list is based primarily on "man fs", "man mount", "mntent.h", "/proc/filesystems", // and "wiki.debian.org/FileSystem". It can be extended over time as we // find additional file systems that should be recognized as a particular drive type. switch (fileSystemName) { case "iso": case "isofs": case "iso9660": case "fuseiso": case "fuseiso9660": case "umview-mod-umfuseiso9660": return DriveType.CDRom; case "adfs": case "affs": case "befs": case "bfs": case "btrfs": case "ecryptfs": case "efs": case "ext": case "ext2": case "ext2_old": case "ext3": case "ext4": case "ext4dev": case "fat": case "fuseblk": case "fuseext2": case "fusefat": case "hfs": case "hfsplus": case "hpfs": case "jbd": case "jbd2": case "jfs": case "jffs": case "jffs2": case "minix": case "minix_old": case "minix2": case "minix2v2": case "msdos": case "ocfs2": case "omfs": case "openprom": case "ntfs": case "qnx4": case "reiserfs": case "squashfs": case "swap": case "sysv": case "ubifs": case "udf": case "ufs": case "umsdos": case "umview-mod-umfuseext2": case "xenix": case "xfs": case "xiafs": case "xmount": case "zfs-fuse": return DriveType.Fixed; case "9p": case "autofs": case "autofs4": case "beaglefs": case "cifs": case "coda": case "coherent": case "curlftpfs": case "davfs2": case "dlm": case "flickrfs": case "fusedav": case "fusesmb": case "gfs2": case "glusterfs-client": case "gmailfs": case "kafs": case "ltspfs": case "ncpfs": case "nfs": case "nfs4": case "obexfs": case "s3ql": case "smb": case "smbfs": case "sshfs": case "sysfs": case "sysv2": case "sysv4": case "vxfs": case "wikipediafs": return DriveType.Network; case "anon_inodefs": case "aptfs": case "avfs": case "bdev": case "binfmt_misc": case "cgroup": case "configfs": case "cramfs": case "cryptkeeper": case "cpuset": case "debugfs": case "devfs": case "devpts": case "devtmpfs": case "encfs": case "fuse": case "fuse.gvfsd-fuse": case "fusectl": case "hugetlbfs": case "libpam-encfs": case "ibpam-mount": case "mtpfs": case "mythtvfs": case "mqueue": case "pipefs": case "plptools": case "proc": case "pstore": case "pytagsfs": case "ramfs": case "rofs": case "romfs": case "rootfs": case "securityfs": case "sockfs": case "tmpfs": return DriveType.Ram; case "gphotofs": case "usbfs": case "usbdevice": case "vfat": return DriveType.Removable; case "aufs": // marking all unions as unknown case "funionfs": case "unionfs-fuse": case "mhddfs": default: return DriveType.Unknown; } } } }
// 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: Unsafe code that uses pointers should use ** SafePointer to fix subtle lifetime problems with the ** underlying resource. ** ===========================================================*/ // Design points: // *) Avoid handle-recycling problems (including ones triggered via // resurrection attacks) for all accesses via pointers. This requires tying // together the lifetime of the unmanaged resource with the code that reads // from that resource, in a package that uses synchronization to enforce // the correct semantics during finalization. We're using SafeHandle's // ref count as a gate on whether the pointer can be dereferenced because that // controls the lifetime of the resource. // // *) Keep the penalties for using this class small, both in terms of space // and time. Having multiple threads reading from a memory mapped file // will already require 2 additional interlocked operations. If we add in // a "current position" concept, that requires additional space in memory and // synchronization. Since the position in memory is often (but not always) // something that can be stored on the stack, we can save some memory by // excluding it from this object. However, avoiding the need for // synchronization is a more significant win. This design allows multiple // threads to read and write memory simultaneously without locks (as long as // you don't write to a region of memory that overlaps with what another // thread is accessing). // // *) Space-wise, we use the following memory, including SafeHandle's fields: // Object Header MT* handle int bool bool <2 pad bytes> length // On 32 bit platforms: 24 bytes. On 64 bit platforms: 40 bytes. // (We can safe 4 bytes on x86 only by shrinking SafeHandle) // // *) Wrapping a SafeHandle would have been a nice solution, but without an // ordering between critical finalizable objects, it would have required // changes to each SafeHandle subclass to opt in to being usable from a // SafeBuffer (or some clever exposure of SafeHandle's state fields and a // way of forcing ReleaseHandle to run even after the SafeHandle has been // finalized with a ref count > 1). We can use less memory and create fewer // objects by simply inserting a SafeBuffer into the class hierarchy. // // *) In an ideal world, we could get marshaling support for SafeBuffer that // would allow us to annotate a P/Invoke declaration, saying this parameter // specifies the length of the buffer, and the units of that length are X. // P/Invoke would then pass that size parameter to SafeBuffer. // [DllImport(...)] // static extern SafeMemoryHandle AllocCharBuffer(int numChars); // If we could put an attribute on the SafeMemoryHandle saying numChars is // the element length, and it must be multiplied by 2 to get to the byte // length, we can simplify the usage model for SafeBuffer. // // *) This class could benefit from a constraint saying T is a value type // containing no GC references. // Implementation notes: // *) The Initialize method must be called before you use any instance of // a SafeBuffer. To avoid race conditions when storing SafeBuffers in statics, // you either need to take a lock when publishing the SafeBuffer, or you // need to create a local, initialize the SafeBuffer, then assign to the // static variable (perhaps using Interlocked.CompareExchange). Of course, // assignments in a static class constructor are under a lock implicitly. using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Runtime.InteropServices { public abstract unsafe class SafeBuffer : SafeHandleZeroOrMinusOneIsInvalid { // Steal UIntPtr.MaxValue as our uninitialized value. private static readonly UIntPtr Uninitialized = (UIntPtr.Size == 4) ? ((UIntPtr)UInt32.MaxValue) : ((UIntPtr)UInt64.MaxValue); private UIntPtr _numBytes; protected SafeBuffer(bool ownsHandle) : base(ownsHandle) { _numBytes = Uninitialized; } /// <summary> /// Specifies the size of the region of memory, in bytes. Must be /// called before using the SafeBuffer. /// </summary> /// <param name="numBytes">Number of valid bytes in memory.</param> [CLSCompliant(false)] public void Initialize(ulong numBytes) { if (numBytes < 0) throw new ArgumentOutOfRangeException(nameof(numBytes), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (IntPtr.Size == 4 && numBytes > UInt32.MaxValue) throw new ArgumentOutOfRangeException(nameof(numBytes), Environment.GetResourceString("ArgumentOutOfRange_AddressSpace")); Contract.EndContractBlock(); if (numBytes >= (ulong)Uninitialized) throw new ArgumentOutOfRangeException(nameof(numBytes), Environment.GetResourceString("ArgumentOutOfRange_UIntPtrMax-1")); _numBytes = (UIntPtr)numBytes; } /// <summary> /// Specifies the the size of the region in memory, as the number of /// elements in an array. Must be called before using the SafeBuffer. /// </summary> [CLSCompliant(false)] public void Initialize(uint numElements, uint sizeOfEachElement) { if (numElements < 0) throw new ArgumentOutOfRangeException(nameof(numElements), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (sizeOfEachElement < 0) throw new ArgumentOutOfRangeException(nameof(sizeOfEachElement), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (IntPtr.Size == 4 && numElements * sizeOfEachElement > UInt32.MaxValue) throw new ArgumentOutOfRangeException("numBytes", Environment.GetResourceString("ArgumentOutOfRange_AddressSpace")); Contract.EndContractBlock(); if (numElements * sizeOfEachElement >= (ulong)Uninitialized) throw new ArgumentOutOfRangeException(nameof(numElements), Environment.GetResourceString("ArgumentOutOfRange_UIntPtrMax-1")); _numBytes = checked((UIntPtr)(numElements * sizeOfEachElement)); } /// <summary> /// Specifies the the size of the region in memory, as the number of /// elements in an array. Must be called before using the SafeBuffer. /// </summary> [CLSCompliant(false)] public void Initialize<T>(uint numElements) where T : struct { Initialize(numElements, Marshal.AlignedSizeOf<T>()); } // Callers should ensure that they check whether the pointer ref param // is null when AcquirePointer returns. If it is not null, they must // call ReleasePointer in a CER. This method calls DangerousAddRef // & exposes the pointer. Unlike Read, it does not alter the "current // position" of the pointer. Here's how to use it: // // byte* pointer = null; // RuntimeHelpers.PrepareConstrainedRegions(); // try { // safeBuffer.AcquirePointer(ref pointer); // // Use pointer here, with your own bounds checking // } // finally { // if (pointer != null) // safeBuffer.ReleasePointer(); // } // // Note: If you cast this byte* to a T*, you have to worry about // whether your pointer is aligned. Additionally, you must take // responsibility for all bounds checking with this pointer. /// <summary> /// Obtain the pointer from a SafeBuffer for a block of code, /// with the express responsibility for bounds checking and calling /// ReleasePointer later within a CER to ensure the pointer can be /// freed later. This method either completes successfully or /// throws an exception and returns with pointer set to null. /// </summary> /// <param name="pointer">A byte*, passed by reference, to receive /// the pointer from within the SafeBuffer. You must set /// pointer to null before calling this method.</param> [CLSCompliant(false)] public void AcquirePointer(ref byte* pointer) { if (_numBytes == Uninitialized) throw NotInitialized(); pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { bool junk = false; DangerousAddRef(ref junk); pointer = (byte*)handle; } } public void ReleasePointer() { if (_numBytes == Uninitialized) throw NotInitialized(); DangerousRelease(); } /// <summary> /// Read a value type from memory at the given offset. This is /// equivalent to: return *(T*)(bytePtr + byteOffset); /// </summary> /// <typeparam name="T">The value type to read</typeparam> /// <param name="byteOffset">Where to start reading from memory. You /// may have to consider alignment.</param> /// <returns>An instance of T read from memory.</returns> [CLSCompliant(false)] public T Read<T>(ulong byteOffset) where T : struct { if (_numBytes == Uninitialized) throw NotInitialized(); uint sizeofT = Marshal.SizeOfType(typeof(T)); byte* ptr = (byte*)handle + byteOffset; SpaceCheck(ptr, sizeofT); // return *(T*) (_ptr + byteOffset); T value; bool mustCallRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustCallRelease); GenericPtrToStructure<T>(ptr, out value, sizeofT); } finally { if (mustCallRelease) DangerousRelease(); } return value; } [CLSCompliant(false)] public void ReadArray<T>(ulong byteOffset, T[] array, int index, int count) where T : struct { if (array == null) throw new ArgumentNullException(nameof(array), Environment.GetResourceString("ArgumentNull_Buffer")); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (array.Length - index < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); if (_numBytes == Uninitialized) throw NotInitialized(); uint sizeofT = Marshal.SizeOfType(typeof(T)); uint alignedSizeofT = Marshal.AlignedSizeOf<T>(); byte* ptr = (byte*)handle + byteOffset; SpaceCheck(ptr, checked((ulong)(alignedSizeofT * count))); bool mustCallRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustCallRelease); for (int i = 0; i < count; i++) unsafe { GenericPtrToStructure<T>(ptr + alignedSizeofT * i, out array[i + index], sizeofT); } } finally { if (mustCallRelease) DangerousRelease(); } } /// <summary> /// Write a value type to memory at the given offset. This is /// equivalent to: *(T*)(bytePtr + byteOffset) = value; /// </summary> /// <typeparam name="T">The type of the value type to write to memory.</typeparam> /// <param name="byteOffset">The location in memory to write to. You /// may have to consider alignment.</param> /// <param name="value">The value type to write to memory.</param> [CLSCompliant(false)] public void Write<T>(ulong byteOffset, T value) where T : struct { if (_numBytes == Uninitialized) throw NotInitialized(); uint sizeofT = Marshal.SizeOfType(typeof(T)); byte* ptr = (byte*)handle + byteOffset; SpaceCheck(ptr, sizeofT); // *((T*) (_ptr + byteOffset)) = value; bool mustCallRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustCallRelease); GenericStructureToPtr(ref value, ptr, sizeofT); } finally { if (mustCallRelease) DangerousRelease(); } } [CLSCompliant(false)] public void WriteArray<T>(ulong byteOffset, T[] array, int index, int count) where T : struct { if (array == null) throw new ArgumentNullException(nameof(array), Environment.GetResourceString("ArgumentNull_Buffer")); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (array.Length - index < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); if (_numBytes == Uninitialized) throw NotInitialized(); uint sizeofT = Marshal.SizeOfType(typeof(T)); uint alignedSizeofT = Marshal.AlignedSizeOf<T>(); byte* ptr = (byte*)handle + byteOffset; SpaceCheck(ptr, checked((ulong)(alignedSizeofT * count))); bool mustCallRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustCallRelease); for (int i = 0; i < count; i++) unsafe { GenericStructureToPtr(ref array[i + index], ptr + alignedSizeofT * i, sizeofT); } } finally { if (mustCallRelease) DangerousRelease(); } } /// <summary> /// Returns the number of bytes in the memory region. /// </summary> [CLSCompliant(false)] public ulong ByteLength { get { if (_numBytes == Uninitialized) throw NotInitialized(); return (ulong)_numBytes; } } /* No indexer. The perf would be misleadingly bad. People should use * AcquirePointer and ReleasePointer instead. */ private void SpaceCheck(byte* ptr, ulong sizeInBytes) { if ((ulong)_numBytes < sizeInBytes) NotEnoughRoom(); if ((ulong)(ptr - (byte*)handle) > ((ulong)_numBytes) - sizeInBytes) NotEnoughRoom(); } private static void NotEnoughRoom() { throw new ArgumentException(Environment.GetResourceString("Arg_BufferTooSmall")); } private static InvalidOperationException NotInitialized() { Debug.Assert(false, "Uninitialized SafeBuffer! Someone needs to call Initialize before using this instance!"); return new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MustCallInitialize")); } // FCALL limitations mean we can't have generic FCALL methods. However, we can pass // TypedReferences to FCALL methods. internal static void GenericPtrToStructure<T>(byte* ptr, out T structure, uint sizeofT) where T : struct { structure = default(T); // Dummy assignment to silence the compiler PtrToStructureNative(ptr, __makeref(structure), sizeofT); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void PtrToStructureNative(byte* ptr, /*out T*/ TypedReference structure, uint sizeofT); internal static void GenericStructureToPtr<T>(ref T structure, byte* ptr, uint sizeofT) where T : struct { StructureToPtrNative(__makeref(structure), ptr, sizeofT); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void StructureToPtrNative(/*ref T*/ TypedReference structure, byte* ptr, uint sizeofT); } }
// <copyright file="GpBiCg.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // // Copyright (c) 2009-2013 Math.NET // // 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. // </copyright> using System; using MathNet.Numerics.LinearAlgebra.Solvers; using MathNet.Numerics.Properties; namespace MathNet.Numerics.LinearAlgebra.Single.Solvers { /// <summary> /// A Generalized Product Bi-Conjugate Gradient iterative matrix solver. /// </summary> /// <remarks> /// <para> /// The Generalized Product Bi-Conjugate Gradient (GPBiCG) solver is an /// alternative version of the Bi-Conjugate Gradient stabilized (CG) solver. /// Unlike the CG solver the GPBiCG solver can be used on /// non-symmetric matrices. <br/> /// Note that much of the success of the solver depends on the selection of the /// proper preconditioner. /// </para> /// <para> /// The GPBiCG algorithm was taken from: <br/> /// GPBiCG(m,l): A hybrid of BiCGSTAB and GPBiCG methods with /// efficiency and robustness /// <br/> /// S. Fujino /// <br/> /// Applied Numerical Mathematics, Volume 41, 2002, pp 107 - 117 /// <br/> /// </para> /// <para> /// The example code below provides an indication of the possible use of the /// solver. /// </para> /// </remarks> public sealed class GpBiCg : IIterativeSolver<float> { /// <summary> /// Indicates the number of <c>BiCGStab</c> steps should be taken /// before switching. /// </summary> int _numberOfBiCgStabSteps = 1; /// <summary> /// Indicates the number of <c>GPBiCG</c> steps should be taken /// before switching. /// </summary> int _numberOfGpbiCgSteps = 4; /// <summary> /// Gets or sets the number of steps taken with the <c>BiCgStab</c> algorithm /// before switching over to the <c>GPBiCG</c> algorithm. /// </summary> public int NumberOfBiCgStabSteps { get { return _numberOfBiCgStabSteps; } set { if (value < 0) { throw new ArgumentOutOfRangeException("value"); } _numberOfBiCgStabSteps = value; } } /// <summary> /// Gets or sets the number of steps taken with the <c>GPBiCG</c> algorithm /// before switching over to the <c>BiCgStab</c> algorithm. /// </summary> public int NumberOfGpBiCgSteps { get { return _numberOfGpbiCgSteps; } set { if (value < 0) { throw new ArgumentOutOfRangeException("value"); } _numberOfGpbiCgSteps = value; } } /// <summary> /// Calculates the <c>true</c> residual of the matrix equation Ax = b according to: residual = b - Ax /// </summary> /// <param name="matrix">Instance of the <see cref="Matrix"/> A.</param> /// <param name="residual">Residual values in <see cref="Vector"/>.</param> /// <param name="x">Instance of the <see cref="Vector"/> x.</param> /// <param name="b">Instance of the <see cref="Vector"/> b.</param> static void CalculateTrueResidual(Matrix<float> matrix, Vector<float> residual, Vector<float> x, Vector<float> b) { // -Ax = residual matrix.Multiply(x, residual); residual.Multiply(-1, residual); // residual + b residual.Add(b, residual); } /// <summary> /// Decide if to do steps with BiCgStab /// </summary> /// <param name="iterationNumber">Number of iteration</param> /// <returns><c>true</c> if yes, otherwise <c>false</c></returns> bool ShouldRunBiCgStabSteps(int iterationNumber) { // Run the first steps as BiCGStab // The number of steps past a whole iteration set var difference = iterationNumber % (_numberOfBiCgStabSteps + _numberOfGpbiCgSteps); // Do steps with BiCGStab if: // - The difference is zero or more (i.e. we have done zero or more complete cycles) // - The difference is less than the number of BiCGStab steps that should be taken return (difference >= 0) && (difference < _numberOfBiCgStabSteps); } /// <summary> /// Solves the matrix equation Ax = b, where A is the coefficient matrix, b is the /// solution vector and x is the unknown vector. /// </summary> /// <param name="matrix">The coefficient matrix, <c>A</c>.</param> /// <param name="input">The solution vector, <c>b</c></param> /// <param name="result">The result vector, <c>x</c></param> /// <param name="iterator">The iterator to use to control when to stop iterating.</param> /// <param name="preconditioner">The preconditioner to use for approximations.</param> public void Solve(Matrix<float> matrix, Vector<float> input, Vector<float> result, Iterator<float> iterator, IPreconditioner<float> preconditioner) { if (matrix.RowCount != matrix.ColumnCount) { throw new ArgumentException(Resources.ArgumentMatrixSquare, "matrix"); } if (result.Count != input.Count) { throw new ArgumentException(Resources.ArgumentVectorsSameLength); } if (input.Count != matrix.RowCount) { throw Matrix.DimensionsDontMatch<ArgumentException>(input, matrix); } if (iterator == null) { iterator = new Iterator<float>(); } if (preconditioner == null) { preconditioner = new UnitPreconditioner<float>(); } preconditioner.Initialize(matrix); // x_0 is initial guess // Take x_0 = 0 var xtemp = new DenseVector(input.Count); // r_0 = b - Ax_0 // This is basically a SAXPY so it could be made a lot faster var residuals = new DenseVector(matrix.RowCount); CalculateTrueResidual(matrix, residuals, xtemp, input); // Define the temporary scalars float beta = 0; // Define the temporary vectors // rDash_0 = r_0 var rdash = DenseVector.OfVector(residuals); // t_-1 = 0 var t = new DenseVector(residuals.Count); var t0 = new DenseVector(residuals.Count); // w_-1 = 0 var w = new DenseVector(residuals.Count); // Define the remaining temporary vectors var c = new DenseVector(residuals.Count); var p = new DenseVector(residuals.Count); var s = new DenseVector(residuals.Count); var u = new DenseVector(residuals.Count); var y = new DenseVector(residuals.Count); var z = new DenseVector(residuals.Count); var temp = new DenseVector(residuals.Count); var temp2 = new DenseVector(residuals.Count); var temp3 = new DenseVector(residuals.Count); // for (k = 0, 1, .... ) var iterationNumber = 0; while (iterator.DetermineStatus(iterationNumber, xtemp, input, residuals) == IterationStatus.Continue) { // p_k = r_k + beta_(k-1) * (p_(k-1) - u_(k-1)) p.Subtract(u, temp); temp.Multiply(beta, temp2); residuals.Add(temp2, p); // Solve M b_k = p_k preconditioner.Approximate(p, temp); // s_k = A b_k matrix.Multiply(temp, s); // alpha_k = (r*_0 * r_k) / (r*_0 * s_k) var alpha = rdash.DotProduct(residuals)/rdash.DotProduct(s); // y_k = t_(k-1) - r_k - alpha_k * w_(k-1) + alpha_k s_k s.Subtract(w, temp); t.Subtract(residuals, y); temp.Multiply(alpha, temp2); y.Add(temp2, temp3); temp3.CopyTo(y); // Store the old value of t in t0 t.CopyTo(t0); // t_k = r_k - alpha_k s_k s.Multiply(-alpha, temp2); residuals.Add(temp2, t); // Solve M d_k = t_k preconditioner.Approximate(t, temp); // c_k = A d_k matrix.Multiply(temp, c); var cdot = c.DotProduct(c); // cDot can only be zero if c is a zero vector // We'll set cDot to 1 if it is zero to prevent NaN's // Note that the calculation should continue fine because // c.DotProduct(t) will be zero and so will c.DotProduct(y) if (cdot.AlmostEqualNumbersBetween(0, 1)) { cdot = 1.0f; } // Even if we don't want to do any BiCGStab steps we'll still have // to do at least one at the start to initialize the // system, but we'll only have to take special measures // if we don't do any so ... var ctdot = c.DotProduct(t); float eta; float sigma; if (((_numberOfBiCgStabSteps == 0) && (iterationNumber == 0)) || ShouldRunBiCgStabSteps(iterationNumber)) { // sigma_k = (c_k * t_k) / (c_k * c_k) sigma = ctdot/cdot; // eta_k = 0 eta = 0; } else { var ydot = y.DotProduct(y); // yDot can only be zero if y is a zero vector // We'll set yDot to 1 if it is zero to prevent NaN's // Note that the calculation should continue fine because // y.DotProduct(t) will be zero and so will c.DotProduct(y) if (ydot.AlmostEqualNumbersBetween(0, 1)) { ydot = 1.0f; } var ytdot = y.DotProduct(t); var cydot = c.DotProduct(y); var denom = (cdot*ydot) - (cydot*cydot); // sigma_k = ((y_k * y_k)(c_k * t_k) - (y_k * t_k)(c_k * y_k)) / ((c_k * c_k)(y_k * y_k) - (y_k * c_k)(c_k * y_k)) sigma = ((ydot*ctdot) - (ytdot*cydot))/denom; // eta_k = ((c_k * c_k)(y_k * t_k) - (y_k * c_k)(c_k * t_k)) / ((c_k * c_k)(y_k * y_k) - (y_k * c_k)(c_k * y_k)) eta = ((cdot*ytdot) - (cydot*ctdot))/denom; } // u_k = sigma_k s_k + eta_k (t_(k-1) - r_k + beta_(k-1) u_(k-1)) u.Multiply(beta, temp2); t0.Add(temp2, temp); temp.Subtract(residuals, temp3); temp3.CopyTo(temp); temp.Multiply(eta, temp); s.Multiply(sigma, temp2); temp.Add(temp2, u); // z_k = sigma_k r_k +_ eta_k z_(k-1) - alpha_k u_k z.Multiply(eta, z); u.Multiply(-alpha, temp2); z.Add(temp2, temp3); temp3.CopyTo(z); residuals.Multiply(sigma, temp2); z.Add(temp2, temp3); temp3.CopyTo(z); // x_(k+1) = x_k + alpha_k p_k + z_k p.Multiply(alpha, temp2); xtemp.Add(temp2, temp3); temp3.CopyTo(xtemp); xtemp.Add(z, temp3); temp3.CopyTo(xtemp); // r_(k+1) = t_k - eta_k y_k - sigma_k c_k // Copy the old residuals to a temp vector because we'll // need those in the next step residuals.CopyTo(t0); y.Multiply(-eta, temp2); t.Add(temp2, residuals); c.Multiply(-sigma, temp2); residuals.Add(temp2, temp3); temp3.CopyTo(residuals); // beta_k = alpha_k / sigma_k * (r*_0 * r_(k+1)) / (r*_0 * r_k) // But first we check if there is a possible NaN. If so just reset beta to zero. beta = (!sigma.AlmostEqualNumbersBetween(0, 1)) ? alpha/sigma*rdash.DotProduct(residuals)/rdash.DotProduct(t0) : 0; // w_k = c_k + beta_k s_k s.Multiply(beta, temp2); c.Add(temp2, w); // Get the real value preconditioner.Approximate(xtemp, result); // Now check for convergence if (iterator.DetermineStatus(iterationNumber, result, input, residuals) != IterationStatus.Continue) { // Recalculate the residuals and go round again. This is done to ensure that // we have the proper residuals. CalculateTrueResidual(matrix, residuals, result, input); } // Next iteration. iterationNumber++; } } } }
using System; using System.Collections.Generic; using System.Text; using MatterHackers.Agg; using MatterHackers.Agg.VertexSource; using MatterHackers.Agg.Image; using MatterHackers.VectorMath; using Gaming.Core; namespace Gaming.Game { public class DataViewGraph { private RGBA_Floats SentDataLineColor = new RGBA_Floats(200, 200, 0); private RGBA_Floats ReceivedDataLineColor = new RGBA_Floats(0, 200, 20); private RGBA_Floats BoxColor = new RGBA_Floats(10, 25, 240); private double m_DataViewMinY; private double m_DataViewMaxY; bool m_DynamiclyScaleYRange; private Vector2 m_Position; private uint m_Width; private uint m_Height; private Dictionary<String, HistoryData> m_DataHistoryArray; private int m_ColorIndex; private PathStorage m_LinesToDraw; internal class HistoryData { int m_Capacity; TwoSidedStack<double> m_Data; internal double m_TotalValue; internal RGBA_Bytes m_Color; internal HistoryData(int Capacity, IColorType Color) { m_Color = Color.GetAsRGBA_Bytes(); m_Capacity = Capacity; m_Data = new TwoSidedStack<double>(); Reset(); } public int Count { get { return m_Data.Count; } } internal void Add(double Value) { if(m_Data.Count == m_Capacity) { m_TotalValue -= m_Data.PopHead(); } m_Data.PushTail(Value); m_TotalValue += Value; } internal void Reset() { m_TotalValue = 0; m_Data.Zero(); } internal double GetItem(int ItemIndex) { if(ItemIndex < m_Data.Count) { return m_Data[ItemIndex]; } else { return 0; } } internal double GetMaxValue() { double Max = -9999999999; for(int i=0; i < m_Data.Count; i++) { if(m_Data[i] > Max) { Max = m_Data[i]; } } return Max; } internal double GetMinValue() { double Min = 9999999999; for (int i = 0; i < m_Data.Count; i++) { if (m_Data[i] < Min) { Min = m_Data[i]; } } return Min; } internal double GetAverageValue() { return m_TotalValue / m_Data.Count; } }; public DataViewGraph(Vector2 RenderPosition) : this(RenderPosition, 80, 50, 0, 0) { m_DynamiclyScaleYRange = true; } public DataViewGraph(Vector2 RenderPosition, uint Width, uint Height) : this(RenderPosition, Width, Height, 0, 0) { m_DynamiclyScaleYRange = true; } public DataViewGraph(Vector2 RenderPosition, uint Width, uint Height, double StartMin, double StartMax) { m_LinesToDraw = new PathStorage(); m_DataHistoryArray = new Dictionary<String, HistoryData>(); m_Width = Width; m_Height = Height; m_DataViewMinY = StartMin; m_DataViewMaxY = StartMax; if(StartMin == 0 && StartMax == 0) { m_DataViewMaxY = -999999; m_DataViewMinY = 999999; } m_Position = RenderPosition; m_DynamiclyScaleYRange = false; } public double GetAverageValue(String DataType) { HistoryData TrendLine; m_DataHistoryArray.TryGetValue(DataType, out TrendLine); if (TrendLine != null) { return TrendLine.GetAverageValue(); } return 0; } public void Draw(MatterHackers.Agg.Transform.ITransform Position, Graphics2D renderer) { double TextHeight = m_Position.y - 20; double Range = (m_DataViewMaxY - m_DataViewMinY); VertexSourceApplyTransform TransformedLinesToDraw; Stroke StrockedTransformedLinesToDraw; RoundedRect BackGround = new RoundedRect(m_Position.x, m_Position.y - 1, m_Position.x + m_Width, m_Position.y - 1 + m_Height + 2, 5); VertexSourceApplyTransform TransformedBackGround = new VertexSourceApplyTransform(BackGround, Position); renderer.Render(TransformedBackGround, new RGBA_Bytes(0, 0, 0, .5)); // if the 0 line is within the window than draw it. if (m_DataViewMinY < 0 && m_DataViewMaxY > 0) { m_LinesToDraw.remove_all(); m_LinesToDraw.MoveTo(m_Position.x, m_Position.y + ((0 - m_DataViewMinY) * m_Height / Range)); m_LinesToDraw.LineTo(m_Position.x + m_Width, m_Position.y + ((0 - m_DataViewMinY) * m_Height / Range)); TransformedLinesToDraw = new VertexSourceApplyTransform(m_LinesToDraw, Position); StrockedTransformedLinesToDraw = new Stroke(TransformedLinesToDraw); renderer.Render(StrockedTransformedLinesToDraw, new RGBA_Bytes(0, 0, 0, 1)); } double MaxMax = -999999999; double MinMin = 999999999; double MaxAverage = 0; foreach (KeyValuePair<String, HistoryData> historyKeyValue in m_DataHistoryArray) { HistoryData history = historyKeyValue.Value; m_LinesToDraw.remove_all(); MaxMax = System.Math.Max(MaxMax, history.GetMaxValue()); MinMin = System.Math.Min(MinMin, history.GetMinValue()); MaxAverage = System.Math.Max(MaxAverage, history.GetAverageValue()); for(int i = 0; i < m_Width - 1; i++) { if(i==0) { m_LinesToDraw.MoveTo(m_Position.x + i, m_Position.y + ((history.GetItem(i) - m_DataViewMinY) * m_Height / Range)); } else { m_LinesToDraw.LineTo(m_Position.x + i, m_Position.y + ((history.GetItem(i) - m_DataViewMinY) * m_Height / Range)); } } TransformedLinesToDraw = new VertexSourceApplyTransform(m_LinesToDraw, Position); StrockedTransformedLinesToDraw = new Stroke(TransformedLinesToDraw); renderer.Render(StrockedTransformedLinesToDraw, history.m_Color); String Text = historyKeyValue.Key + ": Min:" + MinMin.ToString("0.0") + " Max:" + MaxMax.ToString("0.0"); renderer.DrawString(Text, m_Position.x, TextHeight - m_Height); TextHeight -= 20; } RoundedRect BackGround2 = new RoundedRect(m_Position.x, m_Position.y - 1, m_Position.x + m_Width, m_Position.y - 1 + m_Height + 2, 5); VertexSourceApplyTransform TransformedBackGround2 = new VertexSourceApplyTransform(BackGround2, Position); Stroke StrockedTransformedBackGround = new Stroke(TransformedBackGround2); renderer.Render(StrockedTransformedBackGround, new RGBA_Bytes(0.0, 0, 0, 1)); //renderer.Color = BoxColor; //renderer.DrawRect(m_Position.x, m_Position.y - 1, m_Width, m_Height + 2); } public void AddData(String DataType, double NewData) { if (m_DynamiclyScaleYRange) { m_DataViewMaxY = System.Math.Max(m_DataViewMaxY, NewData); m_DataViewMinY = System.Math.Min(m_DataViewMinY, NewData); } if (!m_DataHistoryArray.ContainsKey(DataType)) { RGBA_Bytes LineColor = new RGBA_Bytes(255, 255, 255); switch(m_ColorIndex++ % 3) { case 0: LineColor = new RGBA_Bytes(255, 55, 55); break; case 1: LineColor = new RGBA_Bytes(55, 255, 55); break; case 2: LineColor = new RGBA_Bytes(55, 55, 255); break; } m_DataHistoryArray.Add(DataType, new HistoryData((int)m_Width, LineColor)); } m_DataHistoryArray[DataType].Add(NewData); } public void Reset() { m_DataViewMaxY = 1; m_DataViewMinY = 99999; foreach (KeyValuePair<String, HistoryData> historyKeyValue in m_DataHistoryArray) { historyKeyValue.Value.Reset(); } } }; }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using System.Web; using Amazon; using Amazon.CloudFront; using Amazon.CloudFront.Model; using Amazon.S3; using Amazon.S3.Model; using Amazon.S3.Transfer; using Amazon.Util; using ASC.Common; using ASC.Core; using ASC.Data.Storage.Configuration; using MimeMapping = ASC.Common.Web.MimeMapping; namespace ASC.Data.Storage.S3 { public class S3Storage : BaseStorage { private readonly List<string> _domains = new List<string>(); private readonly Dictionary<string, S3CannedACL> _domainsAcl; private readonly S3CannedACL _moduleAcl; private string _accessKeyId = ""; private string _bucket = ""; private string _recycleDir = ""; private Uri _bucketRoot; private Uri _bucketSSlRoot; private string _region = String.Empty; private string _serviceurl; private bool _forcepathstyle; private string _secretAccessKeyId = ""; private ServerSideEncryptionMethod _sse = ServerSideEncryptionMethod.AES256; private bool _useHttp = true; private bool _lowerCasing = true; private bool _revalidateCloudFront; private string _distributionId = string.Empty; private String _subDir = String.Empty; public S3Storage(string tenant) { _tenant = tenant; _modulename = string.Empty; _dataList = null; //Make expires _domainsExpires = new Dictionary<string, TimeSpan> { { string.Empty, TimeSpan.Zero } }; _domainsAcl = new Dictionary<string, S3CannedACL>(); _moduleAcl = S3CannedACL.PublicRead; } public S3Storage(string tenant, HandlerConfigurationElement handlerConfig, ModuleConfigurationElement moduleConfig) { _tenant = tenant; _modulename = moduleConfig.Name; _dataList = new DataList(moduleConfig); _domains.AddRange( moduleConfig.Domains.Cast<DomainConfigurationElement>().Select(x => string.Format("{0}/", x.Name))); //Make expires _domainsExpires = moduleConfig.Domains.Cast<DomainConfigurationElement>().Where(x => x.Expires != TimeSpan.Zero). ToDictionary(x => x.Name, y => y.Expires); _domainsExpires.Add(string.Empty, moduleConfig.Expires); _domainsAcl = moduleConfig.Domains.Cast<DomainConfigurationElement>().ToDictionary(x => x.Name, y => GetS3Acl(y.Acl)); _moduleAcl = GetS3Acl(moduleConfig.Acl); } private S3CannedACL GetDomainACL(string domain) { if (GetExpire(domain) != TimeSpan.Zero) { return S3CannedACL.Private; } if (_domainsAcl.ContainsKey(domain)) { return _domainsAcl[domain]; } return _moduleAcl; } private S3CannedACL GetS3Acl(ACL acl) { switch (acl) { case ACL.Read: return S3CannedACL.PublicRead; case ACL.Private: return S3CannedACL.Private; default: return S3CannedACL.PublicRead; } } public Uri GetUriInternal(string path) { return new Uri(SecureHelper.IsSecure() ? _bucketSSlRoot : _bucketRoot, path); } public Uri GetUriShared(string domain, string path) { return new Uri(SecureHelper.IsSecure() ? _bucketSSlRoot : _bucketRoot, MakePath(domain, path)); } public override Uri GetInternalUri(string domain, string path, TimeSpan expire, IEnumerable<string> headers) { if (expire == TimeSpan.Zero || expire == TimeSpan.MinValue || expire == TimeSpan.MaxValue) { expire = GetExpire(domain); } if (expire == TimeSpan.Zero || expire == TimeSpan.MinValue || expire == TimeSpan.MaxValue) { return GetUriShared(domain, path); } var pUrlRequest = new GetPreSignedUrlRequest { BucketName = _bucket, Expires = DateTime.UtcNow.Add(expire), Key = MakePath(domain, path), Protocol = SecureHelper.IsSecure() ? Protocol.HTTPS : Protocol.HTTP, Verb = HttpVerb.GET }; if (headers != null && headers.Any()) { var headersOverrides = new ResponseHeaderOverrides(); foreach (var h in headers) { if (h.StartsWith("Content-Disposition")) headersOverrides.ContentDisposition = (h.Substring("Content-Disposition".Length + 1)); else if (h.StartsWith("Cache-Control")) headersOverrides.CacheControl = (h.Substring("Cache-Control".Length + 1)); else if (h.StartsWith("Content-Encoding")) headersOverrides.ContentEncoding = (h.Substring("Content-Encoding".Length + 1)); else if (h.StartsWith("Content-Language")) headersOverrides.ContentLanguage = (h.Substring("Content-Language".Length + 1)); else if (h.StartsWith("Content-Type")) headersOverrides.ContentType = (h.Substring("Content-Type".Length + 1)); else if (h.StartsWith("Expires")) headersOverrides.Expires = (h.Substring("Expires".Length + 1)); else throw new FormatException(string.Format("Invalid header: {0}", h)); } pUrlRequest.ResponseHeaderOverrides = headersOverrides; } using (var client = GetClient()) { return MakeUri(client.GetPreSignedURL(pUrlRequest)); } } private Uri MakeUri(string preSignedURL) { var uri = new Uri(preSignedURL); var signedPart = uri.PathAndQuery.TrimStart('/'); return new UnencodedUri(uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase) ? _bucketSSlRoot : _bucketRoot, signedPart); } public override Stream GetReadStream(string domain, string path) { return GetReadStream(domain, path, 0); } public override Stream GetReadStream(string domain, string path, int offset) { var request = new GetObjectRequest { BucketName = _bucket, Key = MakePath(domain, path) }; if (0 < offset) request.ByteRange = new ByteRange(offset, int.MaxValue); try { using (var client = GetClient()) { return new ResponseStreamWrapper(client.GetObject(request)); } } catch (AmazonS3Exception ex) { if (ex.ErrorCode == "NoSuchKey") { throw new FileNotFoundException("File not found", path); } throw; } } public override async Task<Stream> GetReadStreamAsync(string domain, string path, int offset) { var request = new GetObjectRequest { BucketName = _bucket, Key = MakePath(domain, path) }; if (0 < offset) request.ByteRange = new ByteRange(offset, int.MaxValue); try { using (var client = GetClient()) { return new ResponseStreamWrapper(await client.GetObjectAsync(request)); } } catch (AmazonS3Exception ex) { if (ex.ErrorCode == "NoSuchKey") { throw new FileNotFoundException("File not found", path); } throw; } } protected override Uri SaveWithAutoAttachment(string domain, string path, Stream stream, string attachmentFileName) { var contentDisposition = string.Format("attachment; filename={0};", HttpUtility.UrlPathEncode(attachmentFileName)); if (attachmentFileName.Any(c => c >= 0 && c <= 127)) { contentDisposition = string.Format("attachment; filename*=utf-8''{0};", HttpUtility.UrlPathEncode(attachmentFileName)); } return Save(domain, path, stream, null, contentDisposition); } public override Uri Save(string domain, string path, Stream stream, string contentType, string contentDisposition) { return Save(domain, path, stream, contentType, contentDisposition, ACL.Auto); } public Uri Save(string domain, string path, Stream stream, string contentType, string contentDisposition, ACL acl, string contentEncoding = null, int cacheDays = 5) { var buffered = stream.GetBuffered(); if (QuotaController != null) { QuotaController.QuotaUsedCheck(buffered.Length); } using (var client = GetClient()) using (var uploader = new TransferUtility(client)) { var mime = string.IsNullOrEmpty(contentType) ? MimeMapping.GetMimeMapping(Path.GetFileName(path)) : contentType; var request = new TransferUtilityUploadRequest { BucketName = _bucket, Key = MakePath(domain, path), ContentType = mime, ServerSideEncryptionMethod = _sse, InputStream = buffered, AutoCloseStream = false, Headers = { CacheControl = string.Format("public, maxage={0}", (int)TimeSpan.FromDays(cacheDays).TotalSeconds), ExpiresUtc = DateTime.UtcNow.Add(TimeSpan.FromDays(cacheDays)) } }; if (!WorkContext.IsMono) // System.Net.Sockets.SocketException: Connection reset by peer { switch (acl) { case ACL.Auto: request.CannedACL = GetDomainACL(domain); break; case ACL.Read: case ACL.Private: request.CannedACL = GetS3Acl(acl); break; } } if (!string.IsNullOrEmpty(contentDisposition)) { request.Headers.ContentDisposition = contentDisposition; } else if (mime == "application/octet-stream") { request.Headers.ContentDisposition = "attachment"; } if (!string.IsNullOrEmpty(contentEncoding)) { request.Headers.ContentEncoding = contentEncoding; } uploader.Upload(request); InvalidateCloudFront(MakePath(domain, path)); QuotaUsedAdd(domain, buffered.Length); return GetUri(domain, path); } } private void InvalidateCloudFront(params string[] paths) { if (!_revalidateCloudFront || string.IsNullOrEmpty(_distributionId)) return; using (var cfClient = GetCloudFrontClient()) { var invalidationRequest = new CreateInvalidationRequest { DistributionId = _distributionId, InvalidationBatch = new InvalidationBatch { CallerReference = Guid.NewGuid().ToString(), Paths = new Paths { Items = paths.ToList(), Quantity = paths.Count() } } }; cfClient.CreateInvalidation(invalidationRequest); } } public override Uri Save(string domain, string path, Stream stream) { return Save(domain, path, stream, string.Empty, string.Empty); } public override Uri Save(string domain, string path, Stream stream, string contentEncoding, int cacheDays) { return Save(domain, path, stream, string.Empty, string.Empty, ACL.Auto, contentEncoding, cacheDays); } public override Uri Save(string domain, string path, Stream stream, ACL acl) { return Save(domain, path, stream, null, null, acl); } #region chunking public override string InitiateChunkedUpload(string domain, string path) { var request = new InitiateMultipartUploadRequest { BucketName = _bucket, Key = MakePath(domain, path), ServerSideEncryptionMethod = _sse }; using (var s3 = GetClient()) { var response = s3.InitiateMultipartUpload(request); return response.UploadId; } } public override string UploadChunk(string domain, string path, string uploadId, Stream stream, long defaultChunkSize, int chunkNumber, long chunkLength) { var request = new UploadPartRequest { BucketName = _bucket, Key = MakePath(domain, path), UploadId = uploadId, PartNumber = chunkNumber, InputStream = stream }; try { using (var s3 = GetClient()) { var response = s3.UploadPart(request); return response.ETag; } } catch (AmazonS3Exception error) { if (error.ErrorCode == "NoSuchUpload") { AbortChunkedUpload(domain, path, uploadId); } throw; } } public override Uri FinalizeChunkedUpload(string domain, string path, string uploadId, Dictionary<int, string> eTags) { var request = new CompleteMultipartUploadRequest { BucketName = _bucket, Key = MakePath(domain, path), UploadId = uploadId, PartETags = eTags.Select(x => new PartETag(x.Key, x.Value)).ToList() }; try { using (var s3 = GetClient()) { s3.CompleteMultipartUpload(request); InvalidateCloudFront(MakePath(domain, path)); } if (QuotaController != null) { var size = GetFileSize(domain, path); QuotaUsedAdd(domain, size); } return GetUri(domain, path); } catch (AmazonS3Exception error) { if (error.ErrorCode == "NoSuchUpload") { AbortChunkedUpload(domain, path, uploadId); } throw; } } public override void AbortChunkedUpload(string domain, string path, string uploadId) { var key = MakePath(domain, path); var request = new AbortMultipartUploadRequest { BucketName = _bucket, Key = key, UploadId = uploadId }; using (var s3 = GetClient()) { s3.AbortMultipartUpload(request); } } public override bool IsSupportChunking { get { return true; } } #endregion public override void Delete(string domain, string path) { using (var client = GetClient()) { var key = MakePath(domain, path); var size = GetFileSize(domain, path); Recycle(client, domain, key); var request = new DeleteObjectRequest { BucketName = _bucket, Key = key }; client.DeleteObject(request); QuotaUsedDelete(domain, size); } } public override void DeleteFiles(string domain, List<string> paths) { if (!paths.Any()) return; var keysToDel = new List<string>(); long quotaUsed = 0; foreach (var path in paths) { try { //var obj = GetS3Objects(domain, path).FirstOrDefault(); var key = MakePath(domain, path); if (QuotaController != null) { quotaUsed += GetFileSize(domain, path); } keysToDel.Add(key); //objsToDel.Add(obj); } catch (FileNotFoundException) { } } if (!keysToDel.Any()) return; using (var client = GetClient()) { var deleteRequest = new DeleteObjectsRequest { BucketName = _bucket, Objects = keysToDel.Select(key => new KeyVersion { Key = key }).ToList() }; client.DeleteObjects(deleteRequest); } if (quotaUsed > 0) { QuotaUsedDelete(domain, quotaUsed); } } public override void DeleteFiles(string domain, string path, string pattern, bool recursive) { var makedPath = MakePath(domain, path) + '/'; var objToDel = GetS3Objects(domain, path) .Where(x => Wildcard.IsMatch(pattern, Path.GetFileName(x.Key)) && (recursive || !x.Key.Remove(0, makedPath.Length).Contains('/')) ); using (var client = GetClient()) { foreach (var s3Object in objToDel) { Recycle(client, domain, s3Object.Key); var deleteRequest = new DeleteObjectRequest { BucketName = _bucket, Key = s3Object.Key }; client.DeleteObject(deleteRequest); QuotaUsedDelete(domain, Convert.ToInt64(s3Object.Size)); } } } public override void DeleteFiles(string domain, string path, DateTime fromDate, DateTime toDate) { var objToDel = GetS3Objects(domain, path) .Where(x => x.LastModified >= fromDate && x.LastModified <= toDate); using (var client = GetClient()) { foreach (var s3Object in objToDel) { Recycle(client, domain, s3Object.Key); var deleteRequest = new DeleteObjectRequest { BucketName = _bucket, Key = s3Object.Key }; client.DeleteObject(deleteRequest); QuotaUsedDelete(domain, Convert.ToInt64(s3Object.Size)); } } } public override void MoveDirectory(string srcdomain, string srcdir, string newdomain, string newdir) { var srckey = MakePath(srcdomain, srcdir); var dstkey = MakePath(newdomain, newdir); //List files from src using (var client = GetClient()) { var request = new ListObjectsRequest { BucketName = _bucket, Prefix = srckey }; var response = client.ListObjects(request); foreach (var s3Object in response.S3Objects) { client.CopyObject(new CopyObjectRequest { SourceBucket = _bucket, SourceKey = s3Object.Key, DestinationBucket = _bucket, DestinationKey = s3Object.Key.Replace(srckey, dstkey), CannedACL = GetDomainACL(newdomain), ServerSideEncryptionMethod = _sse }); client.DeleteObject(new DeleteObjectRequest { BucketName = _bucket, Key = s3Object.Key }); } } } public override Uri Move(string srcdomain, string srcpath, string newdomain, string newpath, bool quotaCheckFileSize = true) { using (var client = GetClient()) { var srcKey = MakePath(srcdomain, srcpath); var dstKey = MakePath(newdomain, newpath); var size = GetFileSize(srcdomain, srcpath); var request = new CopyObjectRequest { SourceBucket = _bucket, SourceKey = srcKey, DestinationBucket = _bucket, DestinationKey = dstKey, CannedACL = GetDomainACL(newdomain), MetadataDirective = S3MetadataDirective.REPLACE, ServerSideEncryptionMethod = _sse }; client.CopyObject(request); Delete(srcdomain, srcpath); QuotaUsedDelete(srcdomain, size); QuotaUsedAdd(newdomain, size, quotaCheckFileSize); return GetUri(newdomain, newpath); } } public override Uri SaveTemp(string domain, out string assignedPath, Stream stream) { assignedPath = Guid.NewGuid().ToString(); return Save(domain, assignedPath, stream); } public override string[] ListDirectoriesRelative(string domain, string path, bool recursive) { return GetS3Objects(domain, path) .Select(x => x.Key.Substring((MakePath(domain, path) + "/").Length)) .ToArray(); } public override string SavePrivate(string domain, string path, Stream stream, DateTime expires) { using (var client = GetClient()) using (var uploader = new TransferUtility(client)) { var objectKey = MakePath(domain, path); var buffered = stream.GetBuffered(); var request = new TransferUtilityUploadRequest { BucketName = _bucket, Key = objectKey, CannedACL = S3CannedACL.BucketOwnerFullControl, ContentType = "application/octet-stream", InputStream = buffered, Headers = { CacheControl = string.Format("public, maxage={0}", (int)TimeSpan.FromDays(5).TotalSeconds), ExpiresUtc = DateTime.UtcNow.Add(TimeSpan.FromDays(5)), ContentDisposition = "attachment", } }; request.Metadata.Add("private-expire", expires.ToFileTimeUtc().ToString(CultureInfo.InvariantCulture)); uploader.Upload(request); //Get presigned url var pUrlRequest = new GetPreSignedUrlRequest { BucketName = _bucket, Expires = expires, Key = objectKey, Protocol = Protocol.HTTP, Verb = HttpVerb.GET }; string url = client.GetPreSignedURL(pUrlRequest); //TODO: CNAME! return url; } } public override void DeleteExpired(string domain, string path, TimeSpan oldThreshold) { using (var client = GetClient()) { var s3Obj = GetS3Objects(domain, path); foreach (var s3Object in s3Obj) { var request = new GetObjectMetadataRequest { BucketName = _bucket, Key = s3Object.Key }; var metadata = client.GetObjectMetadata(request); var privateExpireKey = metadata.Metadata["private-expire"]; if (string.IsNullOrEmpty(privateExpireKey)) continue; long fileTime; if (!long.TryParse(privateExpireKey, out fileTime)) continue; if (DateTime.UtcNow <= DateTime.FromFileTimeUtc(fileTime)) continue; //Delete it var deleteObjectRequest = new DeleteObjectRequest { BucketName = _bucket, Key = s3Object.Key }; client.DeleteObject(deleteObjectRequest); } } } public override string GetUploadUrl() { return GetUriInternal(string.Empty).ToString(); } public override string GetPostParams(string domain, string directoryPath, long maxUploadSize, string contentType, string contentDisposition) { var key = MakePath(domain, directoryPath) + "/"; //Generate policy string sign; var policyBase64 = GetPolicyBase64(key, string.Empty, contentType, contentDisposition, maxUploadSize, out sign); var postBuilder = new StringBuilder(); postBuilder.Append("{"); postBuilder.AppendFormat("\"key\":\"{0}${{filename}}\",", key); postBuilder.AppendFormat("\"acl\":\"public-read\","); postBuilder.AppendFormat("\"key\":\"{0}\",", key); postBuilder.AppendFormat("\"success_action_status\":\"{0}\",", 201); if (!string.IsNullOrEmpty(contentType)) postBuilder.AppendFormat("\"Content-Type\":\"{0}\",", contentType); if (!string.IsNullOrEmpty(contentDisposition)) postBuilder.AppendFormat("\"Content-Disposition\":\"{0}\",", contentDisposition); postBuilder.AppendFormat("\"AWSAccessKeyId\":\"{0}\",", _accessKeyId); postBuilder.AppendFormat("\"Policy\":\"{0}\",", policyBase64); postBuilder.AppendFormat("\"Signature\":\"{0}\"", sign); postBuilder.AppendFormat("\"SignatureVersion\":\"{0}\"", 2); postBuilder.AppendFormat("\"SignatureMethod\":\"{0}\"", "HmacSHA1"); postBuilder.Append("}"); return postBuilder.ToString(); } public override string GetUploadForm(string domain, string directoryPath, string redirectTo, long maxUploadSize, string contentType, string contentDisposition, string submitLabel) { var destBucket = GetUploadUrl(); var key = MakePath(domain, directoryPath) + "/"; //Generate policy string sign; var policyBase64 = GetPolicyBase64(key, redirectTo, contentType, contentDisposition, maxUploadSize, out sign); var formBuilder = new StringBuilder(); formBuilder.AppendFormat("<form action=\"{0}\" method=\"post\" enctype=\"multipart/form-data\">", destBucket); formBuilder.AppendFormat("<input type=\"hidden\" name=\"key\" value=\"{0}${{filename}}\" />", key); formBuilder.Append("<input type=\"hidden\" name=\"acl\" value=\"public-read\" />"); if (!string.IsNullOrEmpty(redirectTo)) formBuilder.AppendFormat("<input type=\"hidden\" name=\"success_action_redirect\" value=\"{0}\" />", redirectTo); formBuilder.AppendFormat("<input type=\"hidden\" name=\"success_action_status\" value=\"{0}\" />", 201); if (!string.IsNullOrEmpty(contentType)) formBuilder.AppendFormat("<input type=\"hidden\" name=\"Content-Type\" value=\"{0}\" />", contentType); if (!string.IsNullOrEmpty(contentDisposition)) formBuilder.AppendFormat("<input type=\"hidden\" name=\"Content-Disposition\" value=\"{0}\" />", contentDisposition); formBuilder.AppendFormat("<input type=\"hidden\" name=\"AWSAccessKeyId\" value=\"{0}\"/>", _accessKeyId); formBuilder.AppendFormat("<input type=\"hidden\" name=\"Policy\" value=\"{0}\" />", policyBase64); formBuilder.AppendFormat("<input type=\"hidden\" name=\"Signature\" value=\"{0}\" />", sign); formBuilder.AppendFormat("<input type=\"hidden\" name=\"SignatureVersion\" value=\"{0}\" />", 2); formBuilder.AppendFormat("<input type=\"hidden\" name=\"SignatureMethod\" value=\"{0}\" />", "HmacSHA1"); formBuilder.AppendFormat("<input type=\"file\" name=\"file\" />"); formBuilder.AppendFormat("<input type=\"submit\" name=\"submit\" value=\"{0}\" /></form>", submitLabel); return formBuilder.ToString(); } private string GetPolicyBase64(string key, string redirectTo, string contentType, string contentDisposition, long maxUploadSize, out string sign) { var policyBuilder = new StringBuilder(); policyBuilder.AppendFormat("{{\"expiration\": \"{0}\",\"conditions\":[", DateTime.UtcNow.AddMinutes(15).ToString(AWSSDKUtils.ISO8601DateFormat, CultureInfo.InvariantCulture)); policyBuilder.AppendFormat("{{\"bucket\": \"{0}\"}},", _bucket); policyBuilder.AppendFormat("[\"starts-with\", \"$key\", \"{0}\"],", key); policyBuilder.Append("{\"acl\": \"public-read\"},"); if (!string.IsNullOrEmpty(redirectTo)) { policyBuilder.AppendFormat("{{\"success_action_redirect\": \"{0}\"}},", redirectTo); } policyBuilder.AppendFormat("{{\"success_action_status\": \"{0}\"}},", 201); if (!string.IsNullOrEmpty(contentType)) { policyBuilder.AppendFormat("[\"eq\", \"$Content-Type\", \"{0}\"],", contentType); } if (!string.IsNullOrEmpty(contentDisposition)) { policyBuilder.AppendFormat("[\"eq\", \"$Content-Disposition\", \"{0}\"],", contentDisposition); } policyBuilder.AppendFormat("[\"content-length-range\", 0, {0}]", maxUploadSize); policyBuilder.Append("]}"); var policyBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(policyBuilder.ToString())); //sign = AWSSDKUtils.HMACSign(policyBase64, _secretAccessKeyId, new HMACSHA1()); var algorithm = new HMACSHA1 { Key = Encoding.UTF8.GetBytes(_secretAccessKeyId) }; try { algorithm.Key = Encoding.UTF8.GetBytes(key); sign = Convert.ToBase64String(algorithm.ComputeHash(Encoding.UTF8.GetBytes(policyBase64))); } finally { algorithm.Clear(); } return policyBase64; } public override string GetUploadedUrl(string domain, string directoryPath) { if (HttpContext.Current != null) { var buket = HttpContext.Current.Request.QueryString["bucket"]; var key = HttpContext.Current.Request.QueryString["key"]; var etag = HttpContext.Current.Request.QueryString["etag"]; var destkey = MakePath(domain, directoryPath) + "/"; if (!string.IsNullOrEmpty(buket) && !string.IsNullOrEmpty(key) && string.Equals(buket, _bucket) && key.StartsWith(destkey)) { var domainpath = key.Substring(MakePath(domain, string.Empty).Length); var skipQuota = false; if (HttpContext.Current.Session != null) { var isCounted = HttpContext.Current.Session[etag]; skipQuota = isCounted != null; } //Add to quota controller if (QuotaController != null && !skipQuota) { try { var size = GetFileSize(domain, domainpath); QuotaUsedAdd(domain, size); if (HttpContext.Current.Session != null) { HttpContext.Current.Session.Add(etag, size); } } catch (Exception) { } } return GetUriInternal(key).ToString(); } } return string.Empty; } public override string[] ListFilesRelative(string domain, string path, string pattern, bool recursive) { return GetS3Objects(domain, path) .Where(x => Wildcard.IsMatch(pattern, Path.GetFileName(x.Key))) .Select(x => x.Key.Substring((MakePath(domain, path) + "/").Length).TrimStart('/')) .ToArray(); } private bool CheckKey(string domain, string key) { return !string.IsNullOrEmpty(domain) || _domains.All(configuredDomains => !key.StartsWith(MakePath(configuredDomains, ""))); } public override bool IsFile(string domain, string path) { using (var client = GetClient()) { var a = new Amazon.S3.IO.S3FileInfo(client, _bucket, MakePath(domain, path)); return a.Exists; } } public override async Task<bool> IsFileAsync(string domain, string path) { using (var client = GetClient()) { try { var getObjectMetadataRequest = new GetObjectMetadataRequest { BucketName = _bucket, Key = MakePath(domain, path) }; await client.GetObjectMetadataAsync(getObjectMetadataRequest); return true; } catch (AmazonS3Exception ex) { if (string.Equals(ex.ErrorCode, "NoSuchBucket")) { return false; } if (string.Equals(ex.ErrorCode, "NotFound")) { return false; } throw; } } } public override bool IsDirectory(string domain, string path) { using (var client = GetClient()) { var a = new Amazon.S3.IO.S3DirectoryInfo(client, _bucket, MakePath(domain, path)); return a.Exists; } } public override void DeleteDirectory(string domain, string path) { DeleteFiles(domain, path, "*", true); } public override long GetFileSize(string domain, string path) { using (var client = GetClient()) { var request = new ListObjectsRequest { BucketName = _bucket, Prefix = (MakePath(domain, path)) }; var response = client.ListObjects(request); if (response.S3Objects.Count > 0) { return response.S3Objects[0].Size; } throw new FileNotFoundException("file not found", path); } } public override async Task<long> GetFileSizeAsync(string domain, string path) { using (var client = GetClient()) { var request = new ListObjectsRequest { BucketName = _bucket, Prefix = (MakePath(domain, path)) }; var response = await client.ListObjectsAsync(request); if (response.S3Objects.Count > 0) { return response.S3Objects[0].Size; } throw new FileNotFoundException("file not found", path); } } public override long GetDirectorySize(string domain, string path) { if (!IsDirectory(domain, path)) throw new FileNotFoundException("directory not found", path); return GetS3Objects(domain, path) .Where(x => Wildcard.IsMatch("*.*", Path.GetFileName(x.Key))) .Sum(x => x.Size); } public override long ResetQuota(string domain) { if (QuotaController != null) { var objects = GetS3Objects(domain); var size = objects.Sum(s3Object => s3Object.Size); QuotaController.QuotaUsedSet(_modulename, domain, _dataList.GetData(domain), size); return size; } return 0; } public override long GetUsedQuota(string domain) { var objects = GetS3Objects(domain); return objects.Sum(s3Object => s3Object.Size); } public override Uri Copy(string srcdomain, string srcpath, string newdomain, string newpath) { using (var client = GetClient()) { var srcKey = MakePath(srcdomain, srcpath); var dstKey = MakePath(newdomain, newpath); var size = GetFileSize(srcdomain, srcpath); var request = new CopyObjectRequest { SourceBucket = _bucket, SourceKey = srcKey, DestinationBucket = _bucket, DestinationKey = dstKey, CannedACL = GetDomainACL(newdomain), MetadataDirective = S3MetadataDirective.REPLACE, ServerSideEncryptionMethod = _sse }; client.CopyObject(request); QuotaUsedAdd(newdomain, size); return GetUri(newdomain, newpath); } } public override void CopyDirectory(string srcdomain, string srcdir, string newdomain, string newdir) { var srckey = MakePath(srcdomain, srcdir); var dstkey = MakePath(newdomain, newdir); //List files from src using (var client = GetClient()) { var request = new ListObjectsRequest { BucketName = _bucket, Prefix = srckey }; var response = client.ListObjects(request); foreach (var s3Object in response.S3Objects) { client.CopyObject(new CopyObjectRequest { SourceBucket = _bucket, SourceKey = s3Object.Key, DestinationBucket = _bucket, DestinationKey = s3Object.Key.Replace(srckey, dstkey), CannedACL = GetDomainACL(newdomain), ServerSideEncryptionMethod = _sse }); QuotaUsedAdd(newdomain, s3Object.Size); } } } private IEnumerable<S3Object> GetS3ObjectsByPath(string domain, string path) { using (var client = GetClient()) { var request = new ListObjectsRequest { BucketName = _bucket, Prefix = path, MaxKeys = (1000) }; var objects = new List<S3Object>(); ListObjectsResponse response; do { response = client.ListObjects(request); objects.AddRange(response.S3Objects.Where(entry => CheckKey(domain, entry.Key))); request.Marker = response.NextMarker; } while (response.IsTruncated); return objects; } } private IEnumerable<S3Object> GetS3Objects(string domain, string path = "", bool recycle = false) { path = MakePath(domain, path) + '/'; var obj = GetS3ObjectsByPath(domain, path).ToList(); if (string.IsNullOrEmpty(_recycleDir) || !recycle) return obj; obj.AddRange(GetS3ObjectsByPath(domain, GetRecyclePath(path))); return obj; } public override IDataStore Configure(IDictionary<string, string> props) { _accessKeyId = props["acesskey"]; _secretAccessKeyId = props["secretaccesskey"]; _bucket = props["bucket"]; if (props.ContainsKey("recycleDir")) { _recycleDir = props["recycleDir"]; } if (props.ContainsKey("region") && !string.IsNullOrEmpty(props["region"])) { _region = props["region"]; } if (props.ContainsKey("serviceurl") && !string.IsNullOrEmpty(props["serviceurl"])) { _serviceurl = props["serviceurl"]; } if (props.ContainsKey("forcepathstyle")) { bool fps; if (bool.TryParse(props["forcepathstyle"], out fps)) { _forcepathstyle = fps; } } if (props.ContainsKey("usehttp")) { bool uh; if (bool.TryParse(props["usehttp"], out uh)) { _useHttp = uh; } } if (props.ContainsKey("sse") && !string.IsNullOrEmpty(props["sse"])) { switch (props["sse"].ToLower()) { case "none": _sse = ServerSideEncryptionMethod.None; break; case "aes256": _sse = ServerSideEncryptionMethod.AES256; break; case "awskms": _sse = ServerSideEncryptionMethod.AWSKMS; break; default: _sse = ServerSideEncryptionMethod.None; break; } } _bucketRoot = props.ContainsKey("cname") && Uri.IsWellFormedUriString(props["cname"], UriKind.Absolute) ? new Uri(props["cname"], UriKind.Absolute) : new Uri(String.Format("http://s3.{1}.amazonaws.com/{0}/", _bucket, _region), UriKind.Absolute); _bucketSSlRoot = props.ContainsKey("cnamessl") && Uri.IsWellFormedUriString(props["cnamessl"], UriKind.Absolute) ? new Uri(props["cnamessl"], UriKind.Absolute) : new Uri(String.Format("https://s3.{1}.amazonaws.com/{0}/", _bucket, _region), UriKind.Absolute); if (props.ContainsKey("lower")) { bool.TryParse(props["lower"], out _lowerCasing); } if (props.ContainsKey("cloudfront")) { bool.TryParse(props["cloudfront"], out _revalidateCloudFront); } if (props.ContainsKey("distribution")) { _distributionId = props["distribution"]; } if (props.ContainsKey("subdir")) { _subDir = props["subdir"]; } return this; } private string MakePath(string domain, string path) { string result; path = path.TrimStart('\\', '/').TrimEnd('/').Replace('\\', '/'); if (!String.IsNullOrEmpty(_subDir)) { if (_subDir.Length == 1 && (_subDir[0] == '/' || _subDir[0] == '\\')) result = path; else result = String.Format("{0}/{1}", _subDir, path); // Ignory all, if _subDir is not null } else//Key combined from module+domain+filename result = string.Format("{0}/{1}/{2}/{3}", _tenant, _modulename, domain, path); result = result.Replace("//", "/").TrimStart('/').TrimEnd('/'); if (_lowerCasing) { result = result.ToLowerInvariant(); } return result; } private string GetRecyclePath(string path) { return string.IsNullOrEmpty(_recycleDir) ? "" : string.Format("{0}/{1}", _recycleDir, path.TrimStart('/')); } private void Recycle(IAmazonS3 client, string domain, string key) { if (string.IsNullOrEmpty(_recycleDir)) return; var copyObjectRequest = new CopyObjectRequest { SourceBucket = _bucket, SourceKey = key, DestinationBucket = _bucket, DestinationKey = GetRecyclePath(key), CannedACL = GetDomainACL(domain), MetadataDirective = S3MetadataDirective.REPLACE, ServerSideEncryptionMethod = _sse, StorageClass = S3StorageClass.Glacier, }; client.CopyObject(copyObjectRequest); } private IAmazonCloudFront GetCloudFrontClient() { var cfg = new AmazonCloudFrontConfig { MaxErrorRetry = 3 }; return new AmazonCloudFrontClient(_accessKeyId, _secretAccessKeyId, cfg); } private IAmazonS3 GetClient() { var cfg = new AmazonS3Config { MaxErrorRetry = 3 }; if (!String.IsNullOrEmpty(_serviceurl)) { cfg.ServiceURL = _serviceurl; cfg.ForcePathStyle = _forcepathstyle; } else { cfg.RegionEndpoint = RegionEndpoint.GetBySystemName(_region); } cfg.UseHttp = _useHttp; return new AmazonS3Client(_accessKeyId, _secretAccessKeyId, cfg); } public Stream GetWriteStream(string domain, string path) { throw new NotSupportedException(); } private class ResponseStreamWrapper : Stream { private readonly GetObjectResponse _response; public ResponseStreamWrapper(GetObjectResponse response) { if (response == null) throw new ArgumentNullException("response"); _response = response; } public override bool CanRead { get { return _response.ResponseStream.CanRead; } } public override bool CanSeek { get { return _response.ResponseStream.CanSeek; } } public override bool CanWrite { get { return _response.ResponseStream.CanWrite; } } public override long Length { get { return _response.ContentLength; } } public override long Position { get { return _response.ResponseStream.Position; } set { _response.ResponseStream.Position = value; } } public override int Read(byte[] buffer, int offset, int count) { return _response.ResponseStream.Read(buffer, offset, count); } public override long Seek(long offset, SeekOrigin origin) { return _response.ResponseStream.Seek(offset, origin); } public override void SetLength(long value) { _response.ResponseStream.SetLength(value); } public override void Write(byte[] buffer, int offset, int count) { _response.ResponseStream.Write(buffer, offset, count); } public override void Flush() { _response.ResponseStream.Flush(); } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) _response.Dispose(); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.ProjectManagement; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateType { internal abstract partial class AbstractGenerateTypeService<TService, TSimpleNameSyntax, TObjectCreationExpressionSyntax, TExpressionSyntax, TTypeDeclarationSyntax, TArgumentSyntax> { protected abstract bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType); private partial class Editor { private TService _service; private TargetProjectChangeInLanguage _targetProjectChangeInLanguage = TargetProjectChangeInLanguage.NoChange; private IGenerateTypeService _targetLanguageService; private readonly SemanticDocument _document; private readonly State _state; private readonly bool _intoNamespace; private readonly bool _inNewFile; private readonly bool _fromDialog; private readonly GenerateTypeOptionsResult _generateTypeOptionsResult; private readonly CancellationToken _cancellationToken; public Editor( TService service, SemanticDocument document, State state, bool intoNamespace, bool inNewFile, CancellationToken cancellationToken) { _service = service; _document = document; _state = state; _intoNamespace = intoNamespace; _inNewFile = inNewFile; _cancellationToken = cancellationToken; } public Editor( TService service, SemanticDocument document, State state, bool fromDialog, GenerateTypeOptionsResult generateTypeOptionsResult, CancellationToken cancellationToken) { _service = service; _document = document; _state = state; _fromDialog = fromDialog; _generateTypeOptionsResult = generateTypeOptionsResult; _cancellationToken = cancellationToken; } private enum TargetProjectChangeInLanguage { NoChange, CSharpToVisualBasic, VisualBasicToCSharp } internal async Task<IEnumerable<CodeActionOperation>> GetOperationsAsync() { // Check to see if it is from GFU Dialog if (!_fromDialog) { // Generate the actual type declaration. var namedType = GenerateNamedType(); if (_intoNamespace) { if (_inNewFile) { // Generating into a new file is somewhat complicated. var documentName = GetTypeName(_state) + _service.DefaultFileExtension; return await GetGenerateInNewFileOperationsAsync( namedType, documentName, null, true, null, _document.Project, _document.Project, isDialog: false).ConfigureAwait(false); } else { return await GetGenerateIntoContainingNamespaceOperationsAsync(namedType).ConfigureAwait(false); } } else { return await GetGenerateIntoTypeOperationsAsync(namedType).ConfigureAwait(false); } } else { var namedType = GenerateNamedType(_generateTypeOptionsResult); // Honor the options from the dialog // Check to see if the type is requested to be generated in cross language Project // e.g.: C# -> VB or VB -> C# if (_document.Project.Language != _generateTypeOptionsResult.Project.Language) { _targetProjectChangeInLanguage = _generateTypeOptionsResult.Project.Language == LanguageNames.CSharp ? TargetProjectChangeInLanguage.VisualBasicToCSharp : TargetProjectChangeInLanguage.CSharpToVisualBasic; // Get the cross language service _targetLanguageService = _generateTypeOptionsResult.Project.LanguageServices.GetService<IGenerateTypeService>(); } if (_generateTypeOptionsResult.IsNewFile) { return await GetGenerateInNewFileOperationsAsync( namedType, _generateTypeOptionsResult.NewFileName, _generateTypeOptionsResult.Folders, _generateTypeOptionsResult.AreFoldersValidIdentifiers, _generateTypeOptionsResult.FullFilePath, _generateTypeOptionsResult.Project, _document.Project, isDialog: true).ConfigureAwait(false); } else { return await GetGenerateIntoExistingDocumentAsync( namedType, _document.Project, _generateTypeOptionsResult, isDialog: true).ConfigureAwait(false); } } } private string GetNamespaceToGenerateInto() { var namespaceToGenerateInto = _state.NamespaceToGenerateInOpt.Trim(); var rootNamespace = _service.GetRootNamespace(_document.SemanticModel.Compilation.Options).Trim(); if (!string.IsNullOrWhiteSpace(rootNamespace)) { if (namespaceToGenerateInto == rootNamespace || namespaceToGenerateInto.StartsWith(rootNamespace + ".")) { namespaceToGenerateInto = namespaceToGenerateInto.Substring(rootNamespace.Length); } } return namespaceToGenerateInto; } private string GetNamespaceToGenerateIntoForUsageWithNamespace(Project targetProject, Project triggeringProject) { var namespaceToGenerateInto = _state.NamespaceToGenerateInOpt.Trim(); if (targetProject.Language == LanguageNames.CSharp || targetProject == triggeringProject) { // If the target project is C# project then we don't have to make any modification to the namespace // or // This is a VB project generation into itself which requires no change as well return namespaceToGenerateInto; } // If the target Project is VB then we have to check if the RootNamespace of the VB project is the parent most namespace of the type being generated // True, Remove the RootNamespace // False, Add Global to the Namespace Contract.Assert(targetProject.Language == LanguageNames.VisualBasic); IGenerateTypeService targetLanguageService = null; if (_document.Project.Language == LanguageNames.VisualBasic) { targetLanguageService = _service; } else { Debug.Assert(_targetLanguageService != null); targetLanguageService = _targetLanguageService; } var rootNamespace = targetLanguageService.GetRootNamespace(targetProject.CompilationOptions).Trim(); if (!string.IsNullOrWhiteSpace(rootNamespace)) { var rootNamespaceLength = CheckIfRootNamespacePresentInNamespace(namespaceToGenerateInto, rootNamespace); if (rootNamespaceLength > -1) { // True, Remove the RootNamespace namespaceToGenerateInto = namespaceToGenerateInto.Substring(rootNamespaceLength); } else { // False, Add Global to the Namespace namespaceToGenerateInto = AddGlobalDotToTheNamespace(namespaceToGenerateInto); } } else { // False, Add Global to the Namespace namespaceToGenerateInto = AddGlobalDotToTheNamespace(namespaceToGenerateInto); } return namespaceToGenerateInto; } private string AddGlobalDotToTheNamespace(string namespaceToBeGenerated) { return "Global." + namespaceToBeGenerated; } // Returns the length of the meaningful rootNamespace substring part of namespaceToGenerateInto private int CheckIfRootNamespacePresentInNamespace(string namespaceToGenerateInto, string rootNamespace) { if (namespaceToGenerateInto == rootNamespace) { return rootNamespace.Length; } if (namespaceToGenerateInto.StartsWith(rootNamespace + ".")) { return rootNamespace.Length + 1; } return -1; } private void AddFoldersToNamespaceContainers(List<string> container, IList<string> folders) { // Add the folder as part of the namespace if there are not empty if (folders != null && folders.Count != 0) { // Remove the empty entries and replace the spaces in the folder name to '_' var refinedFolders = folders.Where(n => n != null && !n.IsEmpty()).Select(n => n.Replace(' ', '_')).ToArray(); container.AddRange(refinedFolders); } } private async Task<IEnumerable<CodeActionOperation>> GetGenerateInNewFileOperationsAsync( INamedTypeSymbol namedType, string documentName, IList<string> folders, bool areFoldersValidIdentifiers, string fullFilePath, Project projectToBeUpdated, Project triggeringProject, bool isDialog) { // First, we fork the solution with a new, empty, file in it. var newDocumentId = DocumentId.CreateNewId(projectToBeUpdated.Id, debugName: documentName); var newSolution = projectToBeUpdated.Solution.AddDocument(newDocumentId, documentName, string.Empty, folders, fullFilePath); // Now we get the semantic model for that file we just added. We do that to get the // root namespace in that new document, along with location for that new namespace. // That way, when we use the code gen service we can say "add this symbol to the // root namespace" and it will pick the one in the new file. var newDocument = newSolution.GetDocument(newDocumentId); var newSemanticModel = await newDocument.GetSemanticModelAsync(_cancellationToken).ConfigureAwait(false); var enclosingNamespace = newSemanticModel.GetEnclosingNamespace(0, _cancellationToken); var namespaceContainersAndUsings = GetNamespaceContainersAndAddUsingsOrImport(isDialog, folders, areFoldersValidIdentifiers, projectToBeUpdated, triggeringProject); var containers = namespaceContainersAndUsings.Item1; var includeUsingsOrImports = namespaceContainersAndUsings.Item2; var rootNamespaceOrType = namedType.GenerateRootNamespaceOrType(containers); // Now, actually ask the code gen service to add this namespace or type to the root // namespace in the new file. This will properly generate the code, and add any // additional niceties like imports/usings. var codeGenResult = await CodeGenerator.AddNamespaceOrTypeDeclarationAsync( newSolution, enclosingNamespace, rootNamespaceOrType, new CodeGenerationOptions(newSemanticModel.SyntaxTree.GetLocation(new TextSpan())), _cancellationToken).ConfigureAwait(false); // containers is determined to be // 1: folders -> if triggered from Dialog // 2: containers -> if triggered not from a Dialog but from QualifiedName // 3: triggering document folder structure -> if triggered not from a Dialog and a SimpleName var adjustedContainer = isDialog ? folders : _state.SimpleName != _state.NameOrMemberAccessExpression ? containers.ToList() : _document.Document.Folders.ToList(); // Now, take the code that would be generated and actually create an edit that would // produce a document with that code in it. return CreateAddDocumentAndUpdateUsingsOrImportsOperations( projectToBeUpdated, triggeringProject, documentName, await codeGenResult.GetSyntaxRootAsync(_cancellationToken).ConfigureAwait(false), _document.Document, includeUsingsOrImports, adjustedContainer, SourceCodeKind.Regular, _cancellationToken); } private IEnumerable<CodeActionOperation> CreateAddDocumentAndUpdateUsingsOrImportsOperations( Project projectToBeUpdated, Project triggeringProject, string documentName, SyntaxNode root, Document generatingDocument, string includeUsingsOrImports, IList<string> containers, SourceCodeKind sourceCodeKind, CancellationToken cancellationToken) { // TODO(cyrusn): make sure documentId is unique. var documentId = DocumentId.CreateNewId(projectToBeUpdated.Id, documentName); var updatedSolution = projectToBeUpdated.Solution.AddDocument(DocumentInfo.Create( documentId, documentName, containers, sourceCodeKind)); updatedSolution = updatedSolution.WithDocumentSyntaxRoot(documentId, root, PreservationMode.PreserveIdentity); // Update the Generating Document with a using if required if (includeUsingsOrImports != null) { updatedSolution = _service.TryAddUsingsOrImportToDocument(updatedSolution, null, _document.Document, _state.SimpleName, includeUsingsOrImports, cancellationToken); } // Add reference of the updated project to the triggering Project if they are 2 different projects updatedSolution = AddProjectReference(projectToBeUpdated, triggeringProject, updatedSolution); return new CodeActionOperation[] { new ApplyChangesOperation(updatedSolution), new OpenDocumentOperation(documentId) }; } private static Solution AddProjectReference(Project projectToBeUpdated, Project triggeringProject, Solution updatedSolution) { if (projectToBeUpdated != triggeringProject) { if (!triggeringProject.ProjectReferences.Any(pr => pr.ProjectId == projectToBeUpdated.Id)) { updatedSolution = updatedSolution.AddProjectReference(triggeringProject.Id, new ProjectReference(projectToBeUpdated.Id)); } } return updatedSolution; } private async Task<IEnumerable<CodeActionOperation>> GetGenerateIntoContainingNamespaceOperationsAsync(INamedTypeSymbol namedType) { var enclosingNamespace = _document.SemanticModel.GetEnclosingNamespace( _state.SimpleName.SpanStart, _cancellationToken); var solution = _document.Project.Solution; var codeGenResult = await CodeGenerator.AddNamedTypeDeclarationAsync( solution, enclosingNamespace, namedType, new CodeGenerationOptions(afterThisLocation: _document.SyntaxTree.GetLocation(_state.SimpleName.Span)), _cancellationToken) .ConfigureAwait(false); return new CodeActionOperation[] { new ApplyChangesOperation(codeGenResult.Project.Solution) }; } private async Task<IEnumerable<CodeActionOperation>> GetGenerateIntoExistingDocumentAsync( INamedTypeSymbol namedType, Project triggeringProject, GenerateTypeOptionsResult generateTypeOptionsResult, bool isDialog) { var root = await generateTypeOptionsResult.ExistingDocument.GetSyntaxRootAsync(_cancellationToken).ConfigureAwait(false); var folders = generateTypeOptionsResult.ExistingDocument.Folders; var namespaceContainersAndUsings = GetNamespaceContainersAndAddUsingsOrImport(isDialog, new List<string>(folders), generateTypeOptionsResult.AreFoldersValidIdentifiers, generateTypeOptionsResult.Project, triggeringProject); var containers = namespaceContainersAndUsings.Item1; var includeUsingsOrImports = namespaceContainersAndUsings.Item2; Tuple<INamespaceSymbol, INamespaceOrTypeSymbol, Location> enclosingNamespaceGeneratedTypeToAddAndLocation = null; if (_targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange) { enclosingNamespaceGeneratedTypeToAddAndLocation = _service.GetOrGenerateEnclosingNamespaceSymbol( namedType, containers, generateTypeOptionsResult.ExistingDocument, root, _cancellationToken).WaitAndGetResult(_cancellationToken); } else { enclosingNamespaceGeneratedTypeToAddAndLocation = _targetLanguageService.GetOrGenerateEnclosingNamespaceSymbol( namedType, containers, generateTypeOptionsResult.ExistingDocument, root, _cancellationToken).WaitAndGetResult(_cancellationToken); } var solution = _document.Project.Solution; var codeGenResult = await CodeGenerator.AddNamespaceOrTypeDeclarationAsync( solution, enclosingNamespaceGeneratedTypeToAddAndLocation.Item1, enclosingNamespaceGeneratedTypeToAddAndLocation.Item2, new CodeGenerationOptions(afterThisLocation: enclosingNamespaceGeneratedTypeToAddAndLocation.Item3), _cancellationToken) .ConfigureAwait(false); var newRoot = await codeGenResult.GetSyntaxRootAsync(_cancellationToken).ConfigureAwait(false); var updatedSolution = solution.WithDocumentSyntaxRoot(generateTypeOptionsResult.ExistingDocument.Id, newRoot, PreservationMode.PreserveIdentity); // Update the Generating Document with a using if required if (includeUsingsOrImports != null) { updatedSolution = _service.TryAddUsingsOrImportToDocument( updatedSolution, generateTypeOptionsResult.ExistingDocument.Id == _document.Document.Id ? newRoot : null, _document.Document, _state.SimpleName, includeUsingsOrImports, _cancellationToken); } updatedSolution = AddProjectReference(generateTypeOptionsResult.Project, triggeringProject, updatedSolution); return new CodeActionOperation[] { new ApplyChangesOperation(updatedSolution) }; } private Tuple<string[], string> GetNamespaceContainersAndAddUsingsOrImport( bool isDialog, IList<string> folders, bool areFoldersValidIdentifiers, Project targetProject, Project triggeringProject) { string includeUsingsOrImports = null; if (!areFoldersValidIdentifiers) { folders = SpecializedCollections.EmptyList<string>(); } // Now actually create the symbol that we want to add to the root namespace. The // symbol may either be a named type (if we're not generating into a namespace) or // it may be a namespace symbol. string[] containers = null; if (!isDialog) { // Not generated from the Dialog containers = GetNamespaceToGenerateInto().Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); } else if (!_service.IsSimpleName(_state.NameOrMemberAccessExpression)) { // If the usage was with a namespace containers = GetNamespaceToGenerateIntoForUsageWithNamespace(targetProject, triggeringProject).Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); } else { // Generated from the Dialog List<string> containerList = new List<string>(); string rootNamespaceOfTheProjectGeneratedInto; if (_targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange) { rootNamespaceOfTheProjectGeneratedInto = _service.GetRootNamespace(_generateTypeOptionsResult.Project.CompilationOptions).Trim(); } else { rootNamespaceOfTheProjectGeneratedInto = _targetLanguageService.GetRootNamespace(_generateTypeOptionsResult.Project.CompilationOptions).Trim(); } var projectManagementService = _document.Project.Solution.Workspace.Services.GetService<IProjectManagementService>(); var defaultNamespace = projectManagementService.GetDefaultNamespace(targetProject, targetProject.Solution.Workspace); // Case 1 : If the type is generated into the same C# project or // Case 2 : If the type is generated from a C# project to a C# Project // Case 3 : If the Type is generated from a VB Project to a C# Project // Using and Namespace will be the DefaultNamespace + Folder Structure if ((_document.Project == _generateTypeOptionsResult.Project && _document.Project.Language == LanguageNames.CSharp) || (_targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange && _generateTypeOptionsResult.Project.Language == LanguageNames.CSharp) || _targetProjectChangeInLanguage == TargetProjectChangeInLanguage.VisualBasicToCSharp) { if (!string.IsNullOrWhiteSpace(defaultNamespace)) { containerList.Add(defaultNamespace); } // Populate the ContainerList AddFoldersToNamespaceContainers(containerList, folders); containers = containerList.ToArray(); includeUsingsOrImports = string.Join(".", containerList.ToArray()); } // Case 4 : If the type is generated into the same VB project or // Case 5 : If Type is generated from a VB Project to VB Project // Case 6 : If Type is generated from a C# Project to VB Project // Namespace will be Folder Structure and Import will have the RootNamespace of the project generated into as part of the Imports if ((_document.Project == _generateTypeOptionsResult.Project && _document.Project.Language == LanguageNames.VisualBasic) || (_document.Project != _generateTypeOptionsResult.Project && _targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange && _generateTypeOptionsResult.Project.Language == LanguageNames.VisualBasic) || _targetProjectChangeInLanguage == TargetProjectChangeInLanguage.CSharpToVisualBasic) { // Populate the ContainerList AddFoldersToNamespaceContainers(containerList, folders); containers = containerList.ToArray(); includeUsingsOrImports = string.Join(".", containerList.ToArray()); if (!string.IsNullOrWhiteSpace(rootNamespaceOfTheProjectGeneratedInto)) { includeUsingsOrImports = string.IsNullOrEmpty(includeUsingsOrImports) ? rootNamespaceOfTheProjectGeneratedInto : rootNamespaceOfTheProjectGeneratedInto + "." + includeUsingsOrImports; } } Contract.Assert(includeUsingsOrImports != null); } return Tuple.Create(containers, includeUsingsOrImports); } private async Task<IEnumerable<CodeActionOperation>> GetGenerateIntoTypeOperationsAsync(INamedTypeSymbol namedType) { var codeGenService = GetCodeGenerationService(); var solution = _document.Project.Solution; var codeGenResult = await CodeGenerator.AddNamedTypeDeclarationAsync( solution, _state.TypeToGenerateInOpt, namedType, new CodeGenerationOptions(contextLocation: _state.SimpleName.GetLocation()), _cancellationToken) .ConfigureAwait(false); return new CodeActionOperation[] { new ApplyChangesOperation(codeGenResult.Project.Solution) }; } private IList<ITypeSymbol> GetArgumentTypes(IList<TArgumentSyntax> argumentList) { var types = argumentList.Select(a => _service.DetermineArgumentType(_document.SemanticModel, a, _cancellationToken)); return types.Select(FixType).ToList(); } private ITypeSymbol FixType( ITypeSymbol typeSymbol) { var compilation = _document.SemanticModel.Compilation; return typeSymbol.RemoveUnnamedErrorTypes(compilation); } private ICodeGenerationService GetCodeGenerationService() { var language = _state.TypeToGenerateInOpt == null ? _state.SimpleName.Language : _state.TypeToGenerateInOpt.Language; return _document.Project.Solution.Workspace.Services.GetLanguageServices(language).GetService<ICodeGenerationService>(); } private bool TryFindMatchingField( string parameterName, ITypeSymbol parameterType, Dictionary<string, ISymbol> parameterToFieldMap, bool caseSensitive) { // If the base types have an accessible field or property with the same name and // an acceptable type, then we should just defer to that. if (_state.BaseTypeOrInterfaceOpt != null) { var comparison = caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; var query = _state.BaseTypeOrInterfaceOpt .GetBaseTypesAndThis() .SelectMany(t => t.GetMembers()) .Where(s => s.Name.Equals(parameterName, comparison)); var symbol = query.FirstOrDefault(IsSymbolAccessible); if (IsViableFieldOrProperty(parameterType, symbol)) { parameterToFieldMap[parameterName] = symbol; return true; } } return false; } private bool IsViableFieldOrProperty( ITypeSymbol parameterType, ISymbol symbol) { if (symbol != null && !symbol.IsStatic && parameterType.Language == symbol.Language) { if (symbol is IFieldSymbol) { var field = (IFieldSymbol)symbol; return !field.IsReadOnly && _service.IsConversionImplicit(_document.SemanticModel.Compilation, parameterType, field.Type); } else if (symbol is IPropertySymbol) { var property = (IPropertySymbol)symbol; return property.Parameters.Length == 0 && property.SetMethod != null && IsSymbolAccessible(property.SetMethod) && _service.IsConversionImplicit(_document.SemanticModel.Compilation, parameterType, property.Type); } } return false; } private bool IsSymbolAccessible(ISymbol symbol) { // Public and protected constructors are accessible. Internal constructors are // accessible if we have friend access. We can't call the normal accessibility // checkers since they will think that a protected constructor isn't accessible // (since we don't have the destination type that would have access to them yet). switch (symbol.DeclaredAccessibility) { case Accessibility.ProtectedOrInternal: case Accessibility.Protected: case Accessibility.Public: return true; case Accessibility.ProtectedAndInternal: case Accessibility.Internal: // TODO: Code coverage return _document.SemanticModel.Compilation.Assembly.IsSameAssemblyOrHasFriendAccessTo( symbol.ContainingAssembly); default: return false; } } } } }
#region Copyright // Copyright 2017 Gigya Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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. #endregion using System; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Gigya.Microdot.Interfaces.Logging; namespace Gigya.Microdot.ServiceDiscovery.HostManagement { public class RemoteHost: EndPoint, IEndPointHandle { internal Exception LastException { get; private set; } private object Lock { get; } protected RemoteHostPool HostPool { get; } private ILog Log { get; } private int FailureCount { get; set; } private bool IsMonitoring { get; set; } internal RemoteHost(string hostName, RemoteHostPool remoteHostPool, object sharedLock, int? port=null) { if (hostName == null) throw new ArgumentNullException(nameof(hostName)); if (remoteHostPool == null) throw new ArgumentNullException(nameof(remoteHostPool)); if (sharedLock == null) throw new ArgumentNullException(nameof(sharedLock)); Lock = sharedLock; HostPool = remoteHostPool; HostName = hostName; FailureCount = 0; Log = remoteHostPool.Log; Port = port; } /// <summary> /// Reports that an attempt to contact a <see cref="RemoteHost"/> has failed. Based on these reports, the reachability of <see cref="RemoteHost"/> is determined. /// </summary> /// <param name="ex">Optional. The exception containing the details of the failed attempt.</param> /// <returns>True if this <see cref="RemoteHost"/> is still considered reachable despite the failure, or false if it has been marked as unreachable.</returns> public virtual bool ReportFailure(Exception ex = null) { LastException = ex; lock (Lock) { FailureCount++; var isReachable = FailureCount < 2; if (isReachable == false && HostPool.MarkUnreachable(this)) { Log.Error(_ => _("A remote host has been marked as unreachable due to failing twice. Monitoring " + "started. See tags and inner exception for details.", exception: ex, unencryptedTags: new { endpoint = HostName, requestedService = HostPool.DeploymentIdentifier.ServiceName, requestedServiceEnvironment = HostPool.DeploymentIdentifier.DeploymentEnvironment })); // Task.Run is used here to have the long-running task of monitoring run on the thread pool, // otherwise it might prevent ASP.NET requests from completing or it might be tied to a specific // grain's lifetime, when it is actually a global concern. Task.Run(StartMonitoring); } return isReachable; } } /// <summary> /// Reports that an attempt to contact a <see cref="RemoteHost"/> has succeeded. Based on these reports, the reachability of <see cref="RemoteHost"/> is determined. /// </summary> public virtual void ReportSuccess() { lock (Lock) { FailureCount = 0; } } /// <summary> /// Monitors a host that has been marked unreachable by using the parent RemoteHostPool.IsReachableChecker using exponential backoff. /// </summary> [SuppressMessage("ReSharper", "AccessToModifiedClosure")] private async Task StartMonitoring() { lock (Lock) { if (IsMonitoring) return; IsMonitoring = true; } var config = HostPool.GetConfig(); var start = DateTime.UtcNow; var nextDelay = TimeSpan.FromSeconds(config.FirstAttemptDelaySeconds.Value); var maxDelay = TimeSpan.FromSeconds(config.MaxAttemptDelaySeconds.Value); var attemptCount = 1; while (true) { if (IsMonitoring == false) return; try { attemptCount++; if (await HostPool.ReachabilityChecker.Invoke(this).ConfigureAwait(false)) break; } catch (Exception ex) { Log.Error(_ => _("The supplied reachability checker threw an exception while checking a remote host. See tags and inner exception for details.", exception: ex, unencryptedTags: new { endpoint = HostName, requestedService = HostPool.DeploymentIdentifier.ServiceName, requestedServiceEnvironment = HostPool.DeploymentIdentifier.DeploymentEnvironment })); } if (IsMonitoring == false) return; lock (Lock) FailureCount++; Log.Info(_ => _("A remote host is still unreachable, monitoring continues. See tags for details", unencryptedTags: new { endpoint = HostName, requestedService = HostPool.DeploymentIdentifier.ServiceName, requestedServiceEnvironment = HostPool.DeploymentIdentifier.DeploymentEnvironment, attemptCount, nextDelay, nextAttemptAt = DateTime.UtcNow + nextDelay, downtime = DateTime.UtcNow - start })); await Task.Delay(nextDelay).ConfigureAwait(false); nextDelay = TimeSpan.FromMilliseconds(nextDelay.TotalMilliseconds * config.DelayMultiplier.Value); if (nextDelay > maxDelay) nextDelay = maxDelay; } lock (Lock) { FailureCount = 0; IsMonitoring = false; if (HostPool.MarkReachable(this)) { Log.Info(_ => _("A remote host has become reachable. See tags for details.", unencryptedTags: new { endpoint = HostName, requestedService = HostPool.DeploymentIdentifier.ServiceName, requestedServiceEnvironment = HostPool.DeploymentIdentifier.DeploymentEnvironment, attemptCount, downtime = DateTime.UtcNow - start })); } } } internal void StopMonitoring() { IsMonitoring = false; } public override string ToString() { return HostName; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Exceptions; using Umbraco.Cms.Core.Hosting; using Umbraco.Cms.Core.Mapping; using Umbraco.Cms.Core.Models.ContentEditing; using Umbraco.Cms.Core.PropertyEditors; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Strings; using Umbraco.Cms.Web.Common.DependencyInjection; using Umbraco.Extensions; namespace Umbraco.Cms.Core.Models.Mapping { /// <summary> /// Defines mappings for content/media/members type mappings /// </summary> public class ContentTypeMapDefinition : IMapDefinition { private readonly CommonMapper _commonMapper; private readonly IContentTypeService _contentTypeService; private readonly IDataTypeService _dataTypeService; private readonly IFileService _fileService; private readonly GlobalSettings _globalSettings; private readonly IHostingEnvironment _hostingEnvironment; private readonly ILogger<ContentTypeMapDefinition> _logger; private readonly ILoggerFactory _loggerFactory; private readonly IMediaTypeService _mediaTypeService; private readonly IMemberTypeService _memberTypeService; private readonly PropertyEditorCollection _propertyEditors; private readonly IShortStringHelper _shortStringHelper; private ContentSettings _contentSettings; [Obsolete("Use ctor with all params injected")] public ContentTypeMapDefinition(CommonMapper commonMapper, PropertyEditorCollection propertyEditors, IDataTypeService dataTypeService, IFileService fileService, IContentTypeService contentTypeService, IMediaTypeService mediaTypeService, IMemberTypeService memberTypeService, ILoggerFactory loggerFactory, IShortStringHelper shortStringHelper, IOptions<GlobalSettings> globalSettings, IHostingEnvironment hostingEnvironment) : this(commonMapper, propertyEditors, dataTypeService, fileService, contentTypeService, mediaTypeService, memberTypeService, loggerFactory, shortStringHelper, globalSettings, hostingEnvironment, StaticServiceProvider.Instance.GetRequiredService<IOptionsMonitor<ContentSettings>>()) { } public ContentTypeMapDefinition(CommonMapper commonMapper, PropertyEditorCollection propertyEditors, IDataTypeService dataTypeService, IFileService fileService, IContentTypeService contentTypeService, IMediaTypeService mediaTypeService, IMemberTypeService memberTypeService, ILoggerFactory loggerFactory, IShortStringHelper shortStringHelper, IOptions<GlobalSettings> globalSettings, IHostingEnvironment hostingEnvironment, IOptionsMonitor<ContentSettings> contentSettings) { _commonMapper = commonMapper; _propertyEditors = propertyEditors; _dataTypeService = dataTypeService; _fileService = fileService; _contentTypeService = contentTypeService; _mediaTypeService = mediaTypeService; _memberTypeService = memberTypeService; _loggerFactory = loggerFactory; _logger = _loggerFactory.CreateLogger<ContentTypeMapDefinition>(); _shortStringHelper = shortStringHelper; _globalSettings = globalSettings.Value; _hostingEnvironment = hostingEnvironment; _contentSettings = contentSettings.CurrentValue; contentSettings.OnChange(x => _contentSettings = x); } public void DefineMaps(IUmbracoMapper mapper) { mapper.Define<DocumentTypeSave, IContentType>( (source, context) => new ContentType(_shortStringHelper, source.ParentId), Map); mapper.Define<MediaTypeSave, IMediaType>( (source, context) => new MediaType(_shortStringHelper, source.ParentId), Map); mapper.Define<MemberTypeSave, IMemberType>( (source, context) => new MemberType(_shortStringHelper, source.ParentId), Map); mapper.Define<IContentType, DocumentTypeDisplay>((source, context) => new DocumentTypeDisplay(), Map); mapper.Define<IMediaType, MediaTypeDisplay>((source, context) => new MediaTypeDisplay(), Map); mapper.Define<IMemberType, MemberTypeDisplay>((source, context) => new MemberTypeDisplay(), Map); mapper.Define<PropertyTypeBasic, IPropertyType>( (source, context) => { IDataType dataType = _dataTypeService.GetDataType(source.DataTypeId); if (dataType == null) { throw new NullReferenceException("No data type found with id " + source.DataTypeId); } return new PropertyType(_shortStringHelper, dataType, source.Alias); }, Map); // TODO: isPublishing in ctor? mapper.Define<PropertyGroupBasic<PropertyTypeBasic>, PropertyGroup>( (source, context) => new PropertyGroup(false), Map); mapper.Define<PropertyGroupBasic<MemberPropertyTypeBasic>, PropertyGroup>( (source, context) => new PropertyGroup(false), Map); mapper.Define<IContentTypeComposition, ContentTypeBasic>((source, context) => new ContentTypeBasic(), Map); mapper.Define<IContentType, ContentTypeBasic>((source, context) => new ContentTypeBasic(), Map); mapper.Define<IMediaType, ContentTypeBasic>((source, context) => new ContentTypeBasic(), Map); mapper.Define<IMemberType, ContentTypeBasic>((source, context) => new ContentTypeBasic(), Map); mapper.Define<DocumentTypeSave, DocumentTypeDisplay>((source, context) => new DocumentTypeDisplay(), Map); mapper.Define<MediaTypeSave, MediaTypeDisplay>((source, context) => new MediaTypeDisplay(), Map); mapper.Define<MemberTypeSave, MemberTypeDisplay>((source, context) => new MemberTypeDisplay(), Map); mapper.Define<PropertyGroupBasic<PropertyTypeBasic>, PropertyGroupDisplay<PropertyTypeDisplay>>( (source, context) => new PropertyGroupDisplay<PropertyTypeDisplay>(), Map); mapper.Define<PropertyGroupBasic<MemberPropertyTypeBasic>, PropertyGroupDisplay<MemberPropertyTypeDisplay>>( (source, context) => new PropertyGroupDisplay<MemberPropertyTypeDisplay>(), Map); mapper.Define<PropertyTypeBasic, PropertyTypeDisplay>((source, context) => new PropertyTypeDisplay(), Map); mapper.Define<MemberPropertyTypeBasic, MemberPropertyTypeDisplay>( (source, context) => new MemberPropertyTypeDisplay(), Map); } // no MapAll - take care private void Map(DocumentTypeSave source, IContentType target, MapperContext context) { MapSaveToTypeBase<DocumentTypeSave, PropertyTypeBasic>(source, target, context); MapComposition(source, target, alias => _contentTypeService.Get(alias)); if (target is IContentTypeWithHistoryCleanup targetWithHistoryCleanup) { targetWithHistoryCleanup.HistoryCleanup = source.HistoryCleanup; } target.AllowedTemplates = source.AllowedTemplates .Where(x => x != null) .Select(_fileService.GetTemplate) .Where(x => x != null) .ToArray(); target.SetDefaultTemplate(source.DefaultTemplate == null ? null : _fileService.GetTemplate(source.DefaultTemplate)); } // no MapAll - take care private void Map(MediaTypeSave source, IMediaType target, MapperContext context) { MapSaveToTypeBase<MediaTypeSave, PropertyTypeBasic>(source, target, context); MapComposition(source, target, alias => _mediaTypeService.Get(alias)); } // no MapAll - take care private void Map(MemberTypeSave source, IMemberType target, MapperContext context) { MapSaveToTypeBase<MemberTypeSave, MemberPropertyTypeBasic>(source, target, context); MapComposition(source, target, alias => _memberTypeService.Get(alias)); foreach (MemberPropertyTypeBasic propertyType in source.Groups.SelectMany(x => x.Properties)) { MemberPropertyTypeBasic localCopy = propertyType; IPropertyType destProp = target.PropertyTypes.SingleOrDefault(x => x.Alias.InvariantEquals(localCopy.Alias)); if (destProp == null) { continue; } target.SetMemberCanEditProperty(localCopy.Alias, localCopy.MemberCanEditProperty); target.SetMemberCanViewProperty(localCopy.Alias, localCopy.MemberCanViewProperty); target.SetIsSensitiveProperty(localCopy.Alias, localCopy.IsSensitiveData); } } // no MapAll - take care private void Map(IContentType source, DocumentTypeDisplay target, MapperContext context) { MapTypeToDisplayBase<DocumentTypeDisplay, PropertyTypeDisplay>(source, target); if (source is IContentTypeWithHistoryCleanup sourceWithHistoryCleanup) { target.HistoryCleanup = new HistoryCleanupViewModel { PreventCleanup = sourceWithHistoryCleanup.HistoryCleanup?.PreventCleanup ?? false, KeepAllVersionsNewerThanDays = sourceWithHistoryCleanup.HistoryCleanup?.KeepAllVersionsNewerThanDays, KeepLatestVersionPerDayForDays = sourceWithHistoryCleanup.HistoryCleanup?.KeepLatestVersionPerDayForDays, GlobalKeepAllVersionsNewerThanDays = _contentSettings.ContentVersionCleanupPolicy.KeepAllVersionsNewerThanDays, GlobalKeepLatestVersionPerDayForDays = _contentSettings.ContentVersionCleanupPolicy.KeepLatestVersionPerDayForDays, GlobalEnableCleanup = _contentSettings.ContentVersionCleanupPolicy.EnableCleanup }; } target.AllowCultureVariant = source.VariesByCulture(); target.AllowSegmentVariant = source.VariesBySegment(); target.ContentApps = _commonMapper.GetContentAppsForEntity(source); //sync templates target.AllowedTemplates = context.MapEnumerable<ITemplate, EntityBasic>(source.AllowedTemplates); if (source.DefaultTemplate != null) { target.DefaultTemplate = context.Map<EntityBasic>(source.DefaultTemplate); } //default listview target.ListViewEditorName = Constants.Conventions.DataTypes.ListViewPrefix + "Content"; if (string.IsNullOrEmpty(source.Alias)) { return; } var name = Constants.Conventions.DataTypes.ListViewPrefix + source.Alias; if (_dataTypeService.GetDataType(name) != null) { target.ListViewEditorName = name; } } // no MapAll - take care private void Map(IMediaType source, MediaTypeDisplay target, MapperContext context) { MapTypeToDisplayBase<MediaTypeDisplay, PropertyTypeDisplay>(source, target); //default listview target.ListViewEditorName = Constants.Conventions.DataTypes.ListViewPrefix + "Media"; target.IsSystemMediaType = source.IsSystemMediaType(); if (string.IsNullOrEmpty(source.Name)) { return; } var name = Constants.Conventions.DataTypes.ListViewPrefix + source.Name; if (_dataTypeService.GetDataType(name) != null) { target.ListViewEditorName = name; } } // no MapAll - take care private void Map(IMemberType source, MemberTypeDisplay target, MapperContext context) { MapTypeToDisplayBase<MemberTypeDisplay, MemberPropertyTypeDisplay>(source, target); //map the MemberCanEditProperty,MemberCanViewProperty,IsSensitiveData foreach (IPropertyType propertyType in source.PropertyTypes) { IPropertyType localCopy = propertyType; MemberPropertyTypeDisplay displayProp = target.Groups.SelectMany(dest => dest.Properties) .SingleOrDefault(dest => dest.Alias.InvariantEquals(localCopy.Alias)); if (displayProp == null) { continue; } displayProp.MemberCanEditProperty = source.MemberCanEditProperty(localCopy.Alias); displayProp.MemberCanViewProperty = source.MemberCanViewProperty(localCopy.Alias); displayProp.IsSensitiveData = source.IsSensitiveProperty(localCopy.Alias); } } // Umbraco.Code.MapAll -Blueprints private void Map(IContentTypeBase source, ContentTypeBasic target, string entityType) { target.Udi = Udi.Create(entityType, source.Key); target.Alias = source.Alias; target.CreateDate = source.CreateDate; target.Description = source.Description; target.Icon = source.Icon; target.IconFilePath = target.IconIsClass ? string.Empty : $"{_globalSettings.GetBackOfficePath(_hostingEnvironment).EnsureEndsWith("/")}images/umbraco/{source.Icon}"; target.Trashed = source.Trashed; target.Id = source.Id; target.IsContainer = source.IsContainer; target.IsElement = source.IsElement; target.Key = source.Key; target.Name = source.Name; target.ParentId = source.ParentId; target.Path = source.Path; target.Thumbnail = source.Thumbnail; target.ThumbnailFilePath = target.ThumbnailIsClass ? string.Empty : _hostingEnvironment.ToAbsolute("~/umbraco/images/thumbnails/" + source.Thumbnail); target.UpdateDate = source.UpdateDate; } // no MapAll - uses the IContentTypeBase map method, which has MapAll private void Map(IContentTypeComposition source, ContentTypeBasic target, MapperContext context) => Map(source, target, Constants.UdiEntityType.MemberType); // no MapAll - uses the IContentTypeBase map method, which has MapAll private void Map(IContentType source, ContentTypeBasic target, MapperContext context) => Map(source, target, Constants.UdiEntityType.DocumentType); // no MapAll - uses the IContentTypeBase map method, which has MapAll private void Map(IMediaType source, ContentTypeBasic target, MapperContext context) => Map(source, target, Constants.UdiEntityType.MediaType); // no MapAll - uses the IContentTypeBase map method, which has MapAll private void Map(IMemberType source, ContentTypeBasic target, MapperContext context) => Map(source, target, Constants.UdiEntityType.MemberType); // Umbraco.Code.MapAll -CreateDate -DeleteDate -UpdateDate // Umbraco.Code.MapAll -SupportsPublishing -Key -PropertyEditorAlias -ValueStorageType -Variations private static void Map(PropertyTypeBasic source, IPropertyType target, MapperContext context) { target.Name = source.Label; target.DataTypeId = source.DataTypeId; target.DataTypeKey = source.DataTypeKey; target.Mandatory = source.Validation.Mandatory; target.MandatoryMessage = source.Validation.MandatoryMessage; target.ValidationRegExp = source.Validation.Pattern; target.ValidationRegExpMessage = source.Validation.PatternMessage; target.SetVariesBy(ContentVariation.Culture, source.AllowCultureVariant); target.SetVariesBy(ContentVariation.Segment, source.AllowSegmentVariant); if (source.Id > 0) { target.Id = source.Id; } if (source.GroupId > 0) { target.PropertyGroupId = new Lazy<int>(() => source.GroupId, false); } target.Alias = source.Alias; target.Description = source.Description; target.SortOrder = source.SortOrder; target.LabelOnTop = source.LabelOnTop; } // no MapAll - take care private void Map(DocumentTypeSave source, DocumentTypeDisplay target, MapperContext context) { MapTypeToDisplayBase<DocumentTypeSave, PropertyTypeBasic, DocumentTypeDisplay, PropertyTypeDisplay>(source, target, context); //sync templates IEnumerable<string> destAllowedTemplateAliases = target.AllowedTemplates.Select(x => x.Alias); //if the dest is set and it's the same as the source, then don't change if (destAllowedTemplateAliases.SequenceEqual(source.AllowedTemplates) == false) { IEnumerable<ITemplate> templates = _fileService.GetTemplates(source.AllowedTemplates.ToArray()); target.AllowedTemplates = source.AllowedTemplates .Select(x => { ITemplate template = templates.SingleOrDefault(t => t.Alias == x); return template != null ? context.Map<EntityBasic>(template) : null; }) .WhereNotNull() .ToArray(); } if (source.DefaultTemplate.IsNullOrWhiteSpace() == false) { //if the dest is set and it's the same as the source, then don't change if (target.DefaultTemplate == null || source.DefaultTemplate != target.DefaultTemplate.Alias) { ITemplate template = _fileService.GetTemplate(source.DefaultTemplate); target.DefaultTemplate = template == null ? null : context.Map<EntityBasic>(template); } } else { target.DefaultTemplate = null; } } // no MapAll - take care private void Map(MediaTypeSave source, MediaTypeDisplay target, MapperContext context) => MapTypeToDisplayBase<MediaTypeSave, PropertyTypeBasic, MediaTypeDisplay, PropertyTypeDisplay>(source, target, context); // no MapAll - take care private void Map(MemberTypeSave source, MemberTypeDisplay target, MapperContext context) => MapTypeToDisplayBase<MemberTypeSave, MemberPropertyTypeBasic, MemberTypeDisplay, MemberPropertyTypeDisplay>( source, target, context); // Umbraco.Code.MapAll -CreateDate -UpdateDate -DeleteDate -Key -PropertyTypes private static void Map(PropertyGroupBasic<PropertyTypeBasic> source, PropertyGroup target, MapperContext context) { if (source.Id > 0) { target.Id = source.Id; } target.Key = source.Key; target.Type = source.Type; target.Name = source.Name; target.Alias = source.Alias; target.SortOrder = source.SortOrder; } // Umbraco.Code.MapAll -CreateDate -UpdateDate -DeleteDate -Key -PropertyTypes private static void Map(PropertyGroupBasic<MemberPropertyTypeBasic> source, PropertyGroup target, MapperContext context) { if (source.Id > 0) { target.Id = source.Id; } target.Key = source.Key; target.Type = source.Type; target.Name = source.Name; target.Alias = source.Alias; target.SortOrder = source.SortOrder; } // Umbraco.Code.MapAll -ContentTypeId -ParentTabContentTypes -ParentTabContentTypeNames private static void Map(PropertyGroupBasic<PropertyTypeBasic> source, PropertyGroupDisplay<PropertyTypeDisplay> target, MapperContext context) { target.Inherited = source.Inherited; if (source.Id > 0) { target.Id = source.Id; } target.Key = source.Key; target.Type = source.Type; target.Name = source.Name; target.Alias = source.Alias; target.SortOrder = source.SortOrder; target.Properties = context.MapEnumerable<PropertyTypeBasic, PropertyTypeDisplay>(source.Properties); } // Umbraco.Code.MapAll -ContentTypeId -ParentTabContentTypes -ParentTabContentTypeNames private static void Map(PropertyGroupBasic<MemberPropertyTypeBasic> source, PropertyGroupDisplay<MemberPropertyTypeDisplay> target, MapperContext context) { target.Inherited = source.Inherited; if (source.Id > 0) { target.Id = source.Id; } target.Key = source.Key; target.Type = source.Type; target.Name = source.Name; target.Alias = source.Alias; target.SortOrder = source.SortOrder; target.Properties = context.MapEnumerable<MemberPropertyTypeBasic, MemberPropertyTypeDisplay>(source.Properties); } // Umbraco.Code.MapAll -Editor -View -Config -ContentTypeId -ContentTypeName -Locked -DataTypeIcon -DataTypeName private static void Map(PropertyTypeBasic source, PropertyTypeDisplay target, MapperContext context) { target.Alias = source.Alias; target.AllowCultureVariant = source.AllowCultureVariant; target.AllowSegmentVariant = source.AllowSegmentVariant; target.DataTypeId = source.DataTypeId; target.DataTypeKey = source.DataTypeKey; target.Description = source.Description; target.GroupId = source.GroupId; target.Id = source.Id; target.Inherited = source.Inherited; target.Label = source.Label; target.SortOrder = source.SortOrder; target.Validation = source.Validation; target.LabelOnTop = source.LabelOnTop; } // Umbraco.Code.MapAll -Editor -View -Config -ContentTypeId -ContentTypeName -Locked -DataTypeIcon -DataTypeName private static void Map(MemberPropertyTypeBasic source, MemberPropertyTypeDisplay target, MapperContext context) { target.Alias = source.Alias; target.AllowCultureVariant = source.AllowCultureVariant; target.AllowSegmentVariant = source.AllowSegmentVariant; target.DataTypeId = source.DataTypeId; target.DataTypeKey = source.DataTypeKey; target.Description = source.Description; target.GroupId = source.GroupId; target.Id = source.Id; target.Inherited = source.Inherited; target.IsSensitiveData = source.IsSensitiveData; target.Label = source.Label; target.MemberCanEditProperty = source.MemberCanEditProperty; target.MemberCanViewProperty = source.MemberCanViewProperty; target.SortOrder = source.SortOrder; target.Validation = source.Validation; target.LabelOnTop = source.LabelOnTop; } // Umbraco.Code.MapAll -CreatorId -Level -SortOrder -Variations // Umbraco.Code.MapAll -CreateDate -UpdateDate -DeleteDate // Umbraco.Code.MapAll -ContentTypeComposition (done by AfterMapSaveToType) private static void MapSaveToTypeBase<TSource, TSourcePropertyType>(TSource source, IContentTypeComposition target, MapperContext context) where TSource : ContentTypeSave<TSourcePropertyType> where TSourcePropertyType : PropertyTypeBasic { // TODO: not so clean really var isPublishing = target is IContentType; var id = Convert.ToInt32(source.Id); if (id > 0) { target.Id = id; } target.Alias = source.Alias; target.Description = source.Description; target.Icon = source.Icon; target.IsContainer = source.IsContainer; target.IsElement = source.IsElement; target.Key = source.Key; target.Name = source.Name; target.ParentId = source.ParentId; target.Path = source.Path; target.Thumbnail = source.Thumbnail; target.AllowedAsRoot = source.AllowAsRoot; target.AllowedContentTypes = source.AllowedContentTypes.Select((t, i) => new ContentTypeSort(t, i)); if (!(target is IMemberType)) { target.SetVariesBy(ContentVariation.Culture, source.AllowCultureVariant); target.SetVariesBy(ContentVariation.Segment, source.AllowSegmentVariant); } // handle property groups and property types // note that ContentTypeSave has // - all groups, inherited and local; only *one* occurrence per group *name* // - potentially including the generic properties group // - all properties, inherited and local // // also, see PropertyTypeGroupResolver.ResolveCore: // - if a group is local *and* inherited, then Inherited is true // and the identifier is the identifier of the *local* group // // IContentTypeComposition AddPropertyGroup, AddPropertyType methods do some // unique-alias-checking, etc that is *not* compatible with re-mapping everything // the way we do it here, so we should exclusively do it by // - managing a property group's PropertyTypes collection // - managing the content type's PropertyTypes collection (for generic properties) // handle actual groups (non-generic-properties) PropertyGroup[] destOrigGroups = target.PropertyGroups.ToArray(); // local groups IPropertyType[] destOrigProperties = target.PropertyTypes.ToArray(); // all properties, in groups or not var destGroups = new List<PropertyGroup>(); PropertyGroupBasic<TSourcePropertyType>[] sourceGroups = source.Groups.Where(x => x.IsGenericProperties == false).ToArray(); var sourceGroupParentAliases = sourceGroups.Select(x => x.GetParentAlias()).Distinct().ToArray(); foreach (PropertyGroupBasic<TSourcePropertyType> sourceGroup in sourceGroups) { // get the dest group PropertyGroup destGroup = MapSaveGroup(sourceGroup, destOrigGroups, context); // handle local properties IPropertyType[] destProperties = sourceGroup.Properties .Where(x => x.Inherited == false) .Select(x => MapSaveProperty(x, destOrigProperties, context)) .ToArray(); // if the group has no local properties and is not used as parent, skip it, ie sort-of garbage-collect // local groups which would not have local properties anymore if (destProperties.Length == 0 && !sourceGroupParentAliases.Contains(sourceGroup.Alias)) { continue; } // ensure no duplicate alias, then assign the group properties collection EnsureUniqueAliases(destProperties); destGroup.PropertyTypes = new PropertyTypeCollection(isPublishing, destProperties); destGroups.Add(destGroup); } // ensure no duplicate name, then assign the groups collection EnsureUniqueAliases(destGroups); target.PropertyGroups = new PropertyGroupCollection(destGroups); // because the property groups collection was rebuilt, there is no need to remove // the old groups - they are just gone and will be cleared by the repository // handle non-grouped (ie generic) properties PropertyGroupBasic<TSourcePropertyType> genericPropertiesGroup = source.Groups.FirstOrDefault(x => x.IsGenericProperties); if (genericPropertiesGroup != null) { // handle local properties IPropertyType[] destProperties = genericPropertiesGroup.Properties .Where(x => x.Inherited == false) .Select(x => MapSaveProperty(x, destOrigProperties, context)) .ToArray(); // ensure no duplicate alias, then assign the generic properties collection EnsureUniqueAliases(destProperties); target.NoGroupPropertyTypes = new PropertyTypeCollection(isPublishing, destProperties); } // because all property collections were rebuilt, there is no need to remove // some old properties, they are just gone and will be cleared by the repository } // Umbraco.Code.MapAll -Blueprints -Errors -ListViewEditorName -Trashed private void MapTypeToDisplayBase(IContentTypeComposition source, ContentTypeCompositionDisplay target) { target.Alias = source.Alias; target.AllowAsRoot = source.AllowedAsRoot; target.CreateDate = source.CreateDate; target.Description = source.Description; target.Icon = source.Icon; target.IconFilePath = target.IconIsClass ? string.Empty : $"{_globalSettings.GetBackOfficePath(_hostingEnvironment).EnsureEndsWith("/")}images/umbraco/{source.Icon}"; target.Id = source.Id; target.IsContainer = source.IsContainer; target.IsElement = source.IsElement; target.Key = source.Key; target.Name = source.Name; target.ParentId = source.ParentId; target.Path = source.Path; target.Thumbnail = source.Thumbnail; target.ThumbnailFilePath = target.ThumbnailIsClass ? string.Empty : _hostingEnvironment.ToAbsolute("~/umbraco/images/thumbnails/" + source.Thumbnail); target.Udi = MapContentTypeUdi(source); target.UpdateDate = source.UpdateDate; target.AllowedContentTypes = source.AllowedContentTypes.OrderBy(c => c.SortOrder).Select(x => x.Id.Value); target.CompositeContentTypes = source.ContentTypeComposition.Select(x => x.Alias); target.LockedCompositeContentTypes = MapLockedCompositions(source); } // no MapAll - relies on the non-generic method private void MapTypeToDisplayBase<TTarget, TTargetPropertyType>(IContentTypeComposition source, TTarget target) where TTarget : ContentTypeCompositionDisplay<TTargetPropertyType> where TTargetPropertyType : PropertyTypeDisplay, new() { MapTypeToDisplayBase(source, target); var groupsMapper = new PropertyTypeGroupMapper<TTargetPropertyType>(_propertyEditors, _dataTypeService, _shortStringHelper, _loggerFactory.CreateLogger<PropertyTypeGroupMapper<TTargetPropertyType>>()); target.Groups = groupsMapper.Map(source); } // Umbraco.Code.MapAll -CreateDate -UpdateDate -ListViewEditorName -Errors -LockedCompositeContentTypes private void MapTypeToDisplayBase(ContentTypeSave source, ContentTypeCompositionDisplay target) { target.Alias = source.Alias; target.AllowAsRoot = source.AllowAsRoot; target.AllowedContentTypes = source.AllowedContentTypes; target.Blueprints = source.Blueprints; target.CompositeContentTypes = source.CompositeContentTypes; target.Description = source.Description; target.Icon = source.Icon; target.IconFilePath = target.IconIsClass ? string.Empty : $"{_globalSettings.GetBackOfficePath(_hostingEnvironment).EnsureEndsWith("/")}images/umbraco/{source.Icon}"; target.Id = source.Id; target.IsContainer = source.IsContainer; target.IsElement = source.IsElement; target.Key = source.Key; target.Name = source.Name; target.ParentId = source.ParentId; target.Path = source.Path; target.Thumbnail = source.Thumbnail; target.ThumbnailFilePath = target.ThumbnailIsClass ? string.Empty : _hostingEnvironment.ToAbsolute("~/umbraco/images/thumbnails/" + source.Thumbnail); target.Trashed = source.Trashed; target.Udi = source.Udi; } // no MapAll - relies on the non-generic method private void MapTypeToDisplayBase<TSource, TSourcePropertyType, TTarget, TTargetPropertyType>(TSource source, TTarget target, MapperContext context) where TSource : ContentTypeSave<TSourcePropertyType> where TSourcePropertyType : PropertyTypeBasic where TTarget : ContentTypeCompositionDisplay<TTargetPropertyType> where TTargetPropertyType : PropertyTypeDisplay { MapTypeToDisplayBase(source, target); target.Groups = context .MapEnumerable<PropertyGroupBasic<TSourcePropertyType>, PropertyGroupDisplay<TTargetPropertyType>>( source.Groups); } private IEnumerable<string> MapLockedCompositions(IContentTypeComposition source) { // get ancestor ids from path of parent if not root if (source.ParentId == Constants.System.Root) { return Enumerable.Empty<string>(); } IContentType parent = _contentTypeService.Get(source.ParentId); if (parent == null) { return Enumerable.Empty<string>(); } var aliases = new List<string>(); IEnumerable<int> ancestorIds = parent.Path.Split(Constants.CharArrays.Comma) .Select(s => int.Parse(s, CultureInfo.InvariantCulture)); // loop through all content types and return ordered aliases of ancestors IContentType[] allContentTypes = _contentTypeService.GetAll().ToArray(); foreach (var ancestorId in ancestorIds) { IContentType ancestor = allContentTypes.FirstOrDefault(x => x.Id == ancestorId); if (ancestor != null) { aliases.Add(ancestor.Alias); } } return aliases.OrderBy(x => x); } public static Udi MapContentTypeUdi(IContentTypeComposition source) { if (source == null) { return null; } string udiType; switch (source) { case IMemberType _: udiType = Constants.UdiEntityType.MemberType; break; case IMediaType _: udiType = Constants.UdiEntityType.MediaType; break; case IContentType _: udiType = Constants.UdiEntityType.DocumentType; break; default: throw new PanicException($"Source is of type {source.GetType()} which isn't supported here"); } return Udi.Create(udiType, source.Key); } private static PropertyGroup MapSaveGroup<TPropertyType>(PropertyGroupBasic<TPropertyType> sourceGroup, IEnumerable<PropertyGroup> destOrigGroups, MapperContext context) where TPropertyType : PropertyTypeBasic { PropertyGroup destGroup; if (sourceGroup.Id > 0) { // update an existing group // ensure it is still there, then map/update destGroup = destOrigGroups.FirstOrDefault(x => x.Id == sourceGroup.Id); if (destGroup != null) { context.Map(sourceGroup, destGroup); return destGroup; } // force-clear the ID as it does not match anything sourceGroup.Id = 0; } // insert a new group, or update an existing group that has // been deleted in the meantime and we need to re-create // map/create destGroup = context.Map<PropertyGroup>(sourceGroup); return destGroup; } private static IPropertyType MapSaveProperty(PropertyTypeBasic sourceProperty, IEnumerable<IPropertyType> destOrigProperties, MapperContext context) { IPropertyType destProperty; if (sourceProperty.Id > 0) { // updating an existing property // ensure it is still there, then map/update destProperty = destOrigProperties.FirstOrDefault(x => x.Id == sourceProperty.Id); if (destProperty != null) { context.Map(sourceProperty, destProperty); return destProperty; } // force-clear the ID as it does not match anything sourceProperty.Id = 0; } // insert a new property, or update an existing property that has // been deleted in the meantime and we need to re-create // map/create destProperty = context.Map<IPropertyType>(sourceProperty); return destProperty; } private static void EnsureUniqueAliases(IEnumerable<IPropertyType> properties) { IPropertyType[] propertiesA = properties.ToArray(); var distinctProperties = propertiesA .Select(x => x.Alias?.ToUpperInvariant()) .Distinct() .Count(); if (distinctProperties != propertiesA.Length) { throw new InvalidOperationException("Cannot map properties due to alias conflict."); } } private static void EnsureUniqueAliases(IEnumerable<PropertyGroup> groups) { PropertyGroup[] groupsA = groups.ToArray(); var distinctProperties = groupsA .Select(x => x.Alias) .Distinct() .Count(); if (distinctProperties != groupsA.Length) { throw new InvalidOperationException("Cannot map groups due to alias conflict."); } } private static void MapComposition(ContentTypeSave source, IContentTypeComposition target, Func<string, IContentTypeComposition> getContentType) { var current = target.CompositionAliases().ToArray(); IEnumerable<string> proposed = source.CompositeContentTypes; IEnumerable<string> remove = current.Where(x => !proposed.Contains(x)); IEnumerable<string> add = proposed.Where(x => !current.Contains(x)); foreach (var alias in remove) { target.RemoveContentType(alias); } foreach (var alias in add) { // TODO: Remove N+1 lookup IContentTypeComposition contentType = getContentType(alias); if (contentType != null) { target.AddContentType(contentType); } } } } }
using System; using System.IO; using System.Reflection; using System.Collections; using System.Collections.Generic; using Weborb.Util.Logging; using Weborb.Service; namespace Weborb.Util { public class TypeLoader { private static Dictionary<String, Type> cachedTypes = new Dictionary<String, Type>(); private static Dictionary<String, String> notFoundTypes = new Dictionary<string, string>(); public static bool TypeExists( string typeName ) { return LoadType( typeName ) != null; } public static Type LoadType( string typeName ) { if ( Log.isLogging( LoggingConstants.INFO ) ) Log.log( LoggingConstants.INFO, "loading type: " + typeName ); if ( notFoundTypes.ContainsKey( typeName ) ) return null; Type type; cachedTypes.TryGetValue( typeName, out type ); if ( type != null ) return type; //Following line has been commented out and new code added replacing 'Type.GetType' with 'BuildManager.GetType' type = Type.GetType( typeName, false); // Type type = System.Web.Compilation.BuildManager.GetType( typeName, false ); if ( type != null ) { if ( Log.isLogging( LoggingConstants.DEBUG ) ) Log.log( LoggingConstants.DEBUG, "type is found" ); cachedTypes[ typeName ] = type; return type; } // blob assemblies loading is turned off #if (CLOUD) try { type = LoadType( CloudAssembliesRegistry.CloudAssembliesArray, typeName ); if ( type != null ) { cachedTypes[ typeName ] = type; return type; } } catch ( Exception exception ) { Log.log( LoggingConstants.ERROR, "could not load assembly from CloudAssembliesRegistry", exception ); } #endif #if (FULL_BUILD) AppDomain domain = AppDomain.CurrentDomain; type = LoadType( domain.GetAssemblies(), typeName ); if ( type != null ) { cachedTypes[ typeName ] = type; return type; } //load assemblies from bin directory try { DirectoryInfo binDirectory = new DirectoryInfo( Path.Combine( domain.BaseDirectory, "bin" ) ); if ( !binDirectory.Exists ) binDirectory = new DirectoryInfo( domain.BaseDirectory ); if ( Log.isLogging( LoggingConstants.DEBUG ) ) Log.log( LoggingConstants.DEBUG, "loading asseblies from " + binDirectory.ToString() ); FileInfo[] files = binDirectory.GetFiles( "*.dll" ); if ( Log.isLogging( LoggingConstants.DEBUG ) ) Log.log( LoggingConstants.DEBUG, "got " + files.Length + " assembly files" ); foreach ( FileInfo file in files ) { string assemblyName = file.Name.Substring( 0, file.Name.ToLower().IndexOf( ".dll" ) ); if ( assemblyName.Equals( "cpuinfo" ) ) continue; if ( Log.isLogging( LoggingConstants.DEBUG ) ) Log.log( LoggingConstants.DEBUG, "loading assembly " + assemblyName ); try { domain.Load( assemblyName ); } catch ( BadImageFormatException ) { if ( Log.isLogging( LoggingConstants.INFO ) ) Log.log( LoggingConstants.INFO, "Unable to load type from assembly, assembly was created with a different version of .NET. Assembly name - " + assemblyName ); } catch ( Exception exception ) { if ( Log.isLogging( LoggingConstants.ERROR ) ) Log.log( LoggingConstants.ERROR, "could not load assembly - " + assemblyName, exception ); } } } catch ( Exception exception ) { if ( Log.isLogging( LoggingConstants.ERROR ) ) Log.log( LoggingConstants.ERROR, "could not load assembly", exception ); } type = LoadType( domain.GetAssemblies(), typeName ); if ( type == null ) { if ( Log.isLogging( LoggingConstants.DEBUG ) ) Log.log( LoggingConstants.DEBUG, "type cannot be found - trying Type.GetType" ); type = Type.GetType( typeName ); if ( Log.isLogging( LoggingConstants.DEBUG ) ) { if ( type == null ) Log.log( LoggingConstants.DEBUG, "type cannot be found - " + typeName ); else Log.log( LoggingConstants.DEBUG, "type found " + type.FullName ); } } #endif if ( type != null ) cachedTypes[ typeName ] = type; else notFoundTypes[ typeName ] = typeName; return type; } private static Type LoadType( Assembly[] assemblies, String typeName ) { foreach ( Assembly assembly in assemblies ) { if ( Log.isLogging( LoggingConstants.DEBUG ) ) Log.log( LoggingConstants.DEBUG, "loading type from " + assembly.FullName ); Type t = assembly.GetType( typeName, false ); if ( t != null ) { if ( Log.isLogging( LoggingConstants.DEBUG ) ) Log.log( LoggingConstants.DEBUG, "type is found - returning type" ); return t; } } return null; } //#if( FULL_BUILD ) // public static void LoadAllTypes() // { // AppDomain domain = AppDomain.CurrentDomain; // String path; // try // { // path = Path.Combine( domain.BaseDirectory, "bin" ); // DirectoryInfo assemlyDirectory = new DirectoryInfo( path ); // if( !assemlyDirectory.Exists ) // assemlyDirectory = new DirectoryInfo( domain.BaseDirectory ); // FileInfo[] files = assemlyDirectory.GetFiles( "*.dll" ); // if( Log.isLogging( LoggingConstants.DEBUG ) ) // { // Log.log( LoggingConstants.DEBUG, "loading asseblies from " + assemlyDirectory.ToString() ); // Log.log( LoggingConstants.DEBUG, "got " + files.Length + " assembly files" ); // } // foreach( FileInfo file in files ) // { // string assemblyName = file.Name.Substring( 0, file.Name.ToLower().IndexOf( ".dll" ) ); // Log.log( LoggingConstants.DEBUG, "loading assembly " + assemblyName ); // try // { // AssemblyName assemblyNameObj = AssemblyName.GetAssemblyName( file.FullName ); // Assembly assembly = domain.Load( assemblyNameObj ); // Type[] types = assembly.GetTypes(); // foreach ( Type type in types ) // { // lock ( cachedTypes ) // { // cachedTypes[ type.FullName ] = type; // } // } // } // catch( Exception exception ) // { // Log.log( LoggingConstants.ERROR, "could not load assembly - " + assemblyName, exception ); // } // } // } // catch( Exception exception ) // { // Log.log( LoggingConstants.ERROR, "could not load assembly", exception ); // } // } //#endif #if (CLOUD) public static void clearTypeCache() { cachedTypes = new Dictionary<String, Type>(); } #endif } }
//----------------------------------------------------------------------------- // ScrollTracker.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input.Touch; namespace GameStateManagement { /// <remarks> /// ScrollTracker watches the touchpanel for drag and flick gestures, and computes the appropriate /// position and scale for a viewport within a larger canvas to emulate the behavior of the Silverlight /// scrolling controls. /// /// This class only handles computation of the view rectangle; how that rectangle is used for rendering /// is up tot the client code. /// </remarks> public class ScrollTracker { /// Handling TouchPanel.EnabledGestures /// -------------------------- /// This class watches for HorizontalDrag, DragComplete, and Flick gestures. However, it cannot just /// set TouchPanel.EnabledGestures, because that would most likely interfere with gestures needed /// elsewhere in the application. So it just exposes a const 'HandledGestures' field and relies on /// the client code to set TouchPanel.EnabledGestures appropriately. public const GestureType GesturesNeeded = GestureType.Flick | GestureType.VerticalDrag | GestureType.DragComplete; #region Tuning constants // How far the user is allowed to drag past the "real" border const float SpringMaxDrag = 400; // How far the display moves when dragged to 'SpringMaxDrag' const float SpringMaxOffset = SpringMaxDrag / 3; const float SpringReturnRate = 0.1f; const float SpringReturnMin = 2.0f; const float Deceleration = 500.0f; // pixels/second^2 const float MaxVelocity = 2000.0f; // pixels/second #endregion /// <summary> /// A rectangle (set by the client code) giving the area of the canvas we want to scroll around in. /// Normally taller or wider than the viewport. /// </summary> public Rectangle CanvasRect; /// <summary> /// A rectangle describing the currently visible view area. Normally the caller will set this once /// to set the viewport size and initial position, and from then on let ScrollTracker move it around; /// however, you can set it at any time to change the position or size of the viewport. /// </summary> public Rectangle ViewRect; /// <summary> /// FullCanvasRect is the same as CanvasRect, except it's extended to be at least as large as ViewRect. /// The is the true canvas area that we scroll around in. /// </summary> public Rectangle FullCanvasRect { get { Rectangle value = CanvasRect; if (value.Width < ViewRect.Width) value.Width = ViewRect.Width; if (value.Height < ViewRect.Height) value.Height = ViewRect.Height; return value; } } // Current flick velocity. Vector2 Velocity; // What the view offset would be if we didn't do any clamping Vector2 ViewOrigin; // What the ViewOrigin would be if we didn't do any clamping Vector2 UnclampedViewOrigin; // True if we're currently tracking a drag gesture public bool IsTracking { get; private set; } public bool IsMoving { get { return IsTracking || Velocity.X != 0 || Velocity.Y != 0 || !FullCanvasRect.Contains(ViewRect); } } public ScrollTracker() { ViewRect = new Rectangle { Width = TouchPanel.DisplayWidth, Height = TouchPanel.DisplayHeight }; CanvasRect = ViewRect; } // This must be called manually each tick that the ScrollTracker is active. public void Update(GameTime gametime) { // Apply velocity and clamping float dt = (float)gametime.ElapsedGameTime.TotalSeconds; Vector2 viewMin = new Vector2 { X = 0, Y = 0 }; Vector2 viewMax = new Vector2 { X = CanvasRect.Width - ViewRect.Width, Y = CanvasRect.Height - ViewRect.Height }; viewMax.X = Math.Max(viewMin.X, viewMax.X); viewMax.Y = Math.Max(viewMin.Y, viewMax.Y); if (IsTracking) { // ViewOrigin is a soft-clamped version of UnclampedOffset ViewOrigin.X = SoftClamp(UnclampedViewOrigin.X, viewMin.X, viewMax.X); ViewOrigin.Y = SoftClamp(UnclampedViewOrigin.Y, viewMin.Y, viewMax.Y); } else { // Apply velocity ApplyVelocity(dt, ref ViewOrigin.X, ref Velocity.X, viewMin.X, viewMax.X); ApplyVelocity(dt, ref ViewOrigin.Y, ref Velocity.Y, viewMin.Y, viewMax.Y); } ViewRect.X = (int)ViewOrigin.X; ViewRect.Y = (int)ViewOrigin.Y; } // This must be called manually each tick that the ScrollTracker is active. public void HandleInput(InputState input) { // Turn on tracking as soon as we seen any kind of touch. We can't use gestures for this // because no gesture data is returned on the initial touch. We have to be careful to // pick out only 'Pressed' locations, because TouchState can return other events a frame // *after* we've seen GestureType.Flick or GestureType.DragComplete. if (!IsTracking) { for (int i = 0; i < input.TouchState.Count; i++) { if (input.TouchState[i].State == TouchLocationState.Pressed) { Velocity = Vector2.Zero; UnclampedViewOrigin = ViewOrigin; IsTracking = true; break; } } } foreach (GestureSample sample in input.Gestures) { switch (sample.GestureType) { case GestureType.VerticalDrag: UnclampedViewOrigin.Y -= sample.Delta.Y; break; case GestureType.Flick: // Only respond to mostly-vertical flicks if (Math.Abs(sample.Delta.X) < Math.Abs(sample.Delta.Y)) { IsTracking = false; Velocity = -sample.Delta; } break; case GestureType.DragComplete: IsTracking = false; break; } } } // If x is within the range (min,max), just return x. Otherwise return a value outside of (min,max) // but only partway to where x is. This is used to get the partial-overdrag effect at the edges // of the list. static float SoftClamp(float x, float min, float max) { if (x < min) { return Math.Max(x - min, -SpringMaxDrag) * SpringMaxOffset / SpringMaxDrag + min; } if (x > max) { return Math.Min(x - max, SpringMaxDrag) * SpringMaxOffset / SpringMaxDrag + max; } return x; } // Integrate the given position and velocity over a timespan. Min and max give the // soft limits that the position is allowed to move to. void ApplyVelocity(float dt, ref float x, ref float v, float min, float max) { float x0 = x; x += v * dt; // Apply deceleration to gradually reduce velocity v = MathHelper.Clamp(v, -MaxVelocity, MaxVelocity); v = Math.Max(Math.Abs(v) - dt * Deceleration, 0.0f) * Math.Sign(v); // If we've scrolled past the edge, gradually reset to edge if (x < min) { x = Math.Min(x + (min - x) * SpringReturnRate + SpringReturnMin, min); v = 0; } if (x > max) { x = Math.Max(x - (x - max) * SpringReturnRate - SpringReturnMin, max); v = 0; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsAzureBodyDurationAllSync { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// Test Infrastructure for AutoRest /// </summary> public partial class AutoRestDurationTestService : ServiceClient<AutoRestDurationTestService>, IAutoRestDurationTestService, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Gets Azure subscription credentials. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IDurationOperations. /// </summary> public virtual IDurationOperations Duration { get; private set; } /// <summary> /// Initializes a new instance of the AutoRestDurationTestService class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestDurationTestService(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestDurationTestService class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestDurationTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestDurationTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestDurationTestService(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestDurationTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestDurationTestService(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestDurationTestService class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestDurationTestService(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestDurationTestService class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestDurationTestService(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestDurationTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestDurationTestService(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestDurationTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestDurationTestService(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.Duration = new DurationOperations(this); this.BaseUri = new Uri("https://localhost"); this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Windows; using Microsoft.Practices.Prism.Properties; using Microsoft.Practices.ServiceLocation; namespace Microsoft.Practices.Prism.Regions { /// <summary> /// Implementation of <see cref="IRegion"/> that allows multiple active views. /// </summary> public class Region : IRegion { private ObservableCollection<ItemMetadata> itemMetadataCollection; private string name; private ViewsCollection views; private ViewsCollection activeViews; private object context; private IRegionManager regionManager; private IRegionNavigationService regionNavigationService; private Comparison<object> sort; /// <summary> /// Initializes a new instance of <see cref="Region"/>. /// </summary> public Region() { this.Behaviors = new RegionBehaviorCollection(this); this.sort = Region.DefaultSortComparison; } /// <summary> /// Occurs when a property value changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Gets the collection of <see cref="IRegionBehavior"/>s that can extend the behavior of regions. /// </summary> public IRegionBehaviorCollection Behaviors { get; private set; } /// <summary> /// Gets or sets a context for the region. This value can be used by the user to share context with the views. /// </summary> /// <value>The context value to be shared.</value> public object Context { get { return this.context; } set { if (this.context != value) { this.context = value; this.OnPropertyChanged("Context"); } } } /// <summary> /// Gets the name of the region that uniequely identifies the region within a <see cref="IRegionManager"/>. /// </summary> /// <value>The name of the region.</value> public string Name { get { return this.name; } set { if (this.name != null && this.name != value) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.CannotChangeRegionNameException, this.name)); } if (string.IsNullOrEmpty(value)) { throw new ArgumentException(Resources.RegionNameCannotBeEmptyException); } this.name = value; this.OnPropertyChanged("Name"); } } /// <summary> /// Gets a readonly view of the collection of views in the region. /// </summary> /// <value>An <see cref="IViewsCollection"/> of all the added views.</value> public virtual IViewsCollection Views { get { if (this.views == null) { this.views = new ViewsCollection(ItemMetadataCollection, x => true); this.views.SortComparison = this.sort; } return this.views; } } /// <summary> /// Gets a readonly view of the collection of all the active views in the region. /// </summary> /// <value>An <see cref="IViewsCollection"/> of all the active views.</value> public virtual IViewsCollection ActiveViews { get { if (this.activeViews == null) { this.activeViews = new ViewsCollection(ItemMetadataCollection, x => x.IsActive); this.activeViews.SortComparison = this.sort; } return this.activeViews; } } /// <summary> /// Gets or sets the comparison used to sort the views. /// </summary> /// <value>The comparison to use.</value> public Comparison<object> SortComparison { get { return this.sort; } set { this.sort = value; if (this.activeViews != null) { this.activeViews.SortComparison = this.sort; } if (this.views != null) { this.views.SortComparison = this.sort; } } } /// <summary> /// Gets or sets the <see cref="IRegionManager"/> that will be passed to the views when adding them to the region, unless the view is added by specifying createRegionManagerScope as <see langword="true" />. /// </summary> /// <value>The <see cref="IRegionManager"/> where this <see cref="IRegion"/> is registered.</value> /// <remarks>This is usually used by implementations of <see cref="IRegionManager"/> and should not be /// used by the developer explicitely.</remarks> public IRegionManager RegionManager { get { return this.regionManager; } set { if (this.regionManager != value) { this.regionManager = value; this.OnPropertyChanged("RegionManager"); } } } /// <summary> /// Gets the navigation service. /// </summary> /// <value>The navigation service.</value> public IRegionNavigationService NavigationService { get { if (this.regionNavigationService == null) { this.regionNavigationService = ServiceLocator.Current.GetInstance<IRegionNavigationService>(); this.regionNavigationService.Region = this; } return this.regionNavigationService; } set { this.regionNavigationService = value; } } /// <summary> /// Gets the collection with all the views along with their metadata. /// </summary> /// <value>An <see cref="ObservableCollection{T}"/> of <see cref="ItemMetadata"/> with all the added views.</value> protected virtual ObservableCollection<ItemMetadata> ItemMetadataCollection { get { if (this.itemMetadataCollection == null) { this.itemMetadataCollection = new ObservableCollection<ItemMetadata>(); } return this.itemMetadataCollection; } } /// <overloads>Adds a new view to the region.</overloads> /// <summary> /// Adds a new view to the region. /// </summary> /// <param name="view">The view to add.</param> /// <returns>The <see cref="IRegionManager"/> that is set on the view if it is a <see cref="DependencyObject"/>. It will be the current region manager when using this overload.</returns> public IRegionManager Add(object view) { return this.Add(view, null, false); } /// <summary> /// Adds a new view to the region. /// </summary> /// <param name="view">The view to add.</param> /// <param name="viewName">The name of the view. This can be used to retrieve it later by calling <see cref="IRegion.GetView"/>.</param> /// <returns>The <see cref="IRegionManager"/> that is set on the view if it is a <see cref="DependencyObject"/>. It will be the current region manager when using this overload.</returns> public IRegionManager Add(object view, string viewName) { if (string.IsNullOrEmpty(viewName)) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.StringCannotBeNullOrEmpty, "viewName")); } return this.Add(view, viewName, false); } /// <summary> /// Adds a new view to the region. /// </summary> /// <param name="view">The view to add.</param> /// <param name="viewName">The name of the view. This can be used to retrieve it later by calling <see cref="IRegion.GetView"/>.</param> /// <param name="createRegionManagerScope">When <see langword="true"/>, the added view will receive a new instance of <see cref="IRegionManager"/>, otherwise it will use the current region manager for this region.</param> /// <returns>The <see cref="IRegionManager"/> that is set on the view if it is a <see cref="DependencyObject"/>.</returns> public virtual IRegionManager Add(object view, string viewName, bool createRegionManagerScope) { IRegionManager manager = createRegionManagerScope ? this.RegionManager.CreateRegionManager() : this.RegionManager; this.InnerAdd(view, viewName, manager); return manager; } /// <summary> /// Removes the specified view from the region. /// </summary> /// <param name="view">The view to remove.</param> public virtual void Remove(object view) { ItemMetadata itemMetadata = this.GetItemMetadataOrThrow(view); this.ItemMetadataCollection.Remove(itemMetadata); DependencyObject dependencyObject = view as DependencyObject; if (dependencyObject != null && Regions.RegionManager.GetRegionManager(dependencyObject) == this.RegionManager) { dependencyObject.ClearValue(Regions.RegionManager.RegionManagerProperty); } } /// <summary> /// Marks the specified view as active. /// </summary> /// <param name="view">The view to activate.</param> public virtual void Activate(object view) { ItemMetadata itemMetadata = this.GetItemMetadataOrThrow(view); if (!itemMetadata.IsActive) { itemMetadata.IsActive = true; } } /// <summary> /// Marks the specified view as inactive. /// </summary> /// <param name="view">The view to deactivate.</param> public virtual void Deactivate(object view) { ItemMetadata itemMetadata = this.GetItemMetadataOrThrow(view); if (itemMetadata.IsActive) { itemMetadata.IsActive = false; } } /// <summary> /// Returns the view instance that was added to the region using a specific name. /// </summary> /// <param name="viewName">The name used when adding the view to the region.</param> /// <returns>Returns the named view or <see langword="null"/> if the view with <paramref name="viewName"/> does not exist in the current region.</returns> public virtual object GetView(string viewName) { if (string.IsNullOrEmpty(viewName)) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.StringCannotBeNullOrEmpty, "viewName")); } ItemMetadata metadata = this.ItemMetadataCollection.FirstOrDefault(x => x.Name == viewName); if (metadata != null) { return metadata.Item; } return null; } /// <summary> /// Initiates navigation to the specified target. /// </summary> /// <param name="target">The target.</param> /// <param name="navigationCallback">A callback to execute when the navigation request is completed.</param> public void RequestNavigate(Uri target, Action<NavigationResult> navigationCallback) { this.RequestNavigate(target, navigationCallback, null); } /// <summary> /// Initiates navigation to the specified target. /// </summary> /// <param name="target">The target.</param> /// <param name="navigationCallback">A callback to execute when the navigation request is completed.</param> /// <param name="navigationParameters">The navigation parameters specific to the navigation request.</param> public void RequestNavigate(Uri target, Action<NavigationResult> navigationCallback, NavigationParameters navigationParameters) { this.NavigationService.RequestNavigate(target, navigationCallback, navigationParameters); } private void InnerAdd(object view, string viewName, IRegionManager scopedRegionManager) { if (this.ItemMetadataCollection.FirstOrDefault(x => x.Item == view) != null) { throw new InvalidOperationException(Resources.RegionViewExistsException); } ItemMetadata itemMetadata = new ItemMetadata(view); if (!string.IsNullOrEmpty(viewName)) { if (this.ItemMetadataCollection.FirstOrDefault(x => x.Name == viewName) != null) { throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, Resources.RegionViewNameExistsException, viewName)); } itemMetadata.Name = viewName; } DependencyObject dependencyObject = view as DependencyObject; if (dependencyObject != null) { Regions.RegionManager.SetRegionManager(dependencyObject, scopedRegionManager); } this.ItemMetadataCollection.Add(itemMetadata); } private ItemMetadata GetItemMetadataOrThrow(object view) { if (view == null) { throw new ArgumentNullException("view"); } ItemMetadata itemMetadata = this.ItemMetadataCollection.FirstOrDefault(x => x.Item == view); if (itemMetadata == null) { throw new ArgumentException(Resources.ViewNotInRegionException, "view"); } return itemMetadata; } private void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler eventHandler = this.PropertyChanged; if (eventHandler != null) { eventHandler(this, new PropertyChangedEventArgs(propertyName)); } } /// <summary> /// The default sort algorithm. /// </summary> /// <param name="x">The first view to compare.</param> /// <param name="y">The second view to compare.</param> /// <returns></returns> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "y")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "x")] public static int DefaultSortComparison(object x, object y) { if (x == null) { if (y == null) { return 0; } else { return -1; } } else { if (y == null) { return 1; } else { Type xType = x.GetType(); Type yType = y.GetType(); ViewSortHintAttribute xAttribute = xType.GetCustomAttributes(typeof(ViewSortHintAttribute), true).FirstOrDefault() as ViewSortHintAttribute; ViewSortHintAttribute yAttribute = yType.GetCustomAttributes(typeof(ViewSortHintAttribute), true).FirstOrDefault() as ViewSortHintAttribute; return ViewSortHintAttributeComparison(xAttribute, yAttribute); } } } private static int ViewSortHintAttributeComparison(ViewSortHintAttribute x, ViewSortHintAttribute y) { if (x == null) { if (y == null) { return 0; } else { return -1; } } else { if (y == null) { return 1; } else { return string.Compare(x.Hint, y.Hint, StringComparison.Ordinal); } } } } }
// // The Open Toolkit Library License // // Copyright (c) 2006 - 2009 the Open Toolkit library. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Diagnostics; using OpenTK.Graphics; namespace OpenTK.Platform.Egl { public interface IEglContext { IEglWindowInfo MyWindowInfo { get; } } abstract class EglContext : EmbeddedGraphicsContext, IEglContext { protected readonly RenderableFlags Renderable; internal EglWindowInfo WindowInfo; internal GraphicsContextFlags GraphicsContextFlags { get; set; } internal IntPtr HandleAsEGLContext { get => Handle.Handle; set { Handle = new ContextHandle(value); } } private int swap_interval = 1; // Default interval is defined as 1 in EGL. public EglContext(GraphicsMode mode, EglWindowInfo window, IGraphicsContext sharedContext, int major, int minor, GraphicsContextFlags flags) { if (mode == null) { throw new ArgumentNullException("mode"); } if (window == null) { throw new ArgumentNullException("window"); } //Egl.BindAPI(0x30A0); //bind EGL_OPENGL_ES_API Egl.BindAPI(RenderApi.ES); //bind EGL_OPENGL_ES_API EglContext shared = GetSharedEglContext(sharedContext); WindowInfo = window; // Select an EGLConfig that matches the desired mode. We cannot use the 'mode' // parameter directly, since it may have originated on a different system (e.g. GLX) // and it may not support the desired renderer. Renderable = RenderableFlags.GL; if ((flags & GraphicsContextFlags.Embedded) != 0) { switch (major) { case 3: Renderable = RenderableFlags.ES3; break; case 2: Renderable = RenderableFlags.ES2; break; default: Renderable = RenderableFlags.ES; break; } } RenderApi api = (Renderable & RenderableFlags.GL) != 0 ? RenderApi.GL : RenderApi.ES; Debug.Print("[EGL] Binding {0} rendering API.", api); if (!Egl.BindAPI(api)) { Debug.Print("[EGL] Failed to bind rendering API. Error: {0}", Egl.GetError()); } bool offscreen = (flags & GraphicsContextFlags.Offscreen) != 0; SurfaceType surfaceType = offscreen ? SurfaceType.PBUFFER_BIT : SurfaceType.WINDOW_BIT; Mode = new EglGraphicsMode().SelectGraphicsMode(surfaceType, window.Display, mode.ColorFormat, mode.Depth, mode.Stencil, mode.Samples, mode.AccumulatorFormat, mode.Buffers, mode.Stereo, Renderable); if (!Mode.Index.HasValue) { throw new GraphicsModeException("Invalid or unsupported GraphicsMode."); } IntPtr config = Mode.Index.Value; if (window.Surface == IntPtr.Zero) { if (!offscreen) { window.CreateWindowSurface(config); } else { window.CreatePbufferSurface(config); } } int[] attribList = { Egl.CONTEXT_CLIENT_VERSION, major, Egl.NONE }; IntPtr shareContext = shared?.HandleAsEGLContext ?? IntPtr.Zero; //TODO: review here,*** //temp fix => so We can open multiple GL windows shareContext = IntPtr.Zero; HandleAsEGLContext = Egl.CreateContext(window.Display, config, shareContext, attribList); GraphicsContextFlags = flags; } public EglContext(ContextHandle handle, EglWindowInfo window, IGraphicsContext sharedContext, int major, int minor, GraphicsContextFlags flags) { if (handle == ContextHandle.Zero) { throw new ArgumentException("handle"); } if (window == null) { throw new ArgumentNullException("window"); } Handle = handle; } public override void SwapBuffers() { if (!Egl.SwapBuffers(WindowInfo.Display, WindowInfo.Surface)) { throw new GraphicsContextException(string.Format("Failed to swap buffers for context {0} current. Error: {1}", Handle, Egl.GetError())); } } public override void MakeCurrent(IWindowInfo window) { // Ignore 'window', unless it actually is an EGL window. In other words, // trying to make the EglContext current on a non-EGL window will do, // nothing (the EglContext will remain current on the previous EGL window // or the window it was constructed on (which may not be EGL)). if (window != null) { if (window is EglWindowInfo) { WindowInfo = (EglWindowInfo)window; } #if !ANDROID else if (window is IAngleWindowInfoInternal) { WindowInfo = ((IAngleWindowInfoInternal)window).EglWindowInfo; } #endif if (!Egl.MakeCurrent(WindowInfo.Display, WindowInfo.Surface, WindowInfo.Surface, HandleAsEGLContext)) { throw new GraphicsContextException(string.Format("Failed to make context {0} current. Error: {1}", Handle, Egl.GetError())); } } else { Egl.MakeCurrent(WindowInfo.Display, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); } } public override bool IsCurrent { get { return Egl.GetCurrentContext() == HandleAsEGLContext; } } public override int SwapInterval { get { // Egl.GetSwapInterval does not exist, so store and return the current interval. // The default interval is defined as 1 (true). return swap_interval; } set { if (value < 0) { // EGL does not offer EXT_swap_control_tear yet value = 1; } if (Egl.SwapInterval(WindowInfo.Display, value)) { swap_interval = value; } else { Debug.Print("[Warning] Egl.SwapInterval({0}, {1}) failed. Error: {2}", WindowInfo.Display, value, Egl.GetError()); } } } public override void Update(IWindowInfo window) { MakeCurrent(window); // ANGLE updates the width and height of the back buffer surfaces in the WaitClient function. // So without this calling this function, the surface won't match the size of the window after it // was resized. // https://bugs.chromium.org/p/angleproject/issues/detail?id=1438 if (!Egl.WaitClient()) { Debug.Print("[Warning] Egl.WaitClient() failed. Error: {0}", Egl.GetError()); } } public override IntPtr GetAddress(IntPtr function) { // Try loading a static export from ES1 or ES2 IntPtr address = GetStaticAddress(function, Renderable); // If a static export is not available, try retrieving an extension // function pointer with eglGetProcAddress if (address == IntPtr.Zero) { unsafe { string funcName = new string((sbyte*)function); address = Egl.GetProcAddress(funcName); } } return address; } protected abstract IntPtr GetStaticAddress(IntPtr function, RenderableFlags renderable); // Todo: cross-reference the specs. What should happen if the context is destroyed from a different // thread? protected override void Dispose(bool manual) { if (!IsDisposed) { if (manual) { if (IsCurrent) { Egl.MakeCurrent(WindowInfo.Display, WindowInfo.Surface, WindowInfo.Surface, IntPtr.Zero); } Egl.DestroyContext(WindowInfo.Display, HandleAsEGLContext); } IsDisposed = true; } } private EglContext GetSharedEglContext(IGraphicsContext sharedContext) { if (sharedContext == null) { return null; } var internalContext = sharedContext as IGraphicsContextInternal; if (internalContext != null) { return (EglContext)internalContext.Implementation; } return (EglContext)sharedContext; } public IEglWindowInfo MyWindowInfo { get { return this.WindowInfo; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Text; using Flexo.Extensions; using Tests.Collections.Implementations; namespace Tests.Performance { public enum Format { Json, Xml } [DataContract(Namespace = "")] public class Dummy { [DataMember] public string Oh { get; set; } } public class Benchmarks : GenericListImpl<BenchmarkSerializer> { public const string BenderSerializer = "Bender"; public void Run<T>(Format format, string path) { Run(typeof(T), format, path); } public void Run(Type type, Format format, string path) { var types = new Stack<Type>(AppDomain.CurrentDomain.GenerateTypes(200) .Select(x => type.MakeGenericType(x))); var benchmarks = this.Where(x => x.Format == format).ToList(); var source = File.ReadAllText(path); var random = new Random(); Func<string> generateSource = () => Enumerable.Range(1, 100).Select(x => "%" + x) .Aggregate(source, (a, i) => a.Replace(i, Guid.NewGuid().ToString().Substring(0, random.Next(10, 32)))); Action<BenchmarkSerializer> dummyRun = x => { var dummySource = format == Format.Xml ? "<Dummy><Oh>Hai</Oh></Dummy>" : "{\"Oh\":\"Hai\"}"; x.Run(typeof (Dummy), dummySource, dryRun: true); }; Enumerable.Range(1, 20).ForEach(x => benchmarks.ForEach(y => { var newType = types.Pop(); dummyRun(y); y.Run(newType, generateSource()); // Cold Enumerable.Range(1, 20).ForEach(z => { dummyRun(y); y.Run(newType, generateSource(), true); // Warm }); })); } public IEnumerable<Benchmark> GetResults() { return this .SelectMany(x => x.Select(y => new { x.Name, x.Format, x.Summary, y.Bytes, y.Warm, y.Parse, y.Deserialize, y.Serialize, y.Encode })) .GroupBy(x => "{0}-{1}".ToFormat(x.Name, x.Format)) .Select(x => new Benchmark( x.First().Name, x.First().Format, x.First().Summary) { Bytes = (long)x.Average(y => y.Bytes), ColdSerialize = (long)x.Where(y => !y.Warm).Average(y => y.Serialize), ColdDeserialize = (long)x.Where(y => !y.Warm).Average(y => y.Deserialize), WarmSerialize = (long)x.Where(y => y.Warm).Average(y => y.Serialize), WarmDeserialize = (long)x.Where(y => y.Warm).Average(y => y.Deserialize), ColdEncode = (long)x.Where(y => !y.Warm).Average(y => y.Encode), ColdParse = (long)x.Where(y => !y.Warm).Average(y => y.Parse), WarmEncode = (long)x.Where(y => y.Warm).Average(y => y.Encode), WarmParse = (long)x.Where(y => y.Warm).Average(y => y.Parse) }); } public void SaveSummaryGraph(string path, bool cold = true, bool warm = true) { BenchmarkChart.SaveSummary(GetResults(), Path.Combine("../../", path), cold, warm); } public void SaveJsonSummaryReport(string path) { File.WriteAllText(Path.Combine("../../", path), GetJsonSummaryReport()); } public void SaveTextSummaryReport(string path) { File.WriteAllText(Path.Combine("../../", path), GetTextSummaryReport()); } public void SaveTextDetailReport(string path) { File.WriteAllText(Path.Combine("../../", path), GetTextDetailReport()); } public string GetTextDetailReport(string path) { path = Path.Combine("../../", path); return File.Exists(path) ? File.ReadAllText(path) : ""; } public string GetJsonSummaryReport() { var report = new StringBuilder(); report.AppendLine("["); GetResults().OrderBy(x => x.Name).ForEach(x => report.AppendLine(( "\t{{ \"Name\": \"{0}\", " + "\"Cold\": {{ \"Deserialization\": {1}, \"Serialization\": {2} }}, " + "\"Warm\": {{ \"Deserialization\": {3}, \"Serialization\": {4} }} }}").ToFormat( "{0} {1}".ToFormat(x.Name, x.Format), x.ColdDeserialize + x.ColdParse, x.ColdSerialize + x.ColdEncode, x.WarmDeserialize + x.WarmParse, x.WarmSerialize + x.WarmEncode))); report.AppendLine("]"); return report.ToString(); } public string GetTextSummaryReport() { var results = GetResults().OrderBy(x => x.WarmDeserialize + x.WarmParse + x.WarmEncode + x.WarmSerialize).Select(x => new { x.Format, Results = "{0} | {1} | {2} | {3} | {4} |".ToFormat( "{0} {1}".ToFormat(x.Name, x.Format).PadRight(31), (x.ColdDeserialize + x.ColdParse).ToString("#,###").PadLeft(11), (x.ColdSerialize + x.ColdEncode).ToString("#,###").PadLeft(11), (x.WarmDeserialize + x.WarmParse).ToString("#,###").PadLeft(11), (x.WarmSerialize + x.WarmEncode).ToString("#,###").PadLeft(11))}); var report = new StringBuilder(); report.AppendLine(" ---------------------------------------------------------"); report.AppendLine(" | Cold | Warm |"); report.AppendLine(" | Deserialize | Serialize | Deserialize | Serialize |"); report.AppendLine("-----------------------------------------------------------------------------------------"); results.Where(x => x.Format == Format.Json).ForEach(x => report.AppendLine(x.Results)); report.AppendLine("-----------------------------------------------------------------------------------------"); results.Where(x => x.Format == Format.Xml).ForEach(x => report.AppendLine(x.Results)); report.AppendLine("-----------------------------------------------------------------------------------------"); return report.ToString(); } public string GetTextDetailReport() { var report = new StringBuilder(); const string detailFormat = "{0:#,###} -> {1:#,###}"; report.AppendLine(" -------------------------------------------------------------------------------------------"); report.AppendLine(" | Cold | Warm |"); report.AppendLine(" | Parse -> Deserialize | Serialize -> Encode | Parse -> Deserialize | Serialize -> Encode |"); report.AppendLine("-------------------------------------------------------------------------------------------------------"); GetResults().Where(x => !x.Summary).OrderBy(x => x.Name).ForEach(x => report.AppendLine("{0} | {1} | {2} | {3} | {4} |".ToFormat( "{0} {1}".ToFormat(x.Name, x.Format).PadRight(11), detailFormat.ToFormat(x.ColdParse, x.ColdDeserialize).PadLeft(20), detailFormat.ToFormat(x.ColdSerialize, x.ColdEncode).PadLeft(19), detailFormat.ToFormat(x.WarmParse, x.WarmDeserialize).PadLeft(20), detailFormat.ToFormat(x.WarmSerialize, x.WarmEncode).PadLeft(19)))); report.AppendLine("-------------------------------------------------------------------------------------------------------"); return report.ToString(); } public class Benchmark { public Benchmark(string name, Format format, bool summary) { Name = name; Format = format; Summary = summary; } public string Name { get; } public Format Format { get; } public bool Summary { get; } public long Bytes { get; set; } public bool IsBender => Name == BenderSerializer; public long ColdSerialize { get; set; } public long ColdDeserialize { get; set; } public long WarmSerialize { get; set; } public long WarmDeserialize { get; set; } public long ColdEncode { get; set; } public long ColdParse { get; set; } public long WarmEncode { get; set; } public long WarmParse { get; set; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System { public static partial class MemoryExtensions { public static System.ReadOnlyMemory<char> AsMemory(this string text) { throw null; } public static System.ReadOnlyMemory<char> AsMemory(this string text, System.Index startIndex) { throw null; } public static System.ReadOnlyMemory<char> AsMemory(this string text, int start) { throw null; } public static System.ReadOnlyMemory<char> AsMemory(this string text, int start, int length) { throw null; } public static System.ReadOnlyMemory<char> AsMemory(this string text, System.Range range) { throw null; } public static System.Memory<T> AsMemory<T>(this System.ArraySegment<T> segment) { throw null; } public static System.Memory<T> AsMemory<T>(this System.ArraySegment<T> segment, int start) { throw null; } public static System.Memory<T> AsMemory<T>(this System.ArraySegment<T> segment, int start, int length) { throw null; } public static System.Memory<T> AsMemory<T>(this T[] array) { throw null; } public static System.Memory<T> AsMemory<T>(this T[] array, System.Index startIndex) { throw null; } public static System.Memory<T> AsMemory<T>(this T[] array, int start) { throw null; } public static System.Memory<T> AsMemory<T>(this T[] array, int start, int length) { throw null; } public static System.Memory<T> AsMemory<T>(this T[] array, System.Range range) { throw null; } public static System.ReadOnlySpan<char> AsSpan(this string text) { throw null; } public static System.ReadOnlySpan<char> AsSpan(this string text, int start) { throw null; } public static System.ReadOnlySpan<char> AsSpan(this string text, int start, int length) { throw null; } public static System.Span<T> AsSpan<T>(this System.ArraySegment<T> segment) { throw null; } public static System.Span<T> AsSpan<T>(this System.ArraySegment<T> segment, System.Index startIndex) { throw null; } public static System.Span<T> AsSpan<T>(this System.ArraySegment<T> segment, int start) { throw null; } public static System.Span<T> AsSpan<T>(this System.ArraySegment<T> segment, int start, int length) { throw null; } public static System.Span<T> AsSpan<T>(this System.ArraySegment<T> segment, System.Range range) { throw null; } public static System.Span<T> AsSpan<T>(this T[] array) { throw null; } public static System.Span<T> AsSpan<T>(this T[] array, System.Index startIndex) { throw null; } public static System.Span<T> AsSpan<T>(this T[] array, int start) { throw null; } public static System.Span<T> AsSpan<T>(this T[] array, int start, int length) { throw null; } public static System.Span<T> AsSpan<T>(this T[] array, System.Range range) { throw null; } public static int BinarySearch<T>(this System.ReadOnlySpan<T> span, System.IComparable<T> comparable) { throw null; } public static int BinarySearch<T>(this System.Span<T> span, System.IComparable<T> comparable) { throw null; } public static int BinarySearch<T, TComparer>(this System.ReadOnlySpan<T> span, T value, TComparer comparer) where TComparer : System.Collections.Generic.IComparer<T> { throw null; } public static int BinarySearch<T, TComparable>(this System.ReadOnlySpan<T> span, TComparable comparable) where TComparable : System.IComparable<T> { throw null; } public static int BinarySearch<T, TComparer>(this System.Span<T> span, T value, TComparer comparer) where TComparer : System.Collections.Generic.IComparer<T> { throw null; } public static int BinarySearch<T, TComparable>(this System.Span<T> span, TComparable comparable) where TComparable : System.IComparable<T> { throw null; } public static int CompareTo(this System.ReadOnlySpan<char> span, System.ReadOnlySpan<char> other, System.StringComparison comparisonType) { throw null; } public static bool Contains(this System.ReadOnlySpan<char> span, System.ReadOnlySpan<char> value, System.StringComparison comparisonType) { throw null; } public static bool Contains<T>(this System.ReadOnlySpan<T> span, T value) where T : System.IEquatable<T> { throw null; } public static bool Contains<T>(this System.Span<T> span, T value) where T : System.IEquatable<T> { throw null; } public static void CopyTo<T>(this T[] source, System.Memory<T> destination) { } public static void CopyTo<T>(this T[] source, System.Span<T> destination) { } public static bool EndsWith(this System.ReadOnlySpan<char> span, System.ReadOnlySpan<char> value, System.StringComparison comparisonType) { throw null; } public static bool EndsWith<T>(this System.ReadOnlySpan<T> span, System.ReadOnlySpan<T> value) where T : System.IEquatable<T> { throw null; } public static bool EndsWith<T>(this System.Span<T> span, System.ReadOnlySpan<T> value) where T : System.IEquatable<T> { throw null; } public static System.Text.SpanRuneEnumerator EnumerateRunes(this System.ReadOnlySpan<char> span) { throw null; } public static System.Text.SpanRuneEnumerator EnumerateRunes(this System.Span<char> span) { throw null; } public static bool Equals(this System.ReadOnlySpan<char> span, System.ReadOnlySpan<char> other, System.StringComparison comparisonType) { throw null; } public static int IndexOf(this System.ReadOnlySpan<char> span, System.ReadOnlySpan<char> value, System.StringComparison comparisonType) { throw null; } public static int IndexOfAny<T>(this System.ReadOnlySpan<T> span, System.ReadOnlySpan<T> values) where T : System.IEquatable<T> { throw null; } public static int IndexOfAny<T>(this System.ReadOnlySpan<T> span, T value0, T value1) where T : System.IEquatable<T> { throw null; } public static int IndexOfAny<T>(this System.ReadOnlySpan<T> span, T value0, T value1, T value2) where T : System.IEquatable<T> { throw null; } public static int IndexOfAny<T>(this System.Span<T> span, System.ReadOnlySpan<T> values) where T : System.IEquatable<T> { throw null; } public static int IndexOfAny<T>(this System.Span<T> span, T value0, T value1) where T : System.IEquatable<T> { throw null; } public static int IndexOfAny<T>(this System.Span<T> span, T value0, T value1, T value2) where T : System.IEquatable<T> { throw null; } public static int IndexOf<T>(this System.ReadOnlySpan<T> span, System.ReadOnlySpan<T> value) where T : System.IEquatable<T> { throw null; } public static int IndexOf<T>(this System.ReadOnlySpan<T> span, T value) where T : System.IEquatable<T> { throw null; } public static int IndexOf<T>(this System.Span<T> span, System.ReadOnlySpan<T> value) where T : System.IEquatable<T> { throw null; } public static int IndexOf<T>(this System.Span<T> span, T value) where T : System.IEquatable<T> { throw null; } public static bool IsWhiteSpace(this System.ReadOnlySpan<char> span) { throw null; } public static int LastIndexOf(this System.ReadOnlySpan<char> span, System.ReadOnlySpan<char> value, System.StringComparison comparisonType) { throw null; } public static int LastIndexOfAny<T>(this System.ReadOnlySpan<T> span, System.ReadOnlySpan<T> values) where T : System.IEquatable<T> { throw null; } public static int LastIndexOfAny<T>(this System.ReadOnlySpan<T> span, T value0, T value1) where T : System.IEquatable<T> { throw null; } public static int LastIndexOfAny<T>(this System.ReadOnlySpan<T> span, T value0, T value1, T value2) where T : System.IEquatable<T> { throw null; } public static int LastIndexOfAny<T>(this System.Span<T> span, System.ReadOnlySpan<T> values) where T : System.IEquatable<T> { throw null; } public static int LastIndexOfAny<T>(this System.Span<T> span, T value0, T value1) where T : System.IEquatable<T> { throw null; } public static int LastIndexOfAny<T>(this System.Span<T> span, T value0, T value1, T value2) where T : System.IEquatable<T> { throw null; } public static int LastIndexOf<T>(this System.ReadOnlySpan<T> span, System.ReadOnlySpan<T> value) where T : System.IEquatable<T> { throw null; } public static int LastIndexOf<T>(this System.ReadOnlySpan<T> span, T value) where T : System.IEquatable<T> { throw null; } public static int LastIndexOf<T>(this System.Span<T> span, System.ReadOnlySpan<T> value) where T : System.IEquatable<T> { throw null; } public static int LastIndexOf<T>(this System.Span<T> span, T value) where T : System.IEquatable<T> { throw null; } public static bool Overlaps<T>(this System.ReadOnlySpan<T> span, System.ReadOnlySpan<T> other) { throw null; } public static bool Overlaps<T>(this System.ReadOnlySpan<T> span, System.ReadOnlySpan<T> other, out int elementOffset) { throw null; } public static bool Overlaps<T>(this System.Span<T> span, System.ReadOnlySpan<T> other) { throw null; } public static bool Overlaps<T>(this System.Span<T> span, System.ReadOnlySpan<T> other, out int elementOffset) { throw null; } public static void Reverse<T>(this System.Span<T> span) { } public static int SequenceCompareTo<T>(this System.ReadOnlySpan<T> span, System.ReadOnlySpan<T> other) where T : System.IComparable<T> { throw null; } public static int SequenceCompareTo<T>(this System.Span<T> span, System.ReadOnlySpan<T> other) where T : System.IComparable<T> { throw null; } public static bool SequenceEqual<T>(this System.ReadOnlySpan<T> span, System.ReadOnlySpan<T> other) where T : System.IEquatable<T> { throw null; } public static bool SequenceEqual<T>(this System.Span<T> span, System.ReadOnlySpan<T> other) where T : System.IEquatable<T> { throw null; } public static bool StartsWith(this System.ReadOnlySpan<char> span, System.ReadOnlySpan<char> value, System.StringComparison comparisonType) { throw null; } public static bool StartsWith<T>(this System.ReadOnlySpan<T> span, System.ReadOnlySpan<T> value) where T : System.IEquatable<T> { throw null; } public static bool StartsWith<T>(this System.Span<T> span, System.ReadOnlySpan<T> value) where T : System.IEquatable<T> { throw null; } public static int ToLower(this System.ReadOnlySpan<char> source, System.Span<char> destination, System.Globalization.CultureInfo culture) { throw null; } public static int ToLowerInvariant(this System.ReadOnlySpan<char> source, System.Span<char> destination) { throw null; } public static int ToUpper(this System.ReadOnlySpan<char> source, System.Span<char> destination, System.Globalization.CultureInfo culture) { throw null; } public static int ToUpperInvariant(this System.ReadOnlySpan<char> source, System.Span<char> destination) { throw null; } public static System.ReadOnlySpan<char> Trim(this System.ReadOnlySpan<char> span) { throw null; } public static System.ReadOnlySpan<char> Trim(this System.ReadOnlySpan<char> span, char trimChar) { throw null; } public static System.ReadOnlySpan<char> Trim(this System.ReadOnlySpan<char> span, System.ReadOnlySpan<char> trimChars) { throw null; } public static System.ReadOnlySpan<char> TrimEnd(this System.ReadOnlySpan<char> span) { throw null; } public static System.ReadOnlySpan<char> TrimEnd(this System.ReadOnlySpan<char> span, char trimChar) { throw null; } public static System.ReadOnlySpan<char> TrimEnd(this System.ReadOnlySpan<char> span, System.ReadOnlySpan<char> trimChars) { throw null; } public static System.ReadOnlySpan<char> TrimStart(this System.ReadOnlySpan<char> span) { throw null; } public static System.ReadOnlySpan<char> TrimStart(this System.ReadOnlySpan<char> span, char trimChar) { throw null; } public static System.ReadOnlySpan<char> TrimStart(this System.ReadOnlySpan<char> span, System.ReadOnlySpan<char> trimChars) { throw null; } } public readonly partial struct SequencePosition : System.IEquatable<System.SequencePosition> { private readonly object _dummy; private readonly int _dummyPrimitive; public SequencePosition(object @object, int integer) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } public bool Equals(System.SequencePosition other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public int GetInteger() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public object GetObject() { throw null; } } } namespace System.Buffers { public static partial class BuffersExtensions { public static void CopyTo<T>(this in System.Buffers.ReadOnlySequence<T> source, System.Span<T> destination) { } public static System.SequencePosition? PositionOf<T>(this in System.Buffers.ReadOnlySequence<T> source, T value) where T : System.IEquatable<T> { throw null; } public static T[] ToArray<T>(this in System.Buffers.ReadOnlySequence<T> sequence) { throw null; } public static void Write<T>(this System.Buffers.IBufferWriter<T> writer, System.ReadOnlySpan<T> value) { } } public partial interface IBufferWriter<T> { void Advance(int count); System.Memory<T> GetMemory(int sizeHint = 0); System.Span<T> GetSpan(int sizeHint = 0); } public abstract partial class MemoryPool<T> : System.IDisposable { protected MemoryPool() { } public abstract int MaxBufferSize { get; } public static System.Buffers.MemoryPool<T> Shared { get { throw null; } } public void Dispose() { } protected abstract void Dispose(bool disposing); public abstract System.Buffers.IMemoryOwner<T> Rent(int minBufferSize = -1); } public abstract partial class ReadOnlySequenceSegment<T> { protected ReadOnlySequenceSegment() { } public System.ReadOnlyMemory<T> Memory { get { throw null; } protected set { } } public System.Buffers.ReadOnlySequenceSegment<T> Next { get { throw null; } protected set { } } public long RunningIndex { get { throw null; } protected set { } } } public readonly partial struct ReadOnlySequence<T> { private readonly object _dummy; private readonly int _dummyPrimitive; public static readonly System.Buffers.ReadOnlySequence<T> Empty; public ReadOnlySequence(System.Buffers.ReadOnlySequenceSegment<T> startSegment, int startIndex, System.Buffers.ReadOnlySequenceSegment<T> endSegment, int endIndex) { throw null; } public ReadOnlySequence(System.ReadOnlyMemory<T> memory) { throw null; } public ReadOnlySequence(T[] array) { throw null; } public ReadOnlySequence(T[] array, int start, int length) { throw null; } public System.SequencePosition End { get { throw null; } } public System.ReadOnlyMemory<T> First { get { throw null; } } public bool IsEmpty { get { throw null; } } public bool IsSingleSegment { get { throw null; } } public long Length { get { throw null; } } public System.SequencePosition Start { get { throw null; } } public System.Buffers.ReadOnlySequence<T>.Enumerator GetEnumerator() { throw null; } public System.SequencePosition GetPosition(long offset) { throw null; } public System.SequencePosition GetPosition(long offset, System.SequencePosition origin) { throw null; } public System.Buffers.ReadOnlySequence<T> Slice(int start, int length) { throw null; } public System.Buffers.ReadOnlySequence<T> Slice(int start, System.SequencePosition end) { throw null; } public System.Buffers.ReadOnlySequence<T> Slice(long start) { throw null; } public System.Buffers.ReadOnlySequence<T> Slice(long start, long length) { throw null; } public System.Buffers.ReadOnlySequence<T> Slice(long start, System.SequencePosition end) { throw null; } public System.Buffers.ReadOnlySequence<T> Slice(System.SequencePosition start) { throw null; } public System.Buffers.ReadOnlySequence<T> Slice(System.SequencePosition start, int length) { throw null; } public System.Buffers.ReadOnlySequence<T> Slice(System.SequencePosition start, long length) { throw null; } public System.Buffers.ReadOnlySequence<T> Slice(System.SequencePosition start, System.SequencePosition end) { throw null; } public override string ToString() { throw null; } public bool TryGet(ref System.SequencePosition position, out System.ReadOnlyMemory<T> memory, bool advance = true) { throw null; } public partial struct Enumerator { private object _dummy; private int _dummyPrimitive; public Enumerator(in System.Buffers.ReadOnlySequence<T> sequence) { throw null; } public System.ReadOnlyMemory<T> Current { get { throw null; } } public bool MoveNext() { throw null; } } } public static partial class SequenceReaderExtensions { public static bool TryReadBigEndian(this ref System.Buffers.SequenceReader<byte> reader, out short value) { throw null; } public static bool TryReadBigEndian(this ref System.Buffers.SequenceReader<byte> reader, out int value) { throw null; } public static bool TryReadBigEndian(this ref System.Buffers.SequenceReader<byte> reader, out long value) { throw null; } public static bool TryReadLittleEndian(this ref System.Buffers.SequenceReader<byte> reader, out short value) { throw null; } public static bool TryReadLittleEndian(this ref System.Buffers.SequenceReader<byte> reader, out int value) { throw null; } public static bool TryReadLittleEndian(this ref System.Buffers.SequenceReader<byte> reader, out long value) { throw null; } } public ref partial struct SequenceReader<T> where T : unmanaged, System.IEquatable<T> { public SequenceReader(System.Buffers.ReadOnlySequence<T> sequence) { throw null; } public long Consumed { get { throw null; } } public System.ReadOnlySpan<T> CurrentSpan { get { throw null; } } public int CurrentSpanIndex { get { throw null; } } public bool End { get { throw null; } } public long Length { get { throw null; } } public System.SequencePosition Position { get { throw null; } } public long Remaining { get { throw null; } } public System.Buffers.ReadOnlySequence<T> Sequence { get { throw null; } } public System.ReadOnlySpan<T> UnreadSpan { get { throw null; } } public void Advance(long count) { } public long AdvancePast(T value) { throw null; } public long AdvancePastAny(System.ReadOnlySpan<T> values) { throw null; } public long AdvancePastAny(T value0, T value1) { throw null; } public long AdvancePastAny(T value0, T value1, T value2) { throw null; } public long AdvancePastAny(T value0, T value1, T value2, T value3) { throw null; } public bool IsNext(System.ReadOnlySpan<T> next, bool advancePast = false) { throw null; } public bool IsNext(T next, bool advancePast = false) { throw null; } public void Rewind(long count) { } public bool TryAdvanceTo(T delimiter, bool advancePastDelimiter = true) { throw null; } public bool TryAdvanceToAny(System.ReadOnlySpan<T> delimiters, bool advancePastDelimiter = true) { throw null; } public bool TryCopyTo(System.Span<T> destination) { throw null; } public bool TryPeek(out T value) { throw null; } public bool TryRead(out T value) { throw null; } public bool TryReadTo(out System.Buffers.ReadOnlySequence<T> sequence, System.ReadOnlySpan<T> delimiter, bool advancePastDelimiter = true) { throw null; } public bool TryReadTo(out System.Buffers.ReadOnlySequence<T> sequence, T delimiter, bool advancePastDelimiter = true) { throw null; } public bool TryReadTo(out System.Buffers.ReadOnlySequence<T> sequence, T delimiter, T delimiterEscape, bool advancePastDelimiter = true) { throw null; } public bool TryReadTo(out System.ReadOnlySpan<T> span, T delimiter, bool advancePastDelimiter = true) { throw null; } public bool TryReadTo(out System.ReadOnlySpan<T> span, T delimiter, T delimiterEscape, bool advancePastDelimiter = true) { throw null; } public bool TryReadToAny(out System.Buffers.ReadOnlySequence<T> sequence, System.ReadOnlySpan<T> delimiters, bool advancePastDelimiter = true) { throw null; } public bool TryReadToAny(out System.ReadOnlySpan<T> span, System.ReadOnlySpan<T> delimiters, bool advancePastDelimiter = true) { throw null; } } public readonly partial struct StandardFormat : System.IEquatable<System.Buffers.StandardFormat> { private readonly int _dummyPrimitive; public const byte MaxPrecision = (byte)99; public const byte NoPrecision = (byte)255; public StandardFormat(char symbol, byte precision = (byte)255) { throw null; } public bool HasPrecision { get { throw null; } } public bool IsDefault { get { throw null; } } public byte Precision { get { throw null; } } public char Symbol { get { throw null; } } public bool Equals(System.Buffers.StandardFormat other) { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.Buffers.StandardFormat left, System.Buffers.StandardFormat right) { throw null; } public static implicit operator System.Buffers.StandardFormat (char symbol) { throw null; } public static bool operator !=(System.Buffers.StandardFormat left, System.Buffers.StandardFormat right) { throw null; } public static System.Buffers.StandardFormat Parse(System.ReadOnlySpan<char> format) { throw null; } public static System.Buffers.StandardFormat Parse(string format) { throw null; } public override string ToString() { throw null; } public static bool TryParse(System.ReadOnlySpan<char> format, out System.Buffers.StandardFormat result) { throw null; } } } namespace System.Buffers.Binary { public static partial class BinaryPrimitives { public static short ReadInt16BigEndian(System.ReadOnlySpan<byte> source) { throw null; } public static short ReadInt16LittleEndian(System.ReadOnlySpan<byte> source) { throw null; } public static int ReadInt32BigEndian(System.ReadOnlySpan<byte> source) { throw null; } public static int ReadInt32LittleEndian(System.ReadOnlySpan<byte> source) { throw null; } public static long ReadInt64BigEndian(System.ReadOnlySpan<byte> source) { throw null; } public static long ReadInt64LittleEndian(System.ReadOnlySpan<byte> source) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort ReadUInt16BigEndian(System.ReadOnlySpan<byte> source) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort ReadUInt16LittleEndian(System.ReadOnlySpan<byte> source) { throw null; } [System.CLSCompliantAttribute(false)] public static uint ReadUInt32BigEndian(System.ReadOnlySpan<byte> source) { throw null; } [System.CLSCompliantAttribute(false)] public static uint ReadUInt32LittleEndian(System.ReadOnlySpan<byte> source) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong ReadUInt64BigEndian(System.ReadOnlySpan<byte> source) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong ReadUInt64LittleEndian(System.ReadOnlySpan<byte> source) { throw null; } public static byte ReverseEndianness(byte value) { throw null; } public static short ReverseEndianness(short value) { throw null; } public static int ReverseEndianness(int value) { throw null; } public static long ReverseEndianness(long value) { throw null; } [System.CLSCompliantAttribute(false)] public static sbyte ReverseEndianness(sbyte value) { throw null; } [System.CLSCompliantAttribute(false)] public static ushort ReverseEndianness(ushort value) { throw null; } [System.CLSCompliantAttribute(false)] public static uint ReverseEndianness(uint value) { throw null; } [System.CLSCompliantAttribute(false)] public static ulong ReverseEndianness(ulong value) { throw null; } public static bool TryReadInt16BigEndian(System.ReadOnlySpan<byte> source, out short value) { throw null; } public static bool TryReadInt16LittleEndian(System.ReadOnlySpan<byte> source, out short value) { throw null; } public static bool TryReadInt32BigEndian(System.ReadOnlySpan<byte> source, out int value) { throw null; } public static bool TryReadInt32LittleEndian(System.ReadOnlySpan<byte> source, out int value) { throw null; } public static bool TryReadInt64BigEndian(System.ReadOnlySpan<byte> source, out long value) { throw null; } public static bool TryReadInt64LittleEndian(System.ReadOnlySpan<byte> source, out long value) { throw null; } [System.CLSCompliantAttribute(false)] public static bool TryReadUInt16BigEndian(System.ReadOnlySpan<byte> source, out ushort value) { throw null; } [System.CLSCompliantAttribute(false)] public static bool TryReadUInt16LittleEndian(System.ReadOnlySpan<byte> source, out ushort value) { throw null; } [System.CLSCompliantAttribute(false)] public static bool TryReadUInt32BigEndian(System.ReadOnlySpan<byte> source, out uint value) { throw null; } [System.CLSCompliantAttribute(false)] public static bool TryReadUInt32LittleEndian(System.ReadOnlySpan<byte> source, out uint value) { throw null; } [System.CLSCompliantAttribute(false)] public static bool TryReadUInt64BigEndian(System.ReadOnlySpan<byte> source, out ulong value) { throw null; } [System.CLSCompliantAttribute(false)] public static bool TryReadUInt64LittleEndian(System.ReadOnlySpan<byte> source, out ulong value) { throw null; } public static bool TryWriteInt16BigEndian(System.Span<byte> destination, short value) { throw null; } public static bool TryWriteInt16LittleEndian(System.Span<byte> destination, short value) { throw null; } public static bool TryWriteInt32BigEndian(System.Span<byte> destination, int value) { throw null; } public static bool TryWriteInt32LittleEndian(System.Span<byte> destination, int value) { throw null; } public static bool TryWriteInt64BigEndian(System.Span<byte> destination, long value) { throw null; } public static bool TryWriteInt64LittleEndian(System.Span<byte> destination, long value) { throw null; } [System.CLSCompliantAttribute(false)] public static bool TryWriteUInt16BigEndian(System.Span<byte> destination, ushort value) { throw null; } [System.CLSCompliantAttribute(false)] public static bool TryWriteUInt16LittleEndian(System.Span<byte> destination, ushort value) { throw null; } [System.CLSCompliantAttribute(false)] public static bool TryWriteUInt32BigEndian(System.Span<byte> destination, uint value) { throw null; } [System.CLSCompliantAttribute(false)] public static bool TryWriteUInt32LittleEndian(System.Span<byte> destination, uint value) { throw null; } [System.CLSCompliantAttribute(false)] public static bool TryWriteUInt64BigEndian(System.Span<byte> destination, ulong value) { throw null; } [System.CLSCompliantAttribute(false)] public static bool TryWriteUInt64LittleEndian(System.Span<byte> destination, ulong value) { throw null; } public static void WriteInt16BigEndian(System.Span<byte> destination, short value) { } public static void WriteInt16LittleEndian(System.Span<byte> destination, short value) { } public static void WriteInt32BigEndian(System.Span<byte> destination, int value) { } public static void WriteInt32LittleEndian(System.Span<byte> destination, int value) { } public static void WriteInt64BigEndian(System.Span<byte> destination, long value) { } public static void WriteInt64LittleEndian(System.Span<byte> destination, long value) { } [System.CLSCompliantAttribute(false)] public static void WriteUInt16BigEndian(System.Span<byte> destination, ushort value) { } [System.CLSCompliantAttribute(false)] public static void WriteUInt16LittleEndian(System.Span<byte> destination, ushort value) { } [System.CLSCompliantAttribute(false)] public static void WriteUInt32BigEndian(System.Span<byte> destination, uint value) { } [System.CLSCompliantAttribute(false)] public static void WriteUInt32LittleEndian(System.Span<byte> destination, uint value) { } [System.CLSCompliantAttribute(false)] public static void WriteUInt64BigEndian(System.Span<byte> destination, ulong value) { } [System.CLSCompliantAttribute(false)] public static void WriteUInt64LittleEndian(System.Span<byte> destination, ulong value) { } } } namespace System.Buffers.Text { public static partial class Base64 { public static System.Buffers.OperationStatus DecodeFromUtf8(System.ReadOnlySpan<byte> utf8, System.Span<byte> bytes, out int bytesConsumed, out int bytesWritten, bool isFinalBlock = true) { throw null; } public static System.Buffers.OperationStatus DecodeFromUtf8InPlace(System.Span<byte> buffer, out int bytesWritten) { throw null; } public static System.Buffers.OperationStatus EncodeToUtf8(System.ReadOnlySpan<byte> bytes, System.Span<byte> utf8, out int bytesConsumed, out int bytesWritten, bool isFinalBlock = true) { throw null; } public static System.Buffers.OperationStatus EncodeToUtf8InPlace(System.Span<byte> buffer, int dataLength, out int bytesWritten) { throw null; } public static int GetMaxDecodedFromUtf8Length(int length) { throw null; } public static int GetMaxEncodedToUtf8Length(int length) { throw null; } } public static partial class Utf8Formatter { public static bool TryFormat(bool value, System.Span<byte> destination, out int bytesWritten, System.Buffers.StandardFormat format = default(System.Buffers.StandardFormat)) { throw null; } public static bool TryFormat(byte value, System.Span<byte> destination, out int bytesWritten, System.Buffers.StandardFormat format = default(System.Buffers.StandardFormat)) { throw null; } public static bool TryFormat(System.DateTime value, System.Span<byte> destination, out int bytesWritten, System.Buffers.StandardFormat format = default(System.Buffers.StandardFormat)) { throw null; } public static bool TryFormat(System.DateTimeOffset value, System.Span<byte> destination, out int bytesWritten, System.Buffers.StandardFormat format = default(System.Buffers.StandardFormat)) { throw null; } public static bool TryFormat(decimal value, System.Span<byte> destination, out int bytesWritten, System.Buffers.StandardFormat format = default(System.Buffers.StandardFormat)) { throw null; } public static bool TryFormat(double value, System.Span<byte> destination, out int bytesWritten, System.Buffers.StandardFormat format = default(System.Buffers.StandardFormat)) { throw null; } public static bool TryFormat(System.Guid value, System.Span<byte> destination, out int bytesWritten, System.Buffers.StandardFormat format = default(System.Buffers.StandardFormat)) { throw null; } public static bool TryFormat(short value, System.Span<byte> destination, out int bytesWritten, System.Buffers.StandardFormat format = default(System.Buffers.StandardFormat)) { throw null; } public static bool TryFormat(int value, System.Span<byte> destination, out int bytesWritten, System.Buffers.StandardFormat format = default(System.Buffers.StandardFormat)) { throw null; } public static bool TryFormat(long value, System.Span<byte> destination, out int bytesWritten, System.Buffers.StandardFormat format = default(System.Buffers.StandardFormat)) { throw null; } [System.CLSCompliantAttribute(false)] public static bool TryFormat(sbyte value, System.Span<byte> destination, out int bytesWritten, System.Buffers.StandardFormat format = default(System.Buffers.StandardFormat)) { throw null; } public static bool TryFormat(float value, System.Span<byte> destination, out int bytesWritten, System.Buffers.StandardFormat format = default(System.Buffers.StandardFormat)) { throw null; } public static bool TryFormat(System.TimeSpan value, System.Span<byte> destination, out int bytesWritten, System.Buffers.StandardFormat format = default(System.Buffers.StandardFormat)) { throw null; } [System.CLSCompliantAttribute(false)] public static bool TryFormat(ushort value, System.Span<byte> destination, out int bytesWritten, System.Buffers.StandardFormat format = default(System.Buffers.StandardFormat)) { throw null; } [System.CLSCompliantAttribute(false)] public static bool TryFormat(uint value, System.Span<byte> destination, out int bytesWritten, System.Buffers.StandardFormat format = default(System.Buffers.StandardFormat)) { throw null; } [System.CLSCompliantAttribute(false)] public static bool TryFormat(ulong value, System.Span<byte> destination, out int bytesWritten, System.Buffers.StandardFormat format = default(System.Buffers.StandardFormat)) { throw null; } } public static partial class Utf8Parser { public static bool TryParse(System.ReadOnlySpan<byte> source, out bool value, out int bytesConsumed, char standardFormat = '\0') { throw null; } public static bool TryParse(System.ReadOnlySpan<byte> source, out byte value, out int bytesConsumed, char standardFormat = '\0') { throw null; } public static bool TryParse(System.ReadOnlySpan<byte> source, out System.DateTime value, out int bytesConsumed, char standardFormat = '\0') { throw null; } public static bool TryParse(System.ReadOnlySpan<byte> source, out System.DateTimeOffset value, out int bytesConsumed, char standardFormat = '\0') { throw null; } public static bool TryParse(System.ReadOnlySpan<byte> source, out decimal value, out int bytesConsumed, char standardFormat = '\0') { throw null; } public static bool TryParse(System.ReadOnlySpan<byte> source, out double value, out int bytesConsumed, char standardFormat = '\0') { throw null; } public static bool TryParse(System.ReadOnlySpan<byte> source, out System.Guid value, out int bytesConsumed, char standardFormat = '\0') { throw null; } public static bool TryParse(System.ReadOnlySpan<byte> source, out short value, out int bytesConsumed, char standardFormat = '\0') { throw null; } public static bool TryParse(System.ReadOnlySpan<byte> source, out int value, out int bytesConsumed, char standardFormat = '\0') { throw null; } public static bool TryParse(System.ReadOnlySpan<byte> source, out long value, out int bytesConsumed, char standardFormat = '\0') { throw null; } [System.CLSCompliantAttribute(false)] public static bool TryParse(System.ReadOnlySpan<byte> source, out sbyte value, out int bytesConsumed, char standardFormat = '\0') { throw null; } public static bool TryParse(System.ReadOnlySpan<byte> source, out float value, out int bytesConsumed, char standardFormat = '\0') { throw null; } public static bool TryParse(System.ReadOnlySpan<byte> source, out System.TimeSpan value, out int bytesConsumed, char standardFormat = '\0') { throw null; } [System.CLSCompliantAttribute(false)] public static bool TryParse(System.ReadOnlySpan<byte> source, out ushort value, out int bytesConsumed, char standardFormat = '\0') { throw null; } [System.CLSCompliantAttribute(false)] public static bool TryParse(System.ReadOnlySpan<byte> source, out uint value, out int bytesConsumed, char standardFormat = '\0') { throw null; } [System.CLSCompliantAttribute(false)] public static bool TryParse(System.ReadOnlySpan<byte> source, out ulong value, out int bytesConsumed, char standardFormat = '\0') { throw null; } } } namespace System.Runtime.InteropServices { public static partial class MemoryMarshal { public static System.ReadOnlySpan<byte> AsBytes<T>(System.ReadOnlySpan<T> span) where T : struct { throw null; } public static System.Span<byte> AsBytes<T>(System.Span<T> span) where T : struct { throw null; } public static System.Memory<T> AsMemory<T>(System.ReadOnlyMemory<T> memory) { throw null; } public static ref readonly T AsRef<T>(System.ReadOnlySpan<byte> span) where T : struct { throw null; } public static ref T AsRef<T>(System.Span<byte> span) where T : struct { throw null; } public static System.ReadOnlySpan<TTo> Cast<TFrom, TTo>(System.ReadOnlySpan<TFrom> span) where TFrom : struct where TTo : struct { throw null; } public static System.Span<TTo> Cast<TFrom, TTo>(System.Span<TFrom> span) where TFrom : struct where TTo : struct { throw null; } public static System.Memory<T> CreateFromPinnedArray<T>(T[] array, int start, int length) { throw null; } public static System.ReadOnlySpan<T> CreateReadOnlySpan<T>(ref T reference, int length) { throw null; } public static System.Span<T> CreateSpan<T>(ref T reference, int length) { throw null; } public static ref T GetReference<T>(System.ReadOnlySpan<T> span) { throw null; } public static ref T GetReference<T>(System.Span<T> span) { throw null; } public static T Read<T>(System.ReadOnlySpan<byte> source) where T : struct { throw null; } public static System.Collections.Generic.IEnumerable<T> ToEnumerable<T>(System.ReadOnlyMemory<T> memory) { throw null; } public static bool TryGetArray<T>(System.ReadOnlyMemory<T> memory, out System.ArraySegment<T> segment) { throw null; } public static bool TryGetMemoryManager<T, TManager>(System.ReadOnlyMemory<T> memory, out TManager manager) where TManager : System.Buffers.MemoryManager<T> { throw null; } public static bool TryGetMemoryManager<T, TManager>(System.ReadOnlyMemory<T> memory, out TManager manager, out int start, out int length) where TManager : System.Buffers.MemoryManager<T> { throw null; } public static bool TryGetString(System.ReadOnlyMemory<char> memory, out string text, out int start, out int length) { throw null; } public static bool TryRead<T>(System.ReadOnlySpan<byte> source, out T value) where T : struct { throw null; } public static bool TryWrite<T>(System.Span<byte> destination, ref T value) where T : struct { throw null; } public static void Write<T>(System.Span<byte> destination, ref T value) where T : struct { } } public static partial class SequenceMarshal { public static bool TryGetArray<T>(System.Buffers.ReadOnlySequence<T> sequence, out System.ArraySegment<T> segment) { throw null; } public static bool TryGetReadOnlyMemory<T>(System.Buffers.ReadOnlySequence<T> sequence, out System.ReadOnlyMemory<T> memory) { throw null; } public static bool TryGetReadOnlySequenceSegment<T>(System.Buffers.ReadOnlySequence<T> sequence, out System.Buffers.ReadOnlySequenceSegment<T> startSegment, out int startIndex, out System.Buffers.ReadOnlySequenceSegment<T> endSegment, out int endIndex) { throw null; } public static bool TryRead<T>(ref System.Buffers.SequenceReader<byte> reader, out T value) where T : unmanaged { throw null; } } } namespace System.Text { public ref partial struct SpanRuneEnumerator { private object _dummy; private int _dummyPrimitive; public System.Text.Rune Current { get { throw null; } } public System.Text.SpanRuneEnumerator GetEnumerator() { throw null; } public bool MoveNext() { throw null; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using antilunchbox; public partial class SoundManager : antilunchbox.Singleton<SoundManager> { /// <summary> /// Path to folder where SFX are held in resources /// </summary> public string resourcesPath = "Sounds/SFX"; /// <summary> /// List of local AudioClip SFXs added in inspector or through SaveSFX() /// </summary> public List<AudioClip> storedSFXs = new List<AudioClip>(); /// <summary> /// List of other unowned gameobjects with SFX attached. /// </summary> public List<GameObject> unOwnedSFXObjects = new List<GameObject>(); /// <summary> /// Dictionary of instance ID to cappedID to keep track of capped SFX /// </summary> public Dictionary<int, string> cappedSFXObjects = new Dictionary<int, string>(); /// <summary> /// Dictionary of delayed AudioSources /// </summary> public Dictionary<AudioSource, float> delayedAudioSources = new Dictionary<AudioSource, float>(); /// <summary> /// Dictionary of sfx with runonendfunctions /// </summary> public Dictionary<AudioSource, SongCallBack> runOnEndFunctions = new Dictionary<AudioSource, SongCallBack>(); private AudioSource duckSource; private SongCallBack duckFunction; private bool isDucking = false; private int duckNumber = 0; private float preDuckVolume = 1f; private float preDuckVolumeMusic = 1f; private float preDuckVolumeSFX = 1f; private float preDuckPitch = 1f; private float preDuckPitchMusic = 1f; private float preDuckPitchSFX = 1f; /// <summary> /// The start speed of the ducking effect. /// </summary> public static float duckStartSpeed = .1f; /// <summary> /// The end speed of the ducking effect. /// </summary> public static float duckEndSpeed = .5f; /// <summary> /// List of SFXGroups. At runtime, this is NOT used, so don't modify this. /// </summary> public List<SFXGroup> sfxGroups = new List<SFXGroup>(); // Map of clip names to group names (dictionaries and hashtables are not supported for serialization) /// <summary> /// Editor variable -- IGNORE AND DO NOT MODIFY /// </summary> public List<string> clipToGroupKeys = new List<string>(); /// <summary> /// Editor variable -- IGNORE AND DO NOT MODIFY /// </summary> public List<string> clipToGroupValues = new List<string>(); private Dictionary<string, SFXGroup> groups = new Dictionary<string, SFXGroup>(); private Dictionary<string, string> clipsInGroups = new Dictionary<string, string>(); private Dictionary<string, AudioClip> allClips = new Dictionary<string, AudioClip>(); private Dictionary<string, int> prepools = new Dictionary<string, int>(); private Dictionary<string, float> baseVolumes = new Dictionary<string, float>(); private Dictionary<string, float> volumeVariations = new Dictionary<string, float>(); private Dictionary<string, float> pitchVariations = new Dictionary<string, float>(); /// <summary> /// Turn off the SFX. /// </summary> public bool offTheSFX = false; /// <summary> /// The default cap amount. /// </summary> public int capAmount = 3; /// <summary> /// Gets or sets the SFX volume. /// </summary> /// <value> /// The SFX volume. /// </value> public float volumeSFX { get{ return _volumeSFX; } set { foreach(KeyValuePair<AudioClip, SFXPoolInfo> pair in Instance.ownedPools) { foreach(GameObject ownedSFXObject in pair.Value.ownedAudioClipPool) { if(ownedSFXObject != null) if(ownedSFXObject.GetComponent<AudioSource>() != null && (!isDucking || ownedSFXObject.GetComponent<AudioSource>() != duckSource)) ownedSFXObject.GetComponent<AudioSource>().volume = value; } } foreach(GameObject unOwnedSFXObject in Instance.unOwnedSFXObjects) { if(unOwnedSFXObject != null) if(unOwnedSFXObject.GetComponent<AudioSource>() != null && (!isDucking || unOwnedSFXObject.GetComponent<AudioSource>() != duckSource)) unOwnedSFXObject.GetComponent<AudioSource>().volume = value; } _volumeSFX = value; } } private float _volumeSFX = 1f; /// <summary> /// Gets or sets the SFX pitch. /// </summary> /// <value> /// The SFX pitch. /// </value> public float pitchSFX { get{ return _pitchSFX; } set { foreach(KeyValuePair<AudioClip, SFXPoolInfo> pair in Instance.ownedPools) { foreach(GameObject ownedSFXObject in pair.Value.ownedAudioClipPool) { if(ownedSFXObject != null) if(ownedSFXObject.GetComponent<AudioSource>() != null && (!isDucking || ownedSFXObject.GetComponent<AudioSource>() != duckSource)) ownedSFXObject.GetComponent<AudioSource>().pitch = value; } } foreach(GameObject unOwnedSFXObject in Instance.unOwnedSFXObjects) { if(unOwnedSFXObject != null) if(unOwnedSFXObject.GetComponent<AudioSource>() != null && (!isDucking || unOwnedSFXObject.GetComponent<AudioSource>() != duckSource)) unOwnedSFXObject.GetComponent<AudioSource>().pitch = value; } _pitchSFX = value; } } private float _pitchSFX = 1f; /// <summary> /// Gets or sets the max SFX volume. /// </summary> /// <value> /// The max SFX volume. /// </value> public float maxSFXVolume { get{ return _maxSFXVolume; } set { _maxSFXVolume = value; } } private float _maxSFXVolume = 1f; /// <summary> /// Gets or sets a value indicating whether this <see cref="SoundManager"/> muted SFX. /// </summary> /// <value> /// <c>true</c> if muted SFX; otherwise, <c>false</c>. /// </value> public bool mutedSFX { get { return _mutedSFX; } set { foreach(KeyValuePair<AudioClip, SFXPoolInfo> pair in Instance.ownedPools) { foreach(GameObject ownedSFXObject in pair.Value.ownedAudioClipPool) { if(ownedSFXObject != null) if(ownedSFXObject.GetComponent<AudioSource>() != null) if(value) ownedSFXObject.GetComponent<AudioSource>().mute = value; else if(!Instance.offTheSFX) ownedSFXObject.GetComponent<AudioSource>().mute = value; } } foreach(GameObject unOwnedSFXObject in Instance.unOwnedSFXObjects) { if(unOwnedSFXObject != null) if(unOwnedSFXObject.GetComponent<AudioSource>() != null) if(value) unOwnedSFXObject.GetComponent<AudioSource>().mute = value; else if(!Instance.offTheSFX) unOwnedSFXObject.GetComponent<AudioSource>().mute = value; } _mutedSFX = value; } } private bool _mutedSFX = false; private Dictionary<AudioClip, SFXPoolInfo> ownedPools = new Dictionary<AudioClip, SFXPoolInfo>(); /// <summary> /// The sfx pre pool amounts. At runtime, this is NOT used, so don't modify this. /// </summary> public List<int> sfxPrePoolAmounts = new List<int>(); /// <summary> /// The sfx base volumes. At runtime, this is NOT used, so don't modify this. /// </summary> public List<float> sfxBaseVolumes = new List<float>(); /// <summary> /// The sfx volume variations. At runtime, this is NOT used, so don't modify this. /// </summary> public List<float> sfxVolumeVariations = new List<float>(); /// <summary> /// The sfx pitch variations. At runtime, this is NOT used, so don't modify this. /// </summary> public List<float> sfxPitchVariations = new List<float>(); /// <summary> /// The SFX object lifetime for objects outside of the prepool amount. /// </summary> public float SFXObjectLifetime = 10f; /// <summary> /// The current SoundPocket s by name. /// </summary> public List<string> currentPockets = new List<string>() { "Default" }; /// Default SFX setting for Spatial Blend (0 = 2d, 1 = 3d) public float defaultSFXSpatialBlend = 0f; }
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using Newtonsoft.Json; using System.Threading; using System.Threading.Tasks; using GodotTools.IdeMessaging.Requests; using GodotTools.IdeMessaging.Utils; namespace GodotTools.IdeMessaging { // ReSharper disable once UnusedType.Global public sealed class Client : IDisposable { private readonly ILogger logger; private readonly string identity; private string MetaFilePath { get; } private DateTime? metaFileModifiedTime; private GodotIdeMetadata godotIdeMetadata; private readonly FileSystemWatcher fsWatcher; public string GodotEditorExecutablePath => godotIdeMetadata.EditorExecutablePath; private readonly IMessageHandler messageHandler; private Peer peer; private readonly SemaphoreSlim connectionSem = new SemaphoreSlim(1); private readonly Queue<NotifyAwaiter<bool>> clientConnectedAwaiters = new Queue<NotifyAwaiter<bool>>(); private readonly Queue<NotifyAwaiter<bool>> clientDisconnectedAwaiters = new Queue<NotifyAwaiter<bool>>(); // ReSharper disable once UnusedMember.Global public async Task<bool> AwaitConnected() { var awaiter = new NotifyAwaiter<bool>(); clientConnectedAwaiters.Enqueue(awaiter); return await awaiter; } // ReSharper disable once UnusedMember.Global public async Task<bool> AwaitDisconnected() { var awaiter = new NotifyAwaiter<bool>(); clientDisconnectedAwaiters.Enqueue(awaiter); return await awaiter; } // ReSharper disable once MemberCanBePrivate.Global public bool IsDisposed { get; private set; } // ReSharper disable once MemberCanBePrivate.Global public bool IsConnected => peer != null && !peer.IsDisposed && peer.IsTcpClientConnected; // ReSharper disable once EventNeverSubscribedTo.Global public event Action Connected { add { if (peer != null && !peer.IsDisposed) peer.Connected += value; } remove { if (peer != null && !peer.IsDisposed) peer.Connected -= value; } } // ReSharper disable once EventNeverSubscribedTo.Global public event Action Disconnected { add { if (peer != null && !peer.IsDisposed) peer.Disconnected += value; } remove { if (peer != null && !peer.IsDisposed) peer.Disconnected -= value; } } ~Client() { Dispose(disposing: false); } public async void Dispose() { if (IsDisposed) return; using (await connectionSem.UseAsync()) { if (IsDisposed) // lock may not be fair return; IsDisposed = true; } Dispose(disposing: true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (disposing) { peer?.Dispose(); fsWatcher?.Dispose(); } } public Client(string identity, string godotProjectDir, IMessageHandler messageHandler, ILogger logger) { this.identity = identity; this.messageHandler = messageHandler; this.logger = logger; string projectMetadataDir = Path.Combine(godotProjectDir, ".mono", "metadata"); MetaFilePath = Path.Combine(projectMetadataDir, GodotIdeMetadata.DefaultFileName); // FileSystemWatcher requires an existing directory if (!Directory.Exists(projectMetadataDir)) Directory.CreateDirectory(projectMetadataDir); fsWatcher = new FileSystemWatcher(projectMetadataDir, GodotIdeMetadata.DefaultFileName); } private async void OnMetaFileChanged(object sender, FileSystemEventArgs e) { if (IsDisposed) return; using (await connectionSem.UseAsync()) { if (IsDisposed) return; if (!File.Exists(MetaFilePath)) return; var lastWriteTime = File.GetLastWriteTime(MetaFilePath); if (lastWriteTime == metaFileModifiedTime) return; metaFileModifiedTime = lastWriteTime; var metadata = ReadMetadataFile(); if (metadata != null && metadata != godotIdeMetadata) { godotIdeMetadata = metadata.Value; _ = Task.Run(ConnectToServer); } } } private async void OnMetaFileDeleted(object sender, FileSystemEventArgs e) { if (IsDisposed) return; if (IsConnected) { using (await connectionSem.UseAsync()) peer?.Dispose(); } // The file may have been re-created using (await connectionSem.UseAsync()) { if (IsDisposed) return; if (IsConnected || !File.Exists(MetaFilePath)) return; var lastWriteTime = File.GetLastWriteTime(MetaFilePath); if (lastWriteTime == metaFileModifiedTime) return; metaFileModifiedTime = lastWriteTime; var metadata = ReadMetadataFile(); if (metadata != null) { godotIdeMetadata = metadata.Value; _ = Task.Run(ConnectToServer); } } } private GodotIdeMetadata? ReadMetadataFile() { using (var fileStream = new FileStream(MetaFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var reader = new StreamReader(fileStream)) { string portStr = reader.ReadLine(); if (portStr == null) return null; string editorExecutablePath = reader.ReadLine(); if (editorExecutablePath == null) return null; if (!int.TryParse(portStr, out int port)) return null; return new GodotIdeMetadata(port, editorExecutablePath); } } private async Task AcceptClient(TcpClient tcpClient) { logger.LogDebug("Accept client..."); using (peer = new Peer(tcpClient, new ClientHandshake(), messageHandler, logger)) { // ReSharper disable AccessToDisposedClosure peer.Connected += () => { logger.LogInfo("Connection open with Ide Client"); while (clientConnectedAwaiters.Count > 0) clientConnectedAwaiters.Dequeue().SetResult(true); }; peer.Disconnected += () => { while (clientDisconnectedAwaiters.Count > 0) clientDisconnectedAwaiters.Dequeue().SetResult(true); }; // ReSharper restore AccessToDisposedClosure try { if (!await peer.DoHandshake(identity)) { logger.LogError("Handshake failed"); return; } } catch (Exception e) { logger.LogError("Handshake failed with unhandled exception: ", e); return; } await peer.Process(); logger.LogInfo("Connection closed with Ide Client"); } } private async Task ConnectToServer() { var tcpClient = new TcpClient(); try { logger.LogInfo("Connecting to Godot Ide Server"); await tcpClient.ConnectAsync(IPAddress.Loopback, godotIdeMetadata.Port); logger.LogInfo("Connection open with Godot Ide Server"); await AcceptClient(tcpClient); } catch (SocketException e) { if (e.SocketErrorCode == SocketError.ConnectionRefused) logger.LogError("The connection to the Godot Ide Server was refused"); else throw; } } // ReSharper disable once UnusedMember.Global public async void Start() { fsWatcher.Created += OnMetaFileChanged; fsWatcher.Changed += OnMetaFileChanged; fsWatcher.Deleted += OnMetaFileDeleted; fsWatcher.EnableRaisingEvents = true; using (await connectionSem.UseAsync()) { if (IsDisposed) return; if (IsConnected) return; if (!File.Exists(MetaFilePath)) { logger.LogInfo("There is no Godot Ide Server running"); return; } var metadata = ReadMetadataFile(); if (metadata != null) { godotIdeMetadata = metadata.Value; _ = Task.Run(ConnectToServer); } else { logger.LogError("Failed to read Godot Ide metadata file"); } } } public async Task<TResponse> SendRequest<TResponse>(Request request) where TResponse : Response, new() { if (!IsConnected) { logger.LogError("Cannot write request. Not connected to the Godot Ide Server."); return null; } string body = JsonConvert.SerializeObject(request); return await peer.SendRequest<TResponse>(request.Id, body); } public async Task<TResponse> SendRequest<TResponse>(string id, string body) where TResponse : Response, new() { if (!IsConnected) { logger.LogError("Cannot write request. Not connected to the Godot Ide Server."); return null; } return await peer.SendRequest<TResponse>(id, body); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: BinaryFormatter ** ** ** Purpose: Soap XML Formatter ** ** ===========================================================*/ namespace System.Runtime.Serialization.Formatters.Binary { using System; using System.IO; using System.Reflection; using System.Globalization; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization.Formatters; #if FEATURE_REMOTING using System.Runtime.Remoting.Proxies; #endif using System.Runtime.Remoting; using System.Runtime.Remoting.Messaging; using System.Runtime.Serialization; using System.Security.Permissions; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] sealed public class BinaryFormatter : #if !FEATURE_REMOTING IFormatter #else IRemotingFormatter #endif { internal ISurrogateSelector m_surrogates; internal StreamingContext m_context; internal SerializationBinder m_binder; //internal FormatterTypeStyle m_typeFormat = FormatterTypeStyle.TypesWhenNeeded; internal FormatterTypeStyle m_typeFormat = FormatterTypeStyle.TypesAlways; // For version resiliency, always put out types internal FormatterAssemblyStyle m_assemblyFormat = FormatterAssemblyStyle.Simple; internal TypeFilterLevel m_securityLevel = TypeFilterLevel.Full; internal Object[] m_crossAppDomainArray = null; private static Dictionary<Type, TypeInformation> typeNameCache = new Dictionary<Type, TypeInformation>(); // Property which specifies how types are serialized, // FormatterTypeStyle Enum specifies options public FormatterTypeStyle TypeFormat { get { return m_typeFormat; } set { m_typeFormat = value; } } // Property which specifies how types are serialized, // FormatterAssemblyStyle Enum specifies options public FormatterAssemblyStyle AssemblyFormat { get { return m_assemblyFormat; } set { m_assemblyFormat = value; } } // Property which specifies the security level of formatter // TypeFilterLevel Enum specifies options public TypeFilterLevel FilterLevel { get { return m_securityLevel; } set { m_securityLevel = value; } } public ISurrogateSelector SurrogateSelector { get { return m_surrogates; } set { m_surrogates = value; } } public SerializationBinder Binder { get { return m_binder; } set { m_binder = value; } } public StreamingContext Context { get { return m_context; } set { m_context = value; } } // Constructor public BinaryFormatter() { m_surrogates = null; m_context = new StreamingContext(StreamingContextStates.All); } // Constructor public BinaryFormatter(ISurrogateSelector selector, StreamingContext context) { m_surrogates = selector; m_context = context; } // Deserialize the stream into an object graph. public Object Deserialize(Stream serializationStream) { return Deserialize(serializationStream, null); } [System.Security.SecurityCritical] // auto-generated internal Object Deserialize(Stream serializationStream, HeaderHandler handler, bool fCheck) { #if FEATURE_REMOTING return Deserialize(serializationStream, handler, fCheck, null); #else if (serializationStream == null) { throw new ArgumentNullException("serializationStream", Environment.GetResourceString("ArgumentNull_WithParamName", serializationStream)); } Contract.EndContractBlock(); if (serializationStream.CanSeek && (serializationStream.Length == 0)) throw new SerializationException(Environment.GetResourceString("Serialization_Stream")); SerTrace.Log(this, "Deserialize Entry"); InternalFE formatterEnums = new InternalFE(); formatterEnums.FEtypeFormat = m_typeFormat; formatterEnums.FEserializerTypeEnum = InternalSerializerTypeE.Binary; formatterEnums.FEassemblyFormat = m_assemblyFormat; formatterEnums.FEsecurityLevel = m_securityLevel; ObjectReader sor = new ObjectReader(serializationStream, m_surrogates, m_context, formatterEnums, m_binder); sor.crossAppDomainArray = m_crossAppDomainArray; return sor.Deserialize(handler, new __BinaryParser(serializationStream, sor), fCheck); #endif } // Deserialize the stream into an object graph. [System.Security.SecuritySafeCritical] // auto-generated public Object Deserialize(Stream serializationStream, HeaderHandler handler) { return Deserialize(serializationStream, handler, true); } #if FEATURE_REMOTING [System.Security.SecuritySafeCritical] // auto-generated public Object DeserializeMethodResponse(Stream serializationStream, HeaderHandler handler, IMethodCallMessage methodCallMessage) { return Deserialize(serializationStream, handler, true, methodCallMessage); } #endif [System.Security.SecurityCritical] // auto-generated_required [System.Runtime.InteropServices.ComVisible(false)] public Object UnsafeDeserialize(Stream serializationStream, HeaderHandler handler) { return Deserialize(serializationStream, handler, false); } #if FEATURE_REMOTING [System.Security.SecurityCritical] // auto-generated_required [System.Runtime.InteropServices.ComVisible(false)] public Object UnsafeDeserializeMethodResponse(Stream serializationStream, HeaderHandler handler, IMethodCallMessage methodCallMessage) { return Deserialize(serializationStream, handler, false, methodCallMessage); } [System.Security.SecurityCritical] // auto-generated internal Object Deserialize(Stream serializationStream, HeaderHandler handler, bool fCheck, IMethodCallMessage methodCallMessage) { return Deserialize(serializationStream, handler, fCheck, false/*isCrossAppDomain*/, methodCallMessage); } // Deserialize the stream into an object graph. [System.Security.SecurityCritical] // auto-generated internal Object Deserialize(Stream serializationStream, HeaderHandler handler, bool fCheck, bool isCrossAppDomain, IMethodCallMessage methodCallMessage) { if (serializationStream==null) { throw new ArgumentNullException("serializationStream", Environment.GetResourceString("ArgumentNull_WithParamName",serializationStream)); } Contract.EndContractBlock(); if (serializationStream.CanSeek && (serializationStream.Length == 0)) throw new SerializationException(Environment.GetResourceString("Serialization_Stream")); SerTrace.Log(this, "Deserialize Entry"); InternalFE formatterEnums = new InternalFE(); formatterEnums.FEtypeFormat = m_typeFormat; formatterEnums.FEserializerTypeEnum = InternalSerializerTypeE.Binary; formatterEnums.FEassemblyFormat = m_assemblyFormat; formatterEnums.FEsecurityLevel = m_securityLevel; ObjectReader sor = new ObjectReader(serializationStream, m_surrogates, m_context, formatterEnums, m_binder); sor.crossAppDomainArray = m_crossAppDomainArray; return sor.Deserialize(handler, new __BinaryParser(serializationStream, sor), fCheck, isCrossAppDomain, methodCallMessage); } #endif // FEATURE_REMOTING public void Serialize(Stream serializationStream, Object graph) { Serialize(serializationStream, graph, null); } // Commences the process of serializing the entire graph. All of the data (in the appropriate format // is emitted onto the stream). [System.Security.SecuritySafeCritical] // auto-generated public void Serialize(Stream serializationStream, Object graph, Header[] headers) { Serialize(serializationStream, graph, headers, true); } // Commences the process of serializing the entire graph. All of the data (in the appropriate format // is emitted onto the stream). [System.Security.SecurityCritical] // auto-generated internal void Serialize(Stream serializationStream, Object graph, Header[] headers, bool fCheck) { if (serializationStream == null) { throw new ArgumentNullException("serializationStream", Environment.GetResourceString("ArgumentNull_WithParamName", serializationStream)); } Contract.EndContractBlock(); SerTrace.Log(this, "Serialize Entry"); InternalFE formatterEnums = new InternalFE(); formatterEnums.FEtypeFormat = m_typeFormat; formatterEnums.FEserializerTypeEnum = InternalSerializerTypeE.Binary; formatterEnums.FEassemblyFormat = m_assemblyFormat; ObjectWriter sow = new ObjectWriter(m_surrogates, m_context, formatterEnums, m_binder); __BinaryWriter binaryWriter = new __BinaryWriter(serializationStream, sow, m_typeFormat); sow.Serialize(graph, headers, binaryWriter, fCheck); m_crossAppDomainArray = sow.crossAppDomainArray; } internal static TypeInformation GetTypeInformation(Type type) { lock (typeNameCache) { TypeInformation typeInformation = null; if (!typeNameCache.TryGetValue(type, out typeInformation)) { bool hasTypeForwardedFrom; string assemblyName = FormatterServices.GetClrAssemblyName(type, out hasTypeForwardedFrom); typeInformation = new TypeInformation(FormatterServices.GetClrTypeFullName(type), assemblyName, hasTypeForwardedFrom); typeNameCache.Add(type, typeInformation); } return typeInformation; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace TheBigCatProjectServer.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); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; using System.Security; namespace OLEDB.Test.ModuleCore { //////////////////////////////////////////////////////////////////////// // VARIATION_STATUS // //////////////////////////////////////////////////////////////////////// public enum tagVARIATION_STATUS { eVariationStatusFailed = 0, eVariationStatusPassed, eVariationStatusNotRun, eVariationStatusNonExistent, eVariationStatusUnknown, eVariationStatusTimedOut, eVariationStatusConformanceWarning, eVariationStatusException, eVariationStatusAborted } //////////////////////////////////////////////////////////////////////// // ERRORLEVEL // //////////////////////////////////////////////////////////////////////// public enum tagERRORLEVEL { HR_STRICT, HR_OPTIONAL, HR_SUCCEED, HR_FAIL, HR_WARNING } //////////////////////////////////////////////////////////////////////// // CONSOLEFLAGS // //////////////////////////////////////////////////////////////////////// public enum tagCONSOLEFLAGS { CONSOLE_RAW = 0x00000000, //No fixup - Don't use, unless you know the text contains no CR/LF, no Xml reserverd tokens, or no other non-respresentable characters CONSOLE_TEXT = 0x00000001, //Default - Automatically fixup CR/LF correctly for log files, fixup xml tokens, etc CONSOLE_XML = 0x00000002, //For Xml - User text is placed into a CDATA section (with no xml fixups) CONSOLE_IGNORE = 0x00000004, //Ignore - User text is placed into ignore tags (can combine this with console_xml as well) } //////////////////////////////////////////////////////////////////////// // IError // //////////////////////////////////////////////////////////////////////// public interface IError { // These two methods get/set the ErrorLevel property. This property affects the // behavior of the 'Validate' method. The enum values have the following // effects on that method: // HR_STRICT: The 'hrActual' parameter MUST match the 'hrExpected' parameter, // or else the error count in incremented. // HR_SUCCEED: The 'hrActual' MUST be a success code, or else the error count // is incremented. // HR_FAIL: The 'hrActual' MUST be an error code, or else the error count // is incremented. // HR_OPTIONAL:The error count will not be incremented, regardless of the // parameters passed in to 'Validate.' // tagERRORLEVEL GetErrorLevel(); void SetErrorLevel(tagERRORLEVEL ErrorLevel); // 'GetActualHr' returns the HRESULT recorded from the last call to 'Validate'. // int GetActualHr(); // 'Validate' compares the two HRESULT values passed in and, depending on // the current ErrorLevel, possibly increment the error count and output // an error message to the LTM window. In the cases where validation fails, // the pfResult parameter will be returned as FALSE -- otherwise TRUE. // When an error message is output to LTM, the file name and line numbers // are recorded there as well. // bool Validate(int hrActual, string bstrFileName, int lLineNo, int hrExpected); // 'Compare' will output an error message (similar to that output by 'Validate') // if the fWereEqual parameter passed in is FALSE. // bool Compare(bool fWereEqual, string bstrFileName, int lLineNo); // The 'LogxxxxxxxxHr' methods output error or status message to the LTM // window. The HRESULT parameters passed in are converted to string // messages for this purpose. // void LogExpectedHr(int hrExpected); void LogReceivedHr(int hrReceived, string bstrFileName, int lLineNo); // The 'ResetxxxxErrors' methods simply reset the internal error count of // a Module, Case, or Variation (respectively.) // void ResetModErrors(); void ResetCaseErrors(); void ResetVarErrors(); void ResetModWarnings(); void ResetCaseWarnings(); void ResetVarWarnings(); // 'GetxxxxErrors' retrieve the current number of errors at the Module, // Test Case, or Variation level. // int GetModErrors(); int GetCaseErrors(); int GetVarErrors(); int GetModWarnings(); int GetCaseWarnings(); int GetVarWarnings(); // 'Increment' will increment the error count of the currently running // Test Module, the currently running Test Case, as well as the currently // running Variation. // void Increment(); // 'Transmit' is the way a Test Module can send text messages to LTM. These will // be displayed in LTM's main window, and can be used to inform the user of // any pertinent information at run-time. // void Transmit(string bstrTextString); // 'Initialize' // void Initialize(); } //////////////////////////////////////////////////////////////////////// // ITestConsole // //////////////////////////////////////////////////////////////////////// public interface ITestConsole { //(Error) Logging routines void Log(string bstrActual, string bstrExpected, string bstrSource, string bstrMessage, string bstrDetails, tagCONSOLEFLAGS flags, string bstrFilename, int iline); void Write(tagCONSOLEFLAGS flags, string bstrString); void WriteLine(); } //////////////////////////////////////////////////////////////////////// // IProviderInfo // //////////////////////////////////////////////////////////////////////// public interface IProviderInfo { // The IProviderInfo interface is just a wrapper around a structure which // contains all of the information LTM & Test Modules needs to know about // the provider they are running against (if any.) // // The properties are described as follows: // >Name: The name the provider gives itself. For Kagera this is MSDASQL. // >FriendlyName: A special name the user has given this provider configuration. // >InitString: A string which contains initialization data. The interpretation // of this string is Test Module-specific -- so you simply must // make users of LTM aware of what your particular Test Module // wants to see in this string. // >MachineName: If you will be testing a remote provider, the user will pass // the machine name the provider is located on to you through // this property. // >CLSID: This is the CLSID of the provider you are to run against. // >CLSCTX: This tells you whether the provider will be InProc, Local, or // Remote (values of this property are identical to the values // of the CLSCTX enumeration in wtypes.h) string GetName(); void SetName(string bstrProviderName); string GetFriendlyName(); void SetFriendlyName(string bstrFriendlyName); string GetInitString(); void SetInitString(string bstrInitString); string GetMachineName(); void SetMachineName(string bstrMachineName); string GetCLSID(); void SetCLSID(string bstrCLSID); int GetCLSCTX(); void SetCLSCTX(int ClsCtx); } //////////////////////////////////////////////////////////////////////// // IAliasInfo // //////////////////////////////////////////////////////////////////////// public interface IAliasInfo //: IProviderInfo { //IProviderInfo (as defined above) //TODO: Why do I have to repeat them here. Inheriting from IProviderInfo succeeds, //but the memory layout is incorrect (GetCommandLine actually calls GetName). string GetName(); void SetName(string bstrProviderName); string GetFriendlyName(); void SetFriendlyName(string bstrFriendlyName); string GetInitString(); void SetInitString(string bstrInitString); string GetMachineName(); void SetMachineName(string bstrMachineName); string GetCLSID(); void SetCLSID(string bstrCLSID); int GetCLSCTX(); void SetCLSCTX(int ClsCtx); //IAliasInfo string GetCommandLine(); } //////////////////////////////////////////////////////////////////////// // ITestCases // //////////////////////////////////////////////////////////////////////// public interface ITestCases { // LTM will use these methods to get information about this test case. // string GetName(); string GetDescription(); // SyncProviderInterface() should cause this TestCase to release its current // IProviderInterface (if any) and retrieve a new IProviderInterface // from its owning ITestModule (via the 'GetProviderInterface' call) // // GetProviderInterface() returns the current IProviderInterface for // this test case. // void SyncProviderInterface(); IProviderInfo GetProviderInterface(); // 'GetOwningITestModule' should retrieve the back-pointer // to this test case's owning ITestModule object. // ITestModule GetOwningITestModule(); // LTM will call 'Init' before it runs any variations in this Test Case. // Any code that sets up objects for use by the Variations should go here. // int Init(); // LTM will call 'Terminate' after it runs any variations on this // object -- regardless of the outcome of those calls (even regardless // of whether ITestCases::Init() fails or not.) // bool Terminate(); // 'GetVariationCount' should return the number of variations // this Test Case contains. // int GetVariationCount(); // For these next three, the first parameter is the variation index. 'Index' in // this case means the 0-based index into the complete list of variations // for this test case (if 'GetVariationCount' returns the value 'n', these // functions will always be passed values between 0 and (n - 1) as the first // parameter). // Do not confuse 'index' with 'Variation ID'. The latter is a non-sequential // unique identifier for the variation, which can be any 32-bit number. This // exists so that even when variations are added or removed during test // development, the ID is ALWAYS the same for the same variation (though // the Index will surely change.) // tagVARIATION_STATUS ExecuteVariation(int lIndex); int GetVariationID(int lIndex); string GetVariationDesc(int lIndex); } //////////////////////////////////////////////////////////////////////// // ITestModule // //////////////////////////////////////////////////////////////////////// public interface ITestModule { string GetName(); string GetDescription(); string GetOwnerName(); string GetCLSID(); int GetVersion(); // LTM will call 'SetProviderInterface' after the ITestModule object is instantiated // (if appropriate). // 'GetProviderInterface' is added for the implementor's convenience, but is not // called by LTM. // void SetProviderInterface(IProviderInfo pProvInfo); IProviderInfo GetProviderInterface(); // LTM will call 'SetErrorInterface' after the ITestModule object is instantiated. // 'GetErrorInterface' is added for the implementor's convenience, but is not // called by LTM. // void SetErrorInterface(IError pIError); IError GetErrorInterface(); // 'Init' is called at the beginning of each test run. Any global // data that all Test Cases in this module will use should be setup // here. // int Init(); // 'Terminate' is called at the end of each test run, regardless of the // outcome of the tests (even regardless of whether ITestModule::Init() // succeeds or fails.) // bool Terminate(); // 'GetCaseCount' returns the number of test cases this test module // contains. This value must not be zero. // int GetCaseCount(); // 'GetCase' should create an ITestCases instance for LTM to use. // The first parameter is the 0-based index of the test case. If // 'GetCaseCount' returns 'n' cases, this parameter will always // be between 0 and (n - 1), inclusive. // ITestCases GetCase(int lIndex); } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Management.Automation; using System.Runtime.Serialization; using System.Text; using System.Threading; using System.Xml; using Microsoft.Azure.Commands.RecoveryServices.SiteRecovery.Properties; using Microsoft.Azure.Commands.ResourceManager.Common; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Job = Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models.Job; namespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery { /// <summary> /// The base class for all Windows Azure Recovery Services commands /// </summary> public abstract class SiteRecoveryCmdletBase : AzureRMCmdlet { /// <summary> /// Recovery Services client. /// </summary> private PSRecoveryServicesClient recoveryServicesClient; /// <summary> /// Gets or sets a value indicating whether stop processing has been triggered. /// </summary> internal bool StopProcessingFlag { get; set; } /// <summary> /// Gets Recovery Services client. /// </summary> internal PSRecoveryServicesClient RecoveryServicesClient { get { if (this.recoveryServicesClient == null) { this.recoveryServicesClient = new PSRecoveryServicesClient(this.DefaultProfile); } return this.recoveryServicesClient; } } /// <summary> /// Overriding base implementation go execute cmdlet. /// </summary> public override void ExecuteCmdlet() { try { base.ExecuteCmdlet(); this.ExecuteSiteRecoveryCmdlet(); } catch (Exception ex) { this.HandleException(ex); } } /// <summary> /// Virtual method to be implemented by Site Recovery cmdlets. /// </summary> public virtual void ExecuteSiteRecoveryCmdlet() { SiteRecoveryAutoMapperProfile.Initialize(); // Do Nothing } /// <summary> /// Exception handler. /// </summary> /// <param name="ex">Exception to handle.</param> public void HandleException( Exception ex) { var clientRequestIdMsg = string.Empty; if (this.recoveryServicesClient != null) { clientRequestIdMsg = "ClientRequestId: " + this.recoveryServicesClient.ClientRequestId + "\n"; } var cloudException = ex as CloudException; if ((cloudException != null) && (cloudException.Body != null) && (cloudException.Response != null)) { try { if (cloudException.Message != null) { var error = SafeJsonConvert.DeserializeObject<ARMError>( cloudException.Response.Content); ; var exceptionMessage = new StringBuilder(); exceptionMessage.Append(Resources.CloudExceptionDetails); if (error.Error.Details != null) { foreach (var detail in error.Error.Details) { if (!string.IsNullOrEmpty(detail.ErrorCode)) exceptionMessage.AppendLine("ErrorCode: " + detail.ErrorCode); if (!string.IsNullOrEmpty(detail.Message)) exceptionMessage.AppendLine("Message: " + detail.Message); if (!string.IsNullOrEmpty(detail.PossibleCauses)) exceptionMessage.AppendLine( "Possible Causes: " + detail.PossibleCauses); if (!string.IsNullOrEmpty(detail.RecommendedAction)) exceptionMessage.AppendLine( "Recommended Action: " + detail.RecommendedAction); if (!string.IsNullOrEmpty(detail.ClientRequestId)) exceptionMessage.AppendLine( "ClientRequestId: " + detail.ClientRequestId); if (!string.IsNullOrEmpty(detail.ActivityId)) exceptionMessage.AppendLine("ActivityId: " + detail.ActivityId); exceptionMessage.AppendLine(); } } else { if (!string.IsNullOrEmpty(error.Error.ErrorCode)) exceptionMessage.AppendLine("ErrorCode: " + error.Error.ErrorCode); if (!string.IsNullOrEmpty(error.Error.Message)) exceptionMessage.AppendLine("Message: " + error.Error.Message); } throw new InvalidOperationException(exceptionMessage.ToString()); } throw new Exception( string.Format( Resources.InvalidCloudExceptionErrorMessage, clientRequestIdMsg + ex.Message), ex); } catch (XmlException) { throw new XmlException( string.Format( Resources.InvalidCloudExceptionErrorMessage, cloudException.Message), cloudException); } catch (SerializationException) { throw new SerializationException( string.Format( Resources.InvalidCloudExceptionErrorMessage, clientRequestIdMsg + cloudException.Message), cloudException); } catch (JsonReaderException) { throw new JsonReaderException( string.Format( Resources.InvalidCloudExceptionErrorMessage, clientRequestIdMsg + cloudException.Message), cloudException); } } if (ex.Message != null) { throw new Exception( string.Format( Resources.InvalidCloudExceptionErrorMessage, clientRequestIdMsg + ex.Message), ex); } } /// <summary> /// Waits for the job to complete. /// </summary> /// <param name="jobId">Id of the job to wait for.</param> /// <returns>Final job response</returns> public Job WaitForJobCompletion( string jobId) { Job job = null; do { Thread.Sleep(PSRecoveryServicesClient.TimeToSleepBeforeFetchingJobDetailsAgain); job = this.RecoveryServicesClient.GetAzureSiteRecoveryJobDetails(jobId); this.WriteProgress( new ProgressRecord( 0, Resources.WaitingForCompletion, job.Properties.State)); } while (!((job.Properties.State == TaskStatus.Cancelled) || (job.Properties.State == TaskStatus.Failed) || (job.Properties.State == TaskStatus.Suspended) || (job.Properties.State == TaskStatus.Succeeded) || this.StopProcessingFlag)); return job; } /// <summary> /// Handles interrupts. /// </summary> protected override void StopProcessing() { // Ctrl + C and etc base.StopProcessing(); this.StopProcessingFlag = true; } /// <summary> /// Validates if the usage by ID is allowed or not. /// </summary> /// <param name="replicationProvider">Replication provider.</param> /// <param name="paramName">Parameter name.</param> protected void ValidateUsageById( string replicationProvider, string paramName) { if (replicationProvider != Constants.HyperVReplica2012) { throw new Exception( string.Format( "Call using ID based parameter {0} is not supported for this provider. Please use its corresponding full object parameter instead", paramName)); } this.WriteWarningWithTimestamp( string.Format( Resources.IDBasedParamUsageNotSupportedFromNextRelease, paramName)); } } }
#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 // MONO 1.0 Beta mcs does not like #if !A && !B && !C syntax // .NET Compact Framework 1.0 has no support for Win32 NetMessageBufferSend API #if !NETCF // MONO 1.0 has no support for Win32 NetMessageBufferSend API #if !MONO // SSCLI 1.0 has no support for Win32 NetMessageBufferSend API #if !SSCLI // We don't want framework or platform specific code in the CLI version of Ctrip #if !CLI_1_0 using System; using System.Globalization; using System.Runtime.InteropServices; using Ctrip.Util; using Ctrip.Layout; using Ctrip.Core; namespace Ctrip.Appender { /// <summary> /// Logs entries by sending network messages using the /// <see cref="NetMessageBufferSend" /> native function. /// </summary> /// <remarks> /// <para> /// You can send messages only to names that are active /// on the network. If you send the message to a user name, /// that user must be logged on and running the Messenger /// service to receive the message. /// </para> /// <para> /// The receiver will get a top most window displaying the /// messages one at a time, therefore this appender should /// not be used to deliver a high volume of messages. /// </para> /// <para> /// The following table lists some possible uses for this appender : /// </para> /// <para> /// <list type="table"> /// <listheader> /// <term>Action</term> /// <description>Property Value(s)</description> /// </listheader> /// <item> /// <term>Send a message to a user account on the local machine</term> /// <description> /// <para> /// <see cref="NetSendAppender.Server"/> = &lt;name of the local machine&gt; /// </para> /// <para> /// <see cref="NetSendAppender.Recipient"/> = &lt;user name&gt; /// </para> /// </description> /// </item> /// <item> /// <term>Send a message to a user account on a remote machine</term> /// <description> /// <para> /// <see cref="NetSendAppender.Server"/> = &lt;name of the remote machine&gt; /// </para> /// <para> /// <see cref="NetSendAppender.Recipient"/> = &lt;user name&gt; /// </para> /// </description> /// </item> /// <item> /// <term>Send a message to a domain user account</term> /// <description> /// <para> /// <see cref="NetSendAppender.Server"/> = &lt;name of a domain controller | uninitialized&gt; /// </para> /// <para> /// <see cref="NetSendAppender.Recipient"/> = &lt;user name&gt; /// </para> /// </description> /// </item> /// <item> /// <term>Send a message to all the names in a workgroup or domain</term> /// <description> /// <para> /// <see cref="NetSendAppender.Recipient"/> = &lt;workgroup name | domain name&gt;* /// </para> /// </description> /// </item> /// <item> /// <term>Send a message from the local machine to a remote machine</term> /// <description> /// <para> /// <see cref="NetSendAppender.Server"/> = &lt;name of the local machine | uninitialized&gt; /// </para> /// <para> /// <see cref="NetSendAppender.Recipient"/> = &lt;name of the remote machine&gt; /// </para> /// </description> /// </item> /// </list> /// </para> /// <para> /// <b>Note :</b> security restrictions apply for sending /// network messages, see <see cref="NetMessageBufferSend" /> /// for more information. /// </para> /// </remarks> /// <example> /// <para> /// An example configuration section to log information /// using this appender from the local machine, named /// LOCAL_PC, to machine OPERATOR_PC : /// </para> /// <code lang="XML" escaped="true"> /// <appender name="NetSendAppender_Operator" type="Ctrip.Appender.NetSendAppender"> /// <server value="LOCAL_PC" /> /// <recipient value="OPERATOR_PC" /> /// <layout type="Ctrip.Layout.PatternLayout" value="%-5p %c [%x] - %m%n" /> /// </appender> /// </code> /// </example> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public class NetSendAppender : AppenderSkeleton { #region Member Variables /// <summary> /// The DNS or NetBIOS name of the server on which the function is to execute. /// </summary> private string m_server; /// <summary> /// The sender of the network message. /// </summary> private string m_sender; /// <summary> /// The message alias to which the message should be sent. /// </summary> private string m_recipient; /// <summary> /// The security context to use for privileged calls /// </summary> private SecurityContext m_securityContext; #endregion #region Constructors /// <summary> /// Initializes the appender. /// </summary> /// <remarks> /// The default constructor initializes all fields to their default values. /// </remarks> public NetSendAppender() { } #endregion #region Properties /// <summary> /// Gets or sets the sender of the message. /// </summary> /// <value> /// The sender of the message. /// </value> /// <remarks> /// If this property is not specified, the message is sent from the local computer. /// </remarks> public string Sender { get { return m_sender; } set { m_sender = value; } } /// <summary> /// Gets or sets the message alias to which the message should be sent. /// </summary> /// <value> /// The recipient of the message. /// </value> /// <remarks> /// This property should always be specified in order to send a message. /// </remarks> public string Recipient { get { return m_recipient; } set { m_recipient = value; } } /// <summary> /// Gets or sets the DNS or NetBIOS name of the remote server on which the function is to execute. /// </summary> /// <value> /// DNS or NetBIOS name of the remote server on which the function is to execute. /// </value> /// <remarks> /// <para> /// For Windows NT 4.0 and earlier, the string should begin with \\. /// </para> /// <para> /// If this property is not specified, the local computer is used. /// </para> /// </remarks> public string Server { get { return m_server; } set { m_server = value; } } /// <summary> /// Gets or sets the <see cref="SecurityContext"/> used to call the NetSend method. /// </summary> /// <value> /// The <see cref="SecurityContext"/> used to call the NetSend method. /// </value> /// <remarks> /// <para> /// Unless a <see cref="SecurityContext"/> specified here for this appender /// the <see cref="SecurityContextProvider.DefaultProvider"/> is queried for the /// security context to use. The default behavior is to use the security context /// of the current thread. /// </para> /// </remarks> public SecurityContext SecurityContext { get { return m_securityContext; } set { m_securityContext = value; } } #endregion #region Implementation of IOptionHandler /// <summary> /// Initialize the appender based on the options set. /// </summary> /// <remarks> /// <para> /// This is part of the <see cref="IOptionHandler"/> delayed object /// activation scheme. The <see cref="ActivateOptions"/> method must /// be called on this object after the configuration properties have /// been set. Until <see cref="ActivateOptions"/> is called this /// object is in an undefined state and must not be used. /// </para> /// <para> /// If any of the configuration properties are modified then /// <see cref="ActivateOptions"/> must be called again. /// </para> /// <para> /// The appender will be ignored if no <see cref="Recipient" /> was specified. /// </para> /// </remarks> /// <exception cref="ArgumentNullException">The required property <see cref="Recipient" /> was not specified.</exception> public override void ActivateOptions() { base.ActivateOptions(); if (this.Recipient == null) { throw new ArgumentNullException("Recipient", "The required property 'Recipient' was not specified."); } if (m_securityContext == null) { m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); } } #endregion #region Override implementation of AppenderSkeleton /// <summary> /// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(LoggingEvent)"/> method. /// </summary> /// <param name="loggingEvent">The event to log.</param> /// <remarks> /// <para> /// Sends the event using a network message. /// </para> /// </remarks> #if NET_4_0 [System.Security.SecuritySafeCritical] #endif [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] protected override void Append(LoggingEvent loggingEvent) { NativeError nativeError = null; // Render the event in the callers security context string renderedLoggingEvent = RenderLoggingEvent(loggingEvent); using(m_securityContext.Impersonate(this)) { // Send the message int returnValue = NetMessageBufferSend(this.Server, this.Recipient, this.Sender, renderedLoggingEvent, renderedLoggingEvent.Length * Marshal.SystemDefaultCharSize); // Log the error if the message could not be sent if (returnValue != 0) { // Lookup the native error nativeError = NativeError.GetError(returnValue); } } if (nativeError != null) { // Handle the error over to the ErrorHandler ErrorHandler.Error(nativeError.ToString() + " (Params: Server=" + this.Server + ", Recipient=" + this.Recipient + ", Sender=" + this.Sender + ")"); } } /// <summary> /// This appender requires a <see cref="Layout"/> to be set. /// </summary> /// <value><c>true</c></value> /// <remarks> /// <para> /// This appender requires a <see cref="Layout"/> to be set. /// </para> /// </remarks> override protected bool RequiresLayout { get { return true; } } #endregion #region Stubs For Native Function Calls /// <summary> /// Sends a buffer of information to a registered message alias. /// </summary> /// <param name="serverName">The DNS or NetBIOS name of the server on which the function is to execute.</param> /// <param name="msgName">The message alias to which the message buffer should be sent</param> /// <param name="fromName">The originator of the message.</param> /// <param name="buffer">The message text.</param> /// <param name="bufferSize">The length, in bytes, of the message text.</param> /// <remarks> /// <para> /// The following restrictions apply for sending network messages: /// </para> /// <para> /// <list type="table"> /// <listheader> /// <term>Platform</term> /// <description>Requirements</description> /// </listheader> /// <item> /// <term>Windows NT</term> /// <description> /// <para> /// No special group membership is required to send a network message. /// </para> /// <para> /// Admin, Accounts, Print, or Server Operator group membership is required to /// successfully send a network message on a remote server. /// </para> /// </description> /// </item> /// <item> /// <term>Windows 2000 or later</term> /// <description> /// <para> /// If you send a message on a domain controller that is running Active Directory, /// access is allowed or denied based on the access control list (ACL) for the securable /// object. The default ACL permits only Domain Admins and Account Operators to send a network message. /// </para> /// <para> /// On a member server or workstation, only Administrators and Server Operators can send a network message. /// </para> /// </description> /// </item> /// </list> /// </para> /// <para> /// For more information see <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/netmgmt/netmgmt/security_requirements_for_the_network_management_functions.asp">Security Requirements for the Network Management Functions</a>. /// </para> /// </remarks> /// <returns> /// <para> /// If the function succeeds, the return value is zero. /// </para> /// </returns> [DllImport("netapi32.dll", SetLastError=true)] protected static extern int NetMessageBufferSend( [MarshalAs(UnmanagedType.LPWStr)] string serverName, [MarshalAs(UnmanagedType.LPWStr)] string msgName, [MarshalAs(UnmanagedType.LPWStr)] string fromName, [MarshalAs(UnmanagedType.LPWStr)] string buffer, int bufferSize); #endregion } } #endif // !CLI_1_0 #endif // !SSCLI #endif // !MONO #endif // !NETCF
using UnityEngine; using UnityEditor; using System.Collections.Generic; /// <summary> /// This editor helper class makes it easy to create and show a context menu. /// It ensures that it's possible to add multiple items with the same name. /// </summary> public static class NGUIContextMenu { [MenuItem("Help/NGUI Documentation (v.3.6.8)")] static void ShowHelp0 (MenuCommand command) { NGUIHelp.Show(); } [MenuItem("Help/NGUI Support Forum")] static void ShowHelp01 (MenuCommand command) { Application.OpenURL("http://www.tasharen.com/forum/index.php?board=1.0"); } [MenuItem("CONTEXT/UIWidget/Copy Widget")] static void CopyStyle (MenuCommand command) { NGUISettings.CopyWidget(command.context as UIWidget); } [MenuItem("CONTEXT/UIWidget/Paste Widget Values")] static void PasteStyle (MenuCommand command) { NGUISettings.PasteWidget(command.context as UIWidget, true); } [MenuItem("CONTEXT/UIWidget/Paste Widget Style")] static void PasteStyle2 (MenuCommand command) { NGUISettings.PasteWidget(command.context as UIWidget, false); } [MenuItem("CONTEXT/UIWidget/Help")] static void ShowHelp1 (MenuCommand command) { NGUIHelp.Show(command.context); } [MenuItem("CONTEXT/UIButton/Help")] static void ShowHelp2 (MenuCommand command) { NGUIHelp.Show(typeof(UIButton)); } [MenuItem("CONTEXT/UIToggle/Help")] static void ShowHelp3 (MenuCommand command) { NGUIHelp.Show(typeof(UIToggle)); } [MenuItem("CONTEXT/UIRoot/Help")] static void ShowHelp4 (MenuCommand command) { NGUIHelp.Show(typeof(UIRoot)); } [MenuItem("CONTEXT/UICamera/Help")] static void ShowHelp5 (MenuCommand command) { NGUIHelp.Show(typeof(UICamera)); } [MenuItem("CONTEXT/UIAnchor/Help")] static void ShowHelp6 (MenuCommand command) { NGUIHelp.Show(typeof(UIAnchor)); } [MenuItem("CONTEXT/UIStretch/Help")] static void ShowHelp7 (MenuCommand command) { NGUIHelp.Show(typeof(UIStretch)); } [MenuItem("CONTEXT/UISlider/Help")] static void ShowHelp8 (MenuCommand command) { NGUIHelp.Show(typeof(UISlider)); } [MenuItem("CONTEXT/UI2DSprite/Help")] static void ShowHelp9 (MenuCommand command) { NGUIHelp.Show(typeof(UI2DSprite)); } [MenuItem("CONTEXT/UIScrollBar/Help")] static void ShowHelp10 (MenuCommand command) { NGUIHelp.Show(typeof(UIScrollBar)); } [MenuItem("CONTEXT/UIProgressBar/Help")] static void ShowHelp11 (MenuCommand command) { NGUIHelp.Show(typeof(UIProgressBar)); } [MenuItem("CONTEXT/UIPopupList/Help")] static void ShowHelp12 (MenuCommand command) { NGUIHelp.Show(typeof(UIPopupList)); } [MenuItem("CONTEXT/UIInput/Help")] static void ShowHelp13 (MenuCommand command) { NGUIHelp.Show(typeof(UIInput)); } [MenuItem("CONTEXT/UIKeyBinding/Help")] static void ShowHelp14 (MenuCommand command) { NGUIHelp.Show(typeof(UIKeyBinding)); } [MenuItem("CONTEXT/UIGrid/Help")] static void ShowHelp15 (MenuCommand command) { NGUIHelp.Show(typeof(UIGrid)); } [MenuItem("CONTEXT/UITable/Help")] static void ShowHelp16 (MenuCommand command) { NGUIHelp.Show(typeof(UITable)); } [MenuItem("CONTEXT/UIPlayTween/Help")] static void ShowHelp17 (MenuCommand command) { NGUIHelp.Show(typeof(UIPlayTween)); } [MenuItem("CONTEXT/UIPlayAnimation/Help")] static void ShowHelp18 (MenuCommand command) { NGUIHelp.Show(typeof(UIPlayAnimation)); } [MenuItem("CONTEXT/UIPlaySound/Help")] static void ShowHelp19 (MenuCommand command) { NGUIHelp.Show(typeof(UIPlaySound)); } [MenuItem("CONTEXT/UIScrollView/Help")] static void ShowHelp20 (MenuCommand command) { NGUIHelp.Show(typeof(UIScrollView)); } [MenuItem("CONTEXT/UIDragScrollView/Help")] static void ShowHelp21 (MenuCommand command) { NGUIHelp.Show(typeof(UIDragScrollView)); } [MenuItem("CONTEXT/UICenterOnChild/Help")] static void ShowHelp22 (MenuCommand command) { NGUIHelp.Show(typeof(UICenterOnChild)); } [MenuItem("CONTEXT/UICenterOnClick/Help")] static void ShowHelp23 (MenuCommand command) { NGUIHelp.Show(typeof(UICenterOnClick)); } [MenuItem("CONTEXT/UITweener/Help")] [MenuItem("CONTEXT/UIPlayTween/Help")] static void ShowHelp24 (MenuCommand command) { NGUIHelp.Show(typeof(UITweener)); } [MenuItem("CONTEXT/ActiveAnimation/Help")] [MenuItem("CONTEXT/UIPlayAnimation/Help")] static void ShowHelp25 (MenuCommand command) { NGUIHelp.Show(typeof(UIPlayAnimation)); } [MenuItem("CONTEXT/UIScrollView/Help")] [MenuItem("CONTEXT/UIDragScrollView/Help")] static void ShowHelp26 (MenuCommand command) { NGUIHelp.Show(typeof(UIScrollView)); } [MenuItem("CONTEXT/UIPanel/Help")] static void ShowHelp27 (MenuCommand command) { NGUIHelp.Show(typeof(UIPanel)); } [MenuItem("CONTEXT/UILocalize/Help")] static void ShowHelp28 (MenuCommand command) { NGUIHelp.Show(typeof(UILocalize)); } [MenuItem("CONTEXT/Localization/Help")] static void ShowHelp29 (MenuCommand command) { NGUIHelp.Show(typeof(Localization)); } [MenuItem("CONTEXT/UIKeyNavigation/Help")] static void ShowHelp30 (MenuCommand command) { NGUIHelp.Show(typeof(UIKeyNavigation)); } [MenuItem("CONTEXT/PropertyBinding/Help")] static void ShowHelp31 (MenuCommand command) { NGUIHelp.Show(typeof(PropertyBinding)); } public delegate UIWidget AddFunc (GameObject go); static List<string> mEntries = new List<string>(); static GenericMenu mMenu; /// <summary> /// Clear the context menu list. /// </summary> static public void Clear () { mEntries.Clear(); mMenu = null; } /// <summary> /// Add a new context menu entry. /// </summary> static public void AddItem (string item, bool isChecked, GenericMenu.MenuFunction2 callback, object param) { if (callback != null) { if (mMenu == null) mMenu = new GenericMenu(); int count = 0; for (int i = 0; i < mEntries.Count; ++i) { string str = mEntries[i]; if (str == item) ++count; } mEntries.Add(item); if (count > 0) item += " [" + count + "]"; mMenu.AddItem(new GUIContent(item), isChecked, callback, param); } else AddDisabledItem(item); } /// <summary> /// Wrapper function called by the menu that in turn calls the correct callback. /// </summary> static public void AddChild (object obj) { AddFunc func = obj as AddFunc; UIWidget widget = func(Selection.activeGameObject); if (widget != null) Selection.activeGameObject = widget.gameObject; } /// <summary> /// Add a new context menu entry. /// </summary> static public void AddChildWidget (string item, bool isChecked, AddFunc callback) { if (callback != null) { if (mMenu == null) mMenu = new GenericMenu(); int count = 0; for (int i = 0; i < mEntries.Count; ++i) { string str = mEntries[i]; if (str == item) ++count; } mEntries.Add(item); if (count > 0) item += " [" + count + "]"; mMenu.AddItem(new GUIContent(item), isChecked, AddChild, callback); } else AddDisabledItem(item); } /// <summary> /// Wrapper function called by the menu that in turn calls the correct callback. /// </summary> static public void AddSibling (object obj) { AddFunc func = obj as AddFunc; UIWidget widget = func(Selection.activeTransform.parent.gameObject); if (widget != null) Selection.activeGameObject = widget.gameObject; } /// <summary> /// Add a new context menu entry. /// </summary> static public void AddSiblingWidget (string item, bool isChecked, AddFunc callback) { if (callback != null) { if (mMenu == null) mMenu = new GenericMenu(); int count = 0; for (int i = 0; i < mEntries.Count; ++i) { string str = mEntries[i]; if (str == item) ++count; } mEntries.Add(item); if (count > 0) item += " [" + count + "]"; mMenu.AddItem(new GUIContent(item), isChecked, AddSibling, callback); } else AddDisabledItem(item); } /// <summary> /// Add commonly NGUI context menu options. /// </summary> static public void AddCommonItems (GameObject target) { if (target != null) { UIWidget widget = target.GetComponent<UIWidget>(); string myName = string.Format("Selected {0}", (widget != null) ? NGUITools.GetTypeName(widget) : "Object"); AddItem(myName + "/Bring to Front", false, delegate(object obj) { for (int i = 0; i < Selection.gameObjects.Length; ++i) NGUITools.BringForward(Selection.gameObjects[i]); }, null); AddItem(myName + "/Push to Back", false, delegate(object obj) { for (int i = 0; i < Selection.gameObjects.Length; ++i) NGUITools.PushBack(Selection.gameObjects[i]); }, null); AddItem(myName + "/Nudge Forward", false, delegate(object obj) { for (int i = 0; i < Selection.gameObjects.Length; ++i) NGUITools.AdjustDepth(Selection.gameObjects[i], 1); }, null); AddItem(myName + "/Nudge Back", false, delegate(object obj) { for (int i = 0; i < Selection.gameObjects.Length; ++i) NGUITools.AdjustDepth(Selection.gameObjects[i], -1); }, null); if (widget != null) { NGUIContextMenu.AddSeparator(myName + "/"); AddItem(myName + "/Make Pixel-Perfect", false, OnMakePixelPerfect, Selection.activeTransform); if (target.GetComponent<BoxCollider>() != null) { AddItem(myName + "/Reset Collider Size", false, OnBoxCollider, target); } } NGUIContextMenu.AddSeparator(myName + "/"); AddItem(myName + "/Delete", false, OnDelete, target); NGUIContextMenu.AddSeparator(""); if (Selection.activeTransform.parent != null && widget != null) { AddChildWidget("Create/Sprite/Child", false, NGUISettings.AddSprite); AddChildWidget("Create/Label/Child", false, NGUISettings.AddLabel); AddChildWidget("Create/Invisible Widget/Child", false, NGUISettings.AddWidget); AddChildWidget("Create/Simple Texture/Child", false, NGUISettings.AddTexture); AddChildWidget("Create/Unity 2D Sprite/Child", false, NGUISettings.Add2DSprite); AddSiblingWidget("Create/Sprite/Sibling", false, NGUISettings.AddSprite); AddSiblingWidget("Create/Label/Sibling", false, NGUISettings.AddLabel); AddSiblingWidget("Create/Invisible Widget/Sibling", false, NGUISettings.AddWidget); AddSiblingWidget("Create/Simple Texture/Sibling", false, NGUISettings.AddTexture); AddSiblingWidget("Create/Unity 2D Sprite/Sibling", false, NGUISettings.Add2DSprite); } else { AddChildWidget("Create/Sprite", false, NGUISettings.AddSprite); AddChildWidget("Create/Label", false, NGUISettings.AddLabel); AddChildWidget("Create/Invisible Widget", false, NGUISettings.AddWidget); AddChildWidget("Create/Simple Texture", false, NGUISettings.AddTexture); AddChildWidget("Create/Unity 2D Sprite", false, NGUISettings.Add2DSprite); } NGUIContextMenu.AddSeparator("Create/"); AddItem("Create/Panel", false, AddPanel, target); AddItem("Create/Scroll View", false, AddScrollView, target); AddItem("Create/Grid", false, AddChild<UIGrid>, target); AddItem("Create/Table", false, AddChild<UITable>, target); AddItem("Create/Anchor (Legacy)", false, AddChild<UIAnchor>, target); if (target.GetComponent<UIPanel>() != null) { if (target.GetComponent<UIScrollView>() == null) { AddItem("Attach/Scroll View", false, Attach, typeof(UIScrollView)); NGUIContextMenu.AddSeparator("Attach/"); } } else if (target.GetComponent<Collider>() == null && target.GetComponent<Collider2D>() == null) { AddItem("Attach/Box Collider", false, AttachCollider, null); NGUIContextMenu.AddSeparator("Attach/"); } bool header = false; UIScrollView scrollView = NGUITools.FindInParents<UIScrollView>(target); if (scrollView != null) { if (scrollView.GetComponentInChildren<UICenterOnChild>() == null) { AddItem("Attach/Center Scroll View on Child", false, Attach, typeof(UICenterOnChild)); header = true; } } if (target.GetComponent<Collider>() != null || target.GetComponent<Collider2D>() != null) { if (scrollView != null) { if (target.GetComponent<UIDragScrollView>() == null) { AddItem("Attach/Drag Scroll View", false, Attach, typeof(UIDragScrollView)); header = true; } if (target.GetComponent<UICenterOnClick>() == null && NGUITools.FindInParents<UICenterOnChild>(target) != null) { AddItem("Attach/Center Scroll View on Click", false, Attach, typeof(UICenterOnClick)); header = true; } } if (header) NGUIContextMenu.AddSeparator("Attach/"); AddItem("Attach/Button Script", false, Attach, typeof(UIButton)); AddItem("Attach/Toggle Script", false, Attach, typeof(UIToggle)); AddItem("Attach/Slider Script", false, Attach, typeof(UISlider)); AddItem("Attach/Scroll Bar Script", false, Attach, typeof(UIScrollBar)); AddItem("Attach/Progress Bar Script", false, Attach, typeof(UISlider)); AddItem("Attach/Popup List Script", false, Attach, typeof(UIPopupList)); AddItem("Attach/Input Field Script", false, Attach, typeof(UIInput)); NGUIContextMenu.AddSeparator("Attach/"); if (target.GetComponent<UIDragResize>() == null) AddItem("Attach/Drag Resize Script", false, Attach, typeof(UIDragResize)); if (target.GetComponent<UIDragScrollView>() == null) { for (int i = 0; i < UIPanel.list.Count; ++i) { UIPanel pan = UIPanel.list[i]; if (pan.clipping == UIDrawCall.Clipping.None) continue; UIScrollView dr = pan.GetComponent<UIScrollView>(); if (dr == null) continue; AddItem("Attach/Drag Scroll View", false, delegate(object obj) { target.AddComponent<UIDragScrollView>().scrollView = dr; }, null); header = true; break; } } AddItem("Attach/Key Binding Script", false, Attach, typeof(UIKeyBinding)); if (target.GetComponent<UIKeyNavigation>() == null) AddItem("Attach/Key Navigation Script", false, Attach, typeof(UIKeyNavigation)); NGUIContextMenu.AddSeparator("Attach/"); AddItem("Attach/Play Tween Script", false, Attach, typeof(UIPlayTween)); AddItem("Attach/Play Animation Script", false, Attach, typeof(UIPlayAnimation)); AddItem("Attach/Play Sound Script", false, Attach, typeof(UIPlaySound)); } AddItem("Attach/Property Binding", false, Attach, typeof(PropertyBinding)); if (target.GetComponent<UILocalize>() == null) AddItem("Attach/Localization Script", false, Attach, typeof(UILocalize)); if (widget != null) { AddMissingItem<TweenAlpha>(target, "Tween/Alpha"); AddMissingItem<TweenColor>(target, "Tween/Color"); AddMissingItem<TweenWidth>(target, "Tween/Width"); AddMissingItem<TweenHeight>(target, "Tween/Height"); } else if (target.GetComponent<UIPanel>() != null) { AddMissingItem<TweenAlpha>(target, "Tween/Alpha"); } NGUIContextMenu.AddSeparator("Tween/"); AddMissingItem<TweenPosition>(target, "Tween/Position"); AddMissingItem<TweenRotation>(target, "Tween/Rotation"); AddMissingItem<TweenScale>(target, "Tween/Scale"); AddMissingItem<TweenTransform>(target, "Tween/Transform"); if (target.GetComponent<AudioSource>() != null) AddMissingItem<TweenVolume>(target, "Tween/Volume"); if (target.GetComponent<Camera>() != null) { AddMissingItem<TweenFOV>(target, "Tween/Field of View"); AddMissingItem<TweenOrthoSize>(target, "Tween/Orthographic Size"); } } } /// <summary> /// Helper function that adds a widget collider to the specified object. /// </summary> static void AttachCollider (object obj) { if (Selection.activeGameObject != null) for (int i = 0; i < Selection.gameObjects.Length; ++i) NGUITools.AddWidgetCollider(Selection.gameObjects[i]); } /// <summary> /// Helper function that adds the specified type to all selected game objects. Used with the menu options above. /// </summary> static void Attach (object obj) { if (Selection.activeGameObject == null) return; System.Type type = (System.Type)obj; for (int i = 0; i < Selection.gameObjects.Length; ++i) { GameObject go = Selection.gameObjects[i]; if (go.GetComponent(type) != null) continue; #if !UNITY_3_5 Component cmp = go.AddComponent(type); Undo.RegisterCreatedObjectUndo(cmp, "Attach " + type); #endif } } /// <summary> /// Helper function. /// </summary> static void AddMissingItem<T> (GameObject target, string name) where T : MonoBehaviour { if (target.GetComponent<T>() == null) AddItem(name, false, Attach, typeof(T)); } /// <summary> /// Helper function for menu creation. /// </summary> static void AddChild<T> (object obj) where T : MonoBehaviour { GameObject go = obj as GameObject; T t = NGUITools.AddChild<T>(go); Selection.activeGameObject = t.gameObject; } /// <summary> /// Helper function for menu creation. /// </summary> static void AddPanel (object obj) { GameObject go = obj as GameObject; if (go.GetComponent<UIWidget>() != null) go = go.transform.parent.gameObject; UIPanel panel = NGUISettings.AddPanel(go); Selection.activeGameObject = panel.gameObject; } /// <summary> /// Helper function for menu creation. /// </summary> static void AddScrollView (object obj) { GameObject go = obj as GameObject; if (go.GetComponent<UIWidget>() != null) go = go.transform.parent.gameObject; UIPanel panel = NGUISettings.AddPanel(go); panel.clipping = UIDrawCall.Clipping.SoftClip; panel.gameObject.AddComponent<UIScrollView>(); panel.name = "Scroll View"; Selection.activeGameObject = panel.gameObject; } /// <summary> /// Add help options based on the components present on the specified game object. /// </summary> static public void AddHelp (GameObject go, bool addSeparator) { MonoBehaviour[] comps = Selection.activeGameObject.GetComponents<MonoBehaviour>(); bool addedSomething = false; for (int i = 0; i < comps.Length; ++i) { System.Type type = comps[i].GetType(); string url = NGUIHelp.GetHelpURL(type); if (url != null) { if (addSeparator) { addSeparator = false; AddSeparator(""); } AddItem("Help/" + type, false, delegate(object obj) { Application.OpenURL(url); }, null); addedSomething = true; } } if (addedSomething) AddSeparator("Help/"); AddItem("Help/All Topics", false, delegate(object obj) { NGUIHelp.Show(); }, null); } static void OnHelp (object obj) { NGUIHelp.Show(obj); } static void OnMakePixelPerfect (object obj) { NGUITools.MakePixelPerfect(obj as Transform); } static void OnBoxCollider (object obj) { NGUITools.AddWidgetCollider(obj as GameObject); } static void OnDelete (object obj) { GameObject go = obj as GameObject; Selection.activeGameObject = go.transform.parent.gameObject; Undo.DestroyObjectImmediate(go); } /// <summary> /// Add a new disabled context menu entry. /// </summary> static public void AddDisabledItem (string item) { if (mMenu == null) mMenu = new GenericMenu(); mMenu.AddDisabledItem(new GUIContent(item)); } /// <summary> /// Add a separator to the menu. /// </summary> static public void AddSeparator (string path) { if (mMenu == null) mMenu = new GenericMenu(); // For some weird reason adding separators on OSX causes the entire menu to be disabled. Wtf? if (Application.platform != RuntimePlatform.OSXEditor) mMenu.AddSeparator(path); } /// <summary> /// Show the context menu with all the added items. /// </summary> static public void Show () { if (mMenu != null) { mMenu.ShowAsContext(); mMenu = null; mEntries.Clear(); } } }
// 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. // $Id: GroupRequest.java,v 1.8 2004/09/05 04:54:22 ovidiuf Exp $ using System; using System.Collections; using Alachisoft.NGroups; using Alachisoft.NGroups.Stack; using Alachisoft.NGroups.Util; using Alachisoft.NCache.Common.Net; using Alachisoft.NCache.Common.Monitoring; using System.Text; using System.Configuration; using System.Collections.Generic; using Alachisoft.NCache.Common.Util; using Alachisoft.NCache.Common.Logger; namespace Alachisoft.NGroups.Blocks { /// <summary> Sends a message to all members of the group and waits for all responses (or timeout). Returns a /// boolean value (success or failure). Results (if any) can be retrieved when _done.<p> /// The supported transport to send requests is currently either a RequestCorrelator or a generic /// Transport. One of them has to be given in the constructor. It will then be used to send a /// request. When a message is received by either one, the receiveResponse() of this class has to /// be called (this class does not actively receive requests/responses itself). Also, when a view change /// or suspicion is received, the methods viewChange() or suspect() of this class have to be called.<p> /// When started, an array of responses, correlating to the membership, is created. Each response /// is added to the corresponding field in the array. When all fields have been set, the algorithm /// terminates. /// This algorithm can optionally use a suspicion service (failure detector) to detect (and /// exclude from the membership) fauly members. If no suspicion service is available, timeouts /// can be used instead (see <code>execute()</code>). When _done, a list of suspected members /// can be retrieved.<p> /// Because a channel might deliver requests, and responses to <em>different</em> requests, the /// <code>GroupRequest</code> class cannot itself receive and process requests/responses from the /// channel. A mechanism outside this class has to do this; it has to determine what the responses /// are for the message sent by the <code>execute()</code> method and call <code>receiveResponse()</code> /// to do so.<p> /// <b>Requirements</b>: lossless delivery, e.g. acknowledgment-based message confirmation. /// </summary> /// <author> Bela Ban /// </author> /// <version> $Revision: 1.8 $ /// </version> public class GroupRequest : RspCollector, Command { /// <summary>Returns the results as a RspList </summary> virtual public RspList Results { get { RspList retval = new RspList(); Address sender; lock (rsp_mutex) { for (int i = 0; i < membership.Length; i++) { sender = membership[i]; switch (received[i]) { case SUSPECTED: retval.addSuspect(sender); break; case RECEIVED: retval.addRsp(sender, responses[i]); break; case NOT_RECEIVED: retval.addNotReceived(sender); break; } } return retval; } } } virtual public int NumSuspects { get { return suspects.Count; } } virtual public ArrayList Suspects { get { return suspects; } } virtual public bool Done { get { return _done; } } /// <summary>Generates a new unique request ID </summary> private static long RequestId { get { lock (req_mutex) { //TAIM: Request id ranges from 0 to long.Max. If it reaches the max we //re-initialize it to -1; if (last_req_id == long.MaxValue) last_req_id = -1; long result = ++last_req_id; return result; } } } public void AddNHop(Address sender) { lock (_nhopMutex) { expectedNHopResponses++; if (!nHops.Contains(sender)) nHops.Add(sender); } } public void AddNHopDefaultStatus(Address sender) { if (!receivedFromNHops.ContainsKey(sender)) receivedFromNHops.Add(sender, NOT_RECEIVED); } virtual protected internal bool Responses { get { int num_not_received = getNum(NOT_RECEIVED); int num_received = getNum(RECEIVED); int num_suspected = getNum(SUSPECTED); int num_total = membership.Length; int num_receivedFromNHops = getNumFromNHops(RECEIVED); int num_suspectedNHops = getNumFromNHops(SUSPECTED); int num_okResponsesFromNHops = num_receivedFromNHops + num_suspectedNHops; switch (rsp_mode) { case GET_FIRST: if (num_received > 0) return true; if (num_suspected >= num_total) return true; break; case GET_FIRST_NHOP: if (num_received > 0 && num_okResponsesFromNHops == expectedNHopResponses) return true; if (num_suspected >= num_total) return true; break; case GET_ALL: if (num_not_received > 0) return false; return true; case GET_ALL_NHOP: if (num_not_received > 0) return false; if (num_okResponsesFromNHops < expectedNHopResponses) return false; return true; case GET_N: if (expected_mbrs >= num_total) { rsp_mode = GET_ALL; return Responses; } if (num_received >= expected_mbrs) { return true; } if (num_received + num_not_received < expected_mbrs) { if (num_received + num_suspected >= expected_mbrs) { return true; } return false; } return false; case GET_NONE: return true; default: NCacheLog.Error("rsp_mode " + rsp_mode + " unknown !"); break; } return false; } } /// <summary>return only first response </summary> public const byte GET_FIRST = 1; /// <summary>return all responses </summary> public const byte GET_ALL = 2; /// <summary>return n responses (may block) </summary> public const byte GET_N = 3; /// <summary>return no response (async call) </summary> public const byte GET_NONE = 4; /// <summary> /// This type is used when two nodes dont communicate directly. Consider three nodes 1,2 and 3. /// 1 sends request to 2; 2 forwards request to 3; 3 executes the request and send the response /// directly to 1 instead of 2. /// </summary> public const byte GET_FIRST_NHOP = 5; public const byte GET_ALL_NHOP = 6; private const byte NOT_RECEIVED = 0; private const byte RECEIVED = 1; private const byte SUSPECTED = 2; private Address[] membership = null; // current membership private object[] responses = null; // responses corresponding to membership private byte[] received = null; // status of response for each mbr (see above) private long[] timeStats = null; // responses corresponding to membership /// <summary> /// replica nodes in the cluster from where we are expecting responses. Following is the detail of how /// it works. /// 1. In case of synchronous POR, when an operation is transferred to main node through clustering /// layer, main node does the following: - /// a) it executes the operation on itself. /// b) it transfers the operation to its replica (the next hop). /// c) it sends the response of this operation back and as part of this /// response, it informs the node that another response is expected from replica node (the next hop). /// 2. this dictionary is filled with the replica addresses (next hop addresses) received as part of the response /// from main node along with the status (RECEIVED/NOT_RECEIVED...). /// </summary> private Dictionary<Address, byte> receivedFromNHops = new Dictionary<Address, byte>(); /// <summary> /// list of next hop members. /// </summary> private List<Address> nHops = new List<Address>(); /// <summary> /// number of responses expected from next hops. When one node send requests to other node (NHop Request), /// the node may or may not send the same request to next hop depending on the success/failure of the request /// on this node. this counter tells how many requests were sent to next hops and their responses are now /// expected. /// </summary> private int expectedNHopResponses = 0; private object _nhopMutex = new object(); /// <summary>bounded queue of suspected members </summary> private ArrayList suspects = ArrayList.Synchronized(new ArrayList(10)); /// <summary>list of members, changed by viewChange() </summary> private ArrayList members = ArrayList.Synchronized(new ArrayList(10)); /// <summary> /// the list of all the current members in the cluster. /// this list is different from the members list of the Group Request which /// only contains the addresses of members to which this group request must /// send the message. /// list of total membership is used to determine which member has been /// suspected after the new list of members is received through view change /// event. /// </summary> private ArrayList clusterMembership = ArrayList.Synchronized(new ArrayList(10)); /// <summary>keep suspects vector bounded </summary> private int max_suspects = 40; protected internal Message request_msg = null; protected internal RequestCorrelator corr = null; // either use RequestCorrelator or ... protected internal Transport transport = null; // Transport (one of them has to be non-null) protected internal byte rsp_mode = GET_ALL; private bool _done = false; protected internal object rsp_mutex = new object(); protected internal long timeout = 0; protected internal int expected_mbrs = 0; /// <summary>to generate unique request IDs (see getRequestId()) </summary> private static long last_req_id = -1; protected internal long req_id = -1; // request ID for this request private static object req_mutex = new object(); //private string cacheName; private ILogger _ncacheLog; private ILogger NCacheLog { get { return _ncacheLog; } } private static bool s_allowRequestEnquiry; private static int s_requestEnquiryInterval = 20; private static int s_requestEnquiryRetries = 1; private bool _seqReset; private int _retriesAfteSeqReset; static GroupRequest() { string str = ConfigurationSettings.AppSettings["NCacheServer.AllowRequestEnquiry"]; if (!string.IsNullOrEmpty(str)) { s_allowRequestEnquiry = Convert.ToBoolean(str); } if (s_allowRequestEnquiry) { str = ConfigurationSettings.AppSettings["NCacheServer.RequestEnquiryInterval"]; if (!string.IsNullOrEmpty(str)) { s_requestEnquiryInterval = Convert.ToInt32(str); } str = ConfigurationSettings.AppSettings["NCacheServer.RequestEnquiryRetries"]; if (!string.IsNullOrEmpty(str)) { s_requestEnquiryRetries = Convert.ToInt32(str); if (s_requestEnquiryRetries <= 0) { s_requestEnquiryRetries = 1; } } } } /// <param name="m">The message to be sent /// </param> /// <param name="corr">The request correlator to be used. A request correlator sends requests tagged with /// a unique ID and notifies the sender when matching responses are received. The /// reason <code>GroupRequest</code> uses it instead of a <code>Transport</code> is /// that multiple requests/responses might be sent/received concurrently. /// </param> /// <param name="members">The initial membership. This value reflects the membership to which the request /// is sent (and from which potential responses are expected). Is reset by reset(). /// </param> /// <param name="rsp_mode">How many responses are expected. Can be /// <ol> /// <li><code>GET_ALL</code>: wait for all responses from non-suspected members. /// A suspicion service might warn /// us when a member from which a response is outstanding has crashed, so it can /// be excluded from the responses. If no suspision service is available, a /// timeout can be used (a value of 0 means wait forever). <em>If a timeout of /// 0 is used, no suspicion service is available and a member from which we /// expect a response has crashed, this methods blocks forever !</em>. /// <li><code>GET_FIRST</code>: wait for the first available response. /// <li><code>GET_MAJORITY</code>: wait for the majority of all responses. The /// majority is re-computed when a member is suspected. /// <li><code>GET_ABS_MAJORITY</code>: wait for the majority of /// <em>all</em> members. /// This includes failed members, so it may block if no timeout is specified. /// <li><code>GET_N</CODE>: wait for N members. /// Return if n is >= membership+suspects. /// <li><code>GET_NONE</code>: don't wait for any response. Essentially send an /// asynchronous message to the group members. /// </ol> /// </param> public GroupRequest(Message m, RequestCorrelator corr, ArrayList members, ArrayList clusterCompleteMembership, byte rsp_mode, ILogger NCacheLog) { request_msg = m; this.corr = corr; this.rsp_mode = rsp_mode; this._ncacheLog = NCacheLog; this.clusterMembership = clusterCompleteMembership; reset(members); } /// <param name="timeout">Time to wait for responses (ms). A value of <= 0 means wait indefinitely /// (e.g. if a suspicion service is available; timeouts are not needed). /// </param> public GroupRequest(Message m, RequestCorrelator corr, ArrayList members, ArrayList clusterCompleteMembership, byte rsp_mode, long timeout, int expected_mbrs, ILogger NCacheLog) : this(m, corr, members, clusterCompleteMembership, rsp_mode, NCacheLog) { if (timeout > 0) this.timeout = timeout; this.expected_mbrs = expected_mbrs; } public GroupRequest(Message m, Transport transport, ArrayList members, ArrayList clusterCompleteMembership, byte rsp_mode, ILogger NCacheLog) { request_msg = m; this.transport = transport; this.rsp_mode = rsp_mode; this._ncacheLog = NCacheLog; this.clusterMembership = clusterCompleteMembership; reset(members); } /// <param name="timeout">Time to wait for responses (ms). A value of <= 0 means wait indefinitely /// (e.g. if a suspicion service is available; timeouts are not needed). /// </param> public GroupRequest(Message m, Transport transport, ArrayList members, ArrayList clusterCompleteMembership, byte rsp_mode, long timeout, int expected_mbrs, ILogger NCacheLog) : this(m, transport, members, clusterCompleteMembership, rsp_mode, NCacheLog) { if (timeout > 0) this.timeout = timeout; this.expected_mbrs = expected_mbrs; } /// <summary> Sends the message. Returns when n responses have been received, or a /// timeout has occurred. <em>n</em> can be the first response, all /// responses, or a majority of the responses. /// </summary> public virtual bool execute() { if(ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("GrpReq.Exec", "mode :" + rsp_mode); bool retval; if (corr == null && transport == null) { NCacheLog.Error("GroupRequest.execute()", "both corr and transport are null, cannot send group request"); return false; } lock (rsp_mutex) { _done = false; retval = doExecute(timeout); if (retval == false) { if(NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.execute()", "call did not execute correctly, request is " + ToString()); } if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("GrpReq.Exec", "exited; result:" + retval); _done = true; return retval; } } /// <summary> Resets the group request, so it can be reused for another execution.</summary> public virtual void reset(Message m, byte mode, long timeout) { lock (rsp_mutex) { _done = false; request_msg = m; rsp_mode = mode; this.timeout = timeout; System.Threading.Monitor.PulseAll(rsp_mutex); } } public virtual void reset(Message m, ArrayList members, byte rsp_mode, long timeout, int expected_rsps) { lock (rsp_mutex) { reset(m, rsp_mode, timeout); reset(members); this.expected_mbrs = expected_rsps; System.Threading.Monitor.PulseAll(rsp_mutex); } } /// <summary> This method sets the <code>membership</code> variable to the value of /// <code>members</code>. It requires that the caller already hold the /// <code>rsp_mutex</code> lock. /// </summary> /// <param name="mbrs">The new list of members /// </param> public virtual void reset(ArrayList mbrs) { if (mbrs != null) { int size = mbrs.Count; membership = new Address[size]; responses = new object[size]; received = new byte[size]; timeStats = new long[size]; for (int i = 0; i < size; i++) { membership[i] = (Address)mbrs[i]; responses[i] = null; received[i] = NOT_RECEIVED; timeStats[i] = 0; } // maintain local membership this.members.Clear(); this.members.AddRange(mbrs); } else { if (membership != null) { for (int i = 0; i < membership.Length; i++) { responses[i] = null; received[i] = NOT_RECEIVED; } } } } public void SequenceReset() { lock (rsp_mutex) { _seqReset = true; _retriesAfteSeqReset = 0; System.Threading.Monitor.PulseAll(rsp_mutex); } } /* ---------------------- Interface RspCollector -------------------------- */ /// <summary> <b>Callback</b> (called by RequestCorrelator or Transport). /// Adds a response to the response table. When all responses have been received, /// <code>execute()</code> returns. /// </summary> public virtual void receiveResponse(Message m) { Address sender = m.Src, mbr; object val = null; if (_done) { NCacheLog.Warn("GroupRequest.receiveResponse()", "command is done; cannot add response !"); return; } if (suspects != null && suspects.Count > 0 && suspects.Contains(sender)) { NCacheLog.Warn("GroupRequest.receiveResponse()", "received response from suspected member " + sender + "; discarding"); return; } if (m.Length > 0) { try { if (m.responseExpected) { OperationResponse opRes = new OperationResponse(); opRes.SerializablePayload = m.getFlatObject(); opRes.UserPayload = m.Payload; val = opRes; } else { val = m.getFlatObject(); } } catch (System.Exception e) { NCacheLog.Error("GroupRequest.receiveResponse()", "exception=" + e.Message); } } lock (rsp_mutex) { bool isMainMember = false; for (int i = 0; i < membership.Length; i++) { mbr = membership[i]; if (mbr.Equals(sender)) { isMainMember = true; if (received[i] == NOT_RECEIVED) { responses[i] = val; received[i] = RECEIVED; if (NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.receiveResponse()", "received response for request " + req_id + ", sender=" + sender + ", val=" + val); System.Threading.Monitor.PulseAll(rsp_mutex); // wakes up execute() break; } } } if (!isMainMember) { receivedFromNHops[sender] = RECEIVED; System.Threading.Monitor.PulseAll(rsp_mutex); } } } /// <summary> <b>Callback</b> (called by RequestCorrelator or Transport). /// Report to <code>GroupRequest</code> that a member is reported as faulty (suspected). /// This method would probably be called when getting a suspect message from a failure detector /// (where available). It is used to exclude faulty members from the response list. /// </summary> public virtual void suspect(Address suspected_member) { Address mbr; bool isMainMember = false; lock (rsp_mutex) { // modify 'suspects' and 'responses' array for (int i = 0; i < membership.Length; i++) { mbr = membership[i]; if (mbr.Equals(suspected_member)) { isMainMember = true; addSuspect(suspected_member); responses[i] = null; received[i] = SUSPECTED; System.Threading.Monitor.PulseAll(rsp_mutex); break; } } if (!isMainMember) { if (clusterMembership != null && clusterMembership.Contains(suspected_member)) receivedFromNHops[suspected_member] = SUSPECTED; System.Threading.Monitor.PulseAll(rsp_mutex); } } } /// <summary> Any member of 'membership' that is not in the new view is flagged as /// SUSPECTED. Any member in the new view that is <em>not</em> in the /// membership (ie, the set of responses expected for the current RPC) will /// <em>not</em> be added to it. If we did this we might run into the /// following problem: /// <ul> /// <li>Membership is {A,B} /// <li>A sends a synchronous group RPC (which sleeps for 60 secs in the /// invocation handler) /// <li>C joins while A waits for responses from A and B /// <li>If this would generate a new view {A,B,C} and if this expanded the /// response set to {A,B,C}, A would wait forever on C's response because C /// never received the request in the first place, therefore won't send a /// response. /// </ul> /// </summary> public virtual void viewChange(View new_view) { Address mbr; ArrayList mbrs = new_view != null ? new_view.Members : null; if (membership == null || membership.Length == 0 || mbrs == null) return; lock (rsp_mutex) { ArrayList oldMembership = clusterMembership != null ? clusterMembership.Clone() as ArrayList : null; clusterMembership.Clear(); clusterMembership.AddRange(mbrs); this.members.Clear(); this.members.AddRange(mbrs); for (int i = 0; i < membership.Length; i++) { mbr = membership[i]; if (!mbrs.Contains(mbr)) { addSuspect(mbr); responses[i] = null; received[i] = SUSPECTED; } if (oldMembership != null) oldMembership.Remove(mbr); } //by this time, membershipClone cotains all those members that are not part of //group request normal membership and are no longer part of the cluster membership //according to the new view. //this way we are suspecting replica members. if (oldMembership != null) { foreach (Address member in oldMembership) { if (!mbrs.Contains(member)) receivedFromNHops[member] = SUSPECTED; } } System.Threading.Monitor.PulseAll(rsp_mutex); } } /* -------------------- End of Interface RspCollector ----------------------------------- */ public override string ToString() { System.Text.StringBuilder ret = new System.Text.StringBuilder(); ret.Append("[GroupRequest:\n"); ret.Append("req_id=").Append(req_id).Append('\n'); ret.Append("members: "); for (int i = 0; i < membership.Length; i++) { ret.Append(membership[i] + " "); } ret.Append("\nresponses: "); for (int i = 0; i < responses.Length; i++) { ret.Append(responses[i] + " "); } if (suspects.Count > 0) ret.Append("\nsuspects: " + Global.CollectionToString(suspects)); ret.Append("\nrequest_msg: " + request_msg); ret.Append("\nrsp_mode: " + rsp_mode); ret.Append("\ndone: " + _done); ret.Append("\ntimeout: " + timeout); ret.Append("\nexpected_mbrs: " + expected_mbrs); ret.Append("\n]"); return ret.ToString(); } /* --------------------------------- Private Methods -------------------------------------*/ /// <summary>This method runs with rsp_mutex locked (called by <code>execute()</code>). </summary> protected internal virtual bool doExecute_old(long timeout) { long start_time = 0; Address mbr, suspect; if (rsp_mode != GET_NONE) { req_id = corr.NextRequestId; } reset(null); // clear 'responses' array if (suspects != null) { // mark all suspects in 'received' array for (int i = 0; i < suspects.Count; i++) { suspect = (Address)suspects[i]; for (int j = 0; j < membership.Length; j++) { mbr = membership[j]; if (mbr.Equals(suspect)) { received[j] = SUSPECTED; break; // we can break here because we ensure there are no duplicate members } } } } try { if (NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.doExecute()", "sending request (id=" + req_id + ')'); if (corr != null) { ArrayList tmp = members != null ? members : null; corr.sendRequest(req_id, tmp, request_msg, rsp_mode == GET_NONE ? null : this); } else { transport.send(request_msg); } } catch (System.Exception e) { NCacheLog.Error("GroupRequest.doExecute()", "exception=" + e.Message); if (corr != null) { corr.done(req_id); } return false; } long orig_timeout = timeout; if (timeout <= 0) { while (true) { /* Wait for responses: */ adjustMembership(); // may not be necessary, just to make sure... if (Responses) { if (corr != null) { corr.done(req_id); } if (NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.doExecute()", "received all responses: " + ToString()); return true; } try { System.Threading.Monitor.Wait(rsp_mutex); } catch (System.Exception e) { NCacheLog.Error("GroupRequest.doExecute():2", "exception=" + e.Message); } } } else { start_time = (System.DateTime.Now.Ticks - 621355968000000000) / 10000; while (timeout > 0) { /* Wait for responses: */ if (Responses) { if (corr != null) corr.done(req_id); if (NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.doExecute()", "received all responses: " + ToString()); return true; } timeout = orig_timeout - ((System.DateTime.Now.Ticks - 621355968000000000) / 10000 - start_time); if (timeout > 0) { try { System.Threading.Monitor.Wait(rsp_mutex, TimeSpan.FromMilliseconds(timeout)); } catch (System.Exception e) { NCacheLog.Error("GroupRequest.doExecute():3", "exception=" + e); } } } if (timeout <= 0) { RspList rspList = Results; string failedNodes = ""; if (rspList != null) { for (int i = 0; i < rspList.size(); i++) { Rsp rsp = rspList.elementAt(i) as Rsp; if (rsp != null && !rsp.wasReceived()) failedNodes += rsp.Sender; } } if (NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.doExecute:", "[ " + req_id + " ] did not receive rsp from " + failedNodes + " [Timeout] " + timeout + " [timeout-val =" + orig_timeout + "]"); } if (corr != null) { corr.done(req_id); } return false; } } protected internal virtual bool doExecute(long timeout) { long start_time = 0; Address mbr, suspect; if (rsp_mode != GET_NONE) { req_id = corr.NextRequestId; } reset(null); // clear 'responses' array if (suspects != null) { // mark all suspects in 'received' array for (int i = 0; i < suspects.Count; i++) { suspect = (Address)suspects[i]; for (int j = 0; j < membership.Length; j++) { mbr = membership[j]; if (mbr.Equals(suspect)) { received[j] = SUSPECTED; break; // we can break here because we ensure there are no duplicate members } } } } try { if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("GrpReq.doExec", "sending req_id :" + req_id + "; timeout: " + timeout); if (NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.doExecute()", "sending request (id=" + req_id + ')'); if (corr != null) { ArrayList tmp = members != null ? members : null; if (rsp_mode == GET_FIRST_NHOP || rsp_mode == GET_ALL_NHOP) corr.sendNHopRequest(req_id, tmp, request_msg, this); else corr.sendRequest(req_id, tmp, request_msg, rsp_mode == GET_NONE ? null : this); } else { transport.send(request_msg); } } catch (System.Exception e) { NCacheLog.Error("GroupRequest.doExecute()", "exception=" + e.Message); if (corr != null) { corr.done(req_id); } return false; } long orig_timeout = timeout; if (timeout <= 0) { while (true) { /* Wait for responses: */ adjustMembership(); // may not be necessary, just to make sure... if (Responses) { if (corr != null) { corr.done(req_id); } if (NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.doExecute()", "received all responses: " + ToString()); return true; } try { System.Threading.Monitor.Wait(rsp_mutex); } catch (System.Exception e) { NCacheLog.Error("GroupRequest.doExecute():2", "exception=" + e.Message); } } } else { start_time = (System.DateTime.Now.Ticks - 621355968000000000) / 10000; long wakeuptime = timeout; int retries = s_requestEnquiryRetries; int enquiryFailure = 0; if (s_allowRequestEnquiry) { wakeuptime = s_requestEnquiryInterval * 1000; } while (timeout > 0) { /* Wait for responses: */ if (Responses) { if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("GrpReq.doExec", "req_id :" + req_id + " completed" ); if (corr != null) corr.done(req_id); if (NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.doExecute()", "received all responses: " + ToString()); return true; } timeout = orig_timeout - ((System.DateTime.Now.Ticks - 621355968000000000) / 10000 - start_time); if (s_allowRequestEnquiry) { if (wakeuptime > timeout) wakeuptime = timeout; } else { wakeuptime = timeout; } if (timeout > 0) { try { timeout = orig_timeout - ((System.DateTime.Now.Ticks - 621355968000000000) / 10000 - start_time); bool reacquired = System.Threading.Monitor.Wait(rsp_mutex, TimeSpan.FromMilliseconds(wakeuptime)); if ((!reacquired || _seqReset) && s_allowRequestEnquiry) { if (Responses) { if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("GrpReq.doExec", "req_id :" + req_id + " completed"); if (corr != null) corr.done(req_id); if (NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.doExecute()", "received all responses: " + ToString()); return true; } else { if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("GrpReq.doExec", "req_id :" + req_id + " completed"); if ((timeout > 0 && wakeuptime < timeout) && retries > 0) { if (_seqReset) { _retriesAfteSeqReset++; } retries--; bool enquireAgain = GetRequestStatus(); if (!enquireAgain) enquiryFailure++; //for debugging and tesing purpose only. will be removed after testing. NCacheLog.CriticalInfo("GetRequestStatus, retries : " + retries + ", enquire again : " + enquireAgain.ToString() + ", enquiry failure : " + enquiryFailure); if (enquiryFailure >=3 || _retriesAfteSeqReset > 3) { if (corr != null) corr.done(req_id); return false; } } } } } catch (System.Exception e) { NCacheLog.Error("GroupRequest.doExecute():3", "exception=" + e); } } } if (timeout <= 0) { RspList rspList = Results; string failedNodes = ""; if (rspList != null) { for (int i = 0; i < rspList.size(); i++) { Rsp rsp = rspList.elementAt(i) as Rsp; if (rsp != null && !rsp.wasReceived()) failedNodes += rsp.Sender; } } if (NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.doExecute:", "[ " + req_id + " ] did not receive rsp from " + failedNodes + " [Timeout] " + timeout + " [timeout-val =" + orig_timeout + "]"); } if (corr != null) { corr.done(req_id); } return false; } } private bool GetRequestStatus() { Hashtable statusResult = null; ArrayList failedNodes = new ArrayList(); RspList rspList = Results; bool enquireStatusAgain = true; int suspectCount = 0; string notRecvNodes = ""; if (rspList != null) { for (int i = 0; i < rspList.size(); i++) { Rsp rsp = rspList.elementAt(i) as Rsp; if (rsp != null && !rsp.wasReceived()) { notRecvNodes += rsp.sender + ","; failedNodes.Add(rsp.Sender); } if (rsp != null && rsp.wasSuspected()) suspectCount++; } } if (NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.GetReqStatus", req_id + " rsp not received from " + failedNodes.Count + " nodes"); bool resendReq = true; ArrayList resendList = new ArrayList(); int notRespondingCount = 0; if(failedNodes.Count >0) { if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("GrpReq.GetReqStatus", " did not recv rsps from " + notRecvNodes + " nodes"); statusResult = corr.FetchRequestStatus(failedNodes, this.clusterMembership, req_id); StringBuilder sb = null; if (ServerMonitor.MonitorActivity) sb = new StringBuilder(); if (statusResult != null) { foreach (Address node in failedNodes) { RequestStatus status = statusResult[node] as RequestStatus; if (status.Status == RequestStatus.REQ_NOT_RECEIVED) { if(sb != null) sb.Append("(" + node + ":" + "REQ_NOT_RECEIVED)"); resendList.Add(node); } if (status.Status == RequestStatus.NONE) { if (sb != null) sb.Append("(" + node + ":" + "NONE)"); notRespondingCount++; } if (status.Status == RequestStatus.REQ_PROCESSED) { if (sb != null) sb.Append("(" + node + ":" + "REQ_PROCESSED)"); if (!request_msg.IsSeqRequired) { resendList.Add(node); } } } if (sb != null && ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("GrpReq.GetReqStatus", "status of failed nodes " + sb.ToString()); if (request_msg.IsSeqRequired) { if (resendList.Count != rspList.size()) { if (NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.GetReqStatus", req_id + "sequence message; no need to resend; resend_count " + resendList.Count); if (notRespondingCount > 0) { resendReq = false; } else { enquireStatusAgain = false; resendReq = false; } } } if (NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.GetReqStatus", req_id + "received REQ_NOT_RECEIVED status from " + resendList.Count + " nodes"); } else if (NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.GetReqStatus", req_id + " status result is NULL"); if (resendReq && resendList.Count > 0) { if (corr != null) { if (resendList.Count == 1) { request_msg.Dest = resendList[0] as Address; } else { request_msg.Dests = resendList; } if (NCacheLog.IsInfoEnabled) NCacheLog.Info("GroupRequest.GetReqStatus", req_id + " resending messages to " + resendList.Count); corr.sendRequest(req_id, resendList, request_msg, rsp_mode == GET_NONE ? null : this); } } } return enquireStatusAgain; } /// <summary>Return number of elements of a certain type in array 'received'. Type can be RECEIVED, /// NOT_RECEIVED or SUSPECTED /// </summary> public virtual int getNum(int type) { int retval = 0; for (int i = 0; i < received.Length; i++) if (received[i] == type) retval++; return retval; } public virtual int getNumFromNHops(int type) { int retval = 0; lock (_nhopMutex) { foreach (Address replica in nHops) { byte status = 0; if (receivedFromNHops.TryGetValue(replica, out status)) { if (status == type) retval++; } } } return retval; } public virtual void printReceived() { for (int i = 0; i < received.Length; i++) { if (NCacheLog.IsInfoEnabled) NCacheLog.Info(membership[i] + ": " + (received[i] == NOT_RECEIVED ? "NOT_RECEIVED" : (received[i] == RECEIVED ? "RECEIVED" : "SUSPECTED"))); } } /// <summary> Adjusts the 'received' array in the following way: /// <ul> /// <li>if a member P in 'membership' is not in 'members', P's entry in the 'received' array /// will be marked as SUSPECTED /// <li>if P is 'suspected_mbr', then P's entry in the 'received' array will be marked /// as SUSPECTED /// </ul> /// This call requires exclusive access to rsp_mutex (called by getResponses() which has /// a the rsp_mutex locked, so this should not be a problem). /// </summary> public virtual void adjustMembership() { Address mbr; if (membership == null || membership.Length == 0) { return; } for (int i = 0; i < membership.Length; i++) { mbr = membership[i]; if ((this.members != null && !this.members.Contains(mbr)) || suspects.Contains(mbr)) { addSuspect(mbr); responses[i] = null; received[i] = SUSPECTED; } } } /// <summary> Adds a member to the 'suspects' list. Removes oldest elements from 'suspects' list /// to keep the list bounded ('max_suspects' number of elements) /// </summary> public virtual void addSuspect(Address suspected_mbr) { if (!suspects.Contains(suspected_mbr)) { suspects.Add(suspected_mbr); while (suspects.Count >= max_suspects && suspects.Count > 0) suspects.RemoveAt(0); // keeps queue bounded } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Reflection; using System.Threading.Tasks; using FluentAssertions; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Resources; using JsonApiDotNetCore.Serialization.Objects; using Microsoft.EntityFrameworkCore; using TestBuildingBlocks; using Xunit; namespace JsonApiDotNetCoreTests.IntegrationTests.ReadWrite.Updating.Resources { public sealed class UpdateResourceTests : IClassFixture<IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext>> { private readonly IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext> _testContext; private readonly ReadWriteFakers _fakers = new(); public UpdateResourceTests(IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext> testContext) { _testContext = testContext; testContext.UseController<WorkItemsController>(); testContext.UseController<WorkItemGroupsController>(); testContext.UseController<UserAccountsController>(); testContext.UseController<RgbColorsController>(); testContext.ConfigureServicesAfterStartup(services => { services.AddResourceDefinition<ImplicitlyChangingWorkItemDefinition>(); services.AddResourceDefinition<ImplicitlyChangingWorkItemGroupDefinition>(); }); } [Fact] public async Task Can_update_resource_without_attributes_or_relationships() { // Arrange UserAccount existingUserAccount = _fakers.UserAccount.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.UserAccounts.Add(existingUserAccount); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "userAccounts", id = existingUserAccount.StringId, attributes = new { }, relationships = new { } } }; string route = $"/userAccounts/{existingUserAccount.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { UserAccount userAccountInDatabase = await dbContext.UserAccounts.FirstWithIdAsync(existingUserAccount.Id); userAccountInDatabase.FirstName.Should().Be(existingUserAccount.FirstName); userAccountInDatabase.LastName.Should().Be(existingUserAccount.LastName); }); } [Fact] public async Task Can_update_resource_with_unknown_attribute() { // Arrange UserAccount existingUserAccount = _fakers.UserAccount.Generate(); string newFirstName = _fakers.UserAccount.Generate().FirstName; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.UserAccounts.Add(existingUserAccount); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "userAccounts", id = existingUserAccount.StringId, attributes = new { firstName = newFirstName, doesNotExist = "Ignored" } } }; string route = $"/userAccounts/{existingUserAccount.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { UserAccount userAccountInDatabase = await dbContext.UserAccounts.FirstWithIdAsync(existingUserAccount.Id); userAccountInDatabase.FirstName.Should().Be(newFirstName); userAccountInDatabase.LastName.Should().Be(existingUserAccount.LastName); }); } [Fact] public async Task Can_update_resource_with_unknown_relationship() { // Arrange UserAccount existingUserAccount = _fakers.UserAccount.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.UserAccounts.Add(existingUserAccount); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "userAccounts", id = existingUserAccount.StringId, relationships = new { doesNotExist = new { data = new { type = Unknown.ResourceType, id = Unknown.StringId.Int32 } } } } }; string route = $"/userAccounts/{existingUserAccount.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); } [Fact] public async Task Can_partially_update_resource_with_guid_ID() { // Arrange WorkItemGroup existingGroup = _fakers.WorkItemGroup.Generate(); string newName = _fakers.WorkItemGroup.Generate().Name; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Groups.Add(existingGroup); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItemGroups", id = existingGroup.StringId, attributes = new { name = newName } } }; string route = $"/workItemGroups/{existingGroup.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Type.Should().Be("workItemGroups"); responseDocument.Data.SingleValue.Id.Should().Be(existingGroup.StringId); responseDocument.Data.SingleValue.Attributes["name"].Should().Be($"{newName}{ImplicitlyChangingWorkItemGroupDefinition.Suffix}"); responseDocument.Data.SingleValue.Attributes["isPublic"].Should().Be(existingGroup.IsPublic); responseDocument.Data.SingleValue.Relationships.Should().NotBeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { WorkItemGroup groupInDatabase = await dbContext.Groups.FirstWithIdAsync(existingGroup.Id); groupInDatabase.Name.Should().Be($"{newName}{ImplicitlyChangingWorkItemGroupDefinition.Suffix}"); groupInDatabase.IsPublic.Should().Be(existingGroup.IsPublic); }); PropertyInfo property = typeof(WorkItemGroup).GetProperty(nameof(Identifiable.Id)); property.Should().NotBeNull().And.Subject.PropertyType.Should().Be(typeof(Guid)); } [Fact] public async Task Can_completely_update_resource_with_string_ID() { // Arrange RgbColor existingColor = _fakers.RgbColor.Generate(); string newDisplayName = _fakers.RgbColor.Generate().DisplayName; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.RgbColors.Add(existingColor); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "rgbColors", id = existingColor.StringId, attributes = new { displayName = newDisplayName } } }; string route = $"/rgbColors/{existingColor.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { RgbColor colorInDatabase = await dbContext.RgbColors.FirstWithIdAsync(existingColor.Id); colorInDatabase.DisplayName.Should().Be(newDisplayName); }); PropertyInfo property = typeof(RgbColor).GetProperty(nameof(Identifiable.Id)); property.Should().NotBeNull().And.Subject.PropertyType.Should().Be(typeof(string)); } [Fact] public async Task Can_update_resource_without_side_effects() { // Arrange UserAccount existingUserAccount = _fakers.UserAccount.Generate(); UserAccount newUserAccount = _fakers.UserAccount.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.UserAccounts.Add(existingUserAccount); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "userAccounts", id = existingUserAccount.StringId, attributes = new { firstName = newUserAccount.FirstName, lastName = newUserAccount.LastName } } }; string route = $"/userAccounts/{existingUserAccount.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { UserAccount userAccountInDatabase = await dbContext.UserAccounts.FirstWithIdAsync(existingUserAccount.Id); userAccountInDatabase.FirstName.Should().Be(newUserAccount.FirstName); userAccountInDatabase.LastName.Should().Be(newUserAccount.LastName); }); } [Fact] public async Task Can_update_resource_with_side_effects() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); string newDescription = _fakers.WorkItem.Generate().Description; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", id = existingWorkItem.StringId, attributes = new { description = newDescription, dueAt = (DateTime?)null } } }; string route = $"/workItems/{existingWorkItem.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Type.Should().Be("workItems"); responseDocument.Data.SingleValue.Id.Should().Be(existingWorkItem.StringId); responseDocument.Data.SingleValue.Attributes["description"].Should().Be($"{newDescription}{ImplicitlyChangingWorkItemDefinition.Suffix}"); responseDocument.Data.SingleValue.Attributes["dueAt"].Should().BeNull(); responseDocument.Data.SingleValue.Attributes["priority"].Should().Be(existingWorkItem.Priority); responseDocument.Data.SingleValue.Attributes["isImportant"].Should().Be(existingWorkItem.IsImportant); responseDocument.Data.SingleValue.Relationships.Should().NotBeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { WorkItem workItemInDatabase = await dbContext.WorkItems.FirstWithIdAsync(existingWorkItem.Id); workItemInDatabase.Description.Should().Be($"{newDescription}{ImplicitlyChangingWorkItemDefinition.Suffix}"); workItemInDatabase.DueAt.Should().BeNull(); workItemInDatabase.Priority.Should().Be(existingWorkItem.Priority); }); } [Fact] public async Task Can_update_resource_with_side_effects_with_primary_fieldset() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); string newDescription = _fakers.WorkItem.Generate().Description; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", id = existingWorkItem.StringId, attributes = new { description = newDescription, dueAt = (DateTime?)null } } }; string route = $"/workItems/{existingWorkItem.StringId}?fields[workItems]=description,priority"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Type.Should().Be("workItems"); responseDocument.Data.SingleValue.Id.Should().Be(existingWorkItem.StringId); responseDocument.Data.SingleValue.Attributes.Should().HaveCount(2); responseDocument.Data.SingleValue.Attributes["description"].Should().Be($"{newDescription}{ImplicitlyChangingWorkItemDefinition.Suffix}"); responseDocument.Data.SingleValue.Attributes["priority"].Should().Be(existingWorkItem.Priority); responseDocument.Data.SingleValue.Relationships.Should().BeNull(); await _testContext.RunOnDatabaseAsync(async dbContext => { WorkItem workItemInDatabase = await dbContext.WorkItems.FirstWithIdAsync(existingWorkItem.Id); workItemInDatabase.Description.Should().Be($"{newDescription}{ImplicitlyChangingWorkItemDefinition.Suffix}"); workItemInDatabase.DueAt.Should().BeNull(); workItemInDatabase.Priority.Should().Be(existingWorkItem.Priority); }); } [Fact] public async Task Can_update_resource_with_side_effects_with_include_and_fieldsets() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); existingWorkItem.Tags = _fakers.WorkTag.Generate(1).ToHashSet(); string newDescription = _fakers.WorkItem.Generate().Description; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", id = existingWorkItem.StringId, attributes = new { description = newDescription, dueAt = (DateTime?)null } } }; string route = $"/workItems/{existingWorkItem.StringId}?fields[workItems]=description,priority,tags&include=tags&fields[workTags]=text"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Type.Should().Be("workItems"); responseDocument.Data.SingleValue.Id.Should().Be(existingWorkItem.StringId); responseDocument.Data.SingleValue.Attributes.Should().HaveCount(2); responseDocument.Data.SingleValue.Attributes["description"].Should().Be($"{newDescription}{ImplicitlyChangingWorkItemDefinition.Suffix}"); responseDocument.Data.SingleValue.Attributes["priority"].Should().Be(existingWorkItem.Priority); responseDocument.Data.SingleValue.Relationships.Should().HaveCount(1); responseDocument.Data.SingleValue.Relationships["tags"].Data.ManyValue.Should().HaveCount(1); responseDocument.Data.SingleValue.Relationships["tags"].Data.ManyValue[0].Id.Should().Be(existingWorkItem.Tags.Single().StringId); responseDocument.Included.Should().HaveCount(1); responseDocument.Included[0].Type.Should().Be("workTags"); responseDocument.Included[0].Id.Should().Be(existingWorkItem.Tags.Single().StringId); responseDocument.Included[0].Attributes.Should().HaveCount(1); responseDocument.Included[0].Attributes["text"].Should().Be(existingWorkItem.Tags.Single().Text); responseDocument.Included[0].Relationships.Should().BeNull(); await _testContext.RunOnDatabaseAsync(async dbContext => { WorkItem workItemInDatabase = await dbContext.WorkItems.FirstWithIdAsync(existingWorkItem.Id); workItemInDatabase.Description.Should().Be($"{newDescription}{ImplicitlyChangingWorkItemDefinition.Suffix}"); workItemInDatabase.DueAt.Should().BeNull(); workItemInDatabase.Priority.Should().Be(existingWorkItem.Priority); }); } [Fact] public async Task Update_resource_with_side_effects_hides_relationship_data_in_response() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); existingWorkItem.Assignee = _fakers.UserAccount.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", id = existingWorkItem.StringId } }; string route = $"/workItems/{existingWorkItem.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Relationships.Should().NotBeEmpty(); responseDocument.Data.SingleValue.Relationships.Values.Should().OnlyContain(relationshipObject => relationshipObject.Data.Value == null); responseDocument.Included.Should().BeNull(); } [Fact] public async Task Cannot_update_resource_for_missing_request_body() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); string requestBody = string.Empty; string route = $"/workItems/{existingWorkItem.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.BadRequest); error.Title.Should().Be("Missing request body."); error.Detail.Should().BeNull(); } [Fact] public async Task Cannot_update_resource_for_missing_type() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { id = existingWorkItem.StringId } }; string route = $"/workItems/{existingWorkItem.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: Request body must include 'type' element."); error.Detail.Should().StartWith("Expected 'type' element in 'data' element. - Request body: <<"); } [Fact] public async Task Cannot_update_resource_for_unknown_type() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = Unknown.ResourceType, id = existingWorkItem.StringId } }; string route = $"/workItems/{existingWorkItem.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: Request body includes unknown resource type."); error.Detail.Should().StartWith($"Resource type '{Unknown.ResourceType}' does not exist. - Request body: <<"); } [Fact] public async Task Cannot_update_resource_for_missing_ID() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems" } }; string route = $"/workItems/{existingWorkItem.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: Request body must include 'id' element."); error.Detail.Should().StartWith("Request body: <<"); } [Fact] public async Task Cannot_update_resource_on_unknown_resource_type_in_url() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", id = existingWorkItem.StringId } }; string route = $"/{Unknown.ResourceType}/{existingWorkItem.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Should().BeEmpty(); } [Fact] public async Task Cannot_update_resource_on_unknown_resource_ID_in_url() { // Arrange string workItemId = Unknown.StringId.For<WorkItem, int>(); var requestBody = new { data = new { type = "workItems", id = workItemId } }; string route = $"/workItems/{workItemId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("The requested resource does not exist."); error.Detail.Should().Be($"Resource of type 'workItems' with ID '{workItemId}' does not exist."); } [Fact] public async Task Cannot_update_on_resource_type_mismatch_between_url_and_body() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "rgbColors", id = existingWorkItem.StringId } }; string route = $"/workItems/{existingWorkItem.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Conflict); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.Conflict); error.Title.Should().Be("Resource type mismatch between request body and endpoint URL."); error.Detail.Should().Be("Expected resource of type 'workItems' in PATCH request body at endpoint " + $"'/workItems/{existingWorkItem.StringId}', instead of 'rgbColors'."); } [Fact] public async Task Cannot_update_on_resource_ID_mismatch_between_url_and_body() { // Arrange List<WorkItem> existingWorkItems = _fakers.WorkItem.Generate(2); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.AddRange(existingWorkItems); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", id = existingWorkItems[0].StringId } }; string route = $"/workItems/{existingWorkItems[1].StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Conflict); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.Conflict); error.Title.Should().Be("Resource ID mismatch between request body and endpoint URL."); error.Detail.Should().Be($"Expected resource ID '{existingWorkItems[1].StringId}' in PATCH request body at endpoint " + $"'/workItems/{existingWorkItems[1].StringId}', instead of '{existingWorkItems[0].StringId}'."); } [Fact] public async Task Cannot_update_resource_attribute_with_blocked_capability() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", id = existingWorkItem.StringId, attributes = new { isImportant = true } } }; string route = $"/workItems/{existingWorkItem.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: Changing the value of the requested attribute is not allowed."); error.Detail.Should().StartWith("Changing the value of 'isImportant' is not allowed. - Request body: <<"); } [Fact] public async Task Cannot_update_resource_with_readonly_attribute() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItemGroups", id = existingWorkItem.StringId, attributes = new { isDeprecated = true } } }; string route = $"/workItemGroups/{existingWorkItem.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: Attribute is read-only."); error.Detail.Should().StartWith("Attribute 'isDeprecated' is read-only. - Request body: <<"); } [Fact] public async Task Cannot_update_resource_for_broken_JSON_request_body() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); const string requestBody = "{ \"data {"; string route = $"/workItemGroups/{existingWorkItem.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body."); error.Detail.Should().Match("Expected end of string, but instead reached end of data. * - Request body: <<*"); } [Fact] public async Task Cannot_change_ID_of_existing_resource() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", id = existingWorkItem.StringId, attributes = new { id = Unknown.StringId.For<WorkItem, int>() } } }; string route = $"/workItems/{existingWorkItem.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body."); error.Detail.Should().StartWith("Resource ID is read-only. - Request body: <<"); } [Fact] public async Task Cannot_update_resource_with_incompatible_ID_value() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", id = existingWorkItem.Id, attributes = new { } } }; string route = $"/workItems/{existingWorkItem.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body."); error.Detail.Should().StartWith($"Failed to convert ID '{existingWorkItem.Id}' of type 'Number' to type 'String'. - Request body: <<"); } [Fact] public async Task Cannot_update_resource_with_incompatible_attribute_value() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", id = existingWorkItem.StringId, attributes = new { dueAt = new { Start = 10, End = 20 } } } }; string route = $"/workItems/{existingWorkItem.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body."); error.Detail.Should().Match("Failed to convert attribute 'dueAt' with value '*start*end*' " + "of type 'Object' to type 'Nullable<DateTimeOffset>'. - Request body: <<*"); } [Fact] public async Task Can_update_resource_with_attributes_and_multiple_relationship_types() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); existingWorkItem.Assignee = _fakers.UserAccount.Generate(); existingWorkItem.Subscribers = _fakers.UserAccount.Generate(1).ToHashSet(); existingWorkItem.Tags = _fakers.WorkTag.Generate(1).ToHashSet(); List<UserAccount> existingUserAccounts = _fakers.UserAccount.Generate(2); WorkTag existingTag = _fakers.WorkTag.Generate(); string newDescription = _fakers.WorkItem.Generate().Description; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.AddInRange(existingWorkItem, existingTag); dbContext.UserAccounts.AddRange(existingUserAccounts); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", id = existingWorkItem.StringId, attributes = new { description = newDescription }, relationships = new { assignee = new { data = new { type = "userAccounts", id = existingUserAccounts[0].StringId } }, subscribers = new { data = new[] { new { type = "userAccounts", id = existingUserAccounts[1].StringId } } }, tags = new { data = new[] { new { type = "workTags", id = existingTag.StringId } } } } } }; string route = $"/workItems/{existingWorkItem.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Attributes["description"].Should().Be($"{newDescription}{ImplicitlyChangingWorkItemDefinition.Suffix}"); responseDocument.Data.SingleValue.Relationships.Should().NotBeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { // @formatter:wrap_chained_method_calls chop_always // @formatter:keep_existing_linebreaks true WorkItem workItemInDatabase = await dbContext.WorkItems .Include(workItem => workItem.Assignee) .Include(workItem => workItem.Subscribers) .Include(workItem => workItem.Tags) .FirstWithIdAsync(existingWorkItem.Id); // @formatter:keep_existing_linebreaks restore // @formatter:wrap_chained_method_calls restore workItemInDatabase.Description.Should().Be($"{newDescription}{ImplicitlyChangingWorkItemDefinition.Suffix}"); workItemInDatabase.Assignee.Should().NotBeNull(); workItemInDatabase.Assignee.Id.Should().Be(existingUserAccounts[0].Id); workItemInDatabase.Subscribers.Should().HaveCount(1); workItemInDatabase.Subscribers.Single().Id.Should().Be(existingUserAccounts[1].Id); workItemInDatabase.Tags.Should().HaveCount(1); workItemInDatabase.Tags.Single().Id.Should().Be(existingTag.Id); }); } [Fact] public async Task Can_update_resource_with_multiple_cyclic_relationship_types() { // Arrange WorkItem existingWorkItem = _fakers.WorkItem.Generate(); existingWorkItem.Parent = _fakers.WorkItem.Generate(); existingWorkItem.Children = _fakers.WorkItem.Generate(1); existingWorkItem.RelatedTo = _fakers.WorkItem.Generate(1); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WorkItems.Add(existingWorkItem); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "workItems", id = existingWorkItem.StringId, relationships = new { parent = new { data = new { type = "workItems", id = existingWorkItem.StringId } }, children = new { data = new[] { new { type = "workItems", id = existingWorkItem.StringId } } }, relatedTo = new { data = new[] { new { type = "workItems", id = existingWorkItem.StringId } } } } } }; string route = $"/workItems/{existingWorkItem.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.Should().NotBeNull(); await _testContext.RunOnDatabaseAsync(async dbContext => { // @formatter:wrap_chained_method_calls chop_always // @formatter:keep_existing_linebreaks true WorkItem workItemInDatabase = await dbContext.WorkItems .Include(workItem => workItem.Parent) .Include(workItem => workItem.Children) .Include(workItem => workItem.RelatedFrom) .Include(workItem => workItem.RelatedTo) .FirstWithIdAsync(existingWorkItem.Id); // @formatter:keep_existing_linebreaks restore // @formatter:wrap_chained_method_calls restore workItemInDatabase.Parent.Should().NotBeNull(); workItemInDatabase.Parent.Id.Should().Be(existingWorkItem.Id); workItemInDatabase.Children.Should().HaveCount(1); workItemInDatabase.Children.Single().Id.Should().Be(existingWorkItem.Id); workItemInDatabase.RelatedFrom.Should().HaveCount(1); workItemInDatabase.RelatedFrom.Single().Id.Should().Be(existingWorkItem.Id); workItemInDatabase.RelatedTo.Should().HaveCount(1); workItemInDatabase.RelatedTo.Single().Id.Should().Be(existingWorkItem.Id); }); } } }
using System.Threading; using System.Threading.Tasks; using k8s.Models; using k8s.Util.Common.Generic.Options; using k8s.Autorest; namespace k8s.Util.Common.Generic { /// <summary> /// /// The Generic kubernetes api provides a unified client interface for not only the non-core-group /// built-in resources from kubernetes but also the custom-resources models meet the following /// requirements: /// /// 1. there's a `V1ObjectMeta` field in the model along with its getter/setter. 2. there's a /// `V1ListMeta` field in the list model along with its getter/setter. - supports Json /// serialization/deserialization. 3. the generic kubernetes api covers all the basic operations over /// the custom resources including {get, list, watch, create, update, patch, delete}. /// /// - For kubernetes-defined failures, the server will return a {@link V1Status} with 4xx/5xx /// code. The status object will be nested in {@link KubernetesApiResponse#getStatus()} - For the /// other unknown reason (including network, JVM..), throws an unchecked exception. /// </summary> public class GenericKubernetesApi { private readonly string _apiGroup; private readonly string _apiVersion; private readonly string _resourcePlural; private readonly IKubernetes _client; /// <summary> /// Initializes a new instance of the <see cref="GenericKubernetesApi"/> class. /// </summary> /// <param name="apiGroup"> the api group"></param> /// <param name="apiVersion"> the api version"></param> /// <param name="resourcePlural"> the resource plural, e.g. "jobs""></param> /// <param name="apiClient"> optional client"></param> public GenericKubernetesApi(string apiGroup = default, string apiVersion = default, string resourcePlural = default, IKubernetes apiClient = default) { _apiGroup = apiGroup ?? throw new ArgumentNullException(nameof(apiGroup)); _apiVersion = apiVersion ?? throw new ArgumentNullException(nameof(apiVersion)); _resourcePlural = resourcePlural ?? throw new ArgumentNullException(nameof(resourcePlural)); _client = apiClient ?? new Kubernetes(KubernetesClientConfiguration.BuildDefaultConfig()); } /// <summary> /// Get kubernetes object. /// </summary> /// <typeparam name="T">the object type</typeparam> /// <param name="name">the object name </param> /// <param name="cancellationToken">the token </param> /// <returns>The object</returns> public Task<T> GetAsync<T>(string name, CancellationToken cancellationToken = default) where T : class, IKubernetesObject<V1ObjectMeta> { return GetAsync<T>(name, new GetOptions(), cancellationToken); } /// <summary> /// Get kubernetes object under the namespaceProperty. /// </summary> /// <typeparam name="T">the object type</typeparam> /// <param name="namespaceProperty"> the namespaceProperty</param> /// <param name="name"> the name</param> /// <param name="cancellationToken">the token </param> /// <returns>the kubernetes object</returns> public Task<T> GetAsync<T>(string namespaceProperty, string name, CancellationToken cancellationToken = default) where T : class, IKubernetesObject<V1ObjectMeta> { return GetAsync<T>(namespaceProperty, name, new GetOptions(), cancellationToken); } /// <summary> /// List kubernetes object cluster-scoped. /// </summary> /// <typeparam name="T">the object type</typeparam> /// <param name="cancellationToken">the token </param> /// <returns>the kubernetes object</returns> public Task<T> ListAsync<T>(CancellationToken cancellationToken = default) where T : class, IKubernetesObject<V1ListMeta> { return ListAsync<T>(new ListOptions(), cancellationToken); } /// <summary> /// List kubernetes object under the namespaceProperty. /// </summary> /// <typeparam name="T">the object type</typeparam> /// <param name="namespaceProperty"> the namespace</param> /// <param name="cancellationToken">the token </param> /// <returns>the kubernetes object</returns> public Task<T> ListAsync<T>(string namespaceProperty, CancellationToken cancellationToken = default) where T : class, IKubernetesObject<V1ListMeta> { return ListAsync<T>(namespaceProperty, new ListOptions(), cancellationToken); } /// <summary> /// Create kubernetes object, if the namespaceProperty in the object is present, it will send a /// namespaceProperty-scoped requests, vice versa. /// </summary> /// <typeparam name="T">the object type</typeparam> /// <param name="obj"> the object</param> /// <param name="cancellationToken">the token </param> /// <returns>the kubernetes object</returns> public Task<T> CreateAsync<T>(T obj, CancellationToken cancellationToken = default) where T : class, IKubernetesObject<V1ObjectMeta> { return CreateAsync(obj, new CreateOptions(), cancellationToken); } /// <summary> /// Create kubernetes object, if the namespaceProperty in the object is present, it will send a /// namespaceProperty-scoped requests, vice versa. /// </summary> /// <param name="obj"> the object</param> /// <param name="cancellationToken">the token </param> /// <typeparam name="T">the object type</typeparam> /// <returns>the kubernetes object</returns> public Task<T> UpdateAsync<T>(T obj, CancellationToken cancellationToken = default) where T : class, IKubernetesObject<V1ObjectMeta> { return UpdateAsync(obj, new UpdateOptions(), cancellationToken); } /// <summary> /// Patch kubernetes object. /// </summary> /// <param name="name"> the name</param> /// <param name="patch"> the string patch content</param> /// <param name="cancellationToken">the token </param> /// <typeparam name="T">the object type</typeparam> /// <returns>the kubernetes object</returns> public Task<T> PatchAsync<T>(string name, object patch, CancellationToken cancellationToken = default) where T : class, IKubernetesObject<V1ObjectMeta> { return PatchAsync<T>(name, patch, new PatchOptions(), cancellationToken); } /// <summary> /// Patch kubernetes object under the namespaceProperty. /// </summary> /// <param name="namespaceProperty"> the namespaceProperty</param> /// <param name="name"> the name</param> /// <param name="patch"> the string patch content</param> /// <param name="cancellationToken">the token </param> /// <typeparam name="T">the object type</typeparam> /// <returns>the kubernetes object</returns> public Task<T> PatchAsync<T>(string namespaceProperty, string name, object patch, CancellationToken cancellationToken = default) where T : class, IKubernetesObject<V1ObjectMeta> { return PatchAsync<T>(namespaceProperty, name, patch, new PatchOptions(), cancellationToken); } /// <summary> /// Delete kubernetes object. /// </summary> /// <param name="name"> the name</param> /// <param name="cancellationToken">the token </param> /// <typeparam name="T">the object type</typeparam> /// <returns>the kubernetes object</returns> public Task<T> DeleteAsync<T>(string name, CancellationToken cancellationToken = default) where T : class, IKubernetesObject<V1ObjectMeta> { return DeleteAsync<T>(name, new V1DeleteOptions(), cancellationToken); } /// <summary> /// Delete kubernetes object under the namespaceProperty. /// </summary> /// <param name="namespaceProperty"> the namespaceProperty</param> /// <param name="name"> the name</param> /// <param name="cancellationToken">the token </param> /// <typeparam name="T">the object type</typeparam> /// <returns>the kubernetes object</returns> public Task<T> DeleteAsync<T>(string namespaceProperty, string name, CancellationToken cancellationToken = default) where T : class, IKubernetesObject<V1ObjectMeta> { return DeleteAsync<T>(namespaceProperty, name, new V1DeleteOptions(), cancellationToken); } /// <summary> /// Creates a cluster-scoped Watch on the resource. /// </summary> /// <param name="onEvent">action on event</param> /// <param name="onError">action on error</param> /// <param name="onClosed">action on closed</param> /// <param name="cancellationToken">the token </param> /// <typeparam name="T">the object type</typeparam> /// <returns>the watchable</returns> public Watcher<T> Watch<T>(Action<WatchEventType, T> onEvent, Action<Exception> onError = default, Action onClosed = default, CancellationToken cancellationToken = default) where T : class, IKubernetesObject<V1ObjectMeta> { return Watch(new ListOptions(), onEvent, onError, onClosed, cancellationToken); } /// <summary> /// Creates a namespaceProperty-scoped Watch on the resource. /// </summary> /// <typeparam name="T">the object type</typeparam> /// <param name="namespaceProperty"> the namespaceProperty</param> /// <param name="onEvent">action on event</param> /// <param name="onError">action on error</param> /// <param name="onClosed">action on closed</param> /// <param name="cancellationToken">the token </param> /// <returns>the watchable</returns> public Watcher<T> Watch<T>(string namespaceProperty, Action<WatchEventType, T> onEvent, Action<Exception> onError = default, Action onClosed = default, CancellationToken cancellationToken = default) where T : class, IKubernetesObject<V1ObjectMeta> { return Watch(namespaceProperty, new ListOptions(), onEvent, onError, onClosed, cancellationToken); } // TODO(yue9944882): watch one resource? /// <summary> /// Get kubernetes object. /// </summary> /// <typeparam name="T">the object type</typeparam> /// <param name="name"> the name</param> /// <param name="getOptions">the get options</param> /// <param name="cancellationToken">the token </param> /// <returns>the kubernetes object</returns> public async Task<T> GetAsync<T>(string name, GetOptions getOptions, CancellationToken cancellationToken = default) where T : class, IKubernetesObject<V1ObjectMeta> { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException(nameof(name)); } var resp = await _client.GetClusterCustomObjectWithHttpMessagesAsync(group: _apiGroup, plural: _resourcePlural, version: _apiVersion, name: name, cancellationToken: cancellationToken) .ConfigureAwait(false); return KubernetesJson.Deserialize<T>(resp.Body.ToString()); } /// <summary> /// Get kubernetes object. /// </summary> /// <typeparam name="T">the object type</typeparam> /// <param name="namespaceProperty"> the namespaceProperty</param> /// <param name="name"> the name</param> /// <param name="getOptions">the get options</param> /// <param name="cancellationToken">the token </param> /// <returns>the kubernetes object</returns> public async Task<T> GetAsync<T>(string namespaceProperty, string name, GetOptions getOptions, CancellationToken cancellationToken = default) where T : class, IKubernetesObject<V1ObjectMeta> { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException(nameof(name)); } if (string.IsNullOrEmpty(namespaceProperty)) { throw new ArgumentNullException(nameof(namespaceProperty)); } var resp = await _client.GetNamespacedCustomObjectWithHttpMessagesAsync(group: _apiGroup, plural: _resourcePlural, version: _apiVersion, name: name, namespaceParameter: namespaceProperty, cancellationToken: cancellationToken).ConfigureAwait(false); return KubernetesJson.Deserialize<T>(resp.Body.ToString()); } /// <summary> /// List kubernetes object. /// </summary> /// <typeparam name="T">the object type</typeparam> /// <param name="listOptions">the list options</param> /// <param name="cancellationToken">the token </param> /// <returns>the kubernetes object</returns> public async Task<T> ListAsync<T>(ListOptions listOptions, CancellationToken cancellationToken = default) where T : class, IKubernetesObject<V1ListMeta> { if (listOptions == null) { throw new ArgumentNullException(nameof(listOptions)); } var resp = await _client.ListClusterCustomObjectWithHttpMessagesAsync(group: _apiGroup, plural: _resourcePlural, version: _apiVersion, resourceVersion: listOptions.ResourceVersion, continueParameter: listOptions.Continue, fieldSelector: listOptions.FieldSelector, labelSelector: listOptions.LabelSelector, limit: listOptions.Limit, timeoutSeconds: listOptions.TimeoutSeconds, cancellationToken: cancellationToken).ConfigureAwait(false); return KubernetesJson.Deserialize<T>(resp.Body.ToString()); } /// <summary> /// List kubernetes object. /// </summary> /// <typeparam name="T">the object type</typeparam> /// <param name="namespaceProperty"> the namespaceProperty</param> /// <param name="listOptions">the list options</param> /// <param name="cancellationToken">the token </param> /// <returns>the kubernetes object</returns> public async Task<T> ListAsync<T>(string namespaceProperty, ListOptions listOptions, CancellationToken cancellationToken = default) where T : class, IKubernetesObject<V1ListMeta> { if (listOptions == null) { throw new ArgumentNullException(nameof(listOptions)); } if (string.IsNullOrEmpty(namespaceProperty)) { throw new ArgumentNullException(nameof(namespaceProperty)); } var resp = await _client.ListNamespacedCustomObjectWithHttpMessagesAsync(group: _apiGroup, plural: _resourcePlural, version: _apiVersion, resourceVersion: listOptions.ResourceVersion, continueParameter: listOptions.Continue, fieldSelector: listOptions.FieldSelector, labelSelector: listOptions.LabelSelector, limit: listOptions.Limit, timeoutSeconds: listOptions.TimeoutSeconds, namespaceParameter: namespaceProperty, cancellationToken: cancellationToken).ConfigureAwait(false); return KubernetesJson.Deserialize<T>(resp.Body.ToString()); } /// <summary> /// Create kubernetes object. /// </summary> /// <typeparam name="T">the object type</typeparam> /// <param name="obj">the object</param> /// <param name="createOptions">the create options</param> /// <param name="cancellationToken">the token </param> /// <returns>the kubernetes object</returns> public async Task<T> CreateAsync<T>(T obj, CreateOptions createOptions, CancellationToken cancellationToken = default) where T : class, IKubernetesObject<V1ObjectMeta> { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } if (createOptions == null) { throw new ArgumentNullException(nameof(createOptions)); } V1ObjectMeta objectMeta = obj.Metadata; var isNamespaced = !string.IsNullOrEmpty(objectMeta.NamespaceProperty); if (isNamespaced) { return await CreateAsync(objectMeta.NamespaceProperty, obj, createOptions, cancellationToken).ConfigureAwait(false); } var resp = await _client.CreateClusterCustomObjectWithHttpMessagesAsync(body: obj, group: _apiGroup, plural: _resourcePlural, version: _apiVersion, dryRun: createOptions.DryRun, fieldManager: createOptions.FieldManager, cancellationToken: cancellationToken).ConfigureAwait(false); return KubernetesJson.Deserialize<T>(resp.Body.ToString()); } /// <summary> /// Create namespaced kubernetes object. /// </summary> /// <typeparam name="T">the object type</typeparam> /// <param name="namespaceProperty">the namespace</param> /// <param name="obj">the object</param> /// <param name="createOptions">the create options</param> /// <param name="cancellationToken">the token </param> /// <returns>the kubernetes object</returns> public async Task<T> CreateAsync<T>(string namespaceProperty, T obj, CreateOptions createOptions, CancellationToken cancellationToken = default) where T : class, IKubernetesObject<V1ObjectMeta> { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } if (createOptions == null) { throw new ArgumentNullException(nameof(createOptions)); } var resp = await _client.CreateNamespacedCustomObjectWithHttpMessagesAsync(body: obj, group: _apiGroup, plural: _resourcePlural, version: _apiVersion, namespaceParameter: namespaceProperty, dryRun: createOptions.DryRun, fieldManager: createOptions.FieldManager, cancellationToken: cancellationToken).ConfigureAwait(false); return KubernetesJson.Deserialize<T>(resp.Body.ToString()); } /// <summary> /// Update kubernetes object. /// </summary> /// <typeparam name="T">the object type</typeparam> /// <param name="obj">the object</param> /// <param name="updateOptions">the update options</param> /// <param name="cancellationToken">the token </param> /// <returns>the kubernetes object</returns> public async Task<T> UpdateAsync<T>(T obj, UpdateOptions updateOptions, CancellationToken cancellationToken = default) where T : class, IKubernetesObject<V1ObjectMeta> { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } if (updateOptions == null) { throw new ArgumentNullException(nameof(updateOptions)); } V1ObjectMeta objectMeta = obj.Metadata; var isNamespaced = !string.IsNullOrEmpty(objectMeta.NamespaceProperty); HttpOperationResponse<object> resp; if (isNamespaced) { resp = await _client.ReplaceNamespacedCustomObjectWithHttpMessagesAsync(body: obj, name: objectMeta.Name, group: _apiGroup, plural: _resourcePlural, version: _apiVersion, namespaceParameter: objectMeta.NamespaceProperty, dryRun: updateOptions.DryRun, fieldManager: updateOptions.FieldManager, cancellationToken: cancellationToken) .ConfigureAwait(false); } else { resp = await _client.ReplaceClusterCustomObjectWithHttpMessagesAsync(body: obj, name: objectMeta.Name, group: _apiGroup ?? obj.ApiGroup(), plural: _resourcePlural, version: _apiVersion, dryRun: updateOptions.DryRun, fieldManager: updateOptions.FieldManager, cancellationToken: cancellationToken).ConfigureAwait(false); } return KubernetesJson.Deserialize<T>(resp.Body.ToString()); } /// <summary> /// Create kubernetes object, if the namespaceProperty in the object is present, it will send a /// namespaceProperty-scoped requests, vice versa. /// </summary> /// <typeparam name="T">the object type</typeparam> /// <param name="obj"> the object</param> /// <param name="status"> function to extract the status from the object</param> /// <param name="cancellationToken">the token </param> /// <returns>the kubernetes object</returns> public Task<T> UpdateStatusAsync<T>(T obj, Func<T, object> status, CancellationToken cancellationToken = default) where T : class, IKubernetesObject<V1ObjectMeta> { return UpdateStatusAsync(obj, status, new UpdateOptions(), cancellationToken); } /// <summary> /// Update status of kubernetes object. /// </summary> /// <typeparam name="T">the object type</typeparam> /// <param name="obj"> the object</param> /// <param name="status"> function to extract the status from the object</param> /// <param name="updateOptions">the update options</param> /// <param name="cancellationToken">the token </param> /// <returns>the kubernetes object</returns> public async Task<T> UpdateStatusAsync<T>(T obj, Func<T, object> status, UpdateOptions updateOptions, CancellationToken cancellationToken = default) where T : class, IKubernetesObject<V1ObjectMeta> { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } if (updateOptions == null) { throw new ArgumentNullException(nameof(updateOptions)); } V1ObjectMeta objectMeta = obj.Metadata; HttpOperationResponse<object> resp; var isNamespaced = !string.IsNullOrEmpty(objectMeta.NamespaceProperty); if (isNamespaced) { resp = await _client.PatchNamespacedCustomObjectStatusWithHttpMessagesAsync(body: obj, group: _apiGroup, version: _apiVersion, namespaceParameter: objectMeta.NamespaceProperty, plural: _resourcePlural, name: objectMeta.Name, dryRun: updateOptions.DryRun, fieldManager: updateOptions.FieldManager, force: updateOptions.Force, cancellationToken: cancellationToken).ConfigureAwait(false); } else { resp = await _client.PatchClusterCustomObjectStatusWithHttpMessagesAsync(body: obj, group: _apiGroup, version: _apiVersion, plural: _resourcePlural, name: objectMeta.Name, dryRun: updateOptions.DryRun, fieldManager: updateOptions.FieldManager, force: updateOptions.Force, cancellationToken: cancellationToken).ConfigureAwait(false); } return KubernetesJson.Deserialize<T>(resp.Body.ToString()); } /// <summary> /// Patch kubernetes object. /// </summary> /// <typeparam name="T">the object type</typeparam> /// <param name="name"> the name</param> /// <param name="obj"> the object</param> /// <param name="patchOptions">the patch options</param> /// <param name="cancellationToken">the token </param> /// <returns>the kubernetes object</returns> public async Task<T> PatchAsync<T>(string name, object obj, PatchOptions patchOptions, CancellationToken cancellationToken = default) where T : class, IKubernetesObject<V1ObjectMeta> { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } if (patchOptions == null) { throw new ArgumentNullException(nameof(patchOptions)); } if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException(nameof(name)); } var resp = await _client.PatchClusterCustomObjectWithHttpMessagesAsync(body: obj, group: _apiGroup, version: _apiVersion, plural: _resourcePlural, name: name, dryRun: patchOptions.DryRun, fieldManager: patchOptions.FieldManager, force: patchOptions.Force, cancellationToken: cancellationToken).ConfigureAwait(false); return KubernetesJson.Deserialize<T>(resp.Body.ToString()); } /// <summary> /// Patch kubernetes object. /// </summary> /// <typeparam name="T">the object type</typeparam> /// <param name="namespaceProperty"> the namespaceProperty</param> /// <param name="name"> the name</param> /// <param name="obj"> the object</param> /// <param name="patchOptions">the patch options</param> /// <param name="cancellationToken">the token </param> /// <returns>the kubernetes object</returns> public async Task<T> PatchAsync<T>(string namespaceProperty, string name, object obj, PatchOptions patchOptions, CancellationToken cancellationToken = default) where T : class, IKubernetesObject<V1ObjectMeta> { if (string.IsNullOrEmpty(namespaceProperty)) { throw new ArgumentNullException(nameof(namespaceProperty)); } if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException(nameof(name)); } if (obj == null) { throw new ArgumentNullException(nameof(obj)); } if (patchOptions == null) { throw new ArgumentNullException(nameof(patchOptions)); } var resp = await _client.PatchNamespacedCustomObjectWithHttpMessagesAsync(body: obj, group: _apiGroup, version: _apiVersion, namespaceParameter: namespaceProperty, plural: _resourcePlural, name: name, dryRun: patchOptions.DryRun, fieldManager: patchOptions.FieldManager, force: patchOptions.Force, cancellationToken: cancellationToken).ConfigureAwait(false); return KubernetesJson.Deserialize<T>(resp.Body.ToString()); } /// <summary> /// Delete kubernetes object. /// </summary> /// <typeparam name="T">the object type</typeparam> /// <param name="name"> the name</param> /// <param name="deleteOptions">the delete options</param> /// <param name="cancellationToken">the token </param> /// <returns>the kubernetes object</returns> public async Task<T> DeleteAsync<T>(string name, V1DeleteOptions deleteOptions, CancellationToken cancellationToken = default) where T : class, IKubernetesObject<V1ObjectMeta> { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException(nameof(name)); } var resp = await _client.DeleteClusterCustomObjectWithHttpMessagesAsync( group: _apiGroup, version: _apiVersion, plural: _resourcePlural, name: name, body: deleteOptions, cancellationToken: cancellationToken).ConfigureAwait(false); return KubernetesJson.Deserialize<T>(resp.Body.ToString()); } /// <summary> /// Delete kubernetes object. /// </summary> /// <typeparam name="T">the object type</typeparam> /// <param name="namespaceProperty"> the namespaceProperty</param> /// <param name="name"> the name</param> /// <param name="deleteOptions">the delete options</param> /// <param name="cancellationToken">the token </param> /// <returns>the kubernetes object</returns> public async Task<T> DeleteAsync<T>(string namespaceProperty, string name, V1DeleteOptions deleteOptions, CancellationToken cancellationToken = default) where T : class, IKubernetesObject<V1ObjectMeta> { if (string.IsNullOrEmpty(namespaceProperty)) { throw new ArgumentNullException(nameof(namespaceProperty)); } if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException(nameof(name)); } var resp = await _client.DeleteNamespacedCustomObjectWithHttpMessagesAsync(group: _apiGroup, version: _apiVersion, namespaceParameter: namespaceProperty, plural: _resourcePlural, name: name, body: deleteOptions, cancellationToken: cancellationToken).ConfigureAwait(false); return KubernetesJson.Deserialize<T>(resp.Body.ToString()); } /// <summary> /// Watch watchable. /// </summary> /// <param name="listOptions">the list options</param> /// <param name="onEvent">action on event</param> /// <param name="onError">action on error</param> /// <param name="onClosed">action on closed</param> /// <param name="cancellationToken">the token </param> /// <typeparam name="T">the object type</typeparam> /// <returns>the watchable</returns> public Watcher<T> Watch<T>(ListOptions listOptions, Action<WatchEventType, T> onEvent, Action<Exception> onError = default, Action onClosed = default, CancellationToken cancellationToken = default) where T : class, IKubernetesObject<V1ObjectMeta> { if (listOptions == null) { throw new ArgumentNullException(nameof(listOptions)); } var resp = _client.ListClusterCustomObjectWithHttpMessagesAsync(group: _apiGroup, version: _apiVersion, plural: _resourcePlural, continueParameter: listOptions.Continue, fieldSelector: listOptions.FieldSelector, labelSelector: listOptions.LabelSelector, limit: listOptions.Limit, resourceVersion: listOptions.ResourceVersion, timeoutSeconds: listOptions.TimeoutSeconds, watch: true, cancellationToken: cancellationToken); return resp.Watch(onEvent, onError, onClosed); } /// <summary> /// Watch watchable. /// </summary> /// <param name="namespaceProperty"> the namespaceProperty</param> /// <param name="listOptions">the list options</param> /// <param name="onEvent">action on event</param> /// <param name="onError">action on error</param> /// <param name="onClosed">action on closed</param> /// <param name="cancellationToken">the token </param> /// <typeparam name="T">the object type</typeparam> /// <returns>the watchable</returns> public Watcher<T> Watch<T>(string namespaceProperty, ListOptions listOptions, Action<WatchEventType, T> onEvent, Action<Exception> onError = default, Action onClosed = default, CancellationToken cancellationToken = default) where T : class, IKubernetesObject<V1ObjectMeta> { if (listOptions == null) { throw new ArgumentNullException(nameof(listOptions)); } if (string.IsNullOrEmpty(namespaceProperty)) { throw new ArgumentNullException(nameof(namespaceProperty)); } var resp = _client.ListNamespacedCustomObjectWithHttpMessagesAsync(group: _apiGroup, version: _apiVersion, namespaceParameter: namespaceProperty, plural: _resourcePlural, continueParameter: listOptions.Continue, fieldSelector: listOptions.FieldSelector, labelSelector: listOptions.LabelSelector, limit: listOptions.Limit, resourceVersion: listOptions.ResourceVersion, timeoutSeconds: listOptions.TimeoutSeconds, watch: true, cancellationToken: cancellationToken); return resp.Watch(onEvent, onError, onClosed); } } }
namespace AngleSharp.Js.Tests { using AngleSharp.Dom; using AngleSharp.Html.Dom; using AngleSharp.Io; using AngleSharp.Js.Dom; using AngleSharp.Js.Tests.Mocks; using NUnit.Framework; using System; using System.Threading.Tasks; [TestFixture] public class ScriptEvalTests { public static async Task<String> EvaluateComplexScriptAsync(params String[] sources) { var cfg = Configuration.Default.WithJs().WithEventLoop(); var scripts = "<script>" + String.Join("</script><script>", sources) + "</script>"; var html = "<!doctype html><div id=result></div>" + scripts; var document = await BrowsingContext.New(cfg).OpenAsync(m => m.Content(html)); return document.GetElementById("result").InnerHtml; } public static String SetResult(String eval) { return "document.querySelector('#result').textContent = " + eval + ";"; } [Test] public async Task AccessUndefinedGlobalVariable() { var result = await EvaluateComplexScriptAsync(SetResult("$.toString()")); Assert.AreEqual("", result); } [Test] public async Task AccessGlobalVariablesFromOtherScriptShouldWork() { var result = await EvaluateComplexScriptAsync("var a = 5;", SetResult("a.toString()")); Assert.AreEqual("5", result); } [Test] public async Task AccessLocalVariablesFromOtherScriptShouldNotWork() { var result = await EvaluateComplexScriptAsync("(function () { var a = 5; })();", SetResult("a.toString()")); Assert.AreEqual("", result); } [Test] public async Task ExtendingWindowExplicitlyShouldWork() { var result = await EvaluateComplexScriptAsync("window.foo = 'bla';", SetResult("window.foo")); Assert.AreEqual("bla", result); } [Test] public async Task CreateCustomEventViaGeneralConstructorShouldWork() { var result = await EvaluateComplexScriptAsync("var ev = new Event('foo');", SetResult("ev.type")); Assert.AreEqual("foo", result); } [Test] public async Task CreateCustomEventViaCustomConstructorWithDetailShouldWork() { var result = await EvaluateComplexScriptAsync("var ev = new CustomEvent('bar', { bubbles: false, cancelable: false, details: 'baz' });", SetResult("ev.type + ev.detail")); Assert.AreEqual("barbaz", result); } [Test] public async Task CreateXmlHttpRequestShouldWork() { var result = await EvaluateComplexScriptAsync("var xhr = new XMLHttpRequest(); xhr.open('GET', 'foo');", SetResult("xhr.readyState.toString()")); Assert.AreEqual("1", result); } [Test] public async Task PerformXmlHttpRequestSynchronousToDataUrlShouldWork() { var req = new DataRequester(); var cfg = Configuration.Default.With(req).WithJs().WithEventLoop().WithDefaultLoader(); var script = "var xhr = new XMLHttpRequest(); xhr.open('GET', 'data:plain/text,Hello World!', false);xhr.send();document.querySelector('#result').textContent = xhr.responseText;"; var html = "<!doctype html><div id=result></div><script>" + script + "</script>"; var document = await BrowsingContext.New(cfg).OpenAsync(m => m.Content(html)); var result = document.QuerySelector("#result").TextContent; Assert.AreEqual("Hello World!", result); } [Test] public async Task PerformXmlHttpRequestSynchronousToDelayedResponseShouldWork() { var message = "Hi!"; var req = new DelayedRequester(10, message); var cfg = Configuration.Default.WithJs().WithEventLoop().With(req).WithDefaultLoader(); var script = @" var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://example.com/', false); xhr.send(); document.querySelector('#result').textContent = xhr.responseText;"; var html = "<!doctype html><div id=result></div><script>" + script + "</script>"; var document = await BrowsingContext.New(cfg).OpenAsync(m => m.Content(html)); var result = document.QuerySelector("#result"); Assert.AreEqual(message, result.TextContent); } [Test] public async Task PerformXmlHttpRequestAsynchronousToDelayedResponseShouldWork() { var message = "Hi!"; var req = new DelayedRequester(10, message); var cfg = Configuration.Default.WithJs().WithEventLoop().With(req).WithDefaultLoader(); var script = @" var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://example.com/'); xhr.addEventListener('load', function (ev) { var res = document.querySelector('#result'); res.textContent = xhr.responseText; res.dispatchEvent(new CustomEvent('xhrdone')); }, false); xhr.send();"; var html = "<!doctype html><div id=result></div><script>" + script + "</script>"; var document = await BrowsingContext.New(cfg).OpenAsync(m => m.Content(html)); var result = document.QuerySelector("#result"); Assert.AreEqual("", result.TextContent); Assert.IsTrue(req.IsStarted); await result.AwaitEventAsync("xhrdone").ConfigureAwait(false); Assert.AreEqual(message, result.TextContent); } [Test] public async Task SetContentOfIFrameElement() { var cfg = Configuration.Default .WithDefaultLoader(new LoaderOptions { IsResourceLoadingEnabled = true }) .WithJs() .WithEventLoop(); var html = @"<!doctype html><iframe id=myframe srcdoc=''></iframe><script> var iframe = document.querySelector('#myframe'); var doc = iframe.contentWindow.document; doc.body.textContent = 'Hello world.'; </script>"; var document = await BrowsingContext.New(cfg).OpenAsync(m => m.Content(html)); var result = document.GetElementById("myframe") as IHtmlInlineFrameElement; Assert.AreEqual("Hello world.", result.ContentDocument.Body.TextContent); } [Test] public async Task RunMainScriptFromHtml5Test() { var script = @"var p=[],w=window,d=document,e=f=0;p.push('ua='+encodeURIComponent(navigator.userAgent));e|=w.ActiveXObject?1:0;e|=w.opera?2:0;e|=w.chrome?4:0; e|='getBoxObjectFor' in d || 'mozInnerScreenX' in w?8:0;e|=('WebKitCSSMatrix' in w||'WebKitPoint' in w||'webkitStorageInfo' in w||'webkitURL' in w)?16:0; e|=(e&16&&({}.toString).toString().indexOf(""\n"")===-1)?32:0;p.push('e='+e);f|='sandbox' in d.createElement('iframe')?1:0;f|='WebSocket' in w?2:0; f|=w.Worker?4:0;f|=w.applicationCache?8:0;f|=w.history && history.pushState?16:0;f|=d.documentElement.webkitRequestFullScreen?32:0;f|='FileReader' in w?64:0; p.push('f='+f);p.push('r='+Math.random().toString(36).substring(7));p.push('w='+screen.width);p.push('h='+screen.height);var s=d.createElement('script'); s.src='//api.whichbrowser.net/rel/detect.js?' + p.join('&');d.getElementsByTagName('head')[0].appendChild(s);"; var result = await EvaluateComplexScriptAsync(script, SetResult("p.join('').toString()")); Assert.AreNotEqual("undefined", result); } [Test] public async Task QueryUserAgentShouldMatchAgent() { var userAgent = new Navigator().UserAgent; var result = await EvaluateComplexScriptAsync(SetResult("navigator.userAgent")); Assert.AreEqual(userAgent, result); } [Test] public async Task ScreenPixelDepthShouldYield24() { var result = await EvaluateComplexScriptAsync(SetResult("screen.pixelDepth.toString()")); Assert.AreEqual("24", result); } [Test] public async Task PrototypeObjectOfHtmlDocumentIsCorrect() { var result = await EvaluateComplexScriptAsync(SetResult("Object.getPrototypeOf(document).toString()")); Assert.AreEqual("[object HTMLDocument]", result); } [Test] public async Task PrototypeObjectOfDocumentIsCorrect() { var result = await EvaluateComplexScriptAsync(SetResult("Object.getPrototypeOf(Object.getPrototypeOf(document)).toString()")); Assert.AreEqual("[object Document]", result); } [Test] public async Task PrototypeObjectOfNodeIsCorrect() { var result = await EvaluateComplexScriptAsync(SetResult("Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(document))).toString()")); Assert.AreEqual("[object Node]", result); } [Test] public async Task PrototypeObjectOfEventTargetIsCorrect() { var result = await EvaluateComplexScriptAsync(SetResult("Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(document)))).toString()")); Assert.AreEqual("[object EventTarget]", result); } [Test] public async Task PrototypeObjectOfObjectIsCorrect() { var result = await EvaluateComplexScriptAsync(SetResult("Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(document))))).toString()")); Assert.AreEqual("[object Object]", result); } [Test] public async Task PrototypeObjectOfObjectLiteralIsCorrect() { var result = await EvaluateComplexScriptAsync(SetResult("Object.getPrototypeOf({}).toString()")); Assert.AreEqual("[object Object]", result); } [Test] public async Task PrototypeObjectOfBodyIsCorrect() { var result = await EvaluateComplexScriptAsync(SetResult("Object.getPrototypeOf(document.body).toString()")); Assert.AreEqual("[object HTMLBodyElement]", result); } [Test] public async Task PrototypeObjectOfNavigatorIsCorrect() { var result = await EvaluateComplexScriptAsync(SetResult("Object.getPrototypeOf(navigator).toString()")); Assert.AreEqual("[object Navigator]", result); } [Test] public async Task ConstructorOfHTMLDocumentIsAvailable() { var result = await EvaluateComplexScriptAsync(SetResult("HTMLDocument.toString()")); Assert.AreEqual("function HTMLDocument() { [native code] }", result); } [Test] public async Task StringOfHTMLDocumentIsAvailable() { var result = await EvaluateComplexScriptAsync(SetResult("HTMLDocument.prototype.toString()")); Assert.AreEqual("[object HTMLDocument]", result); } [Test] public async Task QuerySelectorOfHTMLDocumentPrototypeIsAvailable() { var result = await EvaluateComplexScriptAsync(SetResult("HTMLDocument.prototype.querySelector.toString()")); Assert.AreEqual("function querySelector() { [native code] }", result); } [Test] public async Task StringOfMutationObserverIsAvailable() { var result = await EvaluateComplexScriptAsync(SetResult("MutationObserver.prototype.toString()")); Assert.AreEqual("[object MutationObserver]", result); } [Test] public async Task ConstructorOfMutationObserverIsAvailable() { var result = await EvaluateComplexScriptAsync(SetResult("MutationObserver.toString()")); Assert.AreEqual("function MutationObserver() { [native code] }", result); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Diagnostics; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; namespace System.Net.NetworkInformation { public partial class Ping : Component { 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 readonly ManualResetEventSlim _lockObject = new ManualResetEventSlim(initialState: true); // doubles as the ability to wait on the current operation private SendOrPostCallback _onPingCompletedDelegate; private bool _disposeRequested = false; private byte[] _defaultSendBuffer = null; private bool _canceled; // Thread safety: private const int Free = 0; private const int InProgress = 1; private new const int Disposed = 2; private int _status = Free; public Ping() { // This class once inherited a finalizer. For backward compatibility it has one so that // any derived class that depends on it will see the behaviour expected. Since it is // not used by this class itself, suppress it immediately if this is not an instance // of a derived class it doesn't suffer the GC burden of finalization. if (GetType() == typeof(Ping)) { GC.SuppressFinalize(this); } } private static void CheckArgs(int timeout, byte[] buffer, PingOptions options) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (buffer.Length > MaxBufferSize) { throw new ArgumentException(SR.net_invalidPingBufferSize, nameof(buffer)); } if (timeout < 0) { throw new ArgumentOutOfRangeException(nameof(timeout)); } } private void CheckArgs(IPAddress address, int timeout, byte[] buffer, PingOptions options) { CheckArgs(timeout, buffer, options); if (address == null) { throw new ArgumentNullException(nameof(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, nameof(address)); } } private void CheckStart() { if (_disposeRequested) { throw new ObjectDisposedException(GetType().FullName); } int currentStatus; lock (_lockObject) { currentStatus = _status; if (currentStatus == Free) { _canceled = false; _status = InProgress; _lockObject.Reset(); return; } } if (currentStatus == InProgress) { throw new InvalidOperationException(SR.net_inasync); } else { Debug.Assert(currentStatus == Disposed, $"Expected currentStatus == Disposed, got {currentStatus}"); throw new ObjectDisposedException(GetType().FullName); } } private static IPAddress GetAddressSnapshot(IPAddress address) { IPAddress addressSnapshot = address.AddressFamily == AddressFamily.InterNetwork ? #pragma warning disable CS0618 // IPAddress.Address is obsoleted, but it's the most efficient way to get the Int32 IPv4 address new IPAddress(address.Address) : #pragma warning restore CS0618 new IPAddress(address.GetAddressBytes(), address.ScopeId); return addressSnapshot; } private void Finish() { lock (_lockObject) { Debug.Assert(_status == InProgress, $"Invalid status: {_status}"); _status = Free; _lockObject.Set(); } if (_disposeRequested) { InternalDispose(); } } // Cancels pending async requests, closes the handles. private void InternalDispose() { _disposeRequested = true; lock (_lockObject) { if (_status != Free) { // Already disposed, or Finish will call Dispose again once Free. return; } _status = Disposed; } InternalDisposeCore(); } protected override void Dispose(bool disposing) { if (disposing) { // Only on explicit dispose. Otherwise, the GC can cleanup everything else. InternalDispose(); } } public event PingCompletedEventHandler PingCompleted; protected void OnPingCompleted(PingCompletedEventArgs e) { PingCompleted?.Invoke(this, e); } public PingReply Send(string hostNameOrAddress) { return Send(hostNameOrAddress, DefaultTimeout, DefaultSendBuffer); } public PingReply Send(string hostNameOrAddress, int timeout) { return Send(hostNameOrAddress, timeout, DefaultSendBuffer); } public PingReply Send(IPAddress address) { return Send(address, DefaultTimeout, DefaultSendBuffer); } public PingReply Send(IPAddress address, int timeout) { return Send(address, timeout, DefaultSendBuffer); } public PingReply Send(string hostNameOrAddress, int timeout, byte[] buffer) { return Send(hostNameOrAddress, timeout, buffer, null); } public PingReply Send(IPAddress address, int timeout, byte[] buffer) { return Send(address, timeout, buffer, null); } public PingReply Send(string hostNameOrAddress, int timeout, byte[] buffer, PingOptions options) { if (string.IsNullOrEmpty(hostNameOrAddress)) { throw new ArgumentNullException(nameof(hostNameOrAddress)); } if (IPAddress.TryParse(hostNameOrAddress, out IPAddress address)) { return Send(address, timeout, buffer, options); } CheckArgs(timeout, buffer, options); CheckStart(); return GetAddressAndSend(hostNameOrAddress, timeout, buffer, options); } public PingReply Send(IPAddress address, int timeout, byte[] buffer, PingOptions options) { CheckArgs(address, timeout, buffer, options); // 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 = GetAddressSnapshot(address); CheckStart(); try { return SendPingCore(addressSnapshot, buffer, timeout, options); } catch (Exception e) { Finish(); throw new PingException(SR.net_ping, e); } } public 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); } public void SendAsync(IPAddress address, object userToken) { SendAsync(address, DefaultTimeout, DefaultSendBuffer, userToken); } public void SendAsync(IPAddress address, int timeout, object userToken) { SendAsync(address, timeout, DefaultSendBuffer, userToken); } public void SendAsync(string hostNameOrAddress, int timeout, byte[] buffer, object userToken) { SendAsync(hostNameOrAddress, timeout, buffer, null, userToken); } public void SendAsync(IPAddress address, int timeout, byte[] buffer, object userToken) { SendAsync(address, timeout, buffer, null, userToken); } public void SendAsync(string hostNameOrAddress, int timeout, byte[] buffer, PingOptions options, object userToken) { TranslateTaskToEap(userToken, SendPingAsync(hostNameOrAddress, timeout, buffer, options)); } public void SendAsync(IPAddress address, int timeout, byte[] buffer, PingOptions options, object userToken) { TranslateTaskToEap(userToken, SendPingAsync(address, timeout, buffer, options)); } private void TranslateTaskToEap(object userToken, Task<PingReply> pingTask) { pingTask.ContinueWith((t, state) => { var asyncOp = (AsyncOperation)state; var e = new PingCompletedEventArgs(t.IsCompletedSuccessfully ? t.Result : null, t.Exception, t.IsCanceled, asyncOp.UserSuppliedState); SendOrPostCallback callback = _onPingCompletedDelegate ?? (_onPingCompletedDelegate = new SendOrPostCallback(o => { OnPingCompleted((PingCompletedEventArgs)o); })); asyncOp.PostOperationCompleted(callback, e); }, AsyncOperationManager.CreateOperation(userToken), CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default); } public Task<PingReply> SendPingAsync(IPAddress address) { return SendPingAsync(address, DefaultTimeout, DefaultSendBuffer, null); } public Task<PingReply> SendPingAsync(string hostNameOrAddress) { return SendPingAsync(hostNameOrAddress, DefaultTimeout, DefaultSendBuffer, null); } public Task<PingReply> SendPingAsync(IPAddress address, int timeout) { return SendPingAsync(address, timeout, DefaultSendBuffer, null); } public Task<PingReply> SendPingAsync(string hostNameOrAddress, int timeout) { return SendPingAsync(hostNameOrAddress, timeout, DefaultSendBuffer, null); } public Task<PingReply> SendPingAsync(IPAddress address, int timeout, byte[] buffer) { return SendPingAsync(address, timeout, buffer, null); } public Task<PingReply> SendPingAsync(string hostNameOrAddress, int timeout, byte[] buffer) { return SendPingAsync(hostNameOrAddress, timeout, buffer, null); } public Task<PingReply> SendPingAsync(IPAddress address, int timeout, byte[] buffer, PingOptions options) { CheckArgs(address, timeout, buffer, options); // 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 = GetAddressSnapshot(address); CheckStart(); try { return SendPingAsyncCore(addressSnapshot, buffer, timeout, options); } catch (Exception e) { Finish(); return Task.FromException<PingReply>(new PingException(SR.net_ping, e)); } } public Task<PingReply> SendPingAsync(string hostNameOrAddress, int timeout, byte[] buffer, PingOptions options) { if (string.IsNullOrEmpty(hostNameOrAddress)) { throw new ArgumentNullException(nameof(hostNameOrAddress)); } if (IPAddress.TryParse(hostNameOrAddress, out IPAddress address)) { return SendPingAsync(address, timeout, buffer, options); } CheckArgs(timeout, buffer, options); CheckStart(); return GetAddressAndSendAsync(hostNameOrAddress, timeout, buffer, options); } public void SendAsyncCancel() { lock (_lockObject) { if (!_lockObject.IsSet) { // As in the .NET Framework, this doesn't actually cancel an in-progress operation. It just marks it such that // when the operation completes, it's flagged as canceled. _canceled = true; } } // As in the .NET Framework, synchronously wait for the in-flight operation to complete. // If there isn't one in flight, this event will already be set. _lockObject.Wait(); } private PingReply GetAddressAndSend(string hostNameOrAddress, int timeout, byte[] buffer, PingOptions options) { try { IPAddress[] addresses = Dns.GetHostAddresses(hostNameOrAddress); return SendPingCore(addresses[0], buffer, timeout, options); } catch (Exception e) { Finish(); throw new PingException(SR.net_ping, e); } } private async Task<PingReply> GetAddressAndSendAsync(string hostNameOrAddress, int timeout, byte[] buffer, PingOptions options) { bool requiresFinish = true; try { IPAddress[] addresses = await Dns.GetHostAddressesAsync(hostNameOrAddress).ConfigureAwait(false); Task<PingReply> pingReplyTask = SendPingAsyncCore(addresses[0], buffer, timeout, options); requiresFinish = false; return await pingReplyTask.ConfigureAwait(false); } catch (Exception e) { // SendPingAsyncCore will call Finish before completing the Task. If SendPingAsyncCore isn't invoked // because an exception is thrown first, or if it throws out an exception synchronously, then // we need to invoke Finish; otherwise, it has the responsibility to invoke Finish. if (requiresFinish) { Finish(); } throw new PingException(SR.net_ping, e); } } // 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(); partial void InternalDisposeCore(); // 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; } } } }
/*****************************************************************************/ /* Project : SerialPortTerminal */ /* File : InstrumentControl.cs */ /* Version : 1 */ /* Language : C# */ /* Summary : Generic class for the instrument control design */ /* Creation : 15/06/2008 */ /* Autor : Guillaume CHOUTEAU */ /* History : */ /*****************************************************************************/ using System; using System.ComponentModel; using System.Windows.Forms; using System.Collections; using System.Drawing; using System.Text; using System.Data; namespace SerialPortTerminal { class InstrumentControl : System.Windows.Forms.Control { #region Generic methodes /// <summary> /// Rotate an image on a point with a specified angle /// </summary> /// <param name="pe">The paint area event where the image will be displayed</param> /// <param name="img">The image to display</param> /// <param name="alpha">The angle of rotation in radian</param> /// <param name="ptImg">The location of the left upper corner of the image to display in the paint area in nominal situation</param> /// <param name="ptRot">The location of the rotation point in the paint area</param> /// <param name="scaleFactor">Multiplication factor on the display image</param> protected void RotateImage(PaintEventArgs pe, Image img, Double alpha, Point ptImg, Point ptRot, float scaleFactor) { double beta = 0; // Angle between the Horizontal line and the line (Left upper corner - Rotation point) double d = 0; // Distance between Left upper corner and Rotation point) float deltaX = 0; // X componant of the corrected translation float deltaY = 0; // Y componant of the corrected translation // Compute the correction translation coeff if (ptImg != ptRot) { // if (ptRot.X != 0) { beta = Math.Atan((double)ptRot.Y / (double)ptRot.X); } d = Math.Sqrt((ptRot.X * ptRot.X) + (ptRot.Y * ptRot.Y)); // Computed offset deltaX = (float)(d * (Math.Cos(alpha - beta) - Math.Cos(alpha) * Math.Cos(alpha + beta) - Math.Sin(alpha) * Math.Sin(alpha + beta))); deltaY = (float)(d * (Math.Sin(beta - alpha) + Math.Sin(alpha) * Math.Cos(alpha + beta) - Math.Cos(alpha) * Math.Sin(alpha + beta))); } // Rotate image support pe.Graphics.RotateTransform((float)(alpha * 180 / Math.PI)); // Dispay image pe.Graphics.DrawImage(img, (ptImg.X + deltaX) * scaleFactor, (ptImg.Y + deltaY) * scaleFactor, img.Width * scaleFactor, img.Height * scaleFactor); // Put image support as found pe.Graphics.RotateTransform((float)(-alpha * 180 / Math.PI)); } /// <summary> /// Translate an image on line with a specified distance and a spcified angle /// </summary> /// <param name="pe">The paint area event where the image will be displayed</param> /// <param name="img">The image to display</param> ///<param name="deltaPx">The translation distance in pixel</param> /// <param name="alpha">The angle of translation direction in radian</param> /// <param name="ptImg">The location of the left upper corner of the image to display in the paint area in nominal situation</param> /// <param name="scaleFactor">Multiplication factor on the display image</param> protected void TranslateImage(PaintEventArgs pe, Image img, int deltaPx, float alpha, Point ptImg, float scaleFactor) { // Computed offset float deltaX = (float)(deltaPx * (Math.Sin(alpha))); float deltaY = (float)(- deltaPx * (Math.Cos(alpha))); // Dispay image pe.Graphics.DrawImage(img, (ptImg.X + deltaX) * scaleFactor, (ptImg.Y + deltaY) * scaleFactor, img.Width * scaleFactor, img.Height * scaleFactor); } /// <summary> /// Rotate an image an apply a translation on the rotated image and the display it /// </summary> /// <param name="pe">The paint area event where the image will be displayed</param> /// <param name="img">The image to display</param> /// <param name="alphaRot">The angle of rotation in radian</param> /// <param name="alphaTrs">The angle of translation direction in radian, expressed in the rotated image coordonate system</param> /// <param name="ptImg">The location of the left upper corner of the image to display in the paint area in nominal situation</param> /// <param name="ptRot">The location of the rotation point in the paint area</param> /// <param name="deltaPx">The translation distance in pixel</param> /// <param name="ptRot">The location of the rotation point in the paint area</param> /// <param name="scaleFactor">Multiplication factor on the display image</param> protected void RotateAndTranslate(PaintEventArgs pe, Image img, Double alphaRot, Double alphaTrs, Point ptImg, int deltaPx, Point ptRot, float scaleFactor) { double beta = 0; double d = 0; float deltaXRot = 0; float deltaYRot = 0; float deltaXTrs = 0; float deltaYTrs = 0; // Rotation if (ptImg != ptRot) { // Internals coeffs if (ptRot.X != 0) { beta = Math.Atan((double)ptRot.Y / (double)ptRot.X); } d = Math.Sqrt((ptRot.X * ptRot.X) + (ptRot.Y * ptRot.Y)); // Computed offset deltaXRot = (float)(d * (Math.Cos(alphaRot - beta) - Math.Cos(alphaRot) * Math.Cos(alphaRot + beta) - Math.Sin(alphaRot) * Math.Sin(alphaRot + beta))); deltaYRot = (float)(d * (Math.Sin(beta - alphaRot) + Math.Sin(alphaRot) * Math.Cos(alphaRot + beta) - Math.Cos(alphaRot) * Math.Sin(alphaRot + beta))); } // Translation // Computed offset deltaXTrs = (float)(deltaPx * (Math.Sin(alphaTrs))); deltaYTrs = (float)(- deltaPx * (-Math.Cos(alphaTrs))); // Rotate image support pe.Graphics.RotateTransform((float)(alphaRot * 180 / Math.PI)); // Dispay image pe.Graphics.DrawImage(img, (ptImg.X + deltaXRot + deltaXTrs) * scaleFactor, (ptImg.Y + deltaYRot + deltaYTrs) * scaleFactor, img.Width * scaleFactor, img.Height * scaleFactor); // Put image support as found pe.Graphics.RotateTransform((float)(-alphaRot * 180 / Math.PI)); } /// <summary> /// Display a Scroll counter image like on gas pumps /// </summary> /// <param name="pe">The paint area event where the image will be displayed</param> /// <param name="imgBand">The band counter image to display with digts : 0|1|2|3|4|5|6|7|8|9|0</param> /// <param name="nbOfDigits">The number of digits displayed by the counter</param> /// <param name="counterValue">The value to dispay on the counter</param> /// <param name="ptImg">The location of the left upper corner of the image to display in the paint area in nominal situation</param> /// <param name="scaleFactor">Multiplication factor on the display image</param> protected void ScrollCounter(PaintEventArgs pe, Image imgBand, int nbOfDigits, int counterValue, Point ptImg, float scaleFactor) { int indexDigit =0; int digitBoxHeight = (int)(imgBand.Height/11); int digitBoxWidth = imgBand.Width; for(indexDigit = 0; indexDigit<nbOfDigits; indexDigit++) { int currentDigit; int prevDigit; int xOffset; int yOffset; double fader; currentDigit = (int)((counterValue / Math.Pow(10, indexDigit)) % 10); if (indexDigit == 0) { prevDigit = 0; } else { prevDigit = (int)((counterValue / Math.Pow(10, indexDigit-1)) % 10); } // xOffset Computing xOffset = (int)(digitBoxWidth * (nbOfDigits - indexDigit - 1)); // yOffset Computing if(prevDigit == 9) { fader = 0.33; yOffset = (int)(-((fader + currentDigit) * digitBoxHeight)); } else { yOffset = (int)(-(currentDigit * digitBoxHeight)); } // Display Image pe.Graphics.DrawImage(imgBand,(ptImg.X + xOffset)*scaleFactor,(ptImg.Y + yOffset)*scaleFactor,imgBand.Width*scaleFactor,imgBand.Height*scaleFactor); } } protected void DisplayRoundMark(PaintEventArgs pe, Image imgMark, InstrumentControlMarksDefinition insControlMarksDefinition, Point ptImg, int radiusPx, Boolean displayText, float scaleFactor) { Double alphaRot; int textBoxLength; int textPointRadiusPx; int textBoxHeight = (int)(insControlMarksDefinition.fontSize*1.1/scaleFactor); Point textPoint = new Point(); Point rotatePoint = new Point(); Font markFont = new Font("Arial", insControlMarksDefinition.fontSize); SolidBrush markBrush = new SolidBrush(insControlMarksDefinition.fontColor); InstrumentControlMarkPoint[] markArray = new InstrumentControlMarkPoint[2 + insControlMarksDefinition.numberOfDivisions]; // Buid the markArray markArray[0].value = insControlMarksDefinition.minPhy; markArray[0].angle = insControlMarksDefinition.minAngle; markArray[markArray.Length - 1].value = insControlMarksDefinition.maxPhy; markArray[markArray.Length - 1].angle = insControlMarksDefinition.maxAngle; for (int index = 1; index < insControlMarksDefinition.numberOfDivisions+1; index++) { markArray[index].value = (insControlMarksDefinition.maxPhy - insControlMarksDefinition.minPhy) / (insControlMarksDefinition.numberOfDivisions + 1) * index + insControlMarksDefinition.minPhy; markArray[index].angle = (insControlMarksDefinition.maxAngle - insControlMarksDefinition.minAngle) / (insControlMarksDefinition.numberOfDivisions + 1) * index + insControlMarksDefinition.minAngle; } // Define the rotate point (center of the indicator) rotatePoint.X = (int)((this.Width/2)/scaleFactor); rotatePoint.Y = rotatePoint.X; // Display mark array foreach (InstrumentControlMarkPoint markPoint in markArray) { // pre computings alphaRot = (Math.PI / 2) - markPoint.angle; textBoxLength = (int)(Convert.ToString(markPoint.value).Length * insControlMarksDefinition.fontSize*0.8/scaleFactor); textPointRadiusPx = (int)(radiusPx - 1.2*imgMark.Height - 0.5 * textBoxLength); textPoint.X = (int)((textPointRadiusPx * Math.Cos(markPoint.angle) - 0.5 * textBoxLength + rotatePoint.X) * scaleFactor); textPoint.Y = (int)((-textPointRadiusPx * Math.Sin(markPoint.angle) - 0.5 * textBoxHeight + rotatePoint.Y) * scaleFactor); // Display mark RotateImage(pe, imgMark, alphaRot, ptImg, rotatePoint, scaleFactor); // Display text if (displayText == true) { pe.Graphics.DrawString(Convert.ToString(markPoint.value), markFont, markBrush, textPoint); } } } /// <summary> /// Convert a physical value in an rad angle used by the rotate function /// </summary> /// <param name="phyVal">Physical value to interpol/param> /// <param name="minPhy">Minimum physical value</param> /// <param name="maxPhy">Maximum physical value</param> /// <param name="minAngle">The angle related to the minumum value, in deg</param> /// <param name="maxAngle">The angle related to the maximum value, in deg</param> /// <returns>The angle in radian witch correspond to the physical value</returns> protected float InterpolPhyToAngle(float phyVal, float minPhy, float maxPhy, float minAngle, float maxAngle) { float a; float b; float y; float x; if (phyVal < minPhy) { return (float)(minAngle * Math.PI / 180); } else if (phyVal > maxPhy) { return (float)(maxAngle * Math.PI / 180); } else { x = phyVal; a = (maxAngle - minAngle) / (maxPhy - minPhy); b = (float)(0.5 * (maxAngle + minAngle - a * (maxPhy + minPhy))); y = a * x + b; return (float)(y * Math.PI / 180); } } protected Point FromCartRefToImgRef(Point cartPoint) { Point imgPoint = new Point(); imgPoint.X = cartPoint.X + (this.Width/2); imgPoint.Y = -cartPoint.Y + (this.Height/2); return (imgPoint); } protected double FromDegToRad(double degAngle) { double radAngle = degAngle * Math.PI / 180; return radAngle; } #endregion } struct InstrumentControlMarksDefinition { public InstrumentControlMarksDefinition(float myMinPhy, float myMinAngle, float myMaxPhy, float myMaxAngle, int myNumberOfDivisions, int myFontSize, Color myFontColor, InstumentMarkScaleStyle myScaleStyle) { this.minPhy = myMinPhy; this.minAngle = myMinAngle; this.maxPhy = myMaxPhy; this.maxAngle = myMaxAngle; this.numberOfDivisions = myNumberOfDivisions; this.fontSize = myFontSize; this.fontColor = myFontColor; this.scaleStyle = myScaleStyle; } internal float minPhy; internal float minAngle; internal float maxPhy; internal float maxAngle; internal int numberOfDivisions; internal int fontSize; internal Color fontColor; internal InstumentMarkScaleStyle scaleStyle; } struct InstrumentControlMarkPoint { public InstrumentControlMarkPoint(float myValue, float myAngle) { this.value = myValue; this.angle = myAngle; } internal float value; internal float angle; } enum InstumentMarkScaleStyle { Linear = 0, Log = 1, }; }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using OpenSim.Framework; using OpenSim.Framework.Client; using OpenSim.Region.Framework.Scenes; using OpenMetaverse; using Nini.Config; using log4net; namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory { public class InventoryCache { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); protected BaseInventoryConnector m_Connector; protected List<Scene> m_Scenes; // The cache proper protected Dictionary<UUID, Dictionary<AssetType, InventoryFolderBase>> m_InventoryCache; // A cache of userIDs --> ServiceURLs, for HGBroker only protected Dictionary<UUID, string> m_InventoryURLs = new Dictionary<UUID, string>(); public virtual void Init(IConfigSource source, BaseInventoryConnector connector) { m_Scenes = new List<Scene>(); m_InventoryCache = new Dictionary<UUID, Dictionary<AssetType, InventoryFolderBase>>(); m_Connector = connector; } public virtual void AddRegion(Scene scene) { m_Scenes.Add(scene); scene.EventManager.OnMakeRootAgent += OnMakeRootAgent; scene.EventManager.OnClientClosed += OnClientClosed; } public virtual void RemoveRegion(Scene scene) { if ((m_Scenes != null) && m_Scenes.Contains(scene)) { m_Scenes.Remove(scene); } } void OnMakeRootAgent(ScenePresence presence) { // Get system folders // First check if they're here already lock (m_InventoryCache) { if (m_InventoryCache.ContainsKey(presence.UUID)) { m_log.DebugFormat("[INVENTORY CACHE]: OnMakeRootAgent, system folders for {0} {1} already in cache", presence.Firstname, presence.Lastname); return; } } // If not, go get them and place them in the cache Dictionary<AssetType, InventoryFolderBase> folders = CacheSystemFolders(presence.UUID); CacheInventoryServiceURL(presence.Scene, presence.UUID); m_log.DebugFormat("[INVENTORY CACHE]: OnMakeRootAgent in {0}, fetched system folders for {1} {2}: count {3}", presence.Scene.RegionInfo.RegionName, presence.Firstname, presence.Lastname, folders.Count); } void OnClientClosed(UUID clientID, Scene scene) { if (m_InventoryCache.ContainsKey(clientID)) // if it's still in cache { ScenePresence sp = null; foreach (Scene s in m_Scenes) { s.TryGetScenePresence(clientID, out sp); if ((sp != null) && !sp.IsChildAgent && (s != scene)) { m_log.DebugFormat("[INVENTORY CACHE]: OnClientClosed in {0}, but user {1} still in sim. Keeping system folders in cache", scene.RegionInfo.RegionName, clientID); return; } } m_log.DebugFormat( "[INVENTORY CACHE]: OnClientClosed in {0}, user {1} out of sim. Dropping system folders", scene.RegionInfo.RegionName, clientID); DropCachedSystemFolders(clientID); DropInventoryServiceURL(clientID); } } /// <summary> /// Cache a user's 'system' folders. /// </summary> /// <param name="userID"></param> /// <returns>Folders cached</returns> protected Dictionary<AssetType, InventoryFolderBase> CacheSystemFolders(UUID userID) { // If not, go get them and place them in the cache Dictionary<AssetType, InventoryFolderBase> folders = m_Connector.GetSystemFolders(userID); if (folders.Count > 0) lock (m_InventoryCache) m_InventoryCache.Add(userID, folders); return folders; } /// <summary> /// Drop a user's cached 'system' folders /// </summary> /// <param name="userID"></param> protected void DropCachedSystemFolders(UUID userID) { // Drop system folders lock (m_InventoryCache) if (m_InventoryCache.ContainsKey(userID)) m_InventoryCache.Remove(userID); } /// <summary> /// Get the system folder for a particular asset type /// </summary> /// <param name="userID"></param> /// <param name="type"></param> /// <returns></returns> public InventoryFolderBase GetFolderForType(UUID userID, AssetType type) { m_log.DebugFormat("[INVENTORY CACHE]: Getting folder for asset type {0} for user {1}", type, userID); Dictionary<AssetType, InventoryFolderBase> folders = null; lock (m_InventoryCache) { m_InventoryCache.TryGetValue(userID, out folders); // In some situations (such as non-secured standalones), system folders can be requested without // the user being logged in. So we need to try caching them here if we don't already have them. if (null == folders) CacheSystemFolders(userID); m_InventoryCache.TryGetValue(userID, out folders); } if ((folders != null) && folders.ContainsKey(type)) { m_log.DebugFormat( "[INVENTORY CACHE]: Returning folder {0} as type {1} for {2}", folders[type], type, userID); return folders[type]; } m_log.WarnFormat("[INVENTORY CACHE]: Could not find folder for system type {0} for {1}", type, userID); return null; } /// <summary> /// Gets the user's inventory URL from its serviceURLs, if the user is foreign, /// and sticks it in the cache /// </summary> /// <param name="userID"></param> private void CacheInventoryServiceURL(Scene scene, UUID userID) { if (scene.UserAccountService.GetUserAccount(scene.RegionInfo.ScopeID, userID) == null) { // The user does not have a local account; let's cache its service URL string inventoryURL = string.Empty; ScenePresence sp = null; scene.TryGetScenePresence(userID, out sp); if (sp != null) { AgentCircuitData aCircuit = scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode); if (aCircuit.ServiceURLs.ContainsKey("InventoryServerURI")) { inventoryURL = aCircuit.ServiceURLs["InventoryServerURI"].ToString(); if (inventoryURL != null && inventoryURL != string.Empty) { inventoryURL = inventoryURL.Trim(new char[] { '/' }); m_InventoryURLs.Add(userID, inventoryURL); } } } } } private void DropInventoryServiceURL(UUID userID) { lock (m_InventoryURLs) if (m_InventoryURLs.ContainsKey(userID)) m_InventoryURLs.Remove(userID); } public string GetInventoryServiceURL(UUID userID) { if (m_InventoryURLs.ContainsKey(userID)) return m_InventoryURLs[userID]; return null; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using AzureStorage.Queue; using Common.Log; using CompetitionPlatform.Data.AzureRepositories.Expert; using CompetitionPlatform.Data.AzureRepositories.Project; using CompetitionPlatform.Data.AzureRepositories.ProjectStream; using CompetitionPlatform.Data.AzureRepositories.Result; using CompetitionPlatform.Data.AzureRepositories.Settings; using CompetitionPlatform.Data.AzureRepositories.Users; using CompetitionPlatform.Data.AzureRepositories.Vote; using CompetitionPlatform.Data.ProjectCategory; using CompetitionPlatform.Helpers; using CompetitionPlatform.Models; using CompetitionPlatform.Models.ProjectViewModels; using CompetitionPlatform.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Ganss.XSS; using Lykke.Service.PersonalData.Contract; using Lykke.Service.Kyc.Abstractions.Services; using Lykke.Service.Kyc.Abstractions.Domain.Profile; using Lykke.Service.Kyc.Abstractions.Domain.Verification; using CompetitionPlatform.Data.AzureRepositories.Admin; using Lykke.Common.Log; namespace CompetitionPlatform.Controllers { public class ProjectController : Controller { private readonly IProjectRepository _projectRepository; private readonly IProjectCommentsRepository _commentsRepository; private readonly IProjectFileRepository _fileRepository; private readonly IProjectFileInfoRepository _fileInfoRepository; private readonly IProjectParticipantsRepository _participantsRepository; private readonly IProjectCategoriesRepository _categoriesRepository; private readonly IProjectResultRepository _resultRepository; private readonly IProjectFollowRepository _projectFollowRepository; private readonly IProjectWinnersRepository _winnersRepository; private readonly IUserRolesRepository _userRolesRepository; private readonly IProjectWinnersService _winnersService; private readonly IQueueExt _emailsQueue; private readonly IProjectResultVoteRepository _resultVoteRepository; private readonly BaseSettings _settings; private readonly ILog _log; private readonly IProjectExpertsRepository _projectExpertsRepository; private readonly IStreamRepository _streamRepository; private readonly IPersonalDataService _personalDataService; private readonly Lykke.Messages.Email.IEmailSender _emailSender; private readonly IStreamsIdRepository _streamsIdRepository; private readonly IExpertsService _expertsService; private readonly IKycProfileServiceV2 _kycService; private readonly ITermsPageRepository _termsPageRepository; public ProjectController(IProjectRepository projectRepository, IProjectCommentsRepository commentsRepository, IProjectFileRepository fileRepository, IProjectFileInfoRepository fileInfoRepository, IProjectParticipantsRepository participantsRepository, IProjectCategoriesRepository categoriesRepository, IProjectResultRepository resultRepository, IProjectFollowRepository projectFollowRepository, IProjectWinnersRepository winnersRepository, IUserRolesRepository userRolesRepository, IProjectWinnersService winnersService, IQueueExt emailsQueue, IProjectResultVoteRepository resultVoteRepository, BaseSettings settings, IProjectExpertsRepository projectExpertsRepository, IStreamRepository streamRepository, IPersonalDataService personalDataService, Lykke.Messages.Email.IEmailSender emailSender, IStreamsIdRepository streamsIdRepository, IExpertsService expertsService, IKycProfileServiceV2 kycService, ITermsPageRepository termsPageRepository, ILogFactory logFactory) { _projectRepository = projectRepository; _commentsRepository = commentsRepository; _fileRepository = fileRepository; _fileInfoRepository = fileInfoRepository; _participantsRepository = participantsRepository; _categoriesRepository = categoriesRepository; _resultRepository = resultRepository; _projectFollowRepository = projectFollowRepository; _winnersRepository = winnersRepository; _userRolesRepository = userRolesRepository; _winnersService = winnersService; _emailsQueue = emailsQueue; _resultVoteRepository = resultVoteRepository; _settings = settings; _projectExpertsRepository = projectExpertsRepository; _streamRepository = streamRepository; _personalDataService = personalDataService; _emailSender = emailSender; _streamsIdRepository = streamsIdRepository; _expertsService = expertsService; _kycService = kycService; _termsPageRepository = termsPageRepository; if (logFactory == null) throw new ArgumentNullException(nameof(logFactory)); _log = logFactory.CreateLog(this); } // Create a new project [Authorize] public async Task<IActionResult> Create() { // Fetch user and role // TODO: These should be methods on the CompetitionPlatformUser model class // which should probably be broken out from IdentityModels var user = UserModel.GetAuthenticatedUser(User.Identity); var userRole = await _userRolesRepository.GetAsync(user.Email.ToLower()); ViewBag.ProjectCategories = _categoriesRepository.GetCategories(); // TODO: Move these checks into a bool CanCreateProject() or IsVerified() on the CompetitionPlatformUser // avoiding these if trees makes it much easier to test and modify in the future // plus it's used everywhere so we can DRY the code up if (userRole != null) { return View("CreateProject"); } if (!string.IsNullOrEmpty(user.Email)) { if (await IsOkKycStatusAsync(user)) { return View("CreateProject"); } } return View("CreateClosed"); } private async Task<bool> IsOkKycStatusAsync(UserModel user) { if (user.Id == null) return false; var kycStatus = await _kycService.GetStatusAsync(user.Id, KycProfile.Default); var status = (KycStatus)Enum.Parse(typeof(KycStatus), kycStatus.Name); return status == KycStatus.Ok; } // Edit a project [Authorize] public async Task<IActionResult> Edit(string id) { var user = UserModel.GetAuthenticatedUser(User.Identity); var viewModel = await GetProjectViewModel(id); viewModel.IsAuthor = viewModel.AuthorId == user.Email; var termsPage = await _termsPageRepository.GetAsync(id); if (termsPage != null) { ViewBag.TermsPage = TermsPageViewModel.Create(termsPage); } else { ViewBag.TermsPage = TermsPageViewModel.Create(id); } // TODO: move to a bool CanUserEditProject( if (viewModel.IsAdmin) { return View("EditProject", viewModel); } if ((viewModel.Status == Status.Initiative || viewModel.Status == Status.Draft) && viewModel.AuthorId == user.Email) { return View("EditProject", viewModel); } return View("AccessDenied"); } [Authorize] [HttpPost] public async Task<IActionResult> SaveProject(ProjectViewModel projectViewModel, bool draft = false, bool enableVoting = false, bool enableRegistration = false) { // TODO: We should re-check if we can do enums, or some workaround - the serialization/deserialization everywhere // is definitely a surface for bugs to hide in. projectViewModel.Tags = SerializeTags(projectViewModel.Tags); projectViewModel.ProjectStatus = projectViewModel.Status.ToString(); // TODO: Thinking about a Sanitize() method on the ProjectViewModel right before we write to DB, // that way we get every possible user-generated field and don't need to worry about missing one // (e.g. what if you forgot to do the PrizeDescription here?) var sanitizer = new HtmlSanitizer(); projectViewModel.PrizeDescription = sanitizer.Sanitize(projectViewModel.PrizeDescription); projectViewModel.Description = sanitizer.Sanitize(projectViewModel.Description); // TODO: Switch the name of the fields in the projectViewModel so it // is consistent, using the ! operator is difficult to read and reason about here projectViewModel.SkipVoting = !enableVoting; projectViewModel.SkipRegistration = !enableRegistration; // TODO: What's going on in these two if statements? Probably needs a comment, at least, if not a refactor. if (projectViewModel.CompetitionRegistrationDeadline == DateTime.MinValue) projectViewModel.CompetitionRegistrationDeadline = DateTime.UtcNow.Date; if (projectViewModel.VotingDeadline == DateTime.MinValue) projectViewModel.VotingDeadline = DateTime.UtcNow.Date; // TODO: Move to a separate validation function for testing, regexes are notorious. // Also, is the ID field the 'project URL' on the frontend? Should probably be changed, I found // it quite confusing. var idValid = Regex.IsMatch(projectViewModel.Id, @"^[a-z0-9-]+$") && !string.IsNullOrEmpty(projectViewModel.Id); if (!idValid) { ViewBag.ProjectCategories = _categoriesRepository.GetCategories(); ModelState.AddModelError("Id", "Project Url can only contain lowercase letters, numbers and the dash symbol and cannot be empty!"); return View("CreateProject", projectViewModel); } var project = await _projectRepository.GetAsync(projectViewModel.Id); if (project == null) { // TODO: Put this entire if-block into a constructor or a factory method on ProjectViewModel? projectViewModel.Status = draft ? Status.Draft : Status.Initiative; var user = UserModel.GetAuthenticatedUser(User.Identity); var userRole = await _userRolesRepository.GetAsync(user.Email.ToLower()); projectViewModel.AuthorId = user.Email; projectViewModel.AuthorFullName = user.GetFullName(); projectViewModel.AuthorIdentifier = user.Id; //Don't let non-admin users create Initiative projects if (userRole == null || userRole.Role != "ADMIN") { if (await IsOkKycStatusAsync(user) && projectViewModel.Status != Status.Draft) { return View("CreateInitiativeClosed"); } } // TODO: Where is the user-agent used? projectViewModel.UserAgent = HttpContext.Request.Headers["User-Agent"].ToString(); projectViewModel.Created = DateTime.UtcNow; projectViewModel.ParticipantsCount = 0; var projectId = await _projectRepository.SaveAsync(projectViewModel); // TODO: Move these into some kind of post-creation notification? // Especially because we don't want to notify in case of some problem if (projectViewModel.Status == Status.Initiative) { await SendProjectCreateNotification(projectViewModel); } // TODO: How is this different than the _projectRepository.SaveAsync? await SaveProjectFile(projectViewModel.File, projectId); UserModel.GenerateStreamsId(_streamsIdRepository, user.Id); return RedirectToAction("ProjectDetails", "Project", new { id = projectId }); } // TODO: Move this to the validation function, then we can get rid of the if-statement // and the async fetch above ViewBag.ProjectCategories = _categoriesRepository.GetCategories(); ModelState.AddModelError("Id", "Project with that Project Url already exists!"); return View("CreateProject", projectViewModel); } // TODO: This has a lot of duplicated code to SaveProject, rewrite to handle any // edit-specific logic then call SaveProject [Authorize] [HttpPost] public async Task<IActionResult> SaveEditedProject(ProjectViewModel projectViewModel, bool draft = false, bool enableVoting = false, bool enableRegistration = false) { if (projectViewModel.ProjectUrl == null) projectViewModel.ProjectUrl = projectViewModel.Id; projectViewModel.Tags = SerializeTags(projectViewModel.Tags); projectViewModel.ProjectStatus = projectViewModel.Status.ToString(); var sanitizer = new HtmlSanitizer(); projectViewModel.PrizeDescription = sanitizer.Sanitize(projectViewModel.PrizeDescription); projectViewModel.Description = sanitizer.Sanitize(projectViewModel.Description); projectViewModel.SkipVoting = !enableVoting; projectViewModel.SkipRegistration = !enableRegistration; if (projectViewModel.CompetitionRegistrationDeadline == DateTime.MinValue) projectViewModel.CompetitionRegistrationDeadline = DateTime.UtcNow.Date; if (projectViewModel.VotingDeadline == DateTime.MinValue) projectViewModel.VotingDeadline = DateTime.UtcNow.Date; var project = await _projectRepository.GetAsync(projectViewModel.Id); if (projectViewModel.AuthorId == null) projectViewModel.AuthorId = project.AuthorId; if (projectViewModel.AuthorFullName == null) projectViewModel.AuthorFullName = project.AuthorFullName; if (projectViewModel.AuthorIdentifier == null) { projectViewModel.AuthorIdentifier = project.AuthorIdentifier; var profile = await _personalDataService.FindClientsByEmail(projectViewModel.AuthorId); if (profile != null) projectViewModel.AuthorIdentifier = profile.Id; } project.Status = StatusHelper.GetProjectStatusFromString(project.ProjectStatus); var user = UserModel.GetAuthenticatedUser(User.Identity); var userRole = await _userRolesRepository.GetAsync(user.Email.ToLower()); //Don't let non-admin users edit their draft projects to Initiative status if (userRole == null || userRole.Role != "ADMIN") { if (await IsOkKycStatusAsync(user) && projectViewModel.Status != Status.Draft) { return View("CreateInitiativeClosed"); } } projectViewModel.LastModified = DateTime.UtcNow; projectViewModel.UserAgent = HttpContext.Request.Headers["User-Agent"].ToString(); projectViewModel.ParticipantsCount = project.ParticipantsCount; var projectId = projectViewModel.Id; var statusAndUrlChanged = projectViewModel.Status != Status.Draft && projectViewModel.ProjectUrl != projectId; if (!statusAndUrlChanged) { var currentProjectIsInStream = false; var currentProjectWasInOldStream = false; var streamId = ""; if (projectViewModel.StreamType == "New") { var streamProjects = JsonConvert.DeserializeObject<List<StreamProject>>(projectViewModel.SerializedStream); if (streamProjects.Any()) { var newStream = new StreamEntity { Name = projectViewModel.NewStreamName, AuthorId = user.Id, AuthorEmail = user.Email, Stream = projectViewModel.SerializedStream }; streamId = await _streamRepository.SaveAsync(newStream); foreach (var proj in streamProjects) { var streamProject = await _projectRepository.GetAsync(proj.ProjectId); streamProject.StreamId = streamId; await _projectRepository.UpdateAsync(streamProject); } currentProjectIsInStream = streamProjects.Any(p => p.ProjectId == projectViewModel.Id); } } if (projectViewModel.StreamType == "Existing") { var existingStream = await _streamRepository.GetAsync(projectViewModel.ExistingStreamId); var oldProjects = JsonConvert.DeserializeObject<List<StreamProject>>(existingStream.Stream); currentProjectWasInOldStream = oldProjects.Any(p => p.ProjectId == projectViewModel.Id); foreach (var oldProj in oldProjects) { var oldProject = await _projectRepository.GetAsync(oldProj.ProjectId); oldProject.StreamId = null; await _projectRepository.UpdateAsync(oldProject); } existingStream.Stream = projectViewModel.SerializedStream; await _streamRepository.UpdateAsync(existingStream); var newProjects = JsonConvert.DeserializeObject<List<StreamProject>>(projectViewModel.SerializedStream); foreach (var newProj in newProjects) { var streamProject = await _projectRepository.GetAsync(newProj.ProjectId); streamProject.StreamId = existingStream.Id; await _projectRepository.UpdateAsync(streamProject); } currentProjectIsInStream = newProjects.Any(p => p.ProjectId == projectViewModel.Id); streamId = existingStream.Id; } if (currentProjectIsInStream) { projectViewModel.StreamId = streamId; } else if (currentProjectWasInOldStream) { projectViewModel.StreamId = null; } await _projectRepository.UpdateAsync(projectViewModel); } if (project.Status == Status.Draft && projectViewModel.Status == Status.Initiative) { await SendProjectCreateNotification(projectViewModel); } var idValid = false; if (!string.IsNullOrEmpty(projectViewModel.ProjectUrl)) { idValid = Regex.IsMatch(projectViewModel.ProjectUrl, @"^[a-z0-9-]+$"); } else { return await EditWithProjectUrlError(projectViewModel.Id, "Project Url cannot be empty!"); } if (!idValid) { return await EditWithProjectUrlError(projectViewModel.Id, "Project Url can only contain lowercase letters, numbers and the dash symbol!"); } if (projectViewModel.ProjectUrl != projectId) { if (projectViewModel.Status != Status.Draft) { var oldProjUrl = projectViewModel.ProjectUrl; projectViewModel = await GetProjectViewModel(projectId); projectViewModel.ProjectUrl = oldProjUrl; projectViewModel.ProjectCategories = _categoriesRepository.GetCategories(); ModelState.AddModelError("Status", "Status cannot be changed while changing Project Url!"); return View("EditProject", projectViewModel); } if (!string.IsNullOrEmpty(projectViewModel.ProjectUrl)) { idValid = Regex.IsMatch(projectViewModel.ProjectUrl, @"^[a-z0-9-]+$"); } else { return await EditWithProjectUrlError(projectViewModel.Id, "Project Url cannot be empty!"); } if (!idValid) { return await EditWithProjectUrlError(projectViewModel.Id, "Project Url can only contain lowercase letters, numbers and the dash symbol!"); } var projectExists = await _projectRepository.GetAsync(projectViewModel.ProjectUrl); if (projectExists != null) { return await EditWithProjectUrlError(projectViewModel.Id, "Project with that Project Url already exists!"); } projectViewModel.Id = projectViewModel.ProjectUrl; projectViewModel.Created = DateTime.UtcNow; await _projectRepository.SaveAsync(projectViewModel); await _projectRepository.DeleteAsync(projectId); return RedirectToAction("ProjectDetails", "Project", new { id = projectViewModel.ProjectUrl }); } if (project.Status != Status.Registration && projectViewModel.Status == Status.Registration) { await AddCompetitionMailToQueue(project); } if (project.Status != Status.Submission && projectViewModel.Status == Status.Submission) { await AddImplementationMailToQueue(project); } if (project.Status != Status.Voting && projectViewModel.Status == Status.Voting) { await AddVotingMailToQueue(project); } if (projectViewModel.Status == Status.Archive) { if (!project.SkipVoting) { await _winnersService.SaveWinners(projectViewModel.Id, projectViewModel.Winners); } else { await _winnersService.SaveCustomWinners(projectViewModel.Id, projectViewModel.Winners); } await AddArchiveMailToQueue(project); } await _expertsService.SaveExperts(projectViewModel.Id, projectViewModel.Experts); await SaveProjectFile(projectViewModel.File, projectId); return RedirectToAction("ProjectDetails", "Project", new { id = projectViewModel.Id }); } // TODO: These notification tasks should probably be done elsewhere - // I believe I saw that we've got additional requirements around notifications // coming up, so maybe a separate notification controller is in order private async Task AddCompetitionMailToQueue(IProjectData project) { var following = await GetProjectFollows(project.Id); foreach (var follower in following) { if (_emailsQueue != null) { var message = NotificationMessageHelper.GenerateCompetitionMessage(project, follower); await _emailsQueue.PutMessageAsync(message); } } } private async Task AddImplementationMailToQueue(IProjectData project) { var following = await GetProjectFollows(project.Id); var participants = await _participantsRepository.GetProjectParticipantsAsync(project.Id); var projectParticipateData = participants as IList<IProjectParticipateData> ?? participants.ToList(); foreach (var follower in following) { if (_emailsQueue != null) { var participant = projectParticipateData.FirstOrDefault(x => x.ProjectId == project.Id && x.UserId == follower.UserId); var templateType = ""; templateType = participant != null ? "ImplementationParticipant" : "ImplementationFollower"; var message = NotificationMessageHelper.GenerateImplementationMessage(project, follower, templateType); await _emailsQueue.PutMessageAsync(message); } } } private async Task AddVotingMailToQueue(IProjectData project) { var following = await GetProjectFollows(project.Id); foreach (var follower in following) { if (_emailsQueue != null) { var message = NotificationMessageHelper.GenerateVotingMessage(project, follower); await _emailsQueue.PutMessageAsync(message); } } } private async Task AddArchiveMailToQueue(IProjectData project) { var participantsCount = await _participantsRepository.GetProjectParticipantsCountAsync(project.Id); var resultsCount = await _resultRepository.GetResultsCountAsync(project.Id); var winners = await _winnersRepository.GetWinnersAsync(project.Id); var following = await GetProjectFollows(project.Id); foreach (var follower in following) { if (_emailsQueue != null) { var message = NotificationMessageHelper.GenerateArchiveMessage(project, follower, participantsCount, resultsCount, winners); await _emailsQueue.PutMessageAsync(message); } } } // TODO: Move to the new ProjectModel, which will contain details about the project. ProjectViewModel is just // the view-specific data private async Task<IEnumerable<IProjectFollowData>> GetProjectFollows(string projectId) { var follows = await _projectFollowRepository.GetFollowAsync(); var projectFollows = follows.Where(f => f.ProjectId == projectId).ToList(); return projectFollows; } public async Task<IActionResult> ProjectDetails(string id) { if (string.IsNullOrEmpty(id)) { return View("ProjectNotFound"); } if (TempData["ShowParticipantAddedModal"] != null) { ViewBag.ParticipantAdded = (bool)TempData["ShowParticipantAddedModal"]; } if (TempData["ShowVotedForResultModal"] != null) { ViewBag.VotedForResult = (bool)TempData["ShowVotedForResultModal"]; } if (TempData["ShowVotedTwiceModal"] != null) { ViewBag.VotedTwice = (bool)TempData["ShowVotedTwiceModal"]; } ViewBag.IsKycOkStatus = await IsOkKycStatusAsync(UserModel.GetAuthenticatedUser(User.Identity)); var projectExists = await _projectRepository.GetAsync(id); if (projectExists == null) { return View("ProjectNotFound"); } var viewModel = await GetProjectViewModel(id); ViewBag.FacebookShareDescription = viewModel.Overview; return View(viewModel); } // TODO: A lot of this, like the fetch methods should probably be its own ProjectModel class - it's really about the // Project, not just the ProjectView and anything that's related to the view only (like the projectCategories) // can get pushed into the separate ProjectViewModel class that has a ProjectModel property on it. private async Task<ProjectViewModel> GetProjectViewModel(string id) { var projectCategories = _categoriesRepository.GetCategories(); var project = await _projectRepository.GetAsync(id); project.Status = StatusHelper.GetProjectStatusFromString(project.ProjectStatus); var projectDetailsAvatarIds = new List<string>(); projectDetailsAvatarIds.Add(project.AuthorIdentifier); // TODO: And these type of additional fetch methods can be methods on the model - the more we break // it up, the easier it is to test and reuse. var comments = await _commentsRepository.GetProjectCommentsAsync(id); await FormatComments(id, projectDetailsAvatarIds, comments); var participants = await _participantsRepository.GetProjectParticipantsAsync(id); var results = await _resultRepository.GetResultsAsync(id); var user = UserModel.GetAuthenticatedUser(User.Identity); var participant = (user.Email == null) ? null : await _participantsRepository.GetAsync(id, user.Email); var userRole = (user.Email == null) ? null : await _userRolesRepository.GetAsync(user.Email.ToLower()); var isAdmin = (userRole != null) && userRole.Role == StreamsRoles.Admin; var isAuthor = (user.Email != null) && user.Email == project.AuthorId; var participantId = ""; var isParticipant = false; var hasResult = false; if (participant != null) { participantId = user.Email; isParticipant = true; hasResult = results.Any(r => r.ParticipantId == user.Email); } var projectFollowing = (user.Email == null) ? null : await _projectFollowRepository.GetAsync(user.Email, id); var isFollowing = projectFollowing != null; // TODO: As I go through this, wondering if we need a CommentsList model, especially since // comments are probably going to be important to the platform going forwards comments = SortComments(comments); var commenterIsModerator = new Dictionary<string, bool>(); foreach (var comment in comments) { var role = await _userRolesRepository.GetAsync(comment.UserId); var isModerator = role != null && role.Role == StreamsRoles.Admin; commenterIsModerator.Add(comment.Id, isModerator); } // TODO: The votes might also need to be broken out, especially if we want to do // 5-star or numeric scoring var userVotedForResults = new Dictionary<string, bool>(); var resultVotes = await _resultVoteRepository.GetProjectResultVotesAsync(project.Id); foreach (var part in participants) { if (string.IsNullOrEmpty(part.UserIdentifier)) { var profile = await _personalDataService.FindClientsByEmail(part.UserId); if (profile != null) { part.UserIdentifier = profile.Id; await _participantsRepository.UpdateAsync(part); } } projectDetailsAvatarIds.Add(part.UserIdentifier); var participantStreamsId = await _streamsIdRepository.GetOrCreateAsync(part.UserIdentifier); part.StreamsId = participantStreamsId.StreamsId; } foreach (var result in results) { if (string.IsNullOrEmpty(result.ParticipantIdentifier)) { var profile = await _personalDataService.FindClientsByEmail(result.ParticipantId); result.ParticipantIdentifier = profile.Id; await _resultRepository.UpdateAsync(result); } var match = resultVotes.FirstOrDefault(x => x.ParticipantId == result.ParticipantId && x.VoterUserId == user.Email); userVotedForResults.Add(result.ParticipantId, match != null && user.Email != null); var resultStreamsId = await _streamsIdRepository.GetOrCreateAsync(result.ParticipantIdentifier); result.StreamsId = resultStreamsId.StreamsId; } var statusBarPartial = ProjectDetailsStatusBarViewModel.Create(project, participants.Count()); var commentsPartial = new ProjectCommentPartialViewModel { ProjectId = project.Id, UserId = user.Email, Comments = comments, IsAdmin = isAdmin, IsAuthor = isAuthor, CommenterIsModerator = commenterIsModerator, ProjectAuthorId = project.AuthorId }; var participantsPartial = new ProjectParticipantsPartialViewModel { CurrentUserId = user.Email, Participants = participants, Status = project.Status, HasResult = hasResult }; var resultsPartial = new ResultsPartialViewModel { Status = project.Status, Results = results, IsAdmin = isAdmin, SkipVoting = project.SkipVoting, UserVotedForResults = userVotedForResults, SubmissionsDeadline = project.ImplementationDeadline }; var allExperts = await _projectExpertsRepository.GetAllUniqueAsync(); var projectExperts = await _projectExpertsRepository.GetProjectExpertsAsync(id); foreach (var expert in projectExperts) { if (string.IsNullOrEmpty(expert.UserIdentifier) && !string.IsNullOrEmpty(expert.UserId)) { var profile = await _personalDataService.FindClientsByEmail(expert.UserId); if (profile != null) { expert.UserIdentifier = profile.Id; await _projectExpertsRepository.UpdateAsync(expert); } } if (!string.IsNullOrEmpty(expert.UserIdentifier)) { projectDetailsAvatarIds.Add(expert.UserIdentifier); expert.StreamsId = (await _streamsIdRepository.GetOrCreateAsync(expert.UserIdentifier)).StreamsId; } } var avatarsDictionary = await _personalDataService.GetClientAvatarsAsync(projectDetailsAvatarIds); participantsPartial.Avatars = avatarsDictionary.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); commentsPartial.Avatars = avatarsDictionary.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); resultsPartial.Avatars = avatarsDictionary.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); projectExperts = projectExperts.OrderBy(x => x.Priority == 0).ThenBy(x => x.Priority); var authorStreamsId = await _streamsIdRepository.GetOrCreateAsync(project.AuthorIdentifier); var projectViewModel = new ProjectViewModel { Id = project.Id, Name = project.Name, Overview = project.Overview, Description = project.Description, ProjectCategories = projectCategories, Category = project.Category, Status = project.Status, BudgetFirstPlace = project.BudgetFirstPlace, BudgetSecondPlace = project.BudgetSecondPlace, VotesFor = project.VotesFor, VotesAgainst = project.VotesAgainst, Created = project.Created, LastModified = project.LastModified, CompetitionRegistrationDeadline = project.CompetitionRegistrationDeadline, ImplementationDeadline = project.ImplementationDeadline, VotingDeadline = project.VotingDeadline, StatusBarPartial = statusBarPartial, CommentsPartial = commentsPartial, ParticipantsPartial = participantsPartial, ResultsPartial = resultsPartial, AuthorId = project.AuthorId, AuthorFullName = project.AuthorFullName, AuthorIdentifier = project.AuthorIdentifier, ParticipantId = participantId, IsParticipant = isParticipant, IsAdmin = isAdmin, IsFollowing = isFollowing, OtherProjects = await GetOtherProjects(project.Id), ProgrammingResourceName = project.ProgrammingResourceName, ProgrammingResourceLink = project.ProgrammingResourceLink, SkipVoting = project.SkipVoting, SkipRegistration = project.SkipRegistration, ProjectExperts = !projectExperts.Any() ? null : projectExperts, PrizeDescription = project.PrizeDescription, StreamId = project.StreamId, AllStreamProjects = await GetStreamProjects(), CompactStreams = await GetCompactStreams(), NameTag = project.NameTag, AuthorAvatarUrl = avatarsDictionary[project.AuthorIdentifier], AuthorStreamsId = authorStreamsId.StreamsId, Experts = allExperts.Select(ExpertViewModel.Create).ToList(), InfoForKycUsers = project.InfoForKycUsers, DescriptionFooter = project.DescriptionFooter }; if (!string.IsNullOrEmpty(project.Tags)) { projectViewModel.TagsList = JsonConvert.DeserializeObject<List<string>>(project.Tags); var builder = new StringBuilder(); foreach (var tag in projectViewModel.TagsList) { builder.Append(tag).Append(", "); } projectViewModel.Tags = builder.ToString(); } projectViewModel.EditStreamProjects = new EditStreamProjects { ProjectsList = new List<StreamProject>() }; if (!string.IsNullOrEmpty(project.StreamId)) { var stream = await _streamRepository.GetAsync(project.StreamId); projectViewModel.StreamProjects = JsonConvert.DeserializeObject<List<StreamProject>>(stream.Stream); } var fileInfo = await _fileInfoRepository.GetAsync(id); if (fileInfo != null) { var fileInfoViewModel = new ProjectFileInfoViewModel { ContentType = fileInfo.ContentType, FileName = fileInfo.FileName }; projectViewModel.FileInfo = fileInfoViewModel; } if (projectViewModel.Status == Status.Archive) { projectViewModel = await PopulateResultsViewModel(projectViewModel); var winners = await _winnersRepository.GetWinnersAsync(project.Id); projectViewModel.Winners = winners.Select(x => WinnerViewModel.Create(x)).ToList(); } projectViewModel.ProjectUrl = project.Id; return projectViewModel; } private async Task FormatComments(string id, List<string> projectDetailsAvatarIds, IEnumerable<ICommentData> comments) { foreach (var comment in comments) { if (string.IsNullOrEmpty(comment.UserIdentifier)) { var profile = await _personalDataService.FindClientsByEmail(comment.UserId); if (profile != null) { comment.UserIdentifier = profile.Id; await _commentsRepository.UpdateAsync(comment, id); } } projectDetailsAvatarIds.Add(comment.UserIdentifier); var commenterStreamsId = await _streamsIdRepository.GetOrCreateAsync(comment.UserIdentifier); comment.StreamsId = commenterStreamsId.StreamsId; if (!string.IsNullOrEmpty(comment.Comment)) { comment.Comment = Regex.Replace(comment.Comment, @"\r\n?|\n", "<br />"); } } } private async Task<List<OtherProjectViewModel>> GetOtherProjects(string id) { var projects = await _projectRepository.GetProjectsAsync(); var filteredProjects = projects.Where(x => x.Id != id && x.ProjectStatus == Status.Submission.ToString() && x.BudgetFirstPlace > 0).Take(7).ToList(); var otherProjects = new List<OtherProjectViewModel>(); foreach (var project in filteredProjects) { otherProjects.Add(OtherProjectViewModel.Create(project)); } return otherProjects; } private async Task<ProjectViewModel> PopulateResultsViewModel(ProjectViewModel model) { model.ResultsPartial.BudgetFirstPlace = model.BudgetFirstPlace; model.ResultsPartial.BudgetSecondPlace = model.BudgetSecondPlace; model.ResultsPartial.ParticipantCount = model.ParticipantsPartial.Participants.Count(); model.ResultsPartial.DaysOfContest = (model.VotingDeadline - model.Created).Days; var winnersList = await _winnersRepository.GetWinnersAsync(model.Id); winnersList = winnersList.OrderBy(x => x.Place).ThenByDescending(x => x.Votes).ThenByDescending(x => x.Score); foreach (var winner in winnersList) { if (string.IsNullOrEmpty(winner.WinnerIdentifier)) { var profile = await _personalDataService.FindClientsByEmail(winner.WinnerId); if (profile != null) winner.WinnerIdentifier = profile.Id; winner.ProjectId = model.Id; await _winnersRepository.UpdateAsync(winner); } if (!string.IsNullOrEmpty(winner.WinnerIdentifier)) { UserModel.GenerateStreamsId(_streamsIdRepository, winner.WinnerIdentifier); var winnerStreamsId = await _streamsIdRepository.GetOrCreateAsync(winner.WinnerIdentifier); winner.StreamsId = winnerStreamsId.StreamsId; } } model.ResultsPartial.Winners = winnersList; return model; } private string SerializeTags(string tagsString) { if (string.IsNullOrEmpty(tagsString)) return null; var tags = tagsString.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); var tagsList = new List<string>(tags); tagsList = tagsList.Where(s => !string.IsNullOrWhiteSpace(s)).ToList(); tagsList = tagsList.Select(s => s.Trim()).ToList(); return JsonConvert.SerializeObject(tagsList); } private async Task SaveProjectFile(IFormFile file, string projectId) { if (file != null) { await _fileRepository.InsertProjectFile(file.OpenReadStream(), projectId); var fileInfo = ProjectFileInfoEntity.Create(file, projectId); await _fileInfoRepository.SaveAsync(fileInfo); } } private IEnumerable<ICommentData> SortComments(IEnumerable<ICommentData> comments) { var commentsData = comments as IList<ICommentData> ?? comments.ToList(); var childComments = commentsData.Where(x => x.ParentId != null).ToList(); comments = commentsData.Where(x => x.ParentId == null).ToList(); comments = comments.OrderBy(c => c.Created).Reverse().ToList(); var sortedComments = new List<ICommentData>(); foreach (var comment in comments) { sortedComments.Add(comment); var children = childComments.Where(x => x.ParentId == comment.Id).ToList(); children = children.OrderBy(x => x.Created).ToList(); sortedComments.AddRange(children); } return sortedComments; } private async Task<IActionResult> EditWithProjectUrlError(string projectId, string errorText) { var projectViewModel = await GetProjectViewModel(projectId); projectViewModel.ProjectCategories = _categoriesRepository.GetCategories(); ModelState.AddModelError("ProjectUrl", errorText); return View("EditProject", projectViewModel); } private async Task SendProjectCreateNotification(IProjectData model) { var message = NotificationMessageHelper.CreateProjectMessage(model); foreach (var email in _settings.LykkeStreams.ProjectCreateNotificationReceiver) { await _emailSender.SendEmailAsync(NotificationMessageHelper.EmailSender, email, message); } } private async Task<List<StreamProject>> GetStreamProjects() { var projects = await _projectRepository.GetProjectsAsync(); return (from project in projects where project.ProjectStatus != Status.Draft.ToString() && string.IsNullOrEmpty(project.StreamId) select new StreamProject { ProjectId = project.Id, ProjectName = project.Name }).ToList(); } private async Task<List<CompactStream>> GetCompactStreams() { var streams = await _streamRepository.GetStreamsAsync(); return streams.Select(stream => new CompactStream { StreamId = stream.Id, StreamName = stream.Name }) .ToList(); } public async Task<IActionResult> GetEditStreamsTable(string streamId) { var model = new EditStreamProjects { ProjectsList = new List<StreamProject>() }; if (!string.IsNullOrEmpty(streamId)) { var stream = await _streamRepository.GetAsync(streamId); var streamProjects = JsonConvert.DeserializeObject<List<StreamProject>>(stream.Stream); model.ProjectsList = streamProjects; } return PartialView("EditStreamTablePartial", model); } [HttpPost] public async Task<IActionResult> AddExpert(string email, string description, string projectId) { var profile = await _personalDataService.FindClientsByEmail(email); if (profile == null) { return Json(new { Error = "User with this email does not exist!" }); } var expert = ExpertViewModel.Create(profile, projectId, description); try { await _projectExpertsRepository.SaveAsync(expert); } catch (Exception) { return Json(new { Error = "This user is already an expert for this project!" }); } return Json(expert); } [HttpPost] public async Task<IActionResult> DeleteExpert(string email, string projectId) { await _projectExpertsRepository.DeleteAsync(email, projectId); return Json(new { Success = true, }); } } }
// *********************************************************************** // Copyright (c) 2008-2015 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.Framework.Internal.Builders; namespace NUnit.Framework { /// <summary> /// TestCaseSourceAttribute indicates the source to be used to /// provide test fixture instances for a test class. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] public class TestFixtureSourceAttribute : NUnitAttribute, IFixtureBuilder { private readonly NUnitTestFixtureBuilder _builder = new NUnitTestFixtureBuilder(); /// <summary> /// Error message string is public so the tests can use it /// </summary> public const string MUST_BE_STATIC = "The sourceName specified on a TestCaseSourceAttribute must refer to a static field, property or method."; #region Constructors /// <summary> /// Construct with the name of the method, property or field that will provide data /// </summary> /// <param name="sourceName">The name of a static method, property or field that will provide data.</param> public TestFixtureSourceAttribute(string sourceName) { this.SourceName = sourceName; } /// <summary> /// Construct with a Type and name /// </summary> /// <param name="sourceType">The Type that will provide data</param> /// <param name="sourceName">The name of a static method, property or field that will provide data.</param> public TestFixtureSourceAttribute(Type sourceType, string sourceName) { this.SourceType = sourceType; this.SourceName = sourceName; } /// <summary> /// Construct with a Type /// </summary> /// <param name="sourceType">The type that will provide data</param> public TestFixtureSourceAttribute(Type sourceType) { this.SourceType = sourceType; } #endregion #region Properties /// <summary> /// The name of a the method, property or fiend to be used as a source /// </summary> public string SourceName { get; private set; } /// <summary> /// A Type to be used as a source /// </summary> public Type SourceType { get; private set; } /// <summary> /// Gets or sets the category associated with every fixture created from /// this attribute. May be a single category or a comma-separated list. /// </summary> public string Category { get; set; } #endregion #region IFixtureBuilder Members /// <summary> /// Construct one or more TestFixtures from a given Type, /// using available parameter data. /// </summary> /// <param name="typeInfo">The TypeInfo for which fixures are to be constructed.</param> /// <returns>One or more TestFixtures as TestSuite</returns> public IEnumerable<TestSuite> BuildFrom(ITypeInfo typeInfo) { Type sourceType = SourceType ?? typeInfo.Type; foreach (TestFixtureParameters parms in GetParametersFor(sourceType)) yield return _builder.BuildFrom(typeInfo, parms); } #endregion #region Helper Methods /// <summary> /// Returns a set of ITestFixtureData items for use as arguments /// to a parameterized test fixture. /// </summary> /// <param name="sourceType">The type for which data is needed.</param> /// <returns></returns> public IEnumerable<ITestFixtureData> GetParametersFor(Type sourceType) { List<ITestFixtureData> data = new List<ITestFixtureData>(); try { IEnumerable source = GetTestFixtureSource(sourceType); if (source != null) { foreach (object item in source) { var parms = item as ITestFixtureData; if (parms == null) { object[] args = item as object[]; if (args == null) { args = new object[] { item }; } parms = new TestFixtureParameters(args); } if (this.Category != null) foreach (string cat in this.Category.Split(new char[] { ',' })) parms.Properties.Add(PropertyNames.Category, cat); data.Add(parms); } } } catch (Exception ex) { data.Clear(); data.Add(new TestFixtureParameters(ex)); } return data; } private IEnumerable GetTestFixtureSource(Type sourceType) { // Handle Type implementing IEnumerable separately if (SourceName == null) return Reflect.Construct(sourceType) as IEnumerable; MemberInfo[] members = sourceType.GetMember(SourceName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance); if (members.Length == 1) { MemberInfo member = members[0]; var field = member as FieldInfo; if (field != null) return field.IsStatic ? (IEnumerable)field.GetValue(null) : SourceMustBeStaticError(); var property = member as PropertyInfo; if (property != null) return property.GetGetMethod(true).IsStatic ? (IEnumerable)property.GetValue(null, null) : SourceMustBeStaticError(); var m = member as MethodInfo; if (m != null) return m.IsStatic ? (IEnumerable)m.Invoke(null, null) : SourceMustBeStaticError(); } return null; } private static IEnumerable SourceMustBeStaticError() { var parms = new TestFixtureParameters(); parms.RunState = RunState.NotRunnable; parms.Properties.Set(PropertyNames.SkipReason, MUST_BE_STATIC); return new TestFixtureParameters[] { parms }; } #endregion } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using Erwine.Leonard.T.GDIPlus.Palette.ColorCaches.Common; using Erwine.Leonard.T.GDIPlus.Palette.Helpers; namespace Erwine.Leonard.T.GDIPlus.Palette.Quantizers.MedianCut { internal class MedianCutCube { #region | Fields | // red bounds private Int32 redLowBound; private Int32 redHighBound; // green bounds private Int32 greenLowBound; private Int32 greenHighBound; // blue bounds private Int32 blueLowBound; private Int32 blueHighBound; private readonly ICollection<Int32> colorList; #endregion #region | Properties | /// <summary> /// Gets the color model. /// </summary> public ColorModel ColorModel { get; private set; } /// <summary> /// Gets or sets the index of the palette. /// </summary> /// <value>The index of the palette.</value> public Int32 PaletteIndex { get; private set; } #endregion #region | Constructors | /// <summary> /// Initializes a new instance of the <see cref="MedianCutCube"/> class. /// </summary> /// <param name="colors">The colors.</param> public MedianCutCube(ICollection<Int32> colors) { ColorModel = ColorModel.RedGreenBlue; colorList = colors; Shrink(); } #endregion #region | Calculated properties | /// <summary> /// Gets the size of the red side of this cube. /// </summary> /// <value>The size of the red side of this cube.</value> public Int32 RedSize { get { return redHighBound - redLowBound; } } /// <summary> /// Gets the size of the green side of this cube. /// </summary> /// <value>The size of the green side of this cube.</value> public Int32 GreenSize { get { return greenHighBound - greenLowBound; } } /// <summary> /// Gets the size of the blue side of this cube. /// </summary> /// <value>The size of the blue side of this cube.</value> public Int32 BlueSize { get { return blueHighBound - blueLowBound; } } /// <summary> /// Gets the average color from the colors contained in this cube. /// </summary> /// <value>The average color.</value> public Color Color { get { Int32 red = 0, green = 0, blue = 0; foreach (Int32 argb in colorList) { Color color = Color.FromArgb(argb); red += ColorModelHelper.GetComponentA(ColorModel, color); green += ColorModelHelper.GetComponentB(ColorModel, color); blue += ColorModelHelper.GetComponentC(ColorModel, color); } red = colorList.Count == 0 ? 0 : red / colorList.Count; green = colorList.Count == 0 ? 0 : green / colorList.Count; blue = colorList.Count == 0 ? 0 : blue / colorList.Count; // ColorModelHelper.HSBtoRGB(Convert.ToInt32(red/ColorModelHelper.HueFactor), green / 255.0f, blue / 255.0f); Color result = Color.FromArgb(255, red, green, blue); return result; } } #endregion #region | Methods | /// <summary> /// Shrinks this cube to the least dimensions that covers all the colors in the RGB space. /// </summary> private void Shrink() { redLowBound = greenLowBound = blueLowBound = 255; redHighBound = greenHighBound = blueHighBound = 0; foreach (Int32 argb in colorList) { Color color = Color.FromArgb(argb); Int32 red = ColorModelHelper.GetComponentA(ColorModel, color); Int32 green = ColorModelHelper.GetComponentB(ColorModel, color); Int32 blue = ColorModelHelper.GetComponentC(ColorModel, color); if (red < redLowBound) redLowBound = red; if (red > redHighBound) redHighBound = red; if (green < greenLowBound) greenLowBound = green; if (green > greenHighBound) greenHighBound = green; if (blue < blueLowBound) blueLowBound = blue; if (blue > blueHighBound) blueHighBound = blue; } } /// <summary> /// Splits this cube's color list at median index, and returns two newly created cubes. /// </summary> /// <param name="componentIndex">Index of the component (red = 0, green = 1, blue = 2).</param> /// <param name="firstMedianCutCube">The first created cube.</param> /// <param name="secondMedianCutCube">The second created cube.</param> public void SplitAtMedian(Byte componentIndex, out MedianCutCube firstMedianCutCube, out MedianCutCube secondMedianCutCube) { List<Int32> colors; switch (componentIndex) { // red colors case 0: colors = colorList.OrderBy(argb => ColorModelHelper.GetComponentA(ColorModel, Color.FromArgb(argb))).ToList(); break; // green colors case 1: colors = colorList.OrderBy(argb => ColorModelHelper.GetComponentB(ColorModel, Color.FromArgb(argb))).ToList(); break; // blue colors case 2: colors = colorList.OrderBy(argb => ColorModelHelper.GetComponentC(ColorModel, Color.FromArgb(argb))).ToList(); break; default: throw new NotSupportedException("Only three color components are supported (R, G and B)."); } // retrieves the median index (a half point) Int32 medianIndex = colorList.Count >> 1; // creates the two half-cubes firstMedianCutCube = new MedianCutCube(colors.GetRange(0, medianIndex)); secondMedianCutCube = new MedianCutCube(colors.GetRange(medianIndex, colors.Count - medianIndex)); } /// <summary> /// Assigns a palette index to this cube, to be later found by a GetPaletteIndex method. /// </summary> /// <param name="newPaletteIndex">The palette index to be assigned to this cube.</param> public void SetPaletteIndex(Int32 newPaletteIndex) { PaletteIndex = newPaletteIndex; } /// <summary> /// Determines whether the color is in the space of this cube. /// </summary> /// <param name="color">The color to be checked, if it's contained in this cube.</param> /// <returns>if true a color is in the space of this cube, otherwise returns false.</returns> public Boolean IsColorIn(Color color) { Int32 red = ColorModelHelper.GetComponentA(ColorModel, color); Int32 green = ColorModelHelper.GetComponentB(ColorModel, color); Int32 blue = ColorModelHelper.GetComponentC(ColorModel, color); return (red >= redLowBound && red <= redHighBound) && (green >= greenLowBound && green <= greenHighBound) && (blue >= blueLowBound && blue <= blueHighBound); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Sam.Areas.HelpPage.SampleGeneration { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Collections.Generic; using System.Diagnostics; namespace CocosSharp { public delegate void CCButtonTapDelegate(object sender); public class CCControlButton : CCControl { /* Define the button margin for Left/Right edge */ public const int CCControlButtonMarginLR = 8; // px /* Define the button margin for Top/Bottom edge */ public const int CCControlButtonMarginTB = 2; // px public const int kZoomActionTag = (0x7CCB0001); protected bool _parentInited; protected CCNode _backgroundSprite; protected Dictionary<CCControlState, CCNode> _backgroundSpriteDispatchTable; protected string _currentTitle; /** The current color used to display the title. */ protected CCColor3B _currentTitleColor; protected bool _doesAdjustBackgroundImage; protected bool _isPushed; protected CCPoint _labelAnchorPoint; protected int _marginH = CCControlButtonMarginLR; protected int _marginV = CCControlButtonMarginTB; protected CCSize _preferredSize; protected Dictionary<CCControlState, CCColor3B> _titleColorDispatchTable; protected Dictionary<CCControlState, string> _titleDispatchTable; protected CCNode _titleLabel; protected Dictionary<CCControlState, CCNode> _titleLabelDispatchTable; protected bool _zoomOnTouchDown; public event CCButtonTapDelegate OnButtonTap; public CCNode BackgroundSprite { get { return _backgroundSprite; } set { _backgroundSprite = value; } } public CCNode TitleLabel { get { return _titleLabel; } set { _titleLabel = value; } } public override byte Opacity { get { return RealOpacity; } set { base.Opacity = value; foreach (var item in _backgroundSpriteDispatchTable.Values) { if (item != null) { item.Opacity = value; } } } } public override CCColor3B Color { get { return base.RealColor; } set { base.Color = value; foreach (var item in _backgroundSpriteDispatchTable.Values) { if (item != null) { item.Color = value; } } } } public override bool Enabled { get { return base.Enabled; } set { base.Enabled = value; NeedsLayout(); } } public override bool Selected { set { base.Selected = value; NeedsLayout(); } } public override bool Highlighted { set { base.Highlighted = value; var actionState = GetActionState(kZoomActionTag); if (actionState != null) { StopAction(actionState); } NeedsLayout(); if (_zoomOnTouchDown) { float scaleValue = (Highlighted && Enabled && !Selected) ? 1.1f : 1.0f; CCAction zoomAction = new CCScaleTo(0.05f, scaleValue) { Tag = kZoomActionTag }; RunAction(zoomAction); } } } public bool IsPushed { get { return _isPushed; } } /** Adjust the button zooming on touchdown. Default value is YES. */ public bool ZoomOnTouchDown { set { _zoomOnTouchDown = value; } get { return _zoomOnTouchDown; } } /** The prefered size of the button, if label is larger it will be expanded. */ public CCSize PreferredSize { get { return _preferredSize; } set { if (value.Width == 0 && value.Height == 0) { _doesAdjustBackgroundImage = true; } else { _doesAdjustBackgroundImage = false; foreach (var item in _backgroundSpriteDispatchTable) { var sprite = item.Value as CCScale9Sprite; if (sprite != null) { sprite.PreferredSize = value; } } } _preferredSize = value; NeedsLayout(); } } public CCPoint LabelAnchorPoint { get { return _labelAnchorPoint; } set { _labelAnchorPoint = value; if (_titleLabel != null) { _titleLabel.AnchorPoint = value; } } } #region Constructors public CCControlButton() : this("", "Arial", 12.0f) { } public CCControlButton(CCNode label, CCNode backgroundSprite) { InitCCControlButton(label, backgroundSprite); } public CCControlButton(string title, string fontName, float fontSize) : this(new CCLabelTtf(title, fontName, fontSize), new CCNode()) { } public CCControlButton(CCNode sprite) : this(new CCLabelTtf("", "Arial", 30), sprite) { } private void InitCCControlButton(CCNode node, CCNode backgroundSprite) { Debug.Assert(node != null, "Label must not be nil."); var label = node as ICCTextContainer; var rgbaLabel = node; Debug.Assert(backgroundSprite != null, "Background sprite must not be nil."); Debug.Assert(label != null || rgbaLabel != null || backgroundSprite != null); _parentInited = true; // Initialize the button state tables _titleDispatchTable = new Dictionary<CCControlState, string>(); _titleColorDispatchTable = new Dictionary<CCControlState, CCColor3B>(); _titleLabelDispatchTable = new Dictionary<CCControlState, CCNode>(); _backgroundSpriteDispatchTable = new Dictionary<CCControlState, CCNode>(); // Register Touch Event var touchListener = new CCEventListenerTouchOneByOne(); touchListener.IsSwallowTouches = true; touchListener.OnTouchBegan = onTouchBegan; touchListener.OnTouchMoved = onTouchMoved; touchListener.OnTouchEnded = onTouchEnded; touchListener.OnTouchCancelled = onTouchCancelled; AddEventListener(touchListener); _isPushed = false; _zoomOnTouchDown = true; _currentTitle = null; // Adjust the background image by default SetAdjustBackgroundImage(true); PreferredSize = CCSize.Zero; // Zooming button by default _zoomOnTouchDown = true; // Set the default anchor point IgnoreAnchorPointForPosition = false; AnchorPoint = new CCPoint(0.5f, 0.5f); // Set the nodes TitleLabel = node; BackgroundSprite = backgroundSprite; // Set the default color and opacity Color = new CCColor3B(255, 255, 255); Opacity = 255; IsColorModifiedByOpacity = true; // Initialize the dispatch table string tempString = label.Text; //tempString->autorelease(); SetTitleForState(tempString, CCControlState.Normal); SetTitleColorForState(rgbaLabel.Color, CCControlState.Normal); SetTitleLabelForState(node, CCControlState.Normal); SetBackgroundSpriteForState(backgroundSprite, CCControlState.Normal); LabelAnchorPoint = new CCPoint(0.5f, 0.5f); NeedsLayout(); } #endregion Constructors public override void NeedsLayout() { if (!_parentInited) { return; } // Hide the background and the label if (_titleLabel != null) { _titleLabel.Visible = false; } if (_backgroundSprite != null) { _backgroundSprite.Visible = false; } // Update anchor of all labels LabelAnchorPoint = _labelAnchorPoint; // Update the label to match with the current state _currentTitle = GetTitleForState(State); _currentTitleColor = GetTitleColorForState(State); TitleLabel = GetTitleLabelForState(State); var label = (ICCTextContainer)_titleLabel; if (label != null && !String.IsNullOrEmpty(_currentTitle)) { label.Text = (_currentTitle); } var rgbaLabel = _titleLabel; if (rgbaLabel != null) { rgbaLabel.Color = _currentTitleColor; } if (_titleLabel != null) { _titleLabel.Position = new CCPoint(ContentSize.Width / 2, ContentSize.Height / 2); } // Update the background sprite BackgroundSprite = GetBackgroundSpriteForState(State); if (_backgroundSprite != null) { _backgroundSprite.Position = new CCPoint(ContentSize.Width / 2, ContentSize.Height / 2); } // Get the title label size CCSize titleLabelSize = CCSize.Zero; if (_titleLabel != null) { titleLabelSize = _titleLabel.BoundingBox.Size; } // Adjust the background image if necessary if (_doesAdjustBackgroundImage) { // Add the margins if (_backgroundSprite != null) { _backgroundSprite.ContentSize = new CCSize(titleLabelSize.Width + _marginH * 2, titleLabelSize.Height + _marginV * 2); } } else { //TODO: should this also have margins if one of the preferred sizes is relaxed? if (_backgroundSprite != null && _backgroundSprite is CCScale9Sprite) { CCSize preferredSize = ((CCScale9Sprite)_backgroundSprite).PreferredSize; if (preferredSize.Width <= 0) { preferredSize.Width = titleLabelSize.Width; } if (preferredSize.Height <= 0) { preferredSize.Height = titleLabelSize.Height; } _backgroundSprite.ContentSize = preferredSize; } } // Set the content size CCRect rectTitle = CCRect.Zero; if (_titleLabel != null) { rectTitle = _titleLabel.BoundingBox; } CCRect rectBackground = CCRect.Zero; if (_backgroundSprite != null) { rectBackground = _backgroundSprite.BoundingBox; } CCRect maxRect = CCControlUtils.CCRectUnion(rectTitle, rectBackground); ContentSize = new CCSize(maxRect.Size.Width, maxRect.Size.Height); if (_titleLabel != null) { _titleLabel.Position = new CCPoint(ContentSize.Width / 2, ContentSize.Height / 2); // Make visible label _titleLabel.Visible = true; } if (_backgroundSprite != null) { _backgroundSprite.Position = new CCPoint(ContentSize.Width / 2, ContentSize.Height / 2); // Make visible the background _backgroundSprite.Visible = true; } } /** Adjust the background image. YES by default. If the property is set to NO, the background will use the prefered size of the background image. */ public void SetAdjustBackgroundImage(bool adjustBackgroundImage) { _doesAdjustBackgroundImage = adjustBackgroundImage; NeedsLayout(); } public bool DoesAdjustBackgroundImage() { return _doesAdjustBackgroundImage; } /** The current title that is displayed on the button. */ //set the margins at once (so we only have to do one call of needsLayout) protected virtual void SetMargins(int marginH, int marginV) { _marginV = marginV; _marginH = marginH; NeedsLayout(); } //events bool onTouchBegan(CCTouch pTouch, CCEvent touchEvent) { if (!IsTouchInside(pTouch) || !Enabled) { return false; } State = CCControlState.Highlighted; _isPushed = true; Highlighted = true; SendActionsForControlEvents(CCControlEvent.TouchDown); return true; } void onTouchMoved(CCTouch pTouch, CCEvent touchEvent) { if (!Enabled || !IsPushed || Selected) { if (Highlighted) { Highlighted = false; } return; } bool isTouchMoveInside = IsTouchInside(pTouch); if (isTouchMoveInside && !Highlighted) { State = CCControlState.Highlighted; Highlighted = true; SendActionsForControlEvents(CCControlEvent.TouchDragEnter); } else if (isTouchMoveInside && Highlighted) { SendActionsForControlEvents(CCControlEvent.TouchDragInside); } else if (!isTouchMoveInside && Highlighted) { State = CCControlState.Normal; Highlighted = false; SendActionsForControlEvents(CCControlEvent.TouchDragExit); } else if (!isTouchMoveInside && !Highlighted) { SendActionsForControlEvents(CCControlEvent.TouchDragOutside); } } void onTouchEnded(CCTouch pTouch, CCEvent touchEvent) { State = CCControlState.Normal; _isPushed = false; Highlighted = false; if (IsTouchInside(pTouch)) { if (OnButtonTap != null) { OnButtonTap(this); } SendActionsForControlEvents(CCControlEvent.TouchUpInside); } else { SendActionsForControlEvents(CCControlEvent.TouchUpOutside); } } void onTouchCancelled(CCTouch pTouch, CCEvent touchEvent) { State = CCControlState.Normal; _isPushed = false; Highlighted = false; SendActionsForControlEvents(CCControlEvent.TouchCancel); } /** * Returns the title used for a state. * * @param state The state that uses the title. Possible values are described in * "CCControlState". * * @return The title for the specified state. */ public virtual string GetTitleForState(CCControlState state) { if (_titleDispatchTable != null) { string title; if (_titleDispatchTable.TryGetValue(state, out title)) { return title; } if (_titleDispatchTable.TryGetValue(CCControlState.Normal, out title)) { return title; } } return String.Empty; } /** * Sets the title string to use for the specified state. * If a property is not specified for a state, the default is to use * the CCButtonStateNormal value. * * @param title The title string to use for the specified state. * @param state The state that uses the specified title. The values are described * in "CCControlState". */ public virtual void SetTitleForState(string title, CCControlState state) { if (_titleDispatchTable.ContainsKey(state)) { _titleDispatchTable.Remove(state); } if (!String.IsNullOrEmpty(title)) { _titleDispatchTable.Add(state, title); } // If the current state if equal to the given state we update the layout if (State == state) { NeedsLayout(); } } /** * Returns the title color used for a state. * * @param state The state that uses the specified color. The values are described * in "CCControlState". * * @return The color of the title for the specified state. */ public virtual CCColor3B GetTitleColorForState(CCControlState state) { if (_titleColorDispatchTable != null) { CCColor3B color; if (_titleColorDispatchTable.TryGetValue(state, out color)) { return color; } if (_titleColorDispatchTable.TryGetValue(CCControlState.Normal, out color)) { return color; } } return CCColor3B.White; } /** * Sets the color of the title to use for the specified state. * * @param color The color of the title to use for the specified state. * @param state The state that uses the specified color. The values are described * in "CCControlState". */ public virtual void SetTitleColorForState(CCColor3B color, CCControlState state) { if (_titleColorDispatchTable.ContainsKey(state)) { _titleColorDispatchTable.Remove(state); } _titleColorDispatchTable.Add(state, color); // If the current state if equal to the given state we update the layout if (State == state) { NeedsLayout(); } } /** * Returns the title label used for a state. * * @param state The state that uses the title label. Possible values are described * in "CCControlState". */ public virtual CCNode GetTitleLabelForState(CCControlState state) { CCNode titleLabel; if (_titleLabelDispatchTable.TryGetValue(state, out titleLabel)) { return titleLabel; } if (_titleLabelDispatchTable.TryGetValue(CCControlState.Normal, out titleLabel)) { return titleLabel; } return null; } /** * Sets the title label to use for the specified state. * If a property is not specified for a state, the default is to use * the CCButtonStateNormal value. * * @param title The title label to use for the specified state. * @param state The state that uses the specified title. The values are described * in "CCControlState". */ public virtual void SetTitleLabelForState(CCNode titleLabel, CCControlState state) { CCNode previousLabel; if (_titleLabelDispatchTable.TryGetValue(state, out previousLabel)) { RemoveChild(previousLabel, true); _titleLabelDispatchTable.Remove(state); } _titleLabelDispatchTable.Add(state, titleLabel); titleLabel.Visible = false; titleLabel.AnchorPoint = new CCPoint(0.5f, 0.5f); AddChild(titleLabel, 1); // If the current state if equal to the given state we update the layout if (State == state) { NeedsLayout(); } } public virtual void SetTitleTtfForState(string fntFile, CCControlState state) { string title = GetTitleForState(state); if (title == null) { title = String.Empty; } SetTitleLabelForState(new CCLabelTtf(title, fntFile, 12), state); } public virtual string GetTitleTtfForState(CCControlState state) { var label = (ICCTextContainer)GetTitleLabelForState(state); var labelTtf = label as CCLabelTtf; if (labelTtf != null) { return labelTtf.FontName; } return String.Empty; } public virtual void SetTitleTtfSizeForState(float size, CCControlState state) { var label = (ICCTextContainer)GetTitleLabelForState(state); if (label != null) { var labelTtf = label as CCLabelTtf; if (labelTtf != null) { labelTtf.FontSize = size; } } } public virtual float GetTitleTtfSizeForState(CCControlState state) { var labelTtf = GetTitleLabelForState(state) as CCLabelTtf; if (labelTtf != null) { return labelTtf.FontSize; } return 0; } /** * Sets the font of the label, changes the label to a CCLabelBMFont if neccessary. * @param fntFile The name of the font to change to * @param state The state that uses the specified fntFile. The values are described * in "CCControlState". */ public virtual void SetTitleBmFontForState(string fntFile, CCControlState state) { string title = GetTitleForState(state); if (title == null) { title = String.Empty; } SetTitleLabelForState(new CCLabelBMFont(title, fntFile), state); } public virtual string GetTitleBmFontForState(CCControlState state) { var label = (ICCTextContainer)GetTitleLabelForState(state); var labelBmFont = label as CCLabelBMFont; if (labelBmFont != null) { return labelBmFont.FntFile; } return String.Empty; } /** * Returns the background sprite used for a state. * * @param state The state that uses the background sprite. Possible values are * described in "CCControlState". */ public virtual CCNode GetBackgroundSpriteForState(CCControlState state) { CCNode backgroundSprite; if (_backgroundSpriteDispatchTable.TryGetValue(state, out backgroundSprite)) { return backgroundSprite; } if (_backgroundSpriteDispatchTable.TryGetValue(CCControlState.Normal, out backgroundSprite)) { return backgroundSprite; } return null; } /** * Sets the background sprite to use for the specified button state. * * @param sprite The background sprite to use for the specified state. * @param state The state that uses the specified image. The values are described * in "CCControlState". */ public virtual void SetBackgroundSpriteForState(CCNode sprite, CCControlState state) { CCSize oldPreferredSize = _preferredSize; CCNode previousBackgroundSprite; if (_backgroundSpriteDispatchTable.TryGetValue(state, out previousBackgroundSprite)) { RemoveChild(previousBackgroundSprite, true); _backgroundSpriteDispatchTable.Remove(state); } _backgroundSpriteDispatchTable.Add(state, sprite); sprite.Visible = false; sprite.AnchorPoint = new CCPoint(0.5f, 0.5f); AddChild(sprite); if (_preferredSize.Width != 0 || _preferredSize.Height != 0 && sprite is CCScale9Sprite) { var scale9 = ((CCScale9Sprite)sprite); if (oldPreferredSize.Equals(_preferredSize)) { // Force update of preferred size scale9.PreferredSize = new CCSize(oldPreferredSize.Width + 1, oldPreferredSize.Height + 1); } scale9.PreferredSize = _preferredSize; } // If the current state if equal to the given state we update the layout if (State == state) { NeedsLayout(); } } /** * Sets the background spriteFrame to use for the specified button state. * * @param spriteFrame The background spriteFrame to use for the specified state. * @param state The state that uses the specified image. The values are described * in "CCControlState". */ public virtual void SetBackgroundSpriteFrameForState(CCSpriteFrame spriteFrame, CCControlState state) { CCScale9Sprite sprite = new CCScale9SpriteFrame(spriteFrame); SetBackgroundSpriteForState(sprite, state); } } }
// // AddinScanFolderInfo.cs // // Author: // Lluis Sanchez Gual // // Copyright (C) 2007 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Collections; using System.Collections.Specialized; using Mono.Addins.Serialization; using System.Collections.Generic; namespace Mono.Addins.Database { class AddinScanFolderInfo: IBinaryXmlElement { Hashtable files = new Hashtable (); string folder; string fileName; string domain; bool sharedFolder = true; static BinaryXmlTypeMap typeMap = new BinaryXmlTypeMap ( typeof(AddinScanFolderInfo), typeof(AddinFileInfo) ); internal AddinScanFolderInfo () { } public AddinScanFolderInfo (string folder) { this.folder = folder; } public string FileName { get { return fileName; } } public static AddinScanFolderInfo Read (FileDatabase filedb, string file) { AddinScanFolderInfo finfo = (AddinScanFolderInfo) filedb.ReadSharedObject (file, typeMap); if (finfo != null) finfo.fileName = file; return finfo; } public static AddinScanFolderInfo Read (FileDatabase filedb, string basePath, string folderPath) { string fileName; AddinScanFolderInfo finfo = (AddinScanFolderInfo) filedb.ReadSharedObject (basePath, GetDomain (folderPath), ".data", Path.GetFullPath (folderPath), typeMap, out fileName); if (finfo != null) finfo.fileName = fileName; return finfo; } internal static string GetDomain (string path) { path = Path.GetFullPath (path); string s = path.Replace (Path.DirectorySeparatorChar, '_'); s = s.Replace (Path.AltDirectorySeparatorChar, '_'); s = s.Replace (Path.VolumeSeparatorChar, '_'); s = s.Trim ('_'); if (Util.IsWindows) { s = s.ToLowerInvariant(); } return s; } public void Write (FileDatabase filedb, string basePath) { filedb.WriteSharedObject (basePath, GetDomain (folder), ".data", Path.GetFullPath (folder), fileName, typeMap, this); } public string GetExistingLocalDomain () { foreach (AddinFileInfo info in files.Values) { if (info.Domain != null && info.Domain != AddinDatabase.GlobalDomain) return info.Domain; } return AddinDatabase.GlobalDomain; } public string Folder { get { return folder; } } public string Domain { get { if (sharedFolder) return AddinDatabase.GlobalDomain; else return domain; } set { domain = value; sharedFolder = true; } } public string RootsDomain { get { return domain; } set { domain = value; } } public string GetDomain (bool isRoot) { if (isRoot) return RootsDomain; else return Domain; } public bool SharedFolder { get { return sharedFolder; } set { sharedFolder = value; } } public bool FolderHasScanDataIndex { get; set; } public void Reset () { files.Clear (); } public DateTime GetLastScanTime (string file) { AddinFileInfo info = (AddinFileInfo) files [file]; if (info == null) return DateTime.MinValue; else return info.LastScan; } public AddinFileInfo GetAddinFileInfo (string file) { return (AddinFileInfo) files [file]; } public AddinFileInfo SetLastScanTime (string file, string addinId, bool isRoot, DateTime time, bool scanError, string scanDataMD5 = null) { AddinFileInfo info = (AddinFileInfo) files [file]; if (info == null) { info = new AddinFileInfo (); info.File = file; files [file] = info; } info.LastScan = time; info.AddinId = addinId; info.IsRoot = isRoot; info.ScanError = scanError; info.ScanDataMD5 = scanDataMD5; if (addinId != null) info.Domain = GetDomain (isRoot); else info.Domain = null; return info; } public List<AddinFileInfo> GetMissingAddins (AddinFileSystemExtension fs) { var missing = new List<AddinFileInfo> (); if (!fs.DirectoryExists (folder)) { // All deleted foreach (AddinFileInfo info in files.Values) { if (info.IsAddin) missing.Add (info); } files.Clear (); return missing; } var toDelete = new List<string> (); foreach (AddinFileInfo info in files.Values) { if (!fs.FileExists (info.File)) { if (info.IsAddin) missing.Add (info); toDelete.Add (info.File); } else if (info.IsAddin && info.Domain != GetDomain (info.IsRoot)) { missing.Add (info); } } foreach (string file in toDelete) files.Remove (file); return missing; } void IBinaryXmlElement.Write (BinaryXmlWriter writer) { if (files.Count == 0) { domain = null; sharedFolder = true; } writer.WriteValue ("folder", folder); writer.WriteValue ("files", files); writer.WriteValue ("domain", domain); writer.WriteValue ("sharedFolder", sharedFolder); writer.WriteValue ("folderHasDataIndex", FolderHasScanDataIndex); } void IBinaryXmlElement.Read (BinaryXmlReader reader) { folder = reader.ReadStringValue ("folder"); reader.ReadValue ("files", files); domain = reader.ReadStringValue ("domain"); sharedFolder = reader.ReadBooleanValue ("sharedFolder"); FolderHasScanDataIndex = reader.ReadBooleanValue ("folderHasDataIndex"); } } class AddinFileInfo: IBinaryXmlElement { public string File; public DateTime LastScan; public string AddinId; public bool IsRoot; public bool ScanError; public string Domain; public StringCollection IgnorePaths; public string ScanDataMD5; public bool IsAddin { get { return AddinId != null && AddinId.Length != 0; } } public void AddPathToIgnore (string path) { if (IgnorePaths == null) IgnorePaths = new StringCollection (); IgnorePaths.Add (path); } public bool HasChanged (AddinFileSystemExtension fs, string md5) { if (md5 != null && ScanDataMD5 != null) return md5 != ScanDataMD5; return fs.GetLastWriteTime (File) != LastScan; } void IBinaryXmlElement.Write (BinaryXmlWriter writer) { writer.WriteValue ("File", File); writer.WriteValue ("LastScan", LastScan); writer.WriteValue ("AddinId", AddinId); writer.WriteValue ("IsRoot", IsRoot); writer.WriteValue ("ScanError", ScanError); writer.WriteValue ("Domain", Domain); writer.WriteValue ("IgnorePaths", IgnorePaths); writer.WriteValue ("MD5", ScanDataMD5); } void IBinaryXmlElement.Read (BinaryXmlReader reader) { File = reader.ReadStringValue ("File"); LastScan = reader.ReadDateTimeValue ("LastScan"); AddinId = reader.ReadStringValue ("AddinId"); IsRoot = reader.ReadBooleanValue ("IsRoot"); ScanError = reader.ReadBooleanValue ("ScanError"); Domain = reader.ReadStringValue ("Domain"); IgnorePaths = (StringCollection) reader.ReadValue ("IgnorePaths", new StringCollection ()); ScanDataMD5 = reader.ReadStringValue ("MD5"); } } }
// 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.ComponentModel; using System.Diagnostics; using System.IO; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.Net.NetworkInformation { public partial class Ping { private const int IcmpHeaderLengthInBytes = 8; private const int MinIpHeaderLengthInBytes = 20; private const int MaxIpHeaderLengthInBytes = 60; [ThreadStatic] private static Random t_idGenerator; private async Task<PingReply> SendPingAsyncCore(IPAddress address, byte[] buffer, int timeout, PingOptions options) { try { Task<PingReply> t = RawSocketPermissions.CanUseRawSockets(address.AddressFamily) ? SendIcmpEchoRequestOverRawSocket(address, buffer, timeout, options) : SendWithPingUtility(address, buffer, timeout, options); PingReply reply = await t.ConfigureAwait(false); if (_canceled) { throw new OperationCanceledException(); } return reply; } finally { Finish(); } } private async Task<PingReply> SendIcmpEchoRequestOverRawSocket(IPAddress address, byte[] buffer, int timeout, PingOptions options) { EndPoint endPoint = new IPEndPoint(address, 0); bool isIpv4 = address.AddressFamily == AddressFamily.InterNetwork; ProtocolType protocolType = isIpv4 ? ProtocolType.Icmp : ProtocolType.IcmpV6; // Use a random value as the identifier. This doesn't need to be perfectly random // or very unpredictable, rather just good enough to avoid unexpected conflicts. Random rand = t_idGenerator ?? (t_idGenerator = new Random()); ushort identifier = (ushort)rand.Next((int)ushort.MaxValue + 1); IcmpHeader header = new IcmpHeader() { Type = isIpv4 ? (byte)IcmpV4MessageType.EchoRequest : (byte)IcmpV6MessageType.EchoRequest, Code = 0, HeaderChecksum = 0, Identifier = identifier, SequenceNumber = 0, }; byte[] sendBuffer = CreateSendMessageBuffer(header, buffer); using (Socket socket = new Socket(address.AddressFamily, SocketType.Raw, protocolType)) { socket.ReceiveTimeout = timeout; socket.SendTimeout = timeout; // Setting Socket.DontFragment and .Ttl is not supported on Unix, so ignore the PingOptions parameter. int ipHeaderLength = isIpv4 ? MinIpHeaderLengthInBytes : 0; await socket.SendToAsync(new ArraySegment<byte>(sendBuffer), SocketFlags.None, endPoint).ConfigureAwait(false); byte[] receiveBuffer = new byte[MaxIpHeaderLengthInBytes + IcmpHeaderLengthInBytes + buffer.Length]; long elapsed; Stopwatch sw = Stopwatch.StartNew(); // Read from the socket in a loop. We may receive messages that are not echo replies, or that are not in response // to the echo request we just sent. We need to filter such messages out, and continue reading until our timeout. // For example, when pinging the local host, we need to filter out our own echo requests that the socket reads. while ((elapsed = sw.ElapsedMilliseconds) < timeout) { Task<SocketReceiveFromResult> receiveTask = socket.ReceiveFromAsync( new ArraySegment<byte>(receiveBuffer), SocketFlags.None, endPoint); var cts = new CancellationTokenSource(); Task finished = await Task.WhenAny(receiveTask, Task.Delay(timeout - (int)elapsed, cts.Token)).ConfigureAwait(false); cts.Cancel(); if (finished != receiveTask) { sw.Stop(); return CreateTimedOutPingReply(); } SocketReceiveFromResult receiveResult = receiveTask.GetAwaiter().GetResult(); int bytesReceived = receiveResult.ReceivedBytes; if (bytesReceived - ipHeaderLength < IcmpHeaderLengthInBytes) { continue; // Not enough bytes to reconstruct IP header + ICMP header. } byte type, code; unsafe { fixed (byte* bytesPtr = &receiveBuffer[0]) { if (isIpv4) { // Determine actual size of IP header byte ihl = (byte)(bytesPtr[0] & 0x0f); // Internet Header Length ipHeaderLength = 4 * ihl; if (bytesReceived - ipHeaderLength < IcmpHeaderLengthInBytes) { continue; // Not enough bytes to reconstruct actual IP header + ICMP header. } } int icmpHeaderOffset = ipHeaderLength; IcmpHeader receivedHeader = *((IcmpHeader*)(bytesPtr + icmpHeaderOffset)); // Skip IP header. type = receivedHeader.Type; code = receivedHeader.Code; if (identifier != receivedHeader.Identifier || type == (byte)IcmpV4MessageType.EchoRequest || type == (byte)IcmpV6MessageType.EchoRequest) // Echo Request, ignore { continue; } } } sw.Stop(); long roundTripTime = sw.ElapsedMilliseconds; int dataOffset = ipHeaderLength + IcmpHeaderLengthInBytes; // We want to return a buffer with the actual data we sent out, not including the header data. byte[] dataBuffer = new byte[bytesReceived - dataOffset]; Buffer.BlockCopy(receiveBuffer, dataOffset, dataBuffer, 0, dataBuffer.Length); IPStatus status = isIpv4 ? IcmpV4MessageConstants.MapV4TypeToIPStatus(type, code) : IcmpV6MessageConstants.MapV6TypeToIPStatus(type, code); return new PingReply(address, options, status, roundTripTime, dataBuffer); } // We have exceeded our timeout duration, and no reply has been received. sw.Stop(); return CreateTimedOutPingReply(); } } private async Task<PingReply> SendWithPingUtility(IPAddress address, byte[] buffer, int timeout, PingOptions options) { bool isIpv4 = address.AddressFamily == AddressFamily.InterNetwork; string pingExecutable = isIpv4 ? UnixCommandLinePing.Ping4UtilityPath : UnixCommandLinePing.Ping6UtilityPath; if (pingExecutable == null) { throw new PlatformNotSupportedException(SR.net_ping_utility_not_found); } string processArgs = UnixCommandLinePing.ConstructCommandLine(buffer.Length, address.ToString(), isIpv4); ProcessStartInfo psi = new ProcessStartInfo(pingExecutable, processArgs); psi.RedirectStandardOutput = true; psi.RedirectStandardError = true; Process p = new Process() { StartInfo = psi }; var processCompletion = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); p.EnableRaisingEvents = true; p.Exited += (s, e) => processCompletion.SetResult(true); p.Start(); var cts = new CancellationTokenSource(); Task timeoutTask = Task.Delay(timeout, cts.Token); Task finished = await Task.WhenAny(processCompletion.Task, timeoutTask).ConfigureAwait(false); if (finished == timeoutTask && !p.HasExited) { // Try to kill the ping process if it didn't return. If it is already in the process of exiting, a Win32Exception will be thrown. try { p.Kill(); } catch (Win32Exception) { } return CreateTimedOutPingReply(); } else { cts.Cancel(); if (p.ExitCode == 1 || p.ExitCode == 2) { // Throw timeout for known failure return codes from ping functions. return CreateTimedOutPingReply(); } try { string output = await p.StandardOutput.ReadToEndAsync().ConfigureAwait(false); long rtt = UnixCommandLinePing.ParseRoundTripTime(output); return new PingReply( address, null, // Ping utility cannot accommodate these, return null to indicate they were ignored. IPStatus.Success, rtt, Array.Empty<byte>()); // Ping utility doesn't deliver this info. } catch (Exception) { // If the standard output cannot be successfully parsed, throw a generic PingException. throw new PingException(SR.net_ping); } } } private PingReply CreateTimedOutPingReply() { // Documentation indicates that you should only pay attention to the IPStatus value when // its value is not "Success", but the rest of these values match that of the Windows implementation. return new PingReply(new IPAddress(0), null, IPStatus.TimedOut, 0, Array.Empty<byte>()); } #if DEBUG static Ping() { Debug.Assert(Marshal.SizeOf<IcmpHeader>() == 8, "The size of an ICMP Header must be 8 bytes."); } #endif // Must be 8 bytes total. [StructLayout(LayoutKind.Sequential)] internal struct IcmpHeader { public byte Type; public byte Code; public ushort HeaderChecksum; public ushort Identifier; public ushort SequenceNumber; } private static unsafe byte[] CreateSendMessageBuffer(IcmpHeader header, byte[] payload) { int headerSize = sizeof(IcmpHeader); byte[] result = new byte[headerSize + payload.Length]; Marshal.Copy(new IntPtr(&header), result, 0, headerSize); payload.CopyTo(result, headerSize); ushort checksum = ComputeBufferChecksum(result); // Jam the checksum into the buffer. result[2] = (byte)(checksum >> 8); result[3] = (byte)(checksum & (0xFF)); return result; } private static ushort ComputeBufferChecksum(byte[] buffer) { // This is using the "deferred carries" approach outlined in RFC 1071. uint sum = 0; for (int i = 0; i < buffer.Length; i += 2) { // Combine each pair of bytes into a 16-bit number and add it to the sum ushort element0 = (ushort)((buffer[i] << 8) & 0xFF00); ushort element1 = (i + 1 < buffer.Length) ? (ushort)(buffer[i + 1] & 0x00FF) : (ushort)0; // If there's an odd number of bytes, pad by one octet of zeros. ushort combined = (ushort)(element0 | element1); sum += (uint)combined; } // Add back the "carry bits" which have risen to the upper 16 bits of the sum. while ((sum >> 16) != 0) { var partialSum = sum & 0xFFFF; var carries = sum >> 16; sum = partialSum + carries; } return unchecked((ushort)~sum); } } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using ThinMvvm.Data; using ThinMvvm.Data.Infrastructure; using ThinMvvm.Tests.TestInfrastructure; using Xunit; namespace ThinMvvm.Tests.Data { public sealed class DataSourceTests { public sealed class Basic { private sealed class IntDataSource : DataSource<int> { public Func<CancellationToken, Task<int>> Fetch; public IntDataSource( Func<CancellationToken, Task<int>> fetch ) { Fetch = fetch; } protected override Task<int> FetchAsync( CancellationToken cancellationToken ) => Fetch( cancellationToken ); } [Fact] public void InitialState() { var source = new IntDataSource( _ => Task.FromResult( 0 ) ); Assert.Null( source.Data ); Assert.Equal( DataSourceStatus.None, source.Status ); Assert.Null( ( (IDataSource) source ).Data ); Assert.False( ( (IDataSource) source ).CanFetchMore ); } [Fact] public async Task RefreshInProgress() { var taskSource = new TaskCompletionSource<int>(); var source = new IntDataSource( _ => taskSource.Task ); var hits = new List<string>(); source.PropertyChanged += ( _, e ) => { if( e.PropertyName == nameof( IDataSource.Status ) && hits.Count == 0 ) { Assert.Null( source.Data ); Assert.Equal( DataSourceStatus.Loading, source.Status ); Assert.Null( ( (IDataSource) source ).Data ); Assert.False( ( (IDataSource) source ).CanFetchMore ); } hits.Add( e.PropertyName ); }; var task = source.RefreshAsync(); Assert.Equal( new[] { nameof( IDataSource.Status ) }, hits ); taskSource.SetResult( 0 ); await task; } [Fact] public async Task SuccessfulRefresh() { var taskSource = new TaskCompletionSource<int>(); var source = new IntDataSource( _ => taskSource.Task ); var task = source.RefreshAsync(); var hits = new List<string>(); source.PropertyChanged += ( _, e ) => { hits.Add( e.PropertyName ); if( e.PropertyName == nameof( IntDataSource.Status ) ) { Assert.Equal( new DataChunk<int>( 42, DataStatus.Normal, default( DataErrors ) ), source.Data ); Assert.Equal( DataSourceStatus.Loaded, source.Status ); Assert.Equal<IDataChunk>( new[] { source.Data }, ( (IDataSource) source ).Data ); Assert.False( ( (IDataSource) source ).CanFetchMore ); } }; taskSource.SetResult( 42 ); await task; Assert.Equal( new[] { nameof( IDataSource.Data ), nameof( IDataSource.Status ) }, hits ); } [Fact] public async Task FailedRefresh() { var ex = new MyException(); var taskSource = new TaskCompletionSource<int>(); var source = new IntDataSource( _ => taskSource.Task ); var task = source.RefreshAsync(); var hits = new List<string>(); source.PropertyChanged += ( _, e ) => { hits.Add( e.PropertyName ); if( e.PropertyName == nameof( IntDataSource.Status ) ) { Assert.Equal( new DataChunk<int>( 0, DataStatus.Error, new DataErrors( ex, null, null ) ), source.Data ); Assert.Equal( DataSourceStatus.Loaded, source.Status ); Assert.Equal<IDataChunk>( new[] { source.Data }, ( (IDataSource) source ).Data ); Assert.False( ( (IDataSource) source ).CanFetchMore ); } }; taskSource.SetException( ex ); await task; Assert.Equal( new[] { nameof( IDataSource.Data ), nameof( IDataSource.Status ) }, hits ); } [Fact] public async Task RefreshCancelsOlderCall() { var tokens = new List<CancellationToken>(); var source = new IntDataSource( t => { tokens.Add( t ); return Task.FromResult( 42 ); } ); await source.RefreshAsync(); await source.RefreshAsync(); Assert.Equal( 2, tokens.Count ); Assert.True( tokens[0].IsCancellationRequested ); Assert.False( tokens[1].IsCancellationRequested ); } [Fact] public async Task SlowEarlyRefreshDoesNotOverrideLaterOne() { var taskSource = new TaskCompletionSource<int>(); var source = new IntDataSource( _ => taskSource.Task ); // Call 1 begins var task = source.RefreshAsync(); source.Fetch = _ => Task.FromResult( 42 ); // Call 2 begins var task2 = source.RefreshAsync(); // Call 1 completes taskSource.SetResult( 100 ); // Wait for both await task; await task2; Assert.Equal( new DataChunk<int>( 42, DataStatus.Normal, default( DataErrors ) ), source.Data ); Assert.Equal( DataSourceStatus.Loaded, source.Status ); } [Fact] public async Task SlowFailedEarlyRefreshDoesNotOverrideLaterOne() { var taskSource = new TaskCompletionSource<int>(); var source = new IntDataSource( _ => taskSource.Task ); // Call 1 begins var task = source.RefreshAsync(); source.Fetch = _ => Task.FromResult( 42 ); // Call 2 begins var task2 = source.RefreshAsync(); // Call 1 fails taskSource.SetException( new Exception() ); // Wait for both await task; await task2; Assert.Equal( new DataChunk<int>( 42, DataStatus.Normal, default( DataErrors ) ), source.Data ); Assert.Equal( DataSourceStatus.Loaded, source.Status ); } [Fact] public async Task FetchMoreThrows() { var source = new IntDataSource( _ => Task.FromResult( 0 ) ); await source.RefreshAsync(); await Assert.ThrowsAsync<NotSupportedException>( ( (IDataSource) source ).FetchMoreAsync ); } } public sealed class WithTransform { private sealed class IntDataSource : DataSource<int> { public Func<CancellationToken, Task<int>> Fetch; public Func<int, Task<int>> Transformer; public IntDataSource( Func<CancellationToken, Task<int>> fetch, Func<int, Task<int>> transformer ) { Fetch = fetch; Transformer = transformer; } public new Task UpdateValueAsync() => base.UpdateValueAsync(); protected override Task<int> FetchAsync( CancellationToken cancellationToken ) => Fetch( cancellationToken ); protected override Task<int> TransformAsync( int value ) => Transformer( value ); } [Fact] public async Task CannotUpdateValueBeforeRefreshing() { var source = new IntDataSource( _ => Task.FromResult( 0 ), n => Task.FromResult( n + 1 ) ); await Assert.ThrowsAsync<InvalidOperationException>( () => source.UpdateValueAsync() ); } [Fact] public async Task TransformInProgress() { var transformSource = new TaskCompletionSource<int>(); var source = new IntDataSource( _ => Task.FromResult( 1 ), _ => transformSource.Task ); transformSource.SetResult( 10 ); await source.RefreshAsync(); transformSource = new TaskCompletionSource<int>(); var hits = new List<string>(); source.PropertyChanged += ( _, e ) => { if( e.PropertyName == nameof( IDataSource.Status ) && hits.Count == 0 ) { Assert.Equal( DataSourceStatus.Transforming, source.Status ); } hits.Add( e.PropertyName ); }; var updateTask = source.UpdateValueAsync(); Assert.Equal( new[] { nameof( IDataSource.Status ) }, hits ); transformSource.SetResult( 0 ); await updateTask; Assert.Equal( DataSourceStatus.Loaded, source.Status ); } [Fact] public async Task SuccessfulTransform() { var source = new IntDataSource( _ => Task.FromResult( 21 ), n => Task.FromResult( n * 2 ) ); await source.RefreshAsync(); Assert.Equal( new DataChunk<int>( 42, DataStatus.Normal, default( DataErrors ) ), source.Data ); Assert.Equal( DataSourceStatus.Loaded, source.Status ); } [Fact] public async Task FailedTransform() { var ex = new MyException(); var source = new IntDataSource( _ => Task.FromResult( 42 ), _ => { throw ex; } ); await source.RefreshAsync(); Assert.Equal( new DataChunk<int>( 0, DataStatus.Error, new DataErrors( null, null, ex ) ), source.Data ); Assert.Equal( DataSourceStatus.Loaded, source.Status ); } [Fact] public async Task SuccessfulUpdatedTransform() { var source = new IntDataSource( _ => Task.FromResult( 84 ), n => Task.FromResult( n ) ); await source.RefreshAsync(); source.Transformer = n => Task.FromResult( n / 2 ); await source.UpdateValueAsync(); Assert.Equal( new DataChunk<int>( 42, DataStatus.Normal, default( DataErrors ) ), source.Data ); Assert.Equal( DataSourceStatus.Loaded, source.Status ); } [Fact] public async Task FailedUpdatedTransform() { var source = new IntDataSource( _ => Task.FromResult( 42 ), n => Task.FromResult( n ) ); await source.RefreshAsync(); var ex = new MyException(); source.Transformer = _ => { throw ex; }; await source.UpdateValueAsync(); Assert.Equal( new DataChunk<int>( 0, DataStatus.Error, new DataErrors( null, null, ex ) ), source.Data ); Assert.Equal( DataSourceStatus.Loaded, source.Status ); } [Fact] public async Task UpdateDoesNotFetchAgain() { var count = 0; var source = new IntDataSource( _ => { count++; return Task.FromResult( 42 ); }, n => Task.FromResult( n ) ); await source.RefreshAsync(); await source.UpdateValueAsync(); Assert.Equal( 1, count ); } [Fact] public async Task UpdateValuesDuringRefreshDoesNotUpdate() { // Scenario: // After the initial load, one thread starts refreshing data. // While data is refreshing, another thread wants to update the value. // The data refresh ends, then the value update ends. // The update result should be ignored, since its data is no longer up to date. var taskSource = new TaskCompletionSource<int>(); var transformSource = new TaskCompletionSource<int>(); var source = new IntDataSource( _ => taskSource.Task, async n => { if( n == 1 ) { await transformSource.Task; } return 10 * n; } ); // Initial fetch taskSource.SetResult( 1 ); transformSource.SetResult( 0 ); await source.RefreshAsync(); taskSource = new TaskCompletionSource<int>(); transformSource = new TaskCompletionSource<int>(); // Refresh starts... var refreshTask = source.RefreshAsync(); // Update starts... var transformTask = source.UpdateValueAsync(); // Refresh finishes taskSource.SetResult( 2 ); await refreshTask; // Update finishes transformSource.SetResult( 0 ); await transformTask; Assert.Equal( 20, source.Data.Value ); Assert.Equal( DataSourceStatus.Loaded, source.Status ); } } public sealed class WithCache { private sealed class IntDataSource : DataSource<int> { public Func<CancellationToken, Task<int>> Fetch; public IntDataSource( Func<CancellationToken, Task<int>> fetch, Func<CacheMetadata> metadataCreator, IDataStore dataStore = null ) { Fetch = fetch; EnableCache( "X", dataStore ?? new InMemoryDataStore(), metadataCreator ); } protected override Task<int> FetchAsync( CancellationToken cancellationToken ) => Fetch( cancellationToken ); } [Fact] public async Task SuccessfulRefresh() { var source = new IntDataSource( _ => Task.FromResult( 42 ), null ); await source.RefreshAsync(); Assert.Equal( new DataChunk<int>( 42, DataStatus.Normal, default( DataErrors ) ), source.Data ); Assert.Equal( DataSourceStatus.Loaded, source.Status ); } [Fact] public async Task FailedRefresh() { var ex = new MyException(); var source = new IntDataSource( _ => TaskEx.FromException<int>( ex ), null ); await source.RefreshAsync(); Assert.Equal( new DataChunk<int>( 0, DataStatus.Error, new DataErrors( ex, null, null ) ), source.Data ); Assert.Equal( DataSourceStatus.Loaded, source.Status ); } [Fact] public async Task FailedRefreshAfterSuccessfulOne() { var source = new IntDataSource( _ => Task.FromResult( 42 ), null ); await source.RefreshAsync(); var ex = new MyException(); source.Fetch = _ => TaskEx.FromException<int>( ex ); await source.RefreshAsync(); Assert.Equal( new DataChunk<int>( 42, DataStatus.Cached, new DataErrors( ex, null, null ) ), source.Data ); Assert.Equal( DataSourceStatus.Loaded, source.Status ); } [Fact] public async Task RefreshesWithDifferentMetadataDoNotInterfere() { string id = "id"; var source = new IntDataSource( _ => Task.FromResult( 42 ), () => new CacheMetadata( id, null ) ); await source.RefreshAsync(); var ex = new MyException(); source.Fetch = _ => TaskEx.FromException<int>( ex ); id = "id2"; await source.RefreshAsync(); Assert.Equal( new DataChunk<int>( 0, DataStatus.Error, new DataErrors( ex, null, null ) ), source.Data ); Assert.Equal( DataSourceStatus.Loaded, source.Status ); } [Fact] public async Task StaleDataIsNotUsed() { var source = new IntDataSource( _ => Task.FromResult( 42 ), () => new CacheMetadata( "", DateTimeOffset.MinValue ) ); await source.RefreshAsync(); var ex = new MyException(); source.Fetch = _ => TaskEx.FromException<int>( ex ); await source.RefreshAsync(); Assert.Equal( new DataChunk<int>( 0, DataStatus.Error, new DataErrors( ex, null, null ) ), source.Data ); Assert.Equal( DataSourceStatus.Loaded, source.Status ); } [Fact] public async Task DataIsNotUsedWhenMetadataIsNull() { var source = new IntDataSource( _ => Task.FromResult( 42 ), () => null ); await source.RefreshAsync(); var ex = new MyException(); source.Fetch = _ => TaskEx.FromException<int>( ex ); await source.RefreshAsync(); Assert.Equal( new DataChunk<int>( 0, DataStatus.Error, new DataErrors( ex, null, null ) ), source.Data ); Assert.Equal( DataSourceStatus.Loaded, source.Status ); } [Fact] public async Task SuccessfulRefreshButMetadataCreatorThrows() { var ex = new MyException(); var source = new IntDataSource( _ => Task.FromResult( 42 ), () => { throw ex; } ); await source.RefreshAsync(); Assert.Equal( new DataChunk<int>( 42, DataStatus.Normal, new DataErrors( null, ex, null ) ), source.Data ); Assert.Equal( DataSourceStatus.Loaded, source.Status ); } [Fact] public async Task FailedRefreshAfterSuccessfulOneButMetadataCreatorThrows() { bool shouldThrow = false; var cacheEx = new MyException(); var source = new IntDataSource( _ => Task.FromResult( 42 ), () => { if( shouldThrow ) { throw cacheEx; } return CacheMetadata.Default; } ); await source.RefreshAsync(); var fetchEx = new MyException(); source.Fetch = _ => TaskEx.FromException<int>( fetchEx ); shouldThrow = true; await source.RefreshAsync(); Assert.Equal( new DataChunk<int>( 0, DataStatus.Error, new DataErrors( fetchEx, cacheEx, null ) ), source.Data ); Assert.Equal( DataSourceStatus.Loaded, source.Status ); } private sealed class DataStoreFailingToRead : IDataStore { public readonly Exception Exception = new MyException(); public Task<Optional<T>> LoadAsync<T>( string id ) { return TaskEx.FromException<Optional<T>>( Exception ); } public Task StoreAsync<T>( string id, T data ) { return TaskEx.CompletedTask; } public Task DeleteAsync( string id ) { throw new NotSupportedException(); } } [Fact] public async Task CacheFailsToRead() { var store = new DataStoreFailingToRead(); var source = new IntDataSource( _ => Task.FromResult( 42 ), null, store ); await source.RefreshAsync(); var ex = new MyException(); source.Fetch = _ => TaskEx.FromException<int>( ex ); await source.RefreshAsync(); Assert.Equal( new DataChunk<int>( 0, DataStatus.Error, new DataErrors( ex, store.Exception, null ) ), source.Data ); Assert.Equal( DataSourceStatus.Loaded, source.Status ); } private sealed class DataStoreFailingToWrite : IDataStore { public readonly Exception Exception = new MyException(); public Task<Optional<T>> LoadAsync<T>( string id ) { return Task.FromResult( default( Optional<T> ) ); } public Task StoreAsync<T>( string id, T data ) { return TaskEx.FromException<T>( Exception ); } public Task DeleteAsync( string id ) { throw new NotSupportedException(); } } [Fact] public async Task CacheFailsToWrite() { var store = new DataStoreFailingToWrite(); var source = new IntDataSource( _ => Task.FromResult( 42 ), null, store ); await source.RefreshAsync(); Assert.Equal( new DataChunk<int>( 42, DataStatus.Normal, new DataErrors( null, store.Exception, null ) ), source.Data ); Assert.Equal( DataSourceStatus.Loaded, source.Status ); } private sealed class DataSourceWithNullCacheStore : DataSource<int> { public DataSourceWithNullCacheStore() { EnableCache( "X", null ); } protected override Task<int> FetchAsync( CancellationToken cancellationToken ) { return Task.FromResult( 0 ); } } [Fact] public void NullCacheStoreFails() { Assert.Throws<ArgumentNullException>( () => new DataSourceWithNullCacheStore() ); } private sealed class DataSourceWithNullCacheId : DataSource<int> { public DataSourceWithNullCacheId() { EnableCache( null, new InMemoryDataStore() ); } protected override Task<int> FetchAsync( CancellationToken cancellationToken ) { return Task.FromResult( 0 ); } } [Fact] public void NullCacheIdFails() { Assert.Throws<ArgumentNullException>( () => new DataSourceWithNullCacheId() ); } private sealed class DataSourceEnablingCacheTwice : DataSource<int> { public DataSourceEnablingCacheTwice() { EnableCache( "X", new InMemoryDataStore() ); EnableCache( "X", new InMemoryDataStore() ); } protected override Task<int> FetchAsync( CancellationToken cancellationToken ) { return Task.FromResult( 0 ); } } [Fact] public void EnablingCacheTwiceFails() { Assert.Throws<InvalidOperationException>( () => new DataSourceEnablingCacheTwice() ); } } public sealed class WithTransformAndCache { private sealed class IntDataSource : DataSource<int> { public Func<CancellationToken, Task<int>> Fetch; public Func<int, Task<int>> Transformer; public IntDataSource( Func<CancellationToken, Task<int>> fetch, Func<int, Task<int>> transformer, Func<CacheMetadata> metadataCreator ) { Fetch = fetch; Transformer = transformer; EnableCache( "X", new InMemoryDataStore(), metadataCreator ); } public new Task UpdateValueAsync() => base.UpdateValueAsync(); protected override Task<int> FetchAsync( CancellationToken cancellationToken ) => Fetch( cancellationToken ); protected override Task<int> TransformAsync( int value ) => Transformer( value ); } [Fact] public async Task FailedRefreshAfterSuccessfulOne() { var source = new IntDataSource( _ => Task.FromResult( 21 ), n => Task.FromResult( n * 2 ), null ); await source.RefreshAsync(); var ex = new MyException(); source.Fetch = _ => TaskEx.FromException<int>( ex ); await source.RefreshAsync(); Assert.Equal( new DataChunk<int>( 42, DataStatus.Cached, new DataErrors( ex, null, null ) ), source.Data ); Assert.Equal( DataSourceStatus.Loaded, source.Status ); } } } }
// 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.Threading; using System.Threading.Tasks; using Internal.Runtime.CompilerServices; using System.Diagnostics.CodeAnalysis; namespace System.Runtime.CompilerServices { /// <summary> /// Provides a builder for asynchronous methods that return <see cref="System.Threading.Tasks.Task{TResult}"/>. /// This type is intended for compiler use only. /// </summary> /// <remarks> /// AsyncTaskMethodBuilder{TResult} is a value type, and thus it is copied by value. /// Prior to being copied, one of its Task, SetResult, or SetException members must be accessed, /// or else the copies may end up building distinct Task instances. /// </remarks> public struct AsyncTaskMethodBuilder<TResult> { /// <summary>A cached task for default(TResult).</summary> internal static readonly Task<TResult> s_defaultResultTask = AsyncTaskCache.CreateCacheableTask<TResult>(default); /// <summary>The lazily-initialized built task.</summary> private Task<TResult> m_task; // lazily-initialized: must not be readonly. Debugger depends on the exact name of this field. /// <summary>Initializes a new <see cref="AsyncTaskMethodBuilder"/>.</summary> /// <returns>The initialized <see cref="AsyncTaskMethodBuilder"/>.</returns> public static AsyncTaskMethodBuilder<TResult> Create() { // NOTE: If this method is ever updated to perform more initialization, // other Create methods like AsyncTaskMethodBuilder.Create and // AsyncValueTaskMethodBuilder.Create must be updated to call this. return default; } /// <summary>Initiates the builder's execution with the associated state machine.</summary> /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> /// <param name="stateMachine">The state machine instance, passed by reference.</param> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine => AsyncMethodBuilderCore.Start(ref stateMachine); /// <summary>Associates the builder with the state machine it represents.</summary> /// <param name="stateMachine">The heap-allocated state machine object.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="stateMachine"/> argument was null (Nothing in Visual Basic).</exception> /// <exception cref="System.InvalidOperationException">The builder is incorrectly initialized.</exception> public void SetStateMachine(IAsyncStateMachine stateMachine) => AsyncMethodBuilderCore.SetStateMachine(stateMachine, m_task); /// <summary> /// Schedules the specified state machine to be pushed forward when the specified awaiter completes. /// </summary> /// <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam> /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> /// <param name="awaiter">The awaiter.</param> /// <param name="stateMachine">The state machine.</param> public void AwaitOnCompleted<TAwaiter, TStateMachine>( ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { try { awaiter.OnCompleted(GetStateMachineBox(ref stateMachine).MoveNextAction); } catch (Exception e) { System.Threading.Tasks.Task.ThrowAsync(e, targetContext: null); } } /// <summary> /// Schedules the specified state machine to be pushed forward when the specified awaiter completes. /// </summary> /// <typeparam name="TAwaiter">Specifies the type of the awaiter.</typeparam> /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> /// <param name="awaiter">The awaiter.</param> /// <param name="stateMachine">The state machine.</param> // AggressiveOptimization to workaround boxing allocations in Tier0 until: https://github.com/dotnet/coreclr/issues/14474 [MethodImpl(MethodImplOptions.AggressiveOptimization)] public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>( ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { IAsyncStateMachineBox box = GetStateMachineBox(ref stateMachine); // The null tests here ensure that the jit can optimize away the interface // tests when TAwaiter is a ref type. if ((null != (object)default(TAwaiter)!) && (awaiter is ITaskAwaiter)) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { ref TaskAwaiter ta = ref Unsafe.As<TAwaiter, TaskAwaiter>(ref awaiter); // relies on TaskAwaiter/TaskAwaiter<T> having the same layout TaskAwaiter.UnsafeOnCompletedInternal(ta.m_task, box, continueOnCapturedContext: true); } else if ((null != (object)default(TAwaiter)!) && (awaiter is IConfiguredTaskAwaiter)) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { ref ConfiguredTaskAwaitable.ConfiguredTaskAwaiter ta = ref Unsafe.As<TAwaiter, ConfiguredTaskAwaitable.ConfiguredTaskAwaiter>(ref awaiter); TaskAwaiter.UnsafeOnCompletedInternal(ta.m_task, box, ta.m_continueOnCapturedContext); } else if ((null != (object)default(TAwaiter)!) && (awaiter is IStateMachineBoxAwareAwaiter)) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { try { ((IStateMachineBoxAwareAwaiter)awaiter).AwaitUnsafeOnCompleted(box); } catch (Exception e) { // Whereas with Task the code that hooks up and invokes the continuation is all local to corelib, // with ValueTaskAwaiter we may be calling out to an arbitrary implementation of IValueTaskSource // wrapped in the ValueTask, and as such we protect against errant exceptions that may emerge. // We don't want such exceptions propagating back into the async method, which can't handle // exceptions well at that location in the state machine, especially if the exception may occur // after the ValueTaskAwaiter already successfully hooked up the callback, in which case it's possible // two different flows of execution could end up happening in the same async method call. System.Threading.Tasks.Task.ThrowAsync(e, targetContext: null); } } else { // The awaiter isn't specially known. Fall back to doing a normal await. try { awaiter.UnsafeOnCompleted(box.MoveNextAction); } catch (Exception e) { System.Threading.Tasks.Task.ThrowAsync(e, targetContext: null); } } } /// <summary>Gets the "boxed" state machine object.</summary> /// <typeparam name="TStateMachine">Specifies the type of the async state machine.</typeparam> /// <param name="stateMachine">The state machine.</param> /// <returns>The "boxed" state machine.</returns> private IAsyncStateMachineBox GetStateMachineBox<TStateMachine>( ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { ExecutionContext? currentContext = ExecutionContext.Capture(); // Check first for the most common case: not the first yield in an async method. // In this case, the first yield will have already "boxed" the state machine in // a strongly-typed manner into an AsyncStateMachineBox. It will already contain // the state machine as well as a MoveNextDelegate and a context. The only thing // we might need to do is update the context if that's changed since it was stored. if (m_task is AsyncStateMachineBox<TStateMachine> stronglyTypedBox) { if (stronglyTypedBox.Context != currentContext) { stronglyTypedBox.Context = currentContext; } return stronglyTypedBox; } // The least common case: we have a weakly-typed boxed. This results if the debugger // or some other use of reflection accesses a property like ObjectIdForDebugger or a // method like SetNotificationForWaitCompletion prior to the first await happening. In // such situations, we need to get an object to represent the builder, but we don't yet // know the type of the state machine, and thus can't use TStateMachine. Instead, we // use the IAsyncStateMachine interface, which all TStateMachines implement. This will // result in a boxing allocation when storing the TStateMachine if it's a struct, but // this only happens in active debugging scenarios where such performance impact doesn't // matter. if (m_task is AsyncStateMachineBox<IAsyncStateMachine> weaklyTypedBox) { // If this is the first await, we won't yet have a state machine, so store it. if (weaklyTypedBox.StateMachine == null) { Debugger.NotifyOfCrossThreadDependency(); // same explanation as with usage below weaklyTypedBox.StateMachine = stateMachine; } // Update the context. This only happens with a debugger, so no need to spend // extra IL checking for equality before doing the assignment. weaklyTypedBox.Context = currentContext; return weaklyTypedBox; } // Alert a listening debugger that we can't make forward progress unless it slips threads. // If we don't do this, and a method that uses "await foo;" is invoked through funceval, // we could end up hooking up a callback to push forward the async method's state machine, // the debugger would then abort the funceval after it takes too long, and then continuing // execution could result in another callback being hooked up. At that point we have // multiple callbacks registered to push the state machine, which could result in bad behavior. Debugger.NotifyOfCrossThreadDependency(); // At this point, m_task should really be null, in which case we want to create the box. // However, in a variety of debugger-related (erroneous) situations, it might be non-null, // e.g. if the Task property is examined in a Watch window, forcing it to be lazily-intialized // as a Task<TResult> rather than as an AsyncStateMachineBox. The worst that happens in such // cases is we lose the ability to properly step in the debugger, as the debugger uses that // object's identity to track this specific builder/state machine. As such, we proceed to // overwrite whatever's there anyway, even if it's non-null. #if CORERT // DebugFinalizableAsyncStateMachineBox looks like a small type, but it actually is not because // it will have a copy of all the slots from its parent. It will add another hundred(s) bytes // per each async method in CoreRT / ProjectN binaries without adding much value. Avoid // generating this extra code until a better solution is implemented. var box = new AsyncStateMachineBox<TStateMachine>(); #else AsyncStateMachineBox<TStateMachine> box = AsyncMethodBuilderCore.TrackAsyncMethodCompletion ? CreateDebugFinalizableAsyncStateMachineBox<TStateMachine>() : new AsyncStateMachineBox<TStateMachine>(); #endif m_task = box; // important: this must be done before storing stateMachine into box.StateMachine! box.StateMachine = stateMachine; box.Context = currentContext; // Log the creation of the state machine box object / task for this async method. if (AsyncCausalityTracer.LoggingOn) { AsyncCausalityTracer.TraceOperationCreation(box, "Async: " + stateMachine.GetType().Name); } // And if async debugging is enabled, track the task. if (System.Threading.Tasks.Task.s_asyncDebuggingEnabled) { System.Threading.Tasks.Task.AddToActiveTasks(box); } return box; } #if !CORERT // Avoid forcing the JIT to build DebugFinalizableAsyncStateMachineBox<TStateMachine> unless it's actually needed. [MethodImpl(MethodImplOptions.NoInlining)] private static AsyncStateMachineBox<TStateMachine> CreateDebugFinalizableAsyncStateMachineBox<TStateMachine>() where TStateMachine : IAsyncStateMachine => new DebugFinalizableAsyncStateMachineBox<TStateMachine>(); /// <summary> /// Provides an async state machine box with a finalizer that will fire an EventSource /// event about the state machine if it's being finalized without having been completed. /// </summary> /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> private sealed class DebugFinalizableAsyncStateMachineBox<TStateMachine> : // SOS DumpAsync command depends on this name AsyncStateMachineBox<TStateMachine> where TStateMachine : IAsyncStateMachine { ~DebugFinalizableAsyncStateMachineBox() { // If the state machine is being finalized, something went wrong during its processing, // e.g. it awaited something that got collected without itself having been completed. // Fire an event with details about the state machine to help with debugging. if (!IsCompleted) // double-check it's not completed, just to help minimize false positives { TplEventSource.Log.IncompleteAsyncMethod(this); } } } #endif /// <summary>A strongly-typed box for Task-based async state machines.</summary> /// <typeparam name="TStateMachine">Specifies the type of the state machine.</typeparam> private class AsyncStateMachineBox<TStateMachine> : // SOS DumpAsync command depends on this name Task<TResult>, IAsyncStateMachineBox where TStateMachine : IAsyncStateMachine { /// <summary>Delegate used to invoke on an ExecutionContext when passed an instance of this box type.</summary> private static readonly ContextCallback s_callback = ExecutionContextCallback; // Used to initialize s_callback above. We don't use a lambda for this on purpose: a lambda would // introduce a new generic type behind the scenes that comes with a hefty size penalty in AOT builds. private static void ExecutionContextCallback(object? s) { Debug.Assert(s is AsyncStateMachineBox<TStateMachine>); // Only used privately to pass directly to EC.Run Unsafe.As<AsyncStateMachineBox<TStateMachine>>(s).StateMachine!.MoveNext(); } /// <summary>A delegate to the <see cref="MoveNext()"/> method.</summary> private Action? _moveNextAction; /// <summary>The state machine itself.</summary> [AllowNull, MaybeNull] public TStateMachine StateMachine = default; // mutable struct; do not make this readonly. SOS DumpAsync command depends on this name. /// <summary>Captured ExecutionContext with which to invoke <see cref="MoveNextAction"/>; may be null.</summary> public ExecutionContext? Context; /// <summary>A delegate to the <see cref="MoveNext()"/> method.</summary> public Action MoveNextAction => _moveNextAction ??= new Action(MoveNext); internal sealed override void ExecuteFromThreadPool(Thread threadPoolThread) => MoveNext(threadPoolThread); /// <summary>Calls MoveNext on <see cref="StateMachine"/></summary> public void MoveNext() => MoveNext(threadPoolThread: null); private void MoveNext(Thread? threadPoolThread) { Debug.Assert(!IsCompleted); bool loggingOn = AsyncCausalityTracer.LoggingOn; if (loggingOn) { AsyncCausalityTracer.TraceSynchronousWorkStart(this, CausalitySynchronousWork.Execution); } ExecutionContext? context = Context; if (context == null) { Debug.Assert(StateMachine != null); StateMachine.MoveNext(); } else { if (threadPoolThread is null) { ExecutionContext.RunInternal(context, s_callback, this); } else { ExecutionContext.RunFromThreadPoolDispatchLoop(threadPoolThread, context, s_callback, this); } } if (IsCompleted) { // If async debugging is enabled, remove the task from tracking. if (System.Threading.Tasks.Task.s_asyncDebuggingEnabled) { System.Threading.Tasks.Task.RemoveFromActiveTasks(this); } // Clear out state now that the async method has completed. // This avoids keeping arbitrary state referenced by lifted locals // if this Task / state machine box is held onto. StateMachine = default; Context = default; #if !CORERT // In case this is a state machine box with a finalizer, suppress its finalization // as it's now complete. We only need the finalizer to run if the box is collected // without having been completed. if (AsyncMethodBuilderCore.TrackAsyncMethodCompletion) { GC.SuppressFinalize(this); } #endif } if (loggingOn) { AsyncCausalityTracer.TraceSynchronousWorkCompletion(CausalitySynchronousWork.Execution); } } /// <summary>Gets the state machine as a boxed object. This should only be used for debugging purposes.</summary> IAsyncStateMachine IAsyncStateMachineBox.GetStateMachineObject() => StateMachine!; // likely boxes, only use for debugging } /// <summary>Gets the <see cref="System.Threading.Tasks.Task{TResult}"/> for this builder.</summary> /// <returns>The <see cref="System.Threading.Tasks.Task{TResult}"/> representing the builder's asynchronous operation.</returns> public Task<TResult> Task { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => m_task ?? InitializeTaskAsPromise(); } /// <summary> /// Initializes the task, which must not yet be initialized. Used only when the Task is being forced into /// existence when no state machine is needed, e.g. when the builder is being synchronously completed with /// an exception, when the builder is being used out of the context of an async method, etc. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] private Task<TResult> InitializeTaskAsPromise() { Debug.Assert(m_task == null); return m_task = new Task<TResult>(); } /// <summary> /// Initializes the task, which must not yet be initialized. Used only when the Task is being forced into /// existence due to the debugger trying to enable step-out/step-over/etc. prior to the first await yielding /// in an async method. In that case, we don't know the actual TStateMachine type, so we're forced to /// use IAsyncStateMachine instead. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] private Task<TResult> InitializeTaskAsStateMachineBox() { Debug.Assert(m_task == null); #if CORERT // DebugFinalizableAsyncStateMachineBox looks like a small type, but it actually is not because // it will have a copy of all the slots from its parent. It will add another hundred(s) bytes // per each async method in CoreRT / ProjectN binaries without adding much value. Avoid // generating this extra code until a better solution is implemented. return (m_task = new AsyncStateMachineBox<IAsyncStateMachine>()); #else return m_task = AsyncMethodBuilderCore.TrackAsyncMethodCompletion ? CreateDebugFinalizableAsyncStateMachineBox<IAsyncStateMachine>() : new AsyncStateMachineBox<IAsyncStateMachine>(); #endif } /// <summary> /// Completes the <see cref="System.Threading.Tasks.Task{TResult}"/> in the /// <see cref="System.Threading.Tasks.TaskStatus">RanToCompletion</see> state with the specified result. /// </summary> /// <param name="result">The result to use to complete the task.</param> /// <exception cref="System.InvalidOperationException">The task has already completed.</exception> public void SetResult(TResult result) { // Get the currently stored task, which will be non-null if get_Task has already been accessed. // If there isn't one, get a task and store it. if (m_task == null) { m_task = GetTaskForResult(result); Debug.Assert(m_task != null, $"{nameof(GetTaskForResult)} should never return null"); } else { // Slow path: complete the existing task. SetExistingTaskResult(result); } } /// <summary>Completes the already initialized task with the specified result.</summary> /// <param name="result">The result to use to complete the task.</param> private void SetExistingTaskResult([AllowNull] TResult result) { Debug.Assert(m_task != null, "Expected non-null task"); if (AsyncCausalityTracer.LoggingOn) { AsyncCausalityTracer.TraceOperationCompletion(m_task, AsyncCausalityStatus.Completed); } if (!m_task.TrySetResult(result)) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.TaskT_TransitionToFinal_AlreadyCompleted); } } /// <summary> /// Completes the builder by using either the supplied completed task, or by completing /// the builder's previously accessed task using default(TResult). /// </summary> /// <param name="completedTask">A task already completed with the value default(TResult).</param> /// <exception cref="System.InvalidOperationException">The task has already completed.</exception> internal void SetResult(Task<TResult> completedTask) { Debug.Assert(completedTask != null, "Expected non-null task"); Debug.Assert(completedTask.IsCompletedSuccessfully, "Expected a successfully completed task"); // Get the currently stored task, which will be non-null if get_Task has already been accessed. // If there isn't one, store the supplied completed task. if (m_task == null) { m_task = completedTask; } else { // Otherwise, complete the task that's there. SetExistingTaskResult(default!); // Remove ! when nullable attributes are respected } } /// <summary> /// Completes the <see cref="System.Threading.Tasks.Task{TResult}"/> in the /// <see cref="System.Threading.Tasks.TaskStatus">Faulted</see> state with the specified exception. /// </summary> /// <param name="exception">The <see cref="System.Exception"/> to use to fault the task.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="exception"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.InvalidOperationException">The task has already completed.</exception> public void SetException(Exception exception) { if (exception == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.exception); } // Get the task, forcing initialization if it hasn't already been initialized. Task<TResult> task = this.Task; // If the exception represents cancellation, cancel the task. Otherwise, fault the task. bool successfullySet = exception is OperationCanceledException oce ? task.TrySetCanceled(oce.CancellationToken, oce) : task.TrySetException(exception); // Unlike with TaskCompletionSource, we do not need to spin here until _taskAndStateMachine is completed, // since AsyncTaskMethodBuilder.SetException should not be immediately followed by any code // that depends on the task having completely completed. Moreover, with correct usage, // SetResult or SetException should only be called once, so the Try* methods should always // return true, so no spinning would be necessary anyway (the spinning in TCS is only relevant // if another thread completes the task first). if (!successfullySet) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.TaskT_TransitionToFinal_AlreadyCompleted); } } /// <summary> /// Called by the debugger to request notification when the first wait operation /// (await, Wait, Result, etc.) on this builder's task completes. /// </summary> /// <param name="enabled"> /// true to enable notification; false to disable a previously set notification. /// </param> /// <remarks> /// This should only be invoked from within an asynchronous method, /// and only by the debugger. /// </remarks> internal void SetNotificationForWaitCompletion(bool enabled) { // Get the task (forcing initialization if not already initialized), and set debug notification (m_task ?? InitializeTaskAsStateMachineBox()).SetNotificationForWaitCompletion(enabled); // NOTE: It's important that the debugger use builder.SetNotificationForWaitCompletion // rather than builder.Task.SetNotificationForWaitCompletion. Even though the latter will // lazily-initialize the task as well, it'll initialize it to a Task<T> (which is important // to minimize size for cases where an ATMB is used directly by user code to avoid the // allocation overhead of a TaskCompletionSource). If that's done prior to the first await, // the GetMoveNextDelegate code, which needs an AsyncStateMachineBox, will end up creating // a new box and overwriting the previously created task. That'll change the object identity // of the task being used for wait completion notification, and no notification will // ever arrive, breaking step-out behavior when stepping out before the first yielding await. } /// <summary> /// Gets an object that may be used to uniquely identify this builder to the debugger. /// </summary> /// <remarks> /// This property lazily instantiates the ID in a non-thread-safe manner. /// It must only be used by the debugger and tracing purposes, and only in a single-threaded manner /// when no other threads are in the middle of accessing this or other members that lazily initialize the task. /// </remarks> internal object ObjectIdForDebugger => m_task ?? InitializeTaskAsStateMachineBox(); /// <summary> /// Gets a task for the specified result. This will either /// be a cached or new task, never null. /// </summary> /// <param name="result">The result for which we need a task.</param> /// <returns>The completed task containing the result.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] // method looks long, but for a given TResult it results in a relatively small amount of asm internal static Task<TResult> GetTaskForResult(TResult result) { // The goal of this function is to be give back a cached task if possible, // or to otherwise give back a new task. To give back a cached task, // we need to be able to evaluate the incoming result value, and we need // to avoid as much overhead as possible when doing so, as this function // is invoked as part of the return path from every async method. // Most tasks won't be cached, and thus we need the checks for those that are // to be as close to free as possible. This requires some trickiness given the // lack of generic specialization in .NET. // // Be very careful when modifying this code. It has been tuned // to comply with patterns recognized by both 32-bit and 64-bit JITs. // If changes are made here, be sure to look at the generated assembly, as // small tweaks can have big consequences for what does and doesn't get optimized away. // // Note that this code only ever accesses a static field when it knows it'll // find a cached value, since static fields (even if readonly and integral types) // require special access helpers in this NGEN'd and domain-neutral. if (null != (object)default(TResult)!) // help the JIT avoid the value type branches for ref types // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { // Special case simple value types: // - Boolean // - Byte, SByte // - Char // - Int32, UInt32 // - Int64, UInt64 // - Int16, UInt16 // - IntPtr, UIntPtr // As of .NET 4.5, the (Type)(object)result pattern used below // is recognized and optimized by both 32-bit and 64-bit JITs. // For Boolean, we cache all possible values. if (typeof(TResult) == typeof(bool)) // only the relevant branches are kept for each value-type generic instantiation { bool value = (bool)(object)result!; Task<bool> task = value ? AsyncTaskCache.s_trueTask : AsyncTaskCache.s_falseTask; return Unsafe.As<Task<TResult>>(task); // UnsafeCast avoids type check we know will succeed } // For Int32, we cache a range of common values, e.g. [-1,9). else if (typeof(TResult) == typeof(int)) { // Compare to constants to avoid static field access if outside of cached range. // We compare to the upper bound first, as we're more likely to cache miss on the upper side than on the // lower side, due to positive values being more common than negative as return values. int value = (int)(object)result!; if (value < AsyncTaskCache.ExclusiveInt32Max && value >= AsyncTaskCache.InclusiveInt32Min) { Task<int> task = AsyncTaskCache.s_int32Tasks[value - AsyncTaskCache.InclusiveInt32Min]; return Unsafe.As<Task<TResult>>(task); // UnsafeCast avoids a type check we know will succeed } } // For other known value types, we only special-case 0 / default(TResult). else if ( (typeof(TResult) == typeof(uint) && default == (uint)(object)result!) || (typeof(TResult) == typeof(byte) && default(byte) == (byte)(object)result!) || (typeof(TResult) == typeof(sbyte) && default(sbyte) == (sbyte)(object)result!) || (typeof(TResult) == typeof(char) && default(char) == (char)(object)result!) || (typeof(TResult) == typeof(long) && default == (long)(object)result!) || (typeof(TResult) == typeof(ulong) && default == (ulong)(object)result!) || (typeof(TResult) == typeof(short) && default(short) == (short)(object)result!) || (typeof(TResult) == typeof(ushort) && default(ushort) == (ushort)(object)result!) || (typeof(TResult) == typeof(IntPtr) && default == (IntPtr)(object)result!) || (typeof(TResult) == typeof(UIntPtr) && default == (UIntPtr)(object)result!)) { return s_defaultResultTask; } } else if (result == null) // optimized away for value types { return s_defaultResultTask; } // No cached task is available. Manufacture a new one for this result. return new Task<TResult>(result); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using System.Text; using Microsoft.Xunit.Performance; using Xunit; namespace System.Buffers.Text.Tests { public static partial class Utf8ParserTests { private const int InnerCount = 100_000; private static readonly string[] s_UInt32TextArray = new string[10] { "42", "429496", "429496729", "42949", "4", "42949672", "4294", "429", "4294967295", "4294967" }; private static readonly string[] s_UInt32TextArrayHex = new string[8] { "A2", "A29496", "A2949", "A", "A2949672", "A294", "A29", "A294967" }; private static readonly string[] s_Int16TextArray = new string[13] { "21474", "2", "-21474", "31484", "-21", "-2", "214", "2147", "-2147", "-9345", "9345", "1000", "-214" }; private static readonly string[] s_Int32TextArray = new string[20] { "214748364", "2", "21474836", "-21474", "21474", "-21", "-2", "214", "-21474836", "-214748364", "2147", "-2147", "-214748", "-2147483", "214748", "-2147483648", "2147483647", "21", "2147483", "-214" }; private static readonly string[] s_SByteTextArray = new string[17] { "95", "2", "112", "-112", "-21", "-2", "114", "-114", "-124", "117", "-117", "-14", "14", "74", "21", "83", "-127" }; [Benchmark(InnerIterationCount = InnerCount)] [InlineData("2134567890")] // standard parse [InlineData("18446744073709551615")] // max value [InlineData("0")] // min value [InlineData("000000000000000000001235abcdfg")] [InlineData("21474836abcdefghijklmnop")] private static void StringToUInt64_Baseline(string text) { foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { ulong.TryParse(text, out ulong value); TestHelpers.DoNotIgnore(value, 0); } } } } [Benchmark(InnerIterationCount = InnerCount)] [InlineData("abcdef")] // standard parse [InlineData("ffffffffffffffff")] // max value [InlineData("0")] // min value private static void StringToUInt64Hex_Baseline(string text) { foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { ulong.TryParse(text, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ulong value); TestHelpers.DoNotIgnore(value, 0); } } } } [Benchmark(InnerIterationCount = InnerCount)] [InlineData("2134567890")] // standard parse [InlineData("18446744073709551615")] // max value [InlineData("0")] // min value [InlineData("000000000000000000001235abcdfg")] [InlineData("21474836abcdefghijklmnop")] private static void ByteSpanToUInt64(string text) { byte[] utf8ByteArray = Encoding.UTF8.GetBytes(text); ReadOnlySpan<byte> utf8ByteSpan = new ReadOnlySpan<byte>(utf8ByteArray); foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { Utf8Parser.TryParse(utf8ByteSpan, out ulong value, out int bytesConsumed); TestHelpers.DoNotIgnore(value, bytesConsumed); } } } } [Benchmark(InnerIterationCount = InnerCount)] [InlineData("abcdef")] // standard parse [InlineData("ffffffffffffffff")] // max value [InlineData("0")] // min value private static void ByteSpanToUInt64Hex(string text) { byte[] utf8ByteArray = Encoding.UTF8.GetBytes(text); ReadOnlySpan<byte> utf8ByteSpan = new ReadOnlySpan<byte>(utf8ByteArray); foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { Utf8Parser.TryParse(utf8ByteSpan, out ulong value, out int bytesConsumed, 'X'); TestHelpers.DoNotIgnore(value, bytesConsumed); } } } } [Benchmark(InnerIterationCount = InnerCount)] [InlineData("2134567890")] // standard parse [InlineData("4294967295")] // max value [InlineData("0")] // min value [InlineData("000000000000000000001235abcdfg")] [InlineData("21474836abcdefghijklmnop")] private static void StringToUInt32_Baseline(string text) { foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { uint.TryParse(text, out uint value); TestHelpers.DoNotIgnore(value, 0); } } } } [Benchmark(InnerIterationCount = InnerCount)] private static void StringToUInt32_VariableLength_Baseline() { foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { uint.TryParse(s_UInt32TextArray[i % 10], out uint value); TestHelpers.DoNotIgnore(value, 0); } } } } [Benchmark(InnerIterationCount = InnerCount)] [InlineData("abcdef")] // standard parse [InlineData("ffffffff")] // max value [InlineData("0")] // min value private static void StringToUInt32Hex_Baseline(string text) { foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { uint.TryParse(text, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint value); TestHelpers.DoNotIgnore(value, 0); } } } } [Benchmark(InnerIterationCount = InnerCount)] private static void StringToUInt32Hex_VariableLength() { int textLength = s_UInt32TextArrayHex.Length; foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { string text = s_UInt32TextArrayHex[i % textLength]; uint.TryParse(text, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint value); TestHelpers.DoNotIgnore(value, 0); } } } } [Benchmark(InnerIterationCount = InnerCount)] [InlineData("2134567890")] // standard parse [InlineData("4294967295")] // max value [InlineData("0")] // min value [InlineData("000000000000000000001235abcdfg")] [InlineData("21474836abcdefghijklmnop")] private static void ByteSpanToUInt32(string text) { byte[] utf8ByteArray = Encoding.UTF8.GetBytes(text); var utf8ByteSpan = new ReadOnlySpan<byte>(utf8ByteArray); foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { Utf8Parser.TryParse(utf8ByteSpan, out uint value, out int bytesConsumed); TestHelpers.DoNotIgnore(value, bytesConsumed); } } } } [Benchmark(InnerIterationCount = InnerCount)] private static void ByteSpanToUInt32_VariableLength() { int textLength = s_UInt32TextArray.Length; byte[][] utf8ByteArray = (byte[][])Array.CreateInstance(typeof(byte[]), textLength); for (var i = 0; i < textLength; i++) { utf8ByteArray[i] = Encoding.UTF8.GetBytes(s_UInt32TextArray[i]); } foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { ReadOnlySpan<byte> utf8ByteSpan = utf8ByteArray[i % textLength]; Utf8Parser.TryParse(utf8ByteSpan, out uint value, out int bytesConsumed); TestHelpers.DoNotIgnore(value, bytesConsumed); } } } } [Benchmark(InnerIterationCount = InnerCount)] [InlineData("abcdef")] // standard parse [InlineData("ffffffff")] // max value [InlineData("0")] // min value private static void ByteSpanToUInt32Hex(string text) { byte[] utf8ByteArray = Encoding.UTF8.GetBytes(text); var utf8ByteSpan = new ReadOnlySpan<byte>(utf8ByteArray); foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { Utf8Parser.TryParse(utf8ByteSpan, out uint value, out int bytesConsumed, 'X'); TestHelpers.DoNotIgnore(value, bytesConsumed); } } } } [Benchmark(InnerIterationCount = InnerCount)] private static void ByteSpanToUInt32Hex_VariableLength() { int textLength = s_UInt32TextArrayHex.Length; byte[][] utf8ByteArray = (byte[][])Array.CreateInstance(typeof(byte[]), textLength); for (var i = 0; i < textLength; i++) { utf8ByteArray[i] = Encoding.UTF8.GetBytes(s_UInt32TextArrayHex[i]); } foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { ReadOnlySpan<byte> utf8ByteSpan = utf8ByteArray[i % textLength]; Utf8Parser.TryParse(utf8ByteSpan, out uint value, out int bytesConsumed, 'X'); TestHelpers.DoNotIgnore(value, bytesConsumed); } } } } [Benchmark(InnerIterationCount = InnerCount)] private static void ByteSpanToSByte_VariableLength() { int textLength = s_SByteTextArray.Length; byte[][] utf8ByteArray = (byte[][])Array.CreateInstance(typeof(byte[]), textLength); for (var i = 0; i < textLength; i++) { utf8ByteArray[i] = Encoding.UTF8.GetBytes(s_SByteTextArray[i]); } foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { ReadOnlySpan<byte> utf8ByteSpan = utf8ByteArray[i % textLength]; Utf8Parser.TryParse(utf8ByteSpan, out sbyte value, out int bytesConsumed); TestHelpers.DoNotIgnore(value, bytesConsumed); } } } } [Benchmark(InnerIterationCount = InnerCount)] [InlineData("0")] [InlineData("107")] // standard parse [InlineData("127")] // max value [InlineData("-128")] // min value [InlineData("-21abcdefghijklmnop")] [InlineData("21abcdefghijklmnop")] [InlineData("00000000000000000000123")] private static void StringToSByte_Baseline(string text) { foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { sbyte.TryParse(text, out sbyte value); TestHelpers.DoNotIgnore(value, 0); } } } } [Benchmark(InnerIterationCount = InnerCount)] private static void StringToSByte_VariableLength_Baseline() { int textLength = s_SByteTextArray.Length; byte[][] utf8ByteArray = (byte[][])Array.CreateInstance(typeof(byte[]), textLength); for (var i = 0; i < textLength; i++) { utf8ByteArray[i] = Encoding.UTF8.GetBytes(s_SByteTextArray[i]); } foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { sbyte.TryParse(s_SByteTextArray[i % textLength], out sbyte value); TestHelpers.DoNotIgnore(value, 0); } } } } [Benchmark(InnerIterationCount = InnerCount)] [InlineData("0")] [InlineData("107374182")] // standard parse [InlineData("2147483647")] // max value [InlineData("-2147483648")] // min value [InlineData("000000000000000000001235abcdfg")] [InlineData("21474836abcdefghijklmnop")] [InlineData("-21474abcdefghijklmnop")] private static void ByteSpanToInt32(string text) { byte[] utf8ByteArray = Encoding.UTF8.GetBytes(text); var utf8ByteSpan = new ReadOnlySpan<byte>(utf8ByteArray); foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { Utf8Parser.TryParse(utf8ByteSpan, out int value, out int bytesConsumed); TestHelpers.DoNotIgnore(value, bytesConsumed); } } } } [Benchmark(InnerIterationCount = InnerCount)] private static void ByteSpanToInt32_VariableLength() { int textLength = s_Int32TextArray.Length; byte[][] utf8ByteArray = (byte[][])Array.CreateInstance(typeof(byte[]), textLength); for (var i = 0; i < textLength; i++) { utf8ByteArray[i] = Encoding.UTF8.GetBytes(s_Int32TextArray[i]); } foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { ReadOnlySpan<byte> utf8ByteSpan = utf8ByteArray[i % textLength]; Utf8Parser.TryParse(utf8ByteSpan, out int value, out int bytesConsumed); TestHelpers.DoNotIgnore(value, bytesConsumed); } } } } [Benchmark(InnerIterationCount = InnerCount)] [InlineData("0")] [InlineData("107374182")] // standard parse [InlineData("2147483647")] // max value [InlineData("-2147483648")] // min value [InlineData("000000000000000000001235abcdfg")] [InlineData("21474836abcdefghijklmnop")] [InlineData("-21474abcdefghijklmnop")] private static void StringToInt32_Baseline(string text) { foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { int.TryParse(text, out int value); TestHelpers.DoNotIgnore(value, 0); } } } } [Benchmark(InnerIterationCount = InnerCount)] private static void StringToInt32_VariableLength_Baseline() { int textLength = s_Int32TextArray.Length; byte[][] utf8ByteArray = (byte[][])Array.CreateInstance(typeof(byte[]), textLength); for (var i = 0; i < textLength; i++) { utf8ByteArray[i] = Encoding.UTF8.GetBytes(s_Int32TextArray[i]); } foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { int.TryParse(s_Int32TextArray[i % textLength], out int value); TestHelpers.DoNotIgnore(value, 0); } } } } [Benchmark(InnerIterationCount = InnerCount)] private static void ByteSpanToInt16_VariableLength() { int textLength = s_Int16TextArray.Length; byte[][] utf8ByteArray = (byte[][])Array.CreateInstance(typeof(byte[]), textLength); for (var i = 0; i < textLength; i++) { utf8ByteArray[i] = Encoding.UTF8.GetBytes(s_Int16TextArray[i]); } foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { ReadOnlySpan<byte> utf8ByteSpan = utf8ByteArray[i % textLength]; Utf8Parser.TryParse(utf8ByteSpan, out short value, out int bytesConsumed); TestHelpers.DoNotIgnore(value, bytesConsumed); } } } } [Benchmark(InnerIterationCount = InnerCount)] [InlineData("0")] [InlineData("10737")] // standard parse [InlineData("32767")] // max value [InlineData("-32768")] // min value [InlineData("000000000000000000001235abcdfg")] private static void StringToInt16_Baseline(string text) { foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { short.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out short value); TestHelpers.DoNotIgnore(value, 0); } } } } [Benchmark(InnerIterationCount = InnerCount)] private static void StringToInt16_VariableLength_Baseline() { int textLength = s_Int16TextArray.Length; byte[][] utf8ByteArray = (byte[][])Array.CreateInstance(typeof(byte[]), textLength); for (var i = 0; i < textLength; i++) { utf8ByteArray[i] = Encoding.UTF8.GetBytes(s_Int16TextArray[i]); } foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { short.TryParse(s_Int16TextArray[i % textLength], out short value); TestHelpers.DoNotIgnore(value, 0); } } } } [Benchmark(InnerIterationCount = InnerCount)] [InlineData("True")] [InlineData("False")] private static void StringToBool_Baseline(string text) { foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { bool.TryParse(text, out bool value); } } } } [Benchmark(InnerIterationCount = InnerCount)] [InlineData("True")] [InlineData("False")] private static void BytesSpanToBool(string text) { byte[] utf8ByteArray = Encoding.UTF8.GetBytes(text); ReadOnlySpan<byte> utf8ByteSpan = utf8ByteArray; foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { Utf8Parser.TryParse(utf8ByteSpan, out bool value, out int bytesConsumed); TestHelpers.DoNotIgnore(value, bytesConsumed); } } } } [Benchmark(InnerIterationCount = InnerCount)] [InlineData("0")] [InlineData("107")] // standard parse [InlineData("127")] // max value [InlineData("-128")] // min value [InlineData("-21abcdefghijklmnop")] [InlineData("21abcdefghijklmnop")] [InlineData("00000000000000000000123")] private static void ByteSpanToSByte(string text) { byte[] utf8ByteArray = Encoding.UTF8.GetBytes(text); ReadOnlySpan<byte> utf8ByteSpan = utf8ByteArray; foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { Utf8Parser.TryParse(utf8ByteSpan, out sbyte value, out int bytesConsumed); TestHelpers.DoNotIgnore(value, bytesConsumed); } } } } [Benchmark(InnerIterationCount = InnerCount)] [InlineData("42")] // standard parse [InlineData("0")] // min value [InlineData("255")] // max value private static void ByteSpanToByte(string text) { byte[] utf8ByteArray = Encoding.UTF8.GetBytes(text); ReadOnlySpan<byte> utf8ByteSpan = utf8ByteArray; foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { Utf8Parser.TryParse(utf8ByteSpan, out byte value, out int bytesConsumed); TestHelpers.DoNotIgnore(value, bytesConsumed); } } } } [Benchmark(InnerIterationCount = InnerCount)] [InlineData("42")] // standard parse [InlineData("0")] // min value [InlineData("255")] // max value private static void StringToByte_Baseline(string text) { byte[] utf8ByteArray = Encoding.UTF8.GetBytes(text); ReadOnlySpan<byte> utf8ByteSpan = utf8ByteArray; foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { byte.TryParse(text, out byte value); TestHelpers.DoNotIgnore(value, 0); } } } } [Benchmark(InnerIterationCount = InnerCount)] [InlineData("0")] [InlineData("4212")] // standard parse [InlineData("-32768")] // min value [InlineData("32767")] // max value [InlineData("000000000000000000001235abcdfg")] private static void ByteSpanToInt16(string text) { byte[] utf8ByteArray = Encoding.UTF8.GetBytes(text); ReadOnlySpan<byte> utf8ByteSpan = utf8ByteArray; foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { Utf8Parser.TryParse(utf8ByteSpan, out short value, out int bytesConsumed); TestHelpers.DoNotIgnore(value, bytesConsumed); } } } } [Benchmark(InnerIterationCount = InnerCount)] [InlineData("4212")] // standard parse [InlineData("0")] // min value [InlineData("65535")] // max value private static void ByteSpanToUInt16(string text) { byte[] utf8ByteArray = Encoding.UTF8.GetBytes(text); ReadOnlySpan<byte> utf8ByteSpan = utf8ByteArray; foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { Utf8Parser.TryParse(utf8ByteSpan, out ushort value, out int bytesConsumed); TestHelpers.DoNotIgnore(value, bytesConsumed); } } } } [Benchmark(InnerIterationCount = InnerCount)] [InlineData("12837467")] // standard parse [InlineData("-9223372036854775808")] // min value [InlineData("9223372036854775807")] // max value [InlineData("000000000000000000001235abcdfg")] [InlineData("21474836abcdefghijklmnop")] private static void ByteSpanToInt64(string text) { byte[] utf8ByteArray = Encoding.UTF8.GetBytes(text); ReadOnlySpan<byte> utf8ByteSpan = utf8ByteArray; foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { Utf8Parser.TryParse(utf8ByteSpan, out long value, out int bytesConsumed); TestHelpers.DoNotIgnore(value, bytesConsumed); } } } } [Benchmark(InnerIterationCount = InnerCount)] [InlineData("12837467")] // standard parse [InlineData("-9223372036854775808")] // min value [InlineData("9223372036854775807")] // max value [InlineData("000000000000000000001235abcdfg")] [InlineData("21474836abcdefghijklmnop")] private static void StringToInt64_Baseline(string text) { foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { long.TryParse(text, out long value); TestHelpers.DoNotIgnore(value, 0); } } } } [Benchmark(InnerIterationCount = InnerCount)] [InlineData("Fri, 30 Jun 2000 03:15:45 GMT")] // standard parse private static void ByteSpanToTimeOffsetR(string text) { byte[] utf8ByteArray = Encoding.UTF8.GetBytes(text); ReadOnlySpan<byte> utf8ByteSpan = utf8ByteArray; foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { Utf8Parser.TryParse(utf8ByteSpan, out DateTimeOffset value, out int bytesConsumed, 'R'); TestHelpers.DoNotIgnore(value, bytesConsumed); } } } } [Benchmark(InnerIterationCount = InnerCount)] [InlineData("Fri, 30 Jun 2000 03:15:45 GMT")] // standard parse private static void StringToTimeOffsetR_Baseline(string text) { foreach (BenchmarkIteration iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { DateTimeOffset.TryParseExact(text, "r", null, DateTimeStyles.None, out DateTimeOffset value); TestHelpers.DoNotIgnore(value, 0); } } } } } }
//------------------------------------------------------------------------------ // <copyright file="DbConnectionPoolGroup.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ namespace System.Data.ProviderBase { using System; using System.Collections.Concurrent; using System.Data.Common; using System.Diagnostics; using System.Threading; // set_ConnectionString calls DbConnectionFactory.GetConnectionPoolGroup // when not found a new pool entry is created and potentially added // DbConnectionPoolGroup starts in the Active state // Open calls DbConnectionFactory.GetConnectionPool // if the existing pool entry is Disabled, GetConnectionPoolGroup is called for a new entry // DbConnectionFactory.GetConnectionPool calls DbConnectionPoolGroup.GetConnectionPool // DbConnectionPoolGroup.GetConnectionPool will return pool for the current identity // or null if identity is restricted or pooling is disabled or state is disabled at time of add // state changes are Active->Active, Idle->Active // DbConnectionFactory.PruneConnectionPoolGroups calls Prune // which will QueuePoolForRelease on all empty pools // and once no pools remain, change state from Active->Idle->Disabled // Once Disabled, factory can remove its reference to the pool entry sealed internal class DbConnectionPoolGroup { private readonly DbConnectionOptions _connectionOptions; private readonly DbConnectionPoolKey _poolKey; private readonly DbConnectionPoolGroupOptions _poolGroupOptions; private ConcurrentDictionary<DbConnectionPoolIdentity, DbConnectionPool> _poolCollection; private int _state; // see PoolGroupState* below private DbConnectionPoolGroupProviderInfo _providerInfo; private DbMetaDataFactory _metaDataFactory; private static int _objectTypeCount; // Bid counter internal readonly int _objectID = System.Threading.Interlocked.Increment(ref _objectTypeCount); // always lock this before changing _state, we don't want to move out of the 'Disabled' state // PoolGroupStateUninitialized = 0; private const int PoolGroupStateActive = 1; // initial state, GetPoolGroup from cache, connection Open private const int PoolGroupStateIdle = 2; // all pools are pruned via Clear private const int PoolGroupStateDisabled = 4; // factory pool entry prunning method internal DbConnectionPoolGroup (DbConnectionOptions connectionOptions, DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolGroupOptions) { Debug.Assert(null != connectionOptions, "null connection options"); Debug.Assert(null == poolGroupOptions || ADP.IsWindowsNT, "should not have pooling options on Win9x"); _connectionOptions = connectionOptions; _poolKey = key; _poolGroupOptions = poolGroupOptions; // always lock this object before changing state // HybridDictionary does not create any sub-objects until add // so it is safe to use for non-pooled connection as long as // we check _poolGroupOptions first _poolCollection = new ConcurrentDictionary<DbConnectionPoolIdentity, DbConnectionPool>(); _state = PoolGroupStateActive; // VSWhidbey 112102 } internal DbConnectionOptions ConnectionOptions { get { return _connectionOptions; } } internal DbConnectionPoolKey PoolKey { get { return _poolKey; } } internal DbConnectionPoolGroupProviderInfo ProviderInfo { get { return _providerInfo; } set { _providerInfo = value; if(null!=value) { _providerInfo.PoolGroup = this; } } } internal bool IsDisabled { get { return (PoolGroupStateDisabled == _state); } } internal int ObjectID { get { return _objectID; } } internal DbConnectionPoolGroupOptions PoolGroupOptions { get { return _poolGroupOptions; } } internal DbMetaDataFactory MetaDataFactory{ get { return _metaDataFactory; } set { _metaDataFactory = value; } } internal int Clear() { // must be multi-thread safe with competing calls by Clear and Prune via background thread // will return the number of connections in the group after clearing has finished // First, note the old collection and create a new collection to be used ConcurrentDictionary<DbConnectionPoolIdentity, DbConnectionPool> oldPoolCollection = null; lock (this) { if (_poolCollection.Count > 0) { oldPoolCollection = _poolCollection; _poolCollection = new ConcurrentDictionary<DbConnectionPoolIdentity, DbConnectionPool>(); } } // Then, if a new collection was created, release the pools from the old collection if (oldPoolCollection != null) { foreach (var entry in oldPoolCollection) { DbConnectionPool pool = entry.Value; if (pool != null) { // DbConnectionFactory connectionFactory = pool.ConnectionFactory; #if !MOBILE connectionFactory.PerformanceCounters.NumberOfActiveConnectionPools.Decrement(); #endif connectionFactory.QueuePoolForRelease(pool, true); } } } // Finally, return the pool collection count - this may be non-zero if something was added while we were clearing return _poolCollection.Count; } internal DbConnectionPool GetConnectionPool(DbConnectionFactory connectionFactory) { // When this method returns null it indicates that the connection // factory should not use pooling. // We don't support connection pooling on Win9x; it lacks too // many of the APIs we require. // PoolGroupOptions will only be null when we're not supposed to pool // connections. DbConnectionPool pool = null; if (null != _poolGroupOptions) { Debug.Assert(ADP.IsWindowsNT, "should not be pooling on Win9x"); DbConnectionPoolIdentity currentIdentity = DbConnectionPoolIdentity.NoIdentity; if (_poolGroupOptions.PoolByIdentity) { // if we're pooling by identity (because integrated security is // being used for these connections) then we need to go out and // search for the connectionPool that matches the current identity. currentIdentity = DbConnectionPoolIdentity.GetCurrent(); // If the current token is restricted in some way, then we must // not attempt to pool these connections. if (currentIdentity.IsRestricted) { currentIdentity = null; } } if (null != currentIdentity) { if (!_poolCollection.TryGetValue(currentIdentity, out pool)) { // find the pool DbConnectionPoolProviderInfo connectionPoolProviderInfo = connectionFactory.CreateConnectionPoolProviderInfo(this.ConnectionOptions); // optimistically create pool, but its callbacks are delayed until after actual add DbConnectionPool newPool = new DbConnectionPool(connectionFactory, this, currentIdentity, connectionPoolProviderInfo); lock (this) { // Did someone already add it to the list? if (!_poolCollection.TryGetValue(currentIdentity, out pool)) { if (MarkPoolGroupAsActive()) { // If we get here, we know for certain that we there isn't // a pool that matches the current identity, so we have to // add the optimistically created one newPool.Startup(); // must start pool before usage bool addResult = _poolCollection.TryAdd(currentIdentity, newPool); Debug.Assert(addResult, "No other pool with current identity should exist at this point"); #if !MOBILE connectionFactory.PerformanceCounters.NumberOfActiveConnectionPools.Increment(); #endif pool = newPool; newPool = null; } else { // else pool entry has been disabled so don't create new pools Debug.Assert(PoolGroupStateDisabled == _state, "state should be disabled"); } } else { // else found an existing pool to use instead Debug.Assert(PoolGroupStateActive == _state, "state should be active since a pool exists and lock holds"); } } if (null != newPool) { // don't need to call connectionFactory.QueuePoolForRelease(newPool) because // pool callbacks were delayed and no risk of connections being created newPool.Shutdown(); } } // the found pool could be in any state } } if (null == pool) { lock(this) { // keep the pool entry state active when not pooling MarkPoolGroupAsActive(); } } return pool; } private bool MarkPoolGroupAsActive() { // when getting a connection, make the entry active if it was idle (but not disabled) // must always lock this before calling if (PoolGroupStateIdle == _state) { _state = PoolGroupStateActive; Bid.Trace("<prov.DbConnectionPoolGroup.ClearInternal|RES|INFO|CPOOL> %d#, Active\n", ObjectID); } return (PoolGroupStateActive == _state); } internal bool Prune() { // must only call from DbConnectionFactory.PruneConnectionPoolGroups on background timer thread // must lock(DbConnectionFactory._connectionPoolGroups.SyncRoot) before calling ReadyToRemove // to avoid conflict with DbConnectionFactory.CreateConnectionPoolGroup replacing pool entry lock (this) { if (_poolCollection.Count > 0) { var newPoolCollection = new ConcurrentDictionary<DbConnectionPoolIdentity, DbConnectionPool>(); foreach (var entry in _poolCollection) { DbConnectionPool pool = entry.Value; if (pool != null) { // // Actually prune the pool if there are no connections in the pool and no errors occurred. // Empty pool during pruning indicates zero or low activity, but // an error state indicates the pool needs to stay around to // throttle new connection attempts. if ((!pool.ErrorOccurred) && (0 == pool.Count)) { // Order is important here. First we remove the pool // from the collection of pools so no one will try // to use it while we're processing and finally we put the // pool into a list of pools to be released when they // are completely empty. DbConnectionFactory connectionFactory = pool.ConnectionFactory; #if !MOBILE connectionFactory.PerformanceCounters.NumberOfActiveConnectionPools.Decrement(); #endif connectionFactory.QueuePoolForRelease(pool, false); } else { newPoolCollection.TryAdd(entry.Key, entry.Value); } } } _poolCollection = newPoolCollection; } // must be pruning thread to change state and no connections // otherwise pruning thread risks making entry disabled soon after user calls ClearPool if (0 == _poolCollection.Count) { if (PoolGroupStateActive == _state) { _state = PoolGroupStateIdle; Bid.Trace("<prov.DbConnectionPoolGroup.ClearInternal|RES|INFO|CPOOL> %d#, Idle\n", ObjectID); } else if (PoolGroupStateIdle == _state) { _state = PoolGroupStateDisabled; Bid.Trace("<prov.DbConnectionPoolGroup.ReadyToRemove|RES|INFO|CPOOL> %d#, Disabled\n", ObjectID); } } return (PoolGroupStateDisabled == _state); } } } }
using System; using System.Collections.Generic; using Nest.Resolvers.Converters; using Newtonsoft.Json; namespace Nest { [JsonObject(MemberSerialization = MemberSerialization.OptIn)] [JsonConverter(typeof(ReadAsTypeConverter<AggregationContainer>))] public interface IAggregationContainer { [JsonProperty("avg")] IAverageAggregator Average { get; set; } [JsonProperty("date_histogram")] IDateHistogramAggregator DateHistogram { get; set; } [JsonProperty("percentiles")] IPercentilesAggregator Percentiles { get; set; } [JsonProperty("date_range")] IDateRangeAggregator DateRange { get; set; } [JsonProperty("extended_stats")] IExtendedStatsAggregator ExtendedStats { get; set; } [JsonProperty("filter")] IFilterAggregator Filter { get; set; } [JsonProperty("filters")] IFiltersAggregator Filters { get; set; } [JsonProperty("geo_distance")] IGeoDistanceAggregator GeoDistance { get; set; } [JsonProperty("geohash_grid")] IGeoHashAggregator GeoHash { get; set; } [JsonProperty("geo_bounds")] IGeoBoundsAggregator GeoBounds { get; set; } [JsonProperty("histogram")] IHistogramAggregator Histogram { get; set; } [JsonProperty("global")] IGlobalAggregator Global { get; set; } [JsonProperty("ip_range")] IIp4RangeAggregator IpRange { get; set; } [JsonProperty("max")] IMaxAggregator Max { get; set; } [JsonProperty("min")] IMinAggregator Min { get; set; } [JsonProperty("cardinality")] ICardinalityAggregator Cardinality { get; set; } [JsonProperty("missing")] IMissingAggregator Missing { get; set; } [JsonProperty("nested")] INestedAggregator Nested { get; set; } [JsonProperty("reverse_nested")] IReverseNestedAggregator ReverseNested { get; set; } [JsonProperty("range")] IRangeAggregator Range { get; set; } [JsonProperty("stats")] IStatsAggregator Stats { get; set; } [JsonProperty("sum")] ISumAggregator Sum { get; set; } [JsonProperty("terms")] ITermsAggregator Terms { get; set; } [JsonProperty("significant_terms")] ISignificantTermsAggregator SignificantTerms { get; set; } [JsonProperty("value_count")] IValueCountAggregator ValueCount { get; set; } [JsonProperty("percentile_ranks")] IPercentileRanksAggregaor PercentileRanks { get; set; } [JsonProperty("top_hits")] ITopHitsAggregator TopHits { get; set; } [JsonProperty("children")] IChildrenAggregator Children { get; set; } [JsonProperty("scripted_metric")] IScriptedMetricAggregator ScriptedMetric { get; set; } [JsonProperty("aggs")] [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] IDictionary<string, IAggregationContainer> Aggregations { get; set; } } public class AggregationContainer : IAggregationContainer { private IDateHistogramAggregator _dateHistogram; private IPercentilesAggregator _percentiles; private IDateRangeAggregator _dateRange; private IFilterAggregator _filter; private IGeoDistanceAggregator _geoDistance; private IGeoHashAggregator _geoHash; private IGeoBoundsAggregator _geoBounds; private IHistogramAggregator _histogram; private IGlobalAggregator _global; private IIp4RangeAggregator _ipRange; private ICardinalityAggregator _cardinality; private IMissingAggregator _missing; private INestedAggregator _nested; private IReverseNestedAggregator _reverseNested; private IRangeAggregator _range; private ITermsAggregator _terms; private ISignificantTermsAggregator _significantTerms; private IPercentileRanksAggregaor _percentileRanks; private IFiltersAggregator _filters; private ITopHitsAggregator _topHits; private IChildrenAggregator _children; private IScriptedMetricAggregator _scriptedMetric; public IAverageAggregator Average { get; set; } public IValueCountAggregator ValueCount { get; set; } public IMaxAggregator Max { get; set; } public IMinAggregator Min { get; set; } public IStatsAggregator Stats { get; set; } public ISumAggregator Sum { get; set; } public IExtendedStatsAggregator ExtendedStats { get; set; } public IDateHistogramAggregator DateHistogram { get { return _dateHistogram; } set { _dateHistogram = value; } } public IPercentilesAggregator Percentiles { get { return _percentiles; } set { _percentiles = value; } } public IDateRangeAggregator DateRange { get { return _dateRange; } set { _dateRange = value; } } public IFilterAggregator Filter { get { return _filter; } set { _filter = value; } } public IFiltersAggregator Filters { get { return _filters; } set { _filters = value; } } public IGeoDistanceAggregator GeoDistance { get { return _geoDistance; } set { _geoDistance = value; } } public IGeoHashAggregator GeoHash { get { return _geoHash; } set { _geoHash = value; } } public IGeoBoundsAggregator GeoBounds { get { return _geoBounds; } set { _geoBounds = value; } } public IHistogramAggregator Histogram { get { return _histogram; } set { _histogram = value; } } public IGlobalAggregator Global { get { return _global; } set { _global = value; } } public IIp4RangeAggregator IpRange { get { return _ipRange; } set { _ipRange = value; } } public ICardinalityAggregator Cardinality { get { return _cardinality; } set { _cardinality = value; } } public IMissingAggregator Missing { get { return _missing; } set { _missing = value; } } public INestedAggregator Nested { get { return _nested; } set { _nested = value; } } public IReverseNestedAggregator ReverseNested { get { return _reverseNested; } set { _reverseNested = value; } } public IRangeAggregator Range { get { return _range; } set { _range = value; } } public ITermsAggregator Terms { get { return _terms; } set { _terms = value; } } public ISignificantTermsAggregator SignificantTerms { get { return _significantTerms; } set { _significantTerms = value; } } public IPercentileRanksAggregaor PercentileRanks { get { return _percentileRanks; } set { _percentileRanks = value; } } public ITopHitsAggregator TopHits { get { return _topHits; } set { _topHits = value; } } public IChildrenAggregator Children { get { return _children; } set { _children = value; } } public IScriptedMetricAggregator ScriptedMetric { get { return _scriptedMetric; } set { _scriptedMetric = value; } } private void LiftAggregations(IBucketAggregator bucket) { if (bucket == null) return; this.Aggregations = bucket.Aggregations; } public IDictionary<string, IAggregationContainer> Aggregations { get; set; } } public class AggregationDescriptor<T> : IAggregationContainer where T : class { IDictionary<string, IAggregationContainer> IAggregationContainer.Aggregations { get; set; } IAverageAggregator IAggregationContainer.Average { get; set; } IDateHistogramAggregator IAggregationContainer.DateHistogram { get; set; } IPercentilesAggregator IAggregationContainer.Percentiles { get; set; } IDateRangeAggregator IAggregationContainer.DateRange { get; set; } IExtendedStatsAggregator IAggregationContainer.ExtendedStats { get; set; } IFilterAggregator IAggregationContainer.Filter { get; set; } IFiltersAggregator IAggregationContainer.Filters { get; set; } IGeoDistanceAggregator IAggregationContainer.GeoDistance { get; set; } IGeoHashAggregator IAggregationContainer.GeoHash { get; set; } IGeoBoundsAggregator IAggregationContainer.GeoBounds { get; set; } IHistogramAggregator IAggregationContainer.Histogram { get; set; } IGlobalAggregator IAggregationContainer.Global { get; set; } IIp4RangeAggregator IAggregationContainer.IpRange { get; set; } IMaxAggregator IAggregationContainer.Max { get; set; } IMinAggregator IAggregationContainer.Min { get; set; } ICardinalityAggregator IAggregationContainer.Cardinality { get; set; } IMissingAggregator IAggregationContainer.Missing { get; set; } INestedAggregator IAggregationContainer.Nested { get; set; } IReverseNestedAggregator IAggregationContainer.ReverseNested { get; set; } IRangeAggregator IAggregationContainer.Range { get; set; } IStatsAggregator IAggregationContainer.Stats { get; set; } ISumAggregator IAggregationContainer.Sum { get; set; } IValueCountAggregator IAggregationContainer.ValueCount { get; set; } ISignificantTermsAggregator IAggregationContainer.SignificantTerms { get; set; } IPercentileRanksAggregaor IAggregationContainer.PercentileRanks { get;set; } ITermsAggregator IAggregationContainer.Terms { get; set; } ITopHitsAggregator IAggregationContainer.TopHits { get; set; } IChildrenAggregator IAggregationContainer.Children { get; set; } IScriptedMetricAggregator IAggregationContainer.ScriptedMetric { get; set; } public AggregationDescriptor<T> Average(string name, Func<AverageAggregationDescriptor<T>, AverageAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a.Average = d); } public AggregationDescriptor<T> DateHistogram(string name, Func<DateHistogramAggregationDescriptor<T>, DateHistogramAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a.DateHistogram = d); } public AggregationDescriptor<T> Percentiles(string name, Func<PercentilesAggregationDescriptor<T>, PercentilesAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a.Percentiles = d); } public AggregationDescriptor<T> PercentileRanks(string name, Func<PercentileRanksAggregationDescriptor<T>, PercentileRanksAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a.PercentileRanks = d); } public AggregationDescriptor<T> DateRange(string name, Func<DateRangeAggregationDescriptor<T>, DateRangeAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a.DateRange = d); } public AggregationDescriptor<T> ExtendedStats(string name, Func<ExtendedStatsAggregationDescriptor<T>, ExtendedStatsAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a.ExtendedStats = d); } public AggregationDescriptor<T> Filter(string name, Func<FilterAggregationDescriptor<T>, FilterAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a.Filter = d); } public AggregationDescriptor<T> Filters(string name, Func<FiltersAggregationDescriptor<T>, FiltersAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a.Filters = d); } public AggregationDescriptor<T> GeoDistance(string name, Func<GeoDistanceAggregationDescriptor<T>, GeoDistanceAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a.GeoDistance = d); } public AggregationDescriptor<T> GeoHash(string name, Func<GeoHashAggregationDescriptor<T>, GeoHashAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a.GeoHash = d); } public AggregationDescriptor<T> GeoBounds(string name, Func<GeoBoundsAggregationDescriptor<T>, GeoBoundsAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a.GeoBounds = d); } public AggregationDescriptor<T> Histogram(string name, Func<HistogramAggregationDescriptor<T>, HistogramAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a.Histogram = d); } public AggregationDescriptor<T> Global(string name, Func<GlobalAggregationDescriptor<T>, GlobalAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a.Global = d); } public AggregationDescriptor<T> IpRange(string name, Func<Ip4RangeAggregationDescriptor<T>, Ip4RangeAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a.IpRange = d); } public AggregationDescriptor<T> Max(string name, Func<MaxAggregationDescriptor<T>, MaxAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a.Max = d); } public AggregationDescriptor<T> Min(string name, Func<MinAggregationDescriptor<T>, MinAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a.Min = d); } public AggregationDescriptor<T> Cardinality(string name, Func<CardinalityAggregationDescriptor<T>, CardinalityAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a.Cardinality = d); } public AggregationDescriptor<T> Missing(string name, Func<MissingAggregationDescriptor<T>, MissingAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a.Missing = d); } public AggregationDescriptor<T> Nested(string name, Func<NestedAggregationDescriptor<T>, NestedAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a.Nested = d); } public AggregationDescriptor<T> ReverseNested(string name, Func<ReverseNestedAggregationDescriptor<T>, ReverseNestedAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a.ReverseNested = d); } public AggregationDescriptor<T> Range(string name, Func<RangeAggregationDescriptor<T>, RangeAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a.Range = d); } public AggregationDescriptor<T> Stats(string name, Func<StatsAggregationDescriptor<T>, StatsAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a.Stats = d); } public AggregationDescriptor<T> Sum(string name, Func<SumAggregationDescriptor<T>, SumAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a.Sum = d); } public AggregationDescriptor<T> Terms(string name, Func<TermsAggregationDescriptor<T>, TermsAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a.Terms = d); } public AggregationDescriptor<T> SignificantTerms(string name, Func<SignificantTermsAggregationDescriptor<T>, SignificantTermsAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a.SignificantTerms = d); } public AggregationDescriptor<T> ValueCount(string name, Func<ValueCountAggregationDescriptor<T>, ValueCountAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a.ValueCount = d); } public AggregationDescriptor<T> TopHits(string name, Func<TopHitsAggregationDescriptor<T>, TopHitsAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a.TopHits = d); } public AggregationDescriptor<T> Children(string name, Func<ChildrenAggregationDescriptor<T>, ChildrenAggregationDescriptor<T>> selector) { return this.Children<T>(name, selector); } public AggregationDescriptor<T> Children<K>(string name, Func<ChildrenAggregationDescriptor<K>, ChildrenAggregationDescriptor<K>> selector) where K : class { return _SetInnerAggregation(name, selector, (a, d) => a.Children = d); } public AggregationDescriptor<T> ScriptedMetric(string name, Func<ScriptedMetricAggregationDescriptor<T>, ScriptedMetricAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a.ScriptedMetric = d); } private AggregationDescriptor<T> _SetInnerAggregation<TAggregation>( string key, Func<TAggregation, TAggregation> selector , Action<IAggregationContainer, TAggregation> setter ) where TAggregation : IAggregationDescriptor, new() { var innerDescriptor = selector(new TAggregation()); var descriptor = new AggregationDescriptor<T>(); setter(descriptor, innerDescriptor); var bucket = innerDescriptor as IBucketAggregator; IAggregationContainer self = this; if (self.Aggregations == null) self.Aggregations = new Dictionary<string, IAggregationContainer>(); if (bucket != null && bucket.Aggregations.HasAny()) { IAggregationContainer d = descriptor; d.Aggregations = bucket.Aggregations; } self.Aggregations[key] = descriptor; return this; } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmGRVItemQuick { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmGRVItemQuick() : base() { Load += frmGRVItemQuick_Load; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; private System.Windows.Forms.TextBox withEventsField_txtPrice; public System.Windows.Forms.TextBox txtPrice { get { return withEventsField_txtPrice; } set { if (withEventsField_txtPrice != null) { withEventsField_txtPrice.Enter -= txtPrice_Enter; withEventsField_txtPrice.KeyPress -= txtPrice_KeyPress; withEventsField_txtPrice.Leave -= txtPrice_Leave; } withEventsField_txtPrice = value; if (withEventsField_txtPrice != null) { withEventsField_txtPrice.Enter += txtPrice_Enter; withEventsField_txtPrice.KeyPress += txtPrice_KeyPress; withEventsField_txtPrice.Leave += txtPrice_Leave; } } } private System.Windows.Forms.Button withEventsField_cmdProceed; public System.Windows.Forms.Button cmdProceed { get { return withEventsField_cmdProceed; } set { if (withEventsField_cmdProceed != null) { withEventsField_cmdProceed.Click -= cmdProceed_Click; } withEventsField_cmdProceed = value; if (withEventsField_cmdProceed != null) { withEventsField_cmdProceed.Click += cmdProceed_Click; } } } private System.Windows.Forms.TextBox withEventsField_txtDiscountMinus; public System.Windows.Forms.TextBox txtDiscountMinus { get { return withEventsField_txtDiscountMinus; } set { if (withEventsField_txtDiscountMinus != null) { withEventsField_txtDiscountMinus.Enter -= txtDiscountMinus_Enter; withEventsField_txtDiscountMinus.KeyPress -= txtDiscountMinus_KeyPress; withEventsField_txtDiscountMinus.Leave -= txtDiscountMinus_Leave; } withEventsField_txtDiscountMinus = value; if (withEventsField_txtDiscountMinus != null) { withEventsField_txtDiscountMinus.Enter += txtDiscountMinus_Enter; withEventsField_txtDiscountMinus.KeyPress += txtDiscountMinus_KeyPress; withEventsField_txtDiscountMinus.Leave += txtDiscountMinus_Leave; } } } private System.Windows.Forms.TextBox withEventsField_txtDiscountPlus; public System.Windows.Forms.TextBox txtDiscountPlus { get { return withEventsField_txtDiscountPlus; } set { if (withEventsField_txtDiscountPlus != null) { withEventsField_txtDiscountPlus.Enter -= txtDiscountPlus_Enter; withEventsField_txtDiscountPlus.KeyPress -= txtDiscountPlus_KeyPress; withEventsField_txtDiscountPlus.Leave -= txtDiscountPlus_Leave; } withEventsField_txtDiscountPlus = value; if (withEventsField_txtDiscountPlus != null) { withEventsField_txtDiscountPlus.Enter += txtDiscountPlus_Enter; withEventsField_txtDiscountPlus.KeyPress += txtDiscountPlus_KeyPress; withEventsField_txtDiscountPlus.Leave += txtDiscountPlus_Leave; } } } private System.Windows.Forms.TextBox withEventsField_txtQuantity; public System.Windows.Forms.TextBox txtQuantity { get { return withEventsField_txtQuantity; } set { if (withEventsField_txtQuantity != null) { withEventsField_txtQuantity.Enter -= txtQuantity_Enter; withEventsField_txtQuantity.KeyPress -= txtQuantity_KeyPress; withEventsField_txtQuantity.Leave -= txtQuantity_Leave; } withEventsField_txtQuantity = value; if (withEventsField_txtQuantity != null) { withEventsField_txtQuantity.Enter += txtQuantity_Enter; withEventsField_txtQuantity.KeyPress += txtQuantity_KeyPress; withEventsField_txtQuantity.Leave += txtQuantity_Leave; } } } private System.Windows.Forms.CheckBox withEventsField_chkBreakPack; public System.Windows.Forms.CheckBox chkBreakPack { get { return withEventsField_chkBreakPack; } set { if (withEventsField_chkBreakPack != null) { withEventsField_chkBreakPack.CheckStateChanged -= chkBreakPack_CheckStateChanged; withEventsField_chkBreakPack.KeyPress -= chkBreakPack_KeyPress; } withEventsField_chkBreakPack = value; if (withEventsField_chkBreakPack != null) { withEventsField_chkBreakPack.CheckStateChanged += chkBreakPack_CheckStateChanged; withEventsField_chkBreakPack.KeyPress += chkBreakPack_KeyPress; } } } public System.Windows.Forms.Label lblPath; public System.Windows.Forms.Label _lbl_2; public System.Windows.Forms.Label _lbl_1; public System.Windows.Forms.Label Label1; public System.Windows.Forms.Label _lbl_0; public System.Windows.Forms.Label lblName; //Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmGRVItemQuick)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this.txtPrice = new System.Windows.Forms.TextBox(); this.cmdProceed = new System.Windows.Forms.Button(); this.txtDiscountMinus = new System.Windows.Forms.TextBox(); this.txtDiscountPlus = new System.Windows.Forms.TextBox(); this.txtQuantity = new System.Windows.Forms.TextBox(); this.chkBreakPack = new System.Windows.Forms.CheckBox(); this.lblPath = new System.Windows.Forms.Label(); this._lbl_2 = new System.Windows.Forms.Label(); this._lbl_1 = new System.Windows.Forms.Label(); this.Label1 = new System.Windows.Forms.Label(); this._lbl_0 = new System.Windows.Forms.Label(); this.lblName = new System.Windows.Forms.Label(); //Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) this.SuspendLayout(); this.ToolTip1.Active = true; //CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit() this.ControlBox = false; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.ClientSize = new System.Drawing.Size(313, 213); this.Location = new System.Drawing.Point(3, 3); this.MaximizeBox = false; this.MinimizeBox = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Control; this.Enabled = true; this.KeyPreview = false; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.HelpButton = false; this.WindowState = System.Windows.Forms.FormWindowState.Normal; this.Name = "frmGRVItemQuick"; this.txtPrice.AutoSize = false; this.txtPrice.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.txtPrice.Size = new System.Drawing.Size(217, 19); this.txtPrice.Location = new System.Drawing.Point(85, 99); this.txtPrice.TabIndex = 5; this.txtPrice.Text = "Text1"; this.txtPrice.AcceptsReturn = true; this.txtPrice.BackColor = System.Drawing.SystemColors.Window; this.txtPrice.CausesValidation = true; this.txtPrice.Enabled = true; this.txtPrice.ForeColor = System.Drawing.SystemColors.WindowText; this.txtPrice.HideSelection = true; this.txtPrice.ReadOnly = false; this.txtPrice.MaxLength = 0; this.txtPrice.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtPrice.Multiline = false; this.txtPrice.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtPrice.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtPrice.TabStop = true; this.txtPrice.Visible = true; this.txtPrice.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtPrice.Name = "txtPrice"; this.cmdProceed.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdProceed.Text = "&Proceed"; this.cmdProceed.Size = new System.Drawing.Size(85, 31); this.cmdProceed.Location = new System.Drawing.Point(216, 174); this.cmdProceed.TabIndex = 10; this.cmdProceed.BackColor = System.Drawing.SystemColors.Control; this.cmdProceed.CausesValidation = true; this.cmdProceed.Enabled = true; this.cmdProceed.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdProceed.Cursor = System.Windows.Forms.Cursors.Default; this.cmdProceed.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdProceed.TabStop = true; this.cmdProceed.Name = "cmdProceed"; this.txtDiscountMinus.AutoSize = false; this.txtDiscountMinus.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.txtDiscountMinus.Size = new System.Drawing.Size(217, 19); this.txtDiscountMinus.Location = new System.Drawing.Point(84, 147); this.txtDiscountMinus.TabIndex = 9; this.txtDiscountMinus.Text = "Text1"; this.txtDiscountMinus.AcceptsReturn = true; this.txtDiscountMinus.BackColor = System.Drawing.SystemColors.Window; this.txtDiscountMinus.CausesValidation = true; this.txtDiscountMinus.Enabled = true; this.txtDiscountMinus.ForeColor = System.Drawing.SystemColors.WindowText; this.txtDiscountMinus.HideSelection = true; this.txtDiscountMinus.ReadOnly = false; this.txtDiscountMinus.MaxLength = 0; this.txtDiscountMinus.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtDiscountMinus.Multiline = false; this.txtDiscountMinus.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtDiscountMinus.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtDiscountMinus.TabStop = true; this.txtDiscountMinus.Visible = true; this.txtDiscountMinus.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtDiscountMinus.Name = "txtDiscountMinus"; this.txtDiscountPlus.AutoSize = false; this.txtDiscountPlus.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.txtDiscountPlus.Size = new System.Drawing.Size(217, 19); this.txtDiscountPlus.Location = new System.Drawing.Point(84, 126); this.txtDiscountPlus.TabIndex = 7; this.txtDiscountPlus.Text = "Text1"; this.txtDiscountPlus.AcceptsReturn = true; this.txtDiscountPlus.BackColor = System.Drawing.SystemColors.Window; this.txtDiscountPlus.CausesValidation = true; this.txtDiscountPlus.Enabled = true; this.txtDiscountPlus.ForeColor = System.Drawing.SystemColors.WindowText; this.txtDiscountPlus.HideSelection = true; this.txtDiscountPlus.ReadOnly = false; this.txtDiscountPlus.MaxLength = 0; this.txtDiscountPlus.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtDiscountPlus.Multiline = false; this.txtDiscountPlus.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtDiscountPlus.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtDiscountPlus.TabStop = true; this.txtDiscountPlus.Visible = true; this.txtDiscountPlus.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtDiscountPlus.Name = "txtDiscountPlus"; this.txtQuantity.AutoSize = false; this.txtQuantity.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.txtQuantity.Size = new System.Drawing.Size(217, 19); this.txtQuantity.Location = new System.Drawing.Point(84, 78); this.txtQuantity.TabIndex = 3; this.txtQuantity.Text = "Text1"; this.txtQuantity.AcceptsReturn = true; this.txtQuantity.BackColor = System.Drawing.SystemColors.Window; this.txtQuantity.CausesValidation = true; this.txtQuantity.Enabled = true; this.txtQuantity.ForeColor = System.Drawing.SystemColors.WindowText; this.txtQuantity.HideSelection = true; this.txtQuantity.ReadOnly = false; this.txtQuantity.MaxLength = 0; this.txtQuantity.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtQuantity.Multiline = false; this.txtQuantity.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtQuantity.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtQuantity.TabStop = true; this.txtQuantity.Visible = true; this.txtQuantity.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtQuantity.Name = "txtQuantity"; this.chkBreakPack.Text = "Break Pack"; this.chkBreakPack.Size = new System.Drawing.Size(286, 16); this.chkBreakPack.Location = new System.Drawing.Point(12, 54); this.chkBreakPack.TabIndex = 1; this.chkBreakPack.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft; this.chkBreakPack.FlatStyle = System.Windows.Forms.FlatStyle.Standard; this.chkBreakPack.BackColor = System.Drawing.SystemColors.Control; this.chkBreakPack.CausesValidation = true; this.chkBreakPack.Enabled = true; this.chkBreakPack.ForeColor = System.Drawing.SystemColors.ControlText; this.chkBreakPack.Cursor = System.Windows.Forms.Cursors.Default; this.chkBreakPack.RightToLeft = System.Windows.Forms.RightToLeft.No; this.chkBreakPack.Appearance = System.Windows.Forms.Appearance.Normal; this.chkBreakPack.TabStop = true; this.chkBreakPack.CheckState = System.Windows.Forms.CheckState.Unchecked; this.chkBreakPack.Visible = true; this.chkBreakPack.Name = "chkBreakPack"; this.lblPath.BackColor = System.Drawing.Color.Blue; this.lblPath.Text = "GRV Quick Edit"; this.lblPath.ForeColor = System.Drawing.Color.White; this.lblPath.Size = new System.Drawing.Size(568, 25); this.lblPath.Location = new System.Drawing.Point(0, 0); this.lblPath.TabIndex = 11; this.lblPath.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.lblPath.Enabled = true; this.lblPath.Cursor = System.Windows.Forms.Cursors.Default; this.lblPath.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblPath.UseMnemonic = true; this.lblPath.Visible = true; this.lblPath.AutoSize = false; this.lblPath.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblPath.Name = "lblPath"; this._lbl_2.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lbl_2.Text = "Price"; this._lbl_2.Size = new System.Drawing.Size(24, 13); this._lbl_2.Location = new System.Drawing.Point(57, 102); this._lbl_2.TabIndex = 4; this._lbl_2.BackColor = System.Drawing.SystemColors.Control; this._lbl_2.Enabled = true; this._lbl_2.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_2.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_2.UseMnemonic = true; this._lbl_2.Visible = true; this._lbl_2.AutoSize = true; this._lbl_2.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_2.Name = "_lbl_2"; this._lbl_1.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lbl_1.Text = "Surcharges"; this._lbl_1.Size = new System.Drawing.Size(54, 13); this._lbl_1.Location = new System.Drawing.Point(24, 150); this._lbl_1.TabIndex = 8; this._lbl_1.BackColor = System.Drawing.SystemColors.Control; this._lbl_1.Enabled = true; this._lbl_1.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_1.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_1.UseMnemonic = true; this._lbl_1.Visible = true; this._lbl_1.AutoSize = true; this._lbl_1.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_1.Name = "_lbl_1"; this.Label1.TextAlign = System.Drawing.ContentAlignment.TopRight; this.Label1.Text = "Discount"; this.Label1.Size = new System.Drawing.Size(42, 13); this.Label1.Location = new System.Drawing.Point(36, 129); this.Label1.TabIndex = 6; this.Label1.BackColor = System.Drawing.SystemColors.Control; this.Label1.Enabled = true; this.Label1.ForeColor = System.Drawing.SystemColors.ControlText; this.Label1.Cursor = System.Windows.Forms.Cursors.Default; this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label1.UseMnemonic = true; this.Label1.Visible = true; this.Label1.AutoSize = true; this.Label1.BorderStyle = System.Windows.Forms.BorderStyle.None; this.Label1.Name = "Label1"; this._lbl_0.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lbl_0.Text = "Quantity"; this._lbl_0.Size = new System.Drawing.Size(39, 13); this._lbl_0.Location = new System.Drawing.Point(41, 81); this._lbl_0.TabIndex = 2; this._lbl_0.BackColor = System.Drawing.SystemColors.Control; this._lbl_0.Enabled = true; this._lbl_0.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_0.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_0.UseMnemonic = true; this._lbl_0.Visible = true; this._lbl_0.AutoSize = true; this._lbl_0.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_0.Name = "_lbl_0"; this.lblName.Text = "Label1"; this.lblName.Size = new System.Drawing.Size(289, 16); this.lblName.Location = new System.Drawing.Point(12, 33); this.lblName.TabIndex = 0; this.lblName.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.lblName.BackColor = System.Drawing.SystemColors.Control; this.lblName.Enabled = true; this.lblName.ForeColor = System.Drawing.SystemColors.ControlText; this.lblName.Cursor = System.Windows.Forms.Cursors.Default; this.lblName.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblName.UseMnemonic = true; this.lblName.Visible = true; this.lblName.AutoSize = false; this.lblName.BorderStyle = System.Windows.Forms.BorderStyle.None; this.lblName.Name = "lblName"; this.Controls.Add(txtPrice); this.Controls.Add(cmdProceed); this.Controls.Add(txtDiscountMinus); this.Controls.Add(txtDiscountPlus); this.Controls.Add(txtQuantity); this.Controls.Add(chkBreakPack); this.Controls.Add(lblPath); this.Controls.Add(_lbl_2); this.Controls.Add(_lbl_1); this.Controls.Add(Label1); this.Controls.Add(_lbl_0); this.Controls.Add(lblName); //Me.lbl.SetIndex(_lbl_2, CType(2, Short)) //Me.lbl.SetIndex(_lbl_1, CType(1, Short)) //Me.lbl.SetIndex(_lbl_0, CType(0, Short)) //CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit() this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
using System; using System.Security.Cryptography; using System.Text; using System.IO; using System.Collections; using RLToolkit.Logger; namespace RLToolkit.Basic { /// <summary> /// String crypt. /// </summary> public static class StringCrypt { /// <summary>Static TripleDES info to use if none are supplied</summary> public static TripleDES TripleDESAlg; /// <summary>Static RSA crypt info info to use if none are supplied</summary> public static RSACryptInfo RSA_cryptInfo; /// <summary>Static RFC2898 info to use if none are supplied</summary> public static RFC2898CryptInfo RFC2898_cryptInfo; #region implicit encrypt/decrypt /// <summary> /// Method to encrypt with the default technique /// </summary> /// <param name="input">the string to encrypt</param> /// <returns>a byte array of the encrypted data</returns> public static byte[] Encrypt(string input) { // implicit crypt LogManager.Instance.Log().Debug("Calling an implicit Encrypt"); return EncryptRfc2898(input); } /// <summary> /// Method to decryt with the default technique /// </summary> /// <param name="input">the byte array to decrypt</param> /// <returns>decrypted string data</returns> public static string Decrypt(byte[] input) { // implicit Decrypt LogManager.Instance.Log().Debug("Calling an implicit Decrypt"); return DecryptRfc2898(input); } #endregion #region RFC2989 /// <summary> /// Method to encrypt with the RFC2898 technique, with the static RFC2898 info /// </summary> /// <param name="input">the string to encrypt</param> /// <returns>a byte array of the encrypted data</returns> public static byte[] EncryptRfc2898(string input) { LogManager.Instance.Log().Debug("Calling Encrypt RFC2989 with default crypt info"); if (RFC2898_cryptInfo == null) { LogManager.Instance.Log().Debug("Creating a new static instance of RFC2898 Crypt info"); RFC2898_cryptInfo = new RFC2898CryptInfo(); } return EncryptRfc2898(input, RFC2898_cryptInfo); } /// <summary> /// Method to encrypt with the RFC2898 technique, with a supplied RFC2898 info /// </summary> /// <param name="input">the string to encrypt</param> /// <param name="cryptInfo">the RFC2898 crypt info</param> /// <returns>a byte array of the encrypted data</returns> public static byte[] EncryptRfc2898(string input, RFC2898CryptInfo cryptInfo) { LogManager.Instance.Log().Debug("Calling Encrypt RFC2989"); byte[] toEncode = new ASCIIEncoding().GetBytes(input); byte[] key = new Rfc2898DeriveBytes(cryptInfo.password, new ASCIIEncoding().GetBytes(cryptInfo.salt)).GetBytes(256/8); RijndaelManaged symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros }; var encryptor = symmetricKey.CreateEncryptor(key, new ASCIIEncoding().GetBytes(cryptInfo.VIKey)); byte[] encodedBytes; MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream(mStream, encryptor, CryptoStreamMode.Write); cStream.Write(toEncode, 0, toEncode.Length); cStream.FlushFinalBlock(); encodedBytes = mStream.ToArray(); cStream.Close(); mStream.Close(); return encodedBytes; } /// <summary> /// Method to decrypt with the RFC2898 technique, with the static RFC2898 info /// </summary> /// <param name="input">the byte array to decrypt</param> /// <returns>decrypted string data</returns> public static string DecryptRfc2898(byte[] input) { LogManager.Instance.Log().Debug("Calling Decrypt RFC2989 with default crypt info"); if (RFC2898_cryptInfo == null) { LogManager.Instance.Log().Debug("Creating a new static instance of RFC2898 Crypt info"); RFC2898_cryptInfo = new RFC2898CryptInfo(); } return DecryptRfc2898(input, RFC2898_cryptInfo); } /// <summary> /// Method to decrypt with the RFC2898 technique, with a supplied RFC2898 info /// </summary> /// <param name="input">the byte array to decrypt</param> /// <param name="cryptInfo">the RFC2898 crypt info</param> /// <returns>decrypted string data</returns> public static string DecryptRfc2898(byte[] input, RFC2898CryptInfo cryptInfo) { LogManager.Instance.Log().Debug("Calling Decrypt RFC2989"); byte[] key = new Rfc2898DeriveBytes(cryptInfo.password, new ASCIIEncoding().GetBytes(cryptInfo.salt)).GetBytes(256/8); RijndaelManaged symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None }; var decryptor = symmetricKey.CreateDecryptor(key, new ASCIIEncoding().GetBytes(cryptInfo.VIKey)); MemoryStream mStream = new MemoryStream(input); CryptoStream cStream = new CryptoStream(mStream, decryptor, CryptoStreamMode.Read); byte[] fromEncode = new byte[input.Length]; cStream.Read(fromEncode, 0, fromEncode.Length); mStream.Close(); cStream.Close(); return new ASCIIEncoding().GetString(fromEncode).TrimEnd('\0'); } #endregion #region RSA /// <summary> /// Method to encrypt with the RSA technique, with the static RSA info /// </summary> /// <param name="input">the string to encrypt</param> /// <returns>a byte array of the encrypted data</returns> public static byte[] EncryptRSA(string input) { LogManager.Instance.Log().Debug("Calling Decrypt RSA with default crypt info"); if (RSA_cryptInfo == null) { LogManager.Instance.Log().Debug("Creating a new static instance of RSA Crypt info"); RSA_cryptInfo = new RSACryptInfo(512); } return EncryptRSA(input, RSA_cryptInfo); } /// <summary> /// Method to encrypt with the RSA technique, with a supplied RSA info /// </summary> /// <param name="input">the string to encrypt</param> /// <param name="cryptInfo">the RSA crypt info</param> /// <returns>a byte array of the encrypted data</returns> public static byte[] EncryptRSA(string input, RSACryptInfo cryptInfo) { LogManager.Instance.Log().Debug("Calling Encrypt RSA"); try { RSACryptoServiceProvider csp = new RSACryptoServiceProvider(cryptInfo.keySize); csp.ImportParameters(cryptInfo.publicKey); return csp.Encrypt(new ASCIIEncoding().GetBytes(input), false); } catch (CryptographicException e) { LogManager.Instance.Log().Fatal(string.Format("Cryptographic failure occured: {0}", e.Message)); return null; } } /// <summary> /// Method to decrypt with the RSA technique, with the static RSA info /// </summary> /// <param name="input">the byte array to decrypt</param> /// <returns>decrypted string data</returns> public static string DecryptRSA(byte[] input) { LogManager.Instance.Log().Debug("Calling Encrypt RSA with default crypt info"); if (RSA_cryptInfo == null) { LogManager.Instance.Log().Debug("Creating a new static instance of RSA Crypt info"); RSA_cryptInfo = new RSACryptInfo(512); } return DecryptRSA(input, RSA_cryptInfo); } /// <summary> /// Method to decrypt with the RSA technique, with a supplied RSA info /// </summary> /// <param name="input">the byte array to decrypt</param> /// <param name="cryptInfo">the RSA crypt info</param> /// <returns>decrypted string data</returns> public static string DecryptRSA( byte[] input, RSACryptInfo cryptInfo) { LogManager.Instance.Log().Debug("Calling Decrypt RSA"); try { RSACryptoServiceProvider csp = new RSACryptoServiceProvider(cryptInfo.keySize); csp.ImportParameters(cryptInfo.privateKey); return new ASCIIEncoding().GetString(csp.Decrypt(input, false)).Trim('\0'); } catch (CryptographicException e) { LogManager.Instance.Log().Fatal(string.Format("Cryptographic failure occured: {0}", e.Message)); return null; } } #endregion #region TripleDES /// <summary> /// Method to encrypt with the TripleDES technique, with the static TripleDES instance /// </summary> /// <param name="input">the string to encrypt</param> /// <returns>a byte array of the encrypted data</returns> public static byte[] EncryptTripleDES(string input) { LogManager.Instance.Log().Debug("Calling Encrypt TripleDES with default crypt info"); if (TripleDESAlg == null) { LogManager.Instance.Log().Debug("Creating a new static instance of TripleDES"); TripleDESAlg = TripleDES.Create("TripleDES"); } return EncryptTripleDES(input, TripleDESAlg); } /// <summary> /// Method to encrypt with the TripleDES technique, with a supplied TripleDES instance /// </summary> /// <param name="input">the string to encrypt</param> /// <param name="alg">the TripleDES instance</param> /// <returns>a byte array of the encrypted data</returns> public static byte[] EncryptTripleDES(string input, TripleDES alg) { LogManager.Instance.Log().Debug("Calling Encrypt TripleDES"); try { MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream(mStream, alg.CreateEncryptor(alg.Key, alg.IV), CryptoStreamMode.Write); byte[] toEncode = new ASCIIEncoding().GetBytes(input); cStream.Write(toEncode, 0, toEncode.Length); cStream.FlushFinalBlock(); byte[] encodedBytes = mStream.ToArray(); mStream.Close(); cStream.Close(); return encodedBytes; } catch (CryptographicException e) { LogManager.Instance.Log().Fatal(string.Format("Cryptographic failure occured: {0}", e.Message)); return null; } } /// <summary> /// Method to decrypt with the TripleDES technique, with a supplied TripleDES instance /// </summary> /// <param name="input">the byte array to decrypt</param> /// <returns>decrypted string data</returns> public static string DecryptTripleDES(byte[] input) { LogManager.Instance.Log().Debug("Calling Decrypt TripleDES with default crypt info"); if (TripleDESAlg == null) { LogManager.Instance.Log().Debug("Creating a new static instance of TripleDES"); TripleDESAlg = TripleDES.Create("TripleDES"); } return DecryptTripleDES(input, TripleDESAlg); } /// <summary> /// Method to decrypt with the TripleDES technique, with a supplied TripleDES instance /// </summary> /// <param name="input">the byte array to decrypt</param> /// <param name="alg">the TripleDES instance</param> /// <returns>decrypted string data</returns> public static string DecryptTripleDES(byte[] input, TripleDES alg) { LogManager.Instance.Log().Debug("Calling Decrypt TripleDES"); try { MemoryStream mStream = new MemoryStream(input); CryptoStream cStream = new CryptoStream(mStream, alg.CreateDecryptor(alg.Key, alg.IV), CryptoStreamMode.Read); byte[] fromEncode = new byte[input.Length]; cStream.Read(fromEncode, 0, fromEncode.Length); return new ASCIIEncoding().GetString(fromEncode).TrimEnd('\0'); } catch (CryptographicException e) { LogManager.Instance.Log().Fatal(string.Format("Cryptographic failure occured: {0}", e.Message)); return null; } } #endregion #region helper /// <summary> /// Converts the byte array to base64 string. /// </summary> /// <returns>The string representation of the array in base64</returns> /// <param name="input">the byte array</param> public static string ConvertByteArrayToBase64(byte[] input) { return Convert.ToBase64String(input); } /// <summary> /// Converts the base64 string to byte array. /// </summary> /// <returns>The byte array</returns> /// <param name="input">The string representation of the array in base64.</param> public static byte[] ConvertBase64ToByteArray(string input) { return Convert.FromBase64String(input); } #endregion } }
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 AprTipoParto class. /// </summary> [Serializable] public partial class AprTipoPartoCollection : ActiveList<AprTipoParto, AprTipoPartoCollection> { public AprTipoPartoCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>AprTipoPartoCollection</returns> public AprTipoPartoCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { AprTipoParto 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 APR_TipoParto table. /// </summary> [Serializable] public partial class AprTipoParto : ActiveRecord<AprTipoParto>, IActiveRecord { #region .ctors and Default Settings public AprTipoParto() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public AprTipoParto(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public AprTipoParto(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public AprTipoParto(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("APR_TipoParto", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdTipoParto = new TableSchema.TableColumn(schema); colvarIdTipoParto.ColumnName = "idTipoParto"; colvarIdTipoParto.DataType = DbType.Int32; colvarIdTipoParto.MaxLength = 0; colvarIdTipoParto.AutoIncrement = true; colvarIdTipoParto.IsNullable = false; colvarIdTipoParto.IsPrimaryKey = true; colvarIdTipoParto.IsForeignKey = false; colvarIdTipoParto.IsReadOnly = false; colvarIdTipoParto.DefaultSetting = @""; colvarIdTipoParto.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdTipoParto); TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema); colvarNombre.ColumnName = "nombre"; colvarNombre.DataType = DbType.AnsiString; colvarNombre.MaxLength = 50; colvarNombre.AutoIncrement = false; colvarNombre.IsNullable = true; colvarNombre.IsPrimaryKey = false; colvarNombre.IsForeignKey = false; colvarNombre.IsReadOnly = false; colvarNombre.DefaultSetting = @""; colvarNombre.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombre); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("APR_TipoParto",schema); } } #endregion #region Props [XmlAttribute("IdTipoParto")] [Bindable(true)] public int IdTipoParto { get { return GetColumnValue<int>(Columns.IdTipoParto); } set { SetColumnValue(Columns.IdTipoParto, value); } } [XmlAttribute("Nombre")] [Bindable(true)] public string Nombre { get { return GetColumnValue<string>(Columns.Nombre); } set { SetColumnValue(Columns.Nombre, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } private DalSic.AprRecienNacidoCollection colAprRecienNacidoRecords; public DalSic.AprRecienNacidoCollection AprRecienNacidoRecords { get { if(colAprRecienNacidoRecords == null) { colAprRecienNacidoRecords = new DalSic.AprRecienNacidoCollection().Where(AprRecienNacido.Columns.IdTipoParto, IdTipoParto).Load(); colAprRecienNacidoRecords.ListChanged += new ListChangedEventHandler(colAprRecienNacidoRecords_ListChanged); } return colAprRecienNacidoRecords; } set { colAprRecienNacidoRecords = value; colAprRecienNacidoRecords.ListChanged += new ListChangedEventHandler(colAprRecienNacidoRecords_ListChanged); } } void colAprRecienNacidoRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colAprRecienNacidoRecords[e.NewIndex].IdTipoParto = IdTipoParto; } } private DalSic.AprPartoProvisorioCollection colAprPartoProvisorioRecords; public DalSic.AprPartoProvisorioCollection AprPartoProvisorioRecords { get { if(colAprPartoProvisorioRecords == null) { colAprPartoProvisorioRecords = new DalSic.AprPartoProvisorioCollection().Where(AprPartoProvisorio.Columns.IdTerminacionParto, IdTipoParto).Load(); colAprPartoProvisorioRecords.ListChanged += new ListChangedEventHandler(colAprPartoProvisorioRecords_ListChanged); } return colAprPartoProvisorioRecords; } set { colAprPartoProvisorioRecords = value; colAprPartoProvisorioRecords.ListChanged += new ListChangedEventHandler(colAprPartoProvisorioRecords_ListChanged); } } void colAprPartoProvisorioRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colAprPartoProvisorioRecords[e.NewIndex].IdTerminacionParto = IdTipoParto; } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varNombre) { AprTipoParto item = new AprTipoParto(); item.Nombre = varNombre; 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 varIdTipoParto,string varNombre) { AprTipoParto item = new AprTipoParto(); item.IdTipoParto = varIdTipoParto; item.Nombre = varNombre; 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 IdTipoPartoColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn NombreColumn { get { return Schema.Columns[1]; } } #endregion #region Columns Struct public struct Columns { public static string IdTipoParto = @"idTipoParto"; public static string Nombre = @"nombre"; } #endregion #region Update PK Collections public void SetPKValues() { if (colAprRecienNacidoRecords != null) { foreach (DalSic.AprRecienNacido item in colAprRecienNacidoRecords) { if (item.IdTipoParto != IdTipoParto) { item.IdTipoParto = IdTipoParto; } } } if (colAprPartoProvisorioRecords != null) { foreach (DalSic.AprPartoProvisorio item in colAprPartoProvisorioRecords) { if (item.IdTerminacionParto != IdTipoParto) { item.IdTerminacionParto = IdTipoParto; } } } } #endregion #region Deep Save public void DeepSave() { Save(); if (colAprRecienNacidoRecords != null) { colAprRecienNacidoRecords.SaveAll(); } if (colAprPartoProvisorioRecords != null) { colAprPartoProvisorioRecords.SaveAll(); } } #endregion } }
#region license /* DirectShowLib - Provide access to DirectShow interfaces via .NET Copyright (C) 2007 http://sourceforge.net/projects/directshownet/ This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #endregion using System; using System.Runtime.InteropServices; using System.Text; namespace DirectShowLib.DES { #region Utility Classes sealed public class DESResults { private DESResults() { // Prevent people from trying to instantiate this class } public const int E_NotInTree = unchecked((int)0x80040400); public const int E_RenderEngineIsBroken = unchecked((int)0x80040401); public const int E_MustInitRenderer = unchecked((int)0x80040402); public const int E_NotDetermind = unchecked((int)0x80040403); public const int E_NoTimeline = unchecked((int)0x80040404); public const int S_WarnOutputReset = unchecked((int)40404); } sealed public class DESError { private DESError() { // Prevent people from trying to instantiate this class } public static string GetErrorText(int hr) { string sRet = null; switch(hr) { case DESResults.E_NotInTree: sRet = "The object is not contained in the timeline."; break; case DESResults.E_RenderEngineIsBroken: sRet = "Operation failed because project was not rendered successfully."; break; case DESResults.E_MustInitRenderer: sRet = "Render engine has not been initialized."; break; case DESResults.E_NotDetermind: sRet = "Cannot determine requested value."; break; case DESResults.E_NoTimeline: sRet = "There is no timeline object."; break; case DESResults.S_WarnOutputReset: sRet = "The rendering portion of the graph was deleted. The application must rebuild it."; break; default: sRet = DsError.GetErrorText(hr); break; } return sRet; } /// <summary> /// If hr has a "failed" status code (E_*), throw an exception. Note that status /// messages (S_*) are not considered failure codes. If DES or DShow error text /// is available, it is used to build the exception, otherwise a generic com error /// is thrown. /// </summary> /// <param name="hr">The HRESULT to check</param> public static void ThrowExceptionForHR(int hr) { // If an error has occurred if (hr < 0) { // If a string is returned, build a com error from it string buf = GetErrorText(hr); if (buf != null) { throw new COMException(buf, hr); } else { // No string, just use standard com error Marshal.ThrowExceptionForHR(hr); } } } } #endregion #region Classes /// <summary> /// From CLSID_AMTimeline /// </summary> [ComImport, Guid("78530B75-61F9-11D2-8CAD-00A024580902")] public class AMTimeline { } /// <summary> /// From CLSID_PropertySetter /// </summary> [ComImport, Guid("ADF95821-DED7-11d2-ACBE-0080C75E246E")] public class PropertySetter { } /// <summary> /// From CLSID_AMTimelineObj /// </summary> [ComImport, Guid("78530B78-61F9-11D2-8CAD-00A024580902")] public class AMTimelineObj { } /// <summary> /// From CLSID_AMTimelineSrc /// </summary> [ComImport, Guid("78530B7A-61F9-11D2-8CAD-00A024580902")] public class AMTimelineSrc { } /// <summary> /// From CLSID_AMTimelineTrack /// </summary> [ComImport, Guid("8F6C3C50-897B-11d2-8CFB-00A0C9441E20")] public class AMTimelineTrack { } /// <summary> /// From CLSID_AMTimelineComp /// </summary> [ComImport, Guid("74D2EC80-6233-11d2-8CAD-00A024580902")] public class AMTimelineComp { } /// <summary> /// From CLSID_AMTimelineGroup /// </summary> [ComImport, Guid("F6D371E1-B8A6-11d2-8023-00C0DF10D434")] public class AMTimelineGroup { } /// <summary> /// From CLSID_AMTimelineTrans /// </summary> [ComImport, Guid("74D2EC81-6233-11d2-8CAD-00A024580902")] public class AMTimelineTrans { } /// <summary> /// From CLSID_AMTimelineEffect /// </summary> [ComImport, Guid("74D2EC82-6233-11d2-8CAD-00A024580902")] public class AMTimelineEffect { } /// <summary> /// From CLSID_RenderEngine /// </summary> [ComImport, Guid("64D8A8E0-80A2-11d2-8CF3-00A0C9441E20")] public class RenderEngine { } /// <summary> /// From CLSID_SmartRenderEngine /// </summary> [ComImport, Guid("498B0949-BBE9-4072-98BE-6CCAEB79DC6F")] public class SmartRenderEngine { } /// <summary> /// From CLSID_AudMixer /// </summary> [ComImport, Guid("036A9790-C153-11d2-9EF7-006008039E37")] public class AudMixer { } /// <summary> /// From CLSID_Xml2Dex /// </summary> [ComImport, Guid("18C628EE-962A-11D2-8D08-00A0C9441E20")] public class Xml2Dex { } /// <summary> /// From CLSID_MediaLocator /// </summary> [ComImport, Guid("CC1101F2-79DC-11D2-8CE6-00A0C9441E20")] public class MediaLocator { } /// <summary> /// From CLSID_MediaDet /// </summary> [ComImport, Guid("65BD0711-24D2-4ff7-9324-ED2E5D3ABAFA")] public class MediaDet { } /// <summary> /// From CLSID_DxtCompositor /// </summary> [ComImport, Guid("BB44391D-6ABD-422f-9E2E-385C9DFF51FC")] public class DxtCompositor { } /// <summary> /// From CLSID_DxtAlphaSetter /// </summary> [ComImport, Guid("506D89AE-909A-44f7-9444-ABD575896E35")] public class DxtAlphaSetter { } /// <summary> /// From CLSID_DxtJpeg /// </summary> [ComImport, Guid("DE75D012-7A65-11D2-8CEA-00A0C9441E20")] public class DxtJpeg { } /// <summary> /// From CLSID_ColorSource /// </summary> [ComImport, Guid("0cfdd070-581a-11d2-9ee6-006008039e37")] public class ColorSource { } /// <summary> /// From CLSID_DxtKey /// </summary> [ComImport, Guid("C5B19592-145E-11d3-9F04-006008039E37")] public class DxtKey { } #endregion #region Declarations #if ALLOW_UNTESTED_INTERFACES /// <summary> /// From unnamed enum /// </summary> public enum DXTKeys { RGB, NonRed, Luminance, Alpha, Hue } #endif /// <summary> /// From TIMELINE_MAJOR_TYPE /// </summary> [Flags] public enum TimelineMajorType { None = 0, Composite = 1, Effect = 0x10, Group = 0x80, Source = 4, Track= 2, Transition = 8 } /// <summary> /// From unnamed enum /// </summary> public enum TimelineInsertMode { Insert = 1, Overlay = 2 } /// <summary> /// From unnamed enum /// </summary> [Flags] public enum SFNValidateFlags { None = 0x00000000, Check = 0x00000001, Popup = 0x00000002, TellMe = 0x00000004, Replace = 0x00000008, UseLocal = 0x000000010, NoFind = 0x000000020, IgnoreMuted = 0x000000040, End } /// <summary> /// From SCompFmt0 /// </summary> [StructLayout(LayoutKind.Sequential)] public class SCompFmt0 { public int nFormatId; public AMMediaType MediaType; } /// <summary> /// From unnamed enum /// </summary> public enum ResizeFlags { Stretch, Crop, PreserveAspectRatio, PreserveAspectRatioNoLetterBox } /// <summary> /// From DEXTERF_TRACK_SEARCH_FLAGS /// </summary> public enum DexterFTrackSearchFlags { Bounding = -1, ExactlyAt = 0, Forwards = 1 } /// <summary> /// From DEXTER_PARAM /// </summary> [StructLayout(LayoutKind.Sequential, Pack=4)] public struct DexterParam { [MarshalAs(UnmanagedType.BStr)] public string Name; public int dispID; public int nValues; } /// <summary> /// From unnamed enum /// </summary> public enum ConnectFDynamic { None = 0x00000000, Sources = 0x00000001, Effects = 0x00000002 } /// <summary> /// From DEXTER_VALUE /// </summary> [StructLayout(LayoutKind.Sequential, Pack=8)] public struct DexterValue { [MarshalAs(UnmanagedType.Struct)] public object v; public long rt; public Dexterf dwInterp; } /// <summary> /// From DEXTERF /// </summary> public enum Dexterf { Jump, Interpolate } /// <summary> /// From DEX_IDS_* defines /// </summary> public enum DESErrorCode { BadSourceName = 1400, BadSourceName2 = 1401, MissingSourceName = 1402, UnknownSource = 1403, InstallProblem = 1404, NoSourceNames = 1405, BadMediaType = 1406, StreamNumber = 1407, OutOfMemory = 1408, DIBSeqNotAllSame = 1409, ClipTooShort = 1410, InvalidDXT = 1411, InvalidDefaultDXTT = 1412, No3D = 1413, BrokenDXT = 1414, NoSuchProperty = 1415, IllegalPropertyVal = 1416, InvalidXML = 1417, CantFindFilter = 1418, DiskWriteError = 1419, InvalidAudioFX = 1420, CantFindCompressor = 1421, TimelineParse = 1426, GraphError = 1427, GridError = 1428, InterfaceError = 1429 } #endregion #region Interfaces #if ALLOW_UNTESTED_INTERFACES [ComImport, System.Security.SuppressUnmanagedCodeSecurity, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("E31FB81B-1335-11D1-8189-0000F87557DB")] public interface IDXEffect { [PreserveSig] int get_Capabilities( out int pVal ); [PreserveSig] int get_Progress( out float pVal ); [PreserveSig] int put_Progress( float newVal ); [PreserveSig] int get_StepResolution( out float pVal ); [PreserveSig] int get_Duration( out float pVal ); [PreserveSig] int put_Duration( float newVal ); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, Guid("4EE9EAD9-DA4D-43D0-9383-06B90C08B12B"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDxtAlphaSetter : IDXEffect { #region IDXEffect Methods [PreserveSig] new int get_Capabilities( out int pVal ); [PreserveSig] new int get_Progress( out float pVal ); [PreserveSig] new int put_Progress( float newVal ); [PreserveSig] new int get_StepResolution( out float pVal ); [PreserveSig] new int get_Duration( out float pVal ); [PreserveSig] new int put_Duration( float newVal ); #endregion [PreserveSig] int get_Alpha( out int pVal ); [PreserveSig] int put_Alpha( int newVal ); [PreserveSig] int get_AlphaRamp( out double pVal ); [PreserveSig] int put_AlphaRamp( double newVal ); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, Guid("BB44391E-6ABD-422F-9E2E-385C9DFF51FC"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDxtCompositor : IDXEffect { #region IDXEffect [PreserveSig] new int get_Capabilities( out int pVal ); [PreserveSig] new int get_Progress( out float pVal ); [PreserveSig] new int put_Progress( float newVal ); [PreserveSig] new int get_StepResolution( out float pVal ); [PreserveSig] new int get_Duration( out float pVal ); [PreserveSig] new int put_Duration( float newVal ); #endregion [PreserveSig] int get_OffsetX( out int pVal ); [PreserveSig] int put_OffsetX( int newVal ); [PreserveSig] int get_OffsetY( out int pVal ); [PreserveSig] int put_OffsetY( int newVal ); [PreserveSig] int get_Width( out int pVal ); [PreserveSig] int put_Width( int newVal ); [PreserveSig] int get_Height( out int pVal ); [PreserveSig] int put_Height( int newVal ); [PreserveSig] int get_SrcOffsetX( out int pVal ); [PreserveSig] int put_SrcOffsetX( int newVal ); [PreserveSig] int get_SrcOffsetY( out int pVal ); [PreserveSig] int put_SrcOffsetY( int newVal ); [PreserveSig] int get_SrcWidth( out int pVal ); [PreserveSig] int put_SrcWidth( int newVal ); [PreserveSig] int get_SrcHeight( out int pVal ); [PreserveSig] int put_SrcHeight( int newVal ); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, Guid("DE75D011-7A65-11D2-8CEA-00A0C9441E20"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDxtJpeg : IDXEffect { #region IDXEffect [PreserveSig] new int get_Capabilities( out int pVal ); [PreserveSig] new int get_Progress( out float pVal ); [PreserveSig] new int put_Progress( float newVal ); [PreserveSig] new int get_StepResolution( out float pVal ); [PreserveSig] new int get_Duration( out float pVal ); [PreserveSig] new int put_Duration( float newVal ); #endregion [PreserveSig] int get_MaskNum( out int MIDL_0018 ); [PreserveSig] int put_MaskNum( int MIDL_0019 ); [PreserveSig] int get_MaskName( [MarshalAs(UnmanagedType.BStr)] out string pVal ); [PreserveSig] int put_MaskName( [MarshalAs(UnmanagedType.BStr)] string newVal ); [PreserveSig] int get_ScaleX( out double MIDL_0020 ); [PreserveSig] int put_ScaleX( double MIDL_0021 ); [PreserveSig] int get_ScaleY( out double MIDL_0022 ); [PreserveSig] int put_ScaleY( double MIDL_0023 ); [PreserveSig] int get_OffsetX( out int MIDL_0024 ); [PreserveSig] int put_OffsetX( int MIDL_0025 ); [PreserveSig] int get_OffsetY( out int MIDL_0026 ); [PreserveSig] int put_OffsetY( int MIDL_0027 ); [PreserveSig] int get_ReplicateX( out int pVal ); [PreserveSig] int put_ReplicateX( int newVal ); [PreserveSig] int get_ReplicateY( out int pVal ); [PreserveSig] int put_ReplicateY( int newVal ); [PreserveSig] int get_BorderColor( out int pVal ); [PreserveSig] int put_BorderColor( int newVal ); [PreserveSig] int get_BorderWidth( out int pVal ); [PreserveSig] int put_BorderWidth( int newVal ); [PreserveSig] int get_BorderSoftness( out int pVal ); [PreserveSig] int put_BorderSoftness( int newVal ); [PreserveSig] int ApplyChanges(); [PreserveSig] int LoadDefSettings(); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, Guid("3255DE56-38FB-4901-B980-94B438010D7B"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDxtKey : IDXEffect { #region IDXEffect [PreserveSig] new int get_Capabilities( out int pVal ); [PreserveSig] new int get_Progress( out float pVal ); [PreserveSig] new int put_Progress( float newVal ); [PreserveSig] new int get_StepResolution( out float pVal ); [PreserveSig] new int get_Duration( out float pVal ); [PreserveSig] new int put_Duration( float newVal ); #endregion [PreserveSig] int get_KeyType( out int MIDL_0028 ); [PreserveSig] int put_KeyType( int MIDL_0029 ); [PreserveSig] int get_Hue( out int MIDL_0030 ); [PreserveSig] int put_Hue( int MIDL_0031 ); [PreserveSig] int get_Luminance( out int MIDL_0032 ); [PreserveSig] int put_Luminance( int MIDL_0033 ); [PreserveSig] int get_RGB( out int MIDL_0034 ); [PreserveSig] int put_RGB( int MIDL_0035 ); [PreserveSig] int get_Similarity( out int MIDL_0036 ); [PreserveSig] int put_Similarity( int MIDL_0037 ); [PreserveSig] int get_Invert( [MarshalAs(UnmanagedType.Bool)] out bool MIDL_0038 ); [PreserveSig] int put_Invert( [MarshalAs(UnmanagedType.Bool)] bool MIDL_0039 ); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("F03FA8DE-879A-4D59-9B2C-26BB1CF83461")] public interface IFindCompressorCB { [PreserveSig] int GetCompressor( [MarshalAs(UnmanagedType.LPStruct)] AMMediaType pType, [MarshalAs(UnmanagedType.LPStruct)] AMMediaType pCompType, out IBaseFilter ppFilter ); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, InterfaceType(ComInterfaceType.InterfaceIsDual), Guid("AE9472BE-B0C3-11D2-8D24-00A0C9441E20")] public interface IGrfCache { [PreserveSig] int AddFilter(IGrfCache ChainedCache, long Id, IBaseFilter pFilter, [MarshalAs(UnmanagedType.LPWStr)] string pName); [PreserveSig] int ConnectPins(IGrfCache ChainedCache, long PinID1, IPin pPin1, long PinID2, IPin pPin2); [PreserveSig] int SetGraph(IGraphBuilder pGraph); [PreserveSig] int DoConnectionsNow(); } #endif [ComImport, System.Security.SuppressUnmanagedCodeSecurity, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("E43E73A2-0EFA-11D3-9601-00A0C9441E20")] public interface IAMErrorLog { [PreserveSig] int LogError( int Severity, [MarshalAs(UnmanagedType.BStr)] string pErrorString, int ErrorCode, int hresult, [In] IntPtr pExtraInfo ); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("963566DA-BE21-4EAF-88E9-35704F8F52A1")] public interface IAMSetErrorLog { [PreserveSig] int get_ErrorLog( out IAMErrorLog pVal ); [PreserveSig] int put_ErrorLog( IAMErrorLog newVal ); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("78530B74-61F9-11D2-8CAD-00A024580902")] public interface IAMTimeline { [PreserveSig] int CreateEmptyNode( out IAMTimelineObj ppObj, TimelineMajorType Type ); [PreserveSig] int AddGroup( IAMTimelineObj pGroup ); [PreserveSig] int RemGroupFromList( IAMTimelineObj pGroup ); [PreserveSig] int GetGroup( out IAMTimelineObj ppGroup, int WhichGroup ); [PreserveSig] int GetGroupCount( out int pCount ); [PreserveSig] int ClearAllGroups(); [PreserveSig] int GetInsertMode( out TimelineInsertMode pMode ); [PreserveSig] int SetInsertMode( TimelineInsertMode Mode ); [PreserveSig] int EnableTransitions( [MarshalAs(UnmanagedType.Bool)] bool fEnabled ); [PreserveSig] int TransitionsEnabled( [MarshalAs(UnmanagedType.Bool)] out bool pfEnabled ); [PreserveSig] int EnableEffects( [MarshalAs(UnmanagedType.Bool)] bool fEnabled ); [PreserveSig] int EffectsEnabled( [MarshalAs(UnmanagedType.Bool)] out bool pfEnabled ); [PreserveSig] int SetInterestRange( long Start, long Stop ); [PreserveSig] int GetDuration( out long pDuration ); [PreserveSig] int GetDuration2( out double pDuration ); [PreserveSig] int SetDefaultFPS( double FPS ); [PreserveSig] int GetDefaultFPS( out double pFPS ); [PreserveSig] int IsDirty( [MarshalAs(UnmanagedType.Bool)] out bool pDirty ); [PreserveSig] int GetDirtyRange( out long pStart, out long pStop ); [PreserveSig] int GetCountOfType( int Group, out int pVal, out int pValWithComps, TimelineMajorType majortype ); [PreserveSig] int ValidateSourceNames( SFNValidateFlags ValidateFlags, IMediaLocator pOverride, IntPtr NotifyEventHandle ); [PreserveSig] int SetDefaultTransition( [MarshalAs(UnmanagedType.LPStruct)] Guid pGuid ); [PreserveSig] int GetDefaultTransition( out Guid pGuid ); [PreserveSig] int SetDefaultEffect( [MarshalAs(UnmanagedType.LPStruct)] Guid pGuid ); [PreserveSig] int GetDefaultEffect( out Guid pGuid ); [PreserveSig] int SetDefaultTransitionB( [MarshalAs(UnmanagedType.BStr)] string pGuid ); [PreserveSig] int GetDefaultTransitionB( [Out, MarshalAs(UnmanagedType.BStr)] out string sGuid ); [PreserveSig] int SetDefaultEffectB( [MarshalAs(UnmanagedType.BStr)] string pGuid ); [PreserveSig] int GetDefaultEffectB( [Out, MarshalAs(UnmanagedType.BStr)] out string sGuid ); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("EAE58536-622E-11D2-8CAD-00A024580902")] public interface IAMTimelineComp { [PreserveSig] int VTrackInsBefore( IAMTimelineObj pVirtualTrack, int priority ); [PreserveSig] int VTrackSwapPriorities( int VirtualTrackA, int VirtualTrackB ); [PreserveSig] int VTrackGetCount( out int pVal ); [PreserveSig] int GetVTrack( out IAMTimelineObj ppVirtualTrack, int Which ); [PreserveSig] int GetCountOfType( out int pVal, out int pValWithComps, TimelineMajorType majortype ); [PreserveSig] int GetRecursiveLayerOfType( out IAMTimelineObj ppVirtualTrack, int WhichLayer, TimelineMajorType Type ); [PreserveSig] int GetRecursiveLayerOfTypeI( out IAMTimelineObj ppVirtualTrack, [In, Out] ref int pWhichLayer, TimelineMajorType Type ); [PreserveSig] int GetNextVTrack( IAMTimelineObj pVirtualTrack, out IAMTimelineObj ppNextVirtualTrack ); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("BCE0C264-622D-11D2-8CAD-00A024580902")] public interface IAMTimelineEffect { [PreserveSig] int EffectGetPriority(out int pVal); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, Guid("EAE58537-622E-11D2-8CAD-00A024580902"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IAMTimelineEffectable { [PreserveSig] int EffectInsBefore( IAMTimelineObj pFX, int priority ); [PreserveSig] int EffectSwapPriorities( int PriorityA, int PriorityB ); [PreserveSig] int EffectGetCount( out int pCount ); [PreserveSig] int GetEffect( out IAMTimelineObj ppFx, int Which ); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, Guid("9EED4F00-B8A6-11D2-8023-00C0DF10D434"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IAMTimelineGroup { [PreserveSig] int SetTimeline( IAMTimeline pTimeline ); [PreserveSig] int GetTimeline( out IAMTimeline ppTimeline ); [PreserveSig] int GetPriority( out int pPriority ); [PreserveSig] int GetMediaType( [Out, MarshalAs(UnmanagedType.LPStruct)] AMMediaType pmt ); [PreserveSig] int SetMediaType( [In, MarshalAs(UnmanagedType.LPStruct)] AMMediaType pmt ); [PreserveSig] int SetOutputFPS( double FPS ); [PreserveSig] int GetOutputFPS( out double pFPS ); [PreserveSig] int SetGroupName( [MarshalAs(UnmanagedType.BStr)] string pGroupName ); [PreserveSig] int GetGroupName( [MarshalAs(UnmanagedType.BStr)] out string pGroupName ); [PreserveSig] int SetPreviewMode( [MarshalAs(UnmanagedType.Bool)] bool fPreview ); [PreserveSig] int GetPreviewMode( [MarshalAs(UnmanagedType.Bool)] out bool pfPreview ); [PreserveSig] int SetMediaTypeForVB( [In] int Val ); [PreserveSig] int GetOutputBuffering( out int pnBuffer ); [PreserveSig] int SetOutputBuffering( [In] int nBuffer ); [PreserveSig] int SetSmartRecompressFormat( SCompFmt0 pFormat ); [PreserveSig] int GetSmartRecompressFormat( out SCompFmt0 ppFormat ); [PreserveSig] int IsSmartRecompressFormatSet( [MarshalAs(UnmanagedType.Bool)] out bool pVal ); [PreserveSig] int IsRecompressFormatDirty( [MarshalAs(UnmanagedType.Bool)] out bool pVal ); [PreserveSig] int ClearRecompressFormatDirty(); [PreserveSig] int SetRecompFormatFromSource( IAMTimelineSrc pSource ); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, Guid("78530B77-61F9-11D2-8CAD-00A024580902"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IAMTimelineObj { [PreserveSig] int GetStartStop( out long pStart, out long pStop ); [PreserveSig] int GetStartStop2( out double pStart, out double pStop ); [PreserveSig] int FixTimes( ref long pStart, ref long pStop ); [PreserveSig] int FixTimes2( ref double pStart, ref double pStop ); [PreserveSig] int SetStartStop( long Start, long Stop ); [PreserveSig] int SetStartStop2( double Start, double Stop ); [PreserveSig] int GetPropertySetter( out IPropertySetter pVal ); [PreserveSig] int SetPropertySetter( IPropertySetter newVal ); [PreserveSig] int GetSubObject( [MarshalAs(UnmanagedType.IUnknown)] out object pVal ); [PreserveSig] int SetSubObject( [In, MarshalAs(UnmanagedType.IUnknown)] object newVal ); [PreserveSig] int SetSubObjectGUID( Guid newVal ); [PreserveSig] int SetSubObjectGUIDB( [MarshalAs(UnmanagedType.BStr)] string newVal ); [PreserveSig] int GetSubObjectGUID( out Guid pVal ); [PreserveSig] int GetSubObjectGUIDB( [MarshalAs(UnmanagedType.BStr)] out string pVal ); [PreserveSig] int GetSubObjectLoaded( [MarshalAs(UnmanagedType.Bool)] out bool pVal ); [PreserveSig] int GetTimelineType( out TimelineMajorType pVal ); [PreserveSig] int SetTimelineType( TimelineMajorType newVal ); [PreserveSig] int GetUserID( out int pVal ); [PreserveSig] int SetUserID( int newVal ); [PreserveSig] int GetGenID( out int pVal ); [PreserveSig] int GetUserName( [MarshalAs(UnmanagedType.BStr)] out string pVal ); [PreserveSig] int SetUserName( [MarshalAs(UnmanagedType.BStr)] string newVal ); [PreserveSig] int GetUserData( IntPtr pData, out int pSize ); [PreserveSig] int SetUserData( IntPtr pData, int Size ); [PreserveSig] int GetMuted( [MarshalAs(UnmanagedType.Bool)] out bool pVal ); [PreserveSig] int SetMuted( [MarshalAs(UnmanagedType.Bool)] bool newVal ); [PreserveSig] int GetLocked( [MarshalAs(UnmanagedType.Bool)] out bool pVal ); [PreserveSig] int SetLocked( [MarshalAs(UnmanagedType.Bool)] bool newVal ); [PreserveSig] int GetDirtyRange( out long pStart, out long pStop ); [PreserveSig] int GetDirtyRange2( out double pStart, out double pStop ); [PreserveSig] int SetDirtyRange( long Start, long Stop ); [PreserveSig] int SetDirtyRange2( double Start, double Stop ); [PreserveSig] int ClearDirty(); [PreserveSig] int Remove(); [PreserveSig] int RemoveAll(); [PreserveSig] int GetTimelineNoRef( out IAMTimeline ppResult ); [PreserveSig] int GetGroupIBelongTo( out IAMTimelineGroup ppGroup ); [PreserveSig] int GetEmbedDepth( out int pVal ); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("A0F840A0-D590-11D2-8D55-00A0C9441E20")] public interface IAMTimelineSplittable { [PreserveSig] int SplitAt( long Time ); [PreserveSig] int SplitAt2( double Time ); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, Guid("78530B79-61F9-11D2-8CAD-00A024580902"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IAMTimelineSrc { [PreserveSig] int GetMediaTimes( out long pStart, out long pStop ); [PreserveSig] int GetMediaTimes2( out double pStart, out double pStop ); [PreserveSig] int ModifyStopTime( long Stop ); [PreserveSig] int ModifyStopTime2( double Stop ); [PreserveSig] int FixMediaTimes( ref long pStart, ref long pStop ); [PreserveSig] int FixMediaTimes2( ref double pStart, ref double pStop ); [PreserveSig] int SetMediaTimes( long Start, long Stop ); [PreserveSig] int SetMediaTimes2( double Start, double Stop ); [PreserveSig] int SetMediaLength( long Length ); [PreserveSig] int SetMediaLength2( double Length ); [PreserveSig] int GetMediaLength( out long pLength ); [PreserveSig] int GetMediaLength2( out double pLength ); [PreserveSig] int GetMediaName( [MarshalAs(UnmanagedType.BStr)] out string pVal ); [PreserveSig] int SetMediaName( [MarshalAs(UnmanagedType.BStr)] string newVal ); [PreserveSig] int SpliceWithNext( IAMTimelineObj pNext ); [PreserveSig] int GetStreamNumber( out int pVal ); [PreserveSig] int SetStreamNumber( int Val ); [PreserveSig] int IsNormalRate( [MarshalAs(UnmanagedType.Bool)] out bool pVal ); [PreserveSig] int GetDefaultFPS( out double pFPS ); [PreserveSig] int SetDefaultFPS( double FPS ); [PreserveSig] int GetStretchMode( out ResizeFlags pnStretchMode ); [PreserveSig] int SetStretchMode( ResizeFlags nStretchMode ); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, Guid("EAE58538-622E-11D2-8CAD-00A024580902"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IAMTimelineTrack { [PreserveSig] int SrcAdd( IAMTimelineObj pSource ); [PreserveSig] int GetNextSrc( out IAMTimelineObj ppSrc, ref long pInOut ); [PreserveSig] int GetNextSrc2( out IAMTimelineObj ppSrc, ref double pInOut ); [PreserveSig] int MoveEverythingBy( long Start, long MoveBy ); [PreserveSig] int MoveEverythingBy2( double Start, double MoveBy ); [PreserveSig] int GetSourcesCount( out int pVal ); [PreserveSig] int AreYouBlank( [MarshalAs(UnmanagedType.Bool)] out bool pVal ); [PreserveSig] int GetSrcAtTime( out IAMTimelineObj ppSrc, long Time, DexterFTrackSearchFlags SearchDirection ); [PreserveSig] int GetSrcAtTime2( out IAMTimelineObj ppSrc, double Time, DexterFTrackSearchFlags SearchDirection ); [PreserveSig] int InsertSpace( long rtStart, long rtEnd ); [PreserveSig] int InsertSpace2( double rtStart, double rtEnd ); [PreserveSig] int ZeroBetween( long rtStart, long rtEnd ); [PreserveSig] int ZeroBetween2( double rtStart, double rtEnd ); [PreserveSig] int GetNextSrcEx( IAMTimelineObj pLast, out IAMTimelineObj ppNext ); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("BCE0C265-622D-11D2-8CAD-00A024580902")] public interface IAMTimelineTrans { [PreserveSig] int GetCutPoint( out long pTLTime ); [PreserveSig] int GetCutPoint2( out double pTLTime ); [PreserveSig] int SetCutPoint( long TLTime ); [PreserveSig] int SetCutPoint2( double TLTime ); [PreserveSig] int GetSwapInputs( [MarshalAs(UnmanagedType.Bool)] out bool pVal ); [PreserveSig] int SetSwapInputs( [MarshalAs(UnmanagedType.Bool)] bool pVal ); [PreserveSig] int GetCutsOnly( [MarshalAs(UnmanagedType.Bool)] out bool pVal ); [PreserveSig] int SetCutsOnly( [MarshalAs(UnmanagedType.Bool)] bool pVal ); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, Guid("378FA386-622E-11D2-8CAD-00A024580902"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IAMTimelineTransable { [PreserveSig] int TransAdd( IAMTimelineObj pTrans ); [PreserveSig] int TransGetCount( out int pCount ); [PreserveSig] int GetNextTrans( out IAMTimelineObj ppTrans, ref long pInOut ); [PreserveSig] int GetNextTrans2( out IAMTimelineObj ppTrans, ref double pInOut ); [PreserveSig] int GetTransAtTime( out IAMTimelineObj ppObj, long Time, DexterFTrackSearchFlags SearchDirection ); [PreserveSig] int GetTransAtTime2( out IAMTimelineObj ppObj, double Time, DexterFTrackSearchFlags SearchDirection ); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, Guid("A8ED5F80-C2C7-11D2-8D39-00A0C9441E20"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IAMTimelineVirtualTrack { [PreserveSig] int TrackGetPriority( out int pPriority ); [PreserveSig] int SetTrackDirty(); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("65BD0710-24D2-4ff7-9324-ED2E5D3ABAFA")] public interface IMediaDet { [PreserveSig] int get_Filter( [MarshalAs(UnmanagedType.IUnknown)] out object pVal ); [PreserveSig] int put_Filter( [MarshalAs(UnmanagedType.IUnknown)] object newVal ); [PreserveSig] int get_OutputStreams( out int pVal ); [PreserveSig] int get_CurrentStream( out int pVal ); [PreserveSig] int put_CurrentStream( int newVal ); [PreserveSig] int get_StreamType( out Guid pVal ); [PreserveSig] int get_StreamTypeB( [MarshalAs(UnmanagedType.BStr)] out string pVal ); [PreserveSig] int get_StreamLength( out double pVal ); [PreserveSig] int get_Filename( [MarshalAs(UnmanagedType.BStr)] out string pVal ); [PreserveSig] int put_Filename( [MarshalAs(UnmanagedType.BStr)] string newVal ); [PreserveSig] int GetBitmapBits( double StreamTime, out int pBufferSize, [In] IntPtr pBuffer, int Width, int Height ); [PreserveSig] int WriteBitmapBits( double StreamTime, int Width, int Height, [In, MarshalAs(UnmanagedType.BStr)] string Filename); [PreserveSig] int get_StreamMediaType( [Out, MarshalAs(UnmanagedType.LPStruct)] AMMediaType pVal); [PreserveSig] int GetSampleGrabber( out ISampleGrabber ppVal); [PreserveSig] int get_FrameRate( out double pVal); [PreserveSig] int EnterBitmapGrabMode( double SeekTime); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("288581E0-66CE-11D2-918F-00C0DF10D434")] public interface IMediaLocator { [PreserveSig] int FindMediaFile( [MarshalAs(UnmanagedType.BStr)] string Input, [MarshalAs(UnmanagedType.BStr)] string FilterString, [MarshalAs(UnmanagedType.BStr)] out string pOutput, SFNValidateFlags Flags ); [PreserveSig] int AddFoundLocation( [MarshalAs(UnmanagedType.BStr)] string DirectoryName ); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("AE9472BD-B0C3-11D2-8D24-00A0C9441E20")] public interface IPropertySetter { [PreserveSig] int LoadXML( [In, MarshalAs(UnmanagedType.IUnknown)] object pxml ); [PreserveSig] int PrintXML( [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder pszXML, [In] int cbXML, out int pcbPrinted, [In] int indent ); [PreserveSig] int CloneProps( out IPropertySetter ppSetter, [In] long rtStart, [In] long rtStop ); [PreserveSig] int AddProp( [In] DexterParam Param, [In, MarshalAs(UnmanagedType.LPArray)] DexterValue [] paValue ); [PreserveSig] int GetProps( out int pcParams, out IntPtr paParam, out IntPtr paValue ); [PreserveSig] int FreeProps( [In] int cParams, [In] IntPtr paParam, [In] IntPtr paValue ); [PreserveSig] int ClearProps(); [PreserveSig] int SaveToBlob( out int pcSize, out IntPtr ppb ); [PreserveSig] int LoadFromBlob( [In] int cSize, [In] IntPtr pb ); [PreserveSig] int SetProps( [In, MarshalAs(UnmanagedType.IUnknown)] object pTarget, [In] long rtNow ); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("6BEE3A81-66C9-11D2-918F-00C0DF10D434")] public interface IRenderEngine { [PreserveSig] int SetTimelineObject( IAMTimeline pTimeline ); [PreserveSig] int GetTimelineObject( out IAMTimeline ppTimeline ); [PreserveSig] int GetFilterGraph( out IGraphBuilder ppFG ); [PreserveSig] int SetFilterGraph( IGraphBuilder pFG ); [PreserveSig] int SetInterestRange( long Start, long Stop ); [PreserveSig] int SetInterestRange2( double Start, double Stop ); [PreserveSig] int SetRenderRange( long Start, long Stop ); [PreserveSig] int SetRenderRange2( double Start, double Stop ); [PreserveSig] int GetGroupOutputPin( int Group, out IPin ppRenderPin ); [PreserveSig] int ScrapIt(); [PreserveSig] int RenderOutputPins(); [PreserveSig] int GetVendorString( [MarshalAs(UnmanagedType.BStr)] out string sVendor ); [PreserveSig] int ConnectFrontEnd(); [PreserveSig] int SetSourceConnectCallback( #if ALLOW_UNTESTED_INTERFACES IGrfCache pCallback #else object pCallback #endif ); [PreserveSig] int SetDynamicReconnectLevel( ConnectFDynamic Level ); [PreserveSig] int DoSmartRecompression(); [PreserveSig] int UseInSmartRecompressionGraph(); [PreserveSig] int SetSourceNameValidation( [MarshalAs(UnmanagedType.BStr)] string FilterString, IMediaLocator pOverride, SFNValidateFlags Flags ); [PreserveSig] int Commit(); [PreserveSig] int Decommit(); [PreserveSig] int GetCaps( int Index, out int pReturn ); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, Guid("F03FA8CE-879A-4D59-9B2C-26BB1CF83461"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface ISmartRenderEngine { [PreserveSig] int SetGroupCompressor( int Group, IBaseFilter pCompressor ); [PreserveSig] int GetGroupCompressor( int Group, out IBaseFilter pCompressor ); [PreserveSig] int SetFindCompressorCB( #if ALLOW_UNTESTED_INTERFACES IFindCompressorCB pCallback #else object pCallback #endif ); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, InterfaceType(ComInterfaceType.InterfaceIsDual), Guid("18C628ED-962A-11D2-8D08-00A0C9441E20")] public interface IXml2Dex { [PreserveSig] int CreateGraphFromFile( [MarshalAs(UnmanagedType.IUnknown)] out object ppGraph, [MarshalAs(UnmanagedType.IUnknown)] object pTimeline, [MarshalAs(UnmanagedType.BStr)] string Filename ); [PreserveSig] int WriteGrfFile( [MarshalAs(UnmanagedType.IUnknown)] object pGraph, [MarshalAs(UnmanagedType.BStr)] string Filename ); [PreserveSig] int WriteXMLFile( [MarshalAs(UnmanagedType.IUnknown)] object pTimeline, [MarshalAs(UnmanagedType.BStr)] string Filename ); [PreserveSig] int ReadXMLFile( [MarshalAs(UnmanagedType.IUnknown)] object pTimeline, [MarshalAs(UnmanagedType.BStr)] string XMLName ); [PreserveSig] int Delete( [MarshalAs(UnmanagedType.IUnknown)] object pTimeline, double dStart, double dEnd ); [PreserveSig] int WriteXMLPart( [MarshalAs(UnmanagedType.IUnknown)] object pTimeline, double dStart, double dEnd, [MarshalAs(UnmanagedType.BStr)] string Filename ); [PreserveSig] int PasteXMLFile( [MarshalAs(UnmanagedType.IUnknown)] object pTimeline, double dStart, [MarshalAs(UnmanagedType.BStr)] string Filename ); [PreserveSig] int CopyXML( [MarshalAs(UnmanagedType.IUnknown)] object pTimeline, double dStart, double dEnd ); [PreserveSig] int PasteXML( [MarshalAs(UnmanagedType.IUnknown)] object pTimeline, double dStart ); [PreserveSig] int Reset(); [PreserveSig] int ReadXML( [MarshalAs(UnmanagedType.IUnknown)] object pTimeline, [MarshalAs(UnmanagedType.IUnknown)] object pxml ); [PreserveSig] int WriteXML( [MarshalAs(UnmanagedType.IUnknown)] object pTimeline, [MarshalAs(UnmanagedType.BStr)] out string pbstrXML ); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("6BEE3A82-66C9-11d2-918F-00C0DF10D434")] public interface IRenderEngine2 { [PreserveSig] int SetResizerGUID( [In] Guid ResizerGuid ); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("4ada63a0-72d5-11d2-952a-0060081840bc")] public interface IResize { [PreserveSig] int get_Size( out int piHeight, out int piWidth, out ResizeFlags pFlag ); [PreserveSig] int get_InputSize( out int piHeight, out int piWidth ); [PreserveSig] int put_Size( int Height, int Width, ResizeFlags Flag ); [PreserveSig] int get_MediaType( [Out, MarshalAs(UnmanagedType.LPStruct)] AMMediaType pmt ); [PreserveSig] int put_MediaType( [In, MarshalAs(UnmanagedType.LPStruct)] AMMediaType pmt ); } #endregion }
using System; using System.Collections.Generic; namespace Zeus.UserInterface { /// <summary> /// Each of the supported controls (GuiController, GuiTextbox, GuiComboBox, GuiLabel, GuiButton, etc) /// inherit from GuiControl. /// </summary> [Serializable()] public abstract class GuiControl : IGuiControl { protected string _id = string.Empty; protected string _tooltip = string.Empty; protected string _foreColor = "Black"; protected string _backColor = string.Empty; private int _hieght = 16; private int _width = 300; private int _top = 10; private int _left = 10; private bool _visible = true; private bool _enabled = true; private bool _isDataControl = true; private int _tabStripIndex = 0; private List<string> _onblurEvents = new List<string>(); private List<string> _onfocusEvents = new List<string>(); private List<GuiControl> _autoBindingChildControls; /// <summary> /// Sets or gets the controls ID. /// </summary> public virtual string ID { get { return _id; } set { _id = value; } } /// <summary> /// If this control stores input data, this will be true. /// </summary> public virtual bool IsDataControl { get { return _isDataControl; } set { _isDataControl = value; } } /// <summary> /// Sets or gets the controls tooltip. /// </summary> public virtual string ToolTip { get { return _tooltip; } set { _tooltip = value; } } /// <summary> /// The control is invisible if this is false. /// </summary> public virtual bool Visible { get { return _visible; } set { _visible = value; } } /// <summary> /// True if enabled, false if disabled. /// </summary> public virtual bool Enabled { get { return _enabled; } set { _enabled = value; } } /// <summary> /// Sets or gets the controls ForeColor. /// </summary> public virtual string ForeColor { get { return _foreColor; } set { _foreColor = value; } } /// <summary> /// Sets or gets the controls BackColor. /// </summary> public virtual string BackColor { get { return _backColor; } set { _backColor = value; } } /// <summary> /// Returns the value of the control. /// </summary> public abstract object Value { get; } /// <summary> /// Sets or gets the width of the control. /// </summary> public virtual int Width { get { return this._width; } set { this._width = value; } } /// <summary> /// Sets or gets the height of the control. /// </summary> public virtual int Height { get { return this._hieght; } set { this._hieght = value; } } /// <summary> /// Sets or gets the top coordinate of the control. /// </summary> public virtual int Top { get { return this._top; } set { this._top = value; } } /// <summary> /// Sets or gets the left coordinate of the control. /// </summary> public virtual int Left { get { return this._left; } set { this._left = value; } } /// <summary> /// The tabstrip index this tab is assigned to /// </summary> internal int TabStripIndex { get { return this._tabStripIndex; } set { this._tabStripIndex = value; } } /// <summary> /// Attaches the functionName to the eventType event. /// The GuiFilePicker supports the onselect event. /// </summary> /// <param name="eventType">The type of event to attach.</param> /// <param name="functionName">Name of the function to be called when the event fires. /// The functionName should have the signature in the Gui code: /// "eventHandlerFunctionName(GuiFilePicker control)"</param> public virtual void AttachEvent(string eventType, string functionName) { if (eventType.ToLower() == "onblur") { this._onblurEvents.Add(functionName); } else if (eventType.ToLower() == "onfocus") { this._onfocusEvents.Add(functionName); } } /// <summary> /// This returns true if there are any event handlers for the passed in eventType. /// </summary> /// <param name="eventType">The type of event to check for.</param> /// <returns>Returns true if there are any event handlers of the given type.</returns> public virtual bool HasEventHandlers(string eventType) { if (eventType.ToLower() == "onblur") { return (this._onblurEvents.Count > 0); } else if (eventType.ToLower() == "onfocus") { return (this._onfocusEvents.Count > 0); } else { return false; } } /// <summary> /// This returns all of the event handler functions that have been assigned /// to this object for the passed in eventType. /// </summary> /// <param name="eventType">The type of event to return function names for.</param> /// <returns>All of the event handler functions that have been assigned /// to this object for the given eventType</returns> public virtual string[] GetEventHandlers(string eventType) { if (eventType.ToLower() == "onblur") { return this._onblurEvents.ToArray(); } else if (eventType.ToLower() == "onfocus") { return this._onfocusEvents.ToArray(); } else { return new string[0]; } } /// <summary> /// /// </summary> [System.Runtime.InteropServices.ComVisible(false)] public List<GuiControl> AutoBindingChildControls { get { if (_autoBindingChildControls == null) _autoBindingChildControls = new List<GuiControl>(); return _autoBindingChildControls; } } } }
#region File Description //----------------------------------------------------------------------------- // ContentBuilder.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.IO; using System.Diagnostics; using System.Collections.Generic; using Microsoft.Build.Construction; using Microsoft.Build.Evaluation; using Microsoft.Build.Execution; using Microsoft.Build.Framework; #endregion namespace WinFormsContentLoading { /// <summary> /// This class wraps the MSBuild functionality needed to build XNA Framework /// content dynamically at runtime. It creates a temporary MSBuild project /// in memory, and adds whatever content files you choose to this project. /// It then builds the project, which will create compiled .xnb content files /// in a temporary directory. After the build finishes, you can use a regular /// ContentManager to load these temporary .xnb files in the usual way. /// </summary> class ContentBuilder : IDisposable { #region Fields // What importers or processors should we load? const string xnaVersion = ", Version=4.0.0.0, PublicKeyToken=842cf8be1de50553"; static string[] pipelineAssemblies = { "Microsoft.Xna.Framework.Content.Pipeline.FBXImporter" + xnaVersion, "Microsoft.Xna.Framework.Content.Pipeline.XImporter" + xnaVersion, "Microsoft.Xna.Framework.Content.Pipeline.TextureImporter" + xnaVersion, "Microsoft.Xna.Framework.Content.Pipeline.EffectImporter" + xnaVersion, // If you want to use custom importers or processors from // a Content Pipeline Extension Library, add them here. // // If your extension DLL is installed in the GAC, you should refer to it by assembly // name, eg. "MyPipelineExtension, Version=1.0.0.0, PublicKeyToken=1234567812345678". // // If the extension DLL is not in the GAC, you should refer to it by // file path, eg. "c:/MyProject/bin/MyPipelineExtension.dll". }; // MSBuild objects used to dynamically build content. Project buildProject; ProjectRootElement projectRootElement; BuildParameters buildParameters; List<ProjectItem> projectItems = new List<ProjectItem>(); ErrorLogger errorLogger; // Temporary directories used by the content build. string buildDirectory; string processDirectory; string baseDirectory; // Generate unique directory names if there is more than one ContentBuilder. static int directorySalt; // Have we been disposed? bool isDisposed; #endregion #region Properties /// <summary> /// Gets the output directory, which will contain the generated .xnb files. /// </summary> public string OutputDirectory { get { return Path.Combine(buildDirectory, "bin/Content"); } } #endregion #region Initialization /// <summary> /// Creates a new content builder. /// </summary> public ContentBuilder() { CreateTempDirectory(); CreateBuildProject(); } /// <summary> /// Finalizes the content builder. /// </summary> ~ContentBuilder() { Dispose(false); } /// <summary> /// Disposes the content builder when it is no longer required. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Implements the standard .NET IDisposable pattern. /// </summary> protected virtual void Dispose(bool disposing) { if (!isDisposed) { isDisposed = true; DeleteTempDirectory(); } } #endregion #region MSBuild /// <summary> /// Creates a temporary MSBuild content project in memory. /// </summary> void CreateBuildProject() { string projectPath = Path.Combine(buildDirectory, "content.contentproj"); string outputPath = Path.Combine(buildDirectory, "bin"); // Create the build project. projectRootElement = ProjectRootElement.Create(projectPath); // Include the standard targets file that defines how to build XNA Framework content. projectRootElement.AddImport("$(MSBuildExtensionsPath)\\Microsoft\\XNA Game Studio\\" + "v4.0\\Microsoft.Xna.GameStudio.ContentPipeline.targets"); buildProject = new Project(projectRootElement); buildProject.SetProperty("XnaPlatform", "Windows"); buildProject.SetProperty("XnaProfile", "Reach"); buildProject.SetProperty("XnaFrameworkVersion", "v4.0"); buildProject.SetProperty("Configuration", "Release"); buildProject.SetProperty("OutputPath", outputPath); // Register any custom importers or processors. foreach (string pipelineAssembly in pipelineAssemblies) { buildProject.AddItem("Reference", pipelineAssembly); } // Hook up our custom error logger. errorLogger = new ErrorLogger(); buildParameters = new BuildParameters(ProjectCollection.GlobalProjectCollection); buildParameters.Loggers = new ILogger[] { errorLogger }; } /// <summary> /// Adds a new content file to the MSBuild project. The importer and /// processor are optional: if you leave the importer null, it will /// be autodetected based on the file extension, and if you leave the /// processor null, data will be passed through without any processing. /// </summary> public void Add(string filename, string name, string importer, string processor) { ProjectItem item = buildProject.AddItem("Compile", filename)[0]; item.SetMetadataValue("Link", Path.GetFileName(filename)); item.SetMetadataValue("Name", name); if (!string.IsNullOrEmpty(importer)) item.SetMetadataValue("Importer", importer); if (!string.IsNullOrEmpty(processor)) item.SetMetadataValue("Processor", processor); projectItems.Add(item); } /// <summary> /// Removes all content files from the MSBuild project. /// </summary> public void Clear() { buildProject.RemoveItems(projectItems); projectItems.Clear(); } /// <summary> /// Builds all the content files which have been added to the project, /// dynamically creating .xnb files in the OutputDirectory. /// Returns an error message if the build fails. /// </summary> public string Build() { // Clear any previous errors. errorLogger.Errors.Clear(); // Create and submit a new asynchronous build request. BuildManager.DefaultBuildManager.BeginBuild(buildParameters); BuildRequestData request = new BuildRequestData(buildProject.CreateProjectInstance(), new string[0]); BuildSubmission submission = BuildManager.DefaultBuildManager.PendBuildRequest(request); submission.ExecuteAsync(null, null); // Wait for the build to finish. submission.WaitHandle.WaitOne(); BuildManager.DefaultBuildManager.EndBuild(); // If the build failed, return an error string. if (submission.BuildResult.OverallResult == BuildResultCode.Failure) { return string.Join("\n", errorLogger.Errors.ToArray()); } return null; } #endregion #region Temp Directories /// <summary> /// Creates a temporary directory in which to build content. /// </summary> void CreateTempDirectory() { // Start with a standard base name: // // %temp%\WinFormsContentLoading.ContentBuilder baseDirectory = Path.Combine(Path.GetTempPath(), GetType().FullName); // Include our process ID, in case there is more than // one copy of the program running at the same time: // // %temp%\WinFormsContentLoading.ContentBuilder\<ProcessId> int processId = Process.GetCurrentProcess().Id; processDirectory = Path.Combine(baseDirectory, processId.ToString()); // Include a salt value, in case the program // creates more than one ContentBuilder instance: // // %temp%\WinFormsContentLoading.ContentBuilder\<ProcessId>\<Salt> directorySalt++; buildDirectory = Path.Combine(processDirectory, directorySalt.ToString()); // Create our temporary directory. Directory.CreateDirectory(buildDirectory); PurgeStaleTempDirectories(); } /// <summary> /// Deletes our temporary directory when we are finished with it. /// </summary> void DeleteTempDirectory() { Directory.Delete(buildDirectory, true); // If there are no other instances of ContentBuilder still using their // own temp directories, we can delete the process directory as well. if (Directory.GetDirectories(processDirectory).Length == 0) { Directory.Delete(processDirectory); // If there are no other copies of the program still using their // own temp directories, we can delete the base directory as well. if (Directory.GetDirectories(baseDirectory).Length == 0) { Directory.Delete(baseDirectory); } } } /// <summary> /// Ideally, we want to delete our temp directory when we are finished using /// it. The DeleteTempDirectory method (called by whichever happens first out /// of Dispose or our finalizer) does exactly that. Trouble is, sometimes /// these cleanup methods may never execute. For instance if the program /// crashes, or is halted using the debugger, we never get a chance to do /// our deleting. The next time we start up, this method checks for any temp /// directories that were left over by previous runs which failed to shut /// down cleanly. This makes sure these orphaned directories will not just /// be left lying around forever. /// </summary> void PurgeStaleTempDirectories() { // Check all subdirectories of our base location. foreach (string directory in Directory.GetDirectories(baseDirectory)) { // The subdirectory name is the ID of the process which created it. int processId; if (int.TryParse(Path.GetFileName(directory), out processId)) { try { // Is the creator process still running? Process.GetProcessById(processId); } catch (ArgumentException) { // If the process is gone, we can delete its temp directory. Directory.Delete(directory, true); } } } } #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.13.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; public static partial class NetworkSecurityGroupsOperationsExtensions { /// <summary> /// The Delete NetworkSecurityGroup operation deletes the specifed network /// security group /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> public static void Delete(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName) { Task.Factory.StartNew(s => ((INetworkSecurityGroupsOperations)s).DeleteAsync(resourceGroupName, networkSecurityGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Delete NetworkSecurityGroup operation deletes the specifed network /// security group /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync( this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// The Delete NetworkSecurityGroup operation deletes the specifed network /// security group /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> public static void BeginDelete(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName) { Task.Factory.StartNew(s => ((INetworkSecurityGroupsOperations)s).BeginDeleteAsync(resourceGroupName, networkSecurityGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Delete NetworkSecurityGroup operation deletes the specifed network /// security group /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync( this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// The Get NetworkSecurityGroups operation retrieves information about the /// specified network security group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='expand'> /// expand references resources. /// </param> public static NetworkSecurityGroup Get(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, string expand = default(string)) { return Task.Factory.StartNew(s => ((INetworkSecurityGroupsOperations)s).GetAsync(resourceGroupName, networkSecurityGroupName, expand), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get NetworkSecurityGroups operation retrieves information about the /// specified network security group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='expand'> /// expand references resources. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<NetworkSecurityGroup> GetAsync( this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<NetworkSecurityGroup> result = await operations.GetWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, expand, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The Put NetworkSecurityGroup operation creates/updates a network security /// groupin the specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/update Network Security Group operation /// </param> public static NetworkSecurityGroup CreateOrUpdate(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters) { return Task.Factory.StartNew(s => ((INetworkSecurityGroupsOperations)s).CreateOrUpdateAsync(resourceGroupName, networkSecurityGroupName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Put NetworkSecurityGroup operation creates/updates a network security /// groupin the specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/update Network Security Group operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<NetworkSecurityGroup> CreateOrUpdateAsync( this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<NetworkSecurityGroup> result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, parameters, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The Put NetworkSecurityGroup operation creates/updates a network security /// groupin the specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/update Network Security Group operation /// </param> public static NetworkSecurityGroup BeginCreateOrUpdate(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters) { return Task.Factory.StartNew(s => ((INetworkSecurityGroupsOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, networkSecurityGroupName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Put NetworkSecurityGroup operation creates/updates a network security /// groupin the specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/update Network Security Group operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<NetworkSecurityGroup> BeginCreateOrUpdateAsync( this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<NetworkSecurityGroup> result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, parameters, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The list NetworkSecurityGroups returns all network security groups in a /// subscription /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<NetworkSecurityGroup> ListAll(this INetworkSecurityGroupsOperations operations) { return Task.Factory.StartNew(s => ((INetworkSecurityGroupsOperations)s).ListAllAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The list NetworkSecurityGroups returns all network security groups in a /// subscription /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NetworkSecurityGroup>> ListAllAsync( this INetworkSecurityGroupsOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<NetworkSecurityGroup>> result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The list NetworkSecurityGroups returns all network security groups in a /// resource group /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> public static IPage<NetworkSecurityGroup> List(this INetworkSecurityGroupsOperations operations, string resourceGroupName) { return Task.Factory.StartNew(s => ((INetworkSecurityGroupsOperations)s).ListAsync(resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The list NetworkSecurityGroups returns all network security groups in a /// resource group /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NetworkSecurityGroup>> ListAsync( this INetworkSecurityGroupsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<NetworkSecurityGroup>> result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The list NetworkSecurityGroups returns all network security groups in a /// subscription /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<NetworkSecurityGroup> ListAllNext(this INetworkSecurityGroupsOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((INetworkSecurityGroupsOperations)s).ListAllNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The list NetworkSecurityGroups returns all network security groups in a /// subscription /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NetworkSecurityGroup>> ListAllNextAsync( this INetworkSecurityGroupsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<NetworkSecurityGroup>> result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The list NetworkSecurityGroups returns all network security groups in a /// resource group /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<NetworkSecurityGroup> ListNext(this INetworkSecurityGroupsOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((INetworkSecurityGroupsOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The list NetworkSecurityGroups returns all network security groups in a /// resource group /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NetworkSecurityGroup>> ListNextAsync( this INetworkSecurityGroupsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<NetworkSecurityGroup>> result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false); return result.Body; } } }
// ---------------------------------------------------------------------------------- // // FXMaker // Modify by ismoon - 2012 - ismoonto@gmail.com // // reference source - http://wiki.unity3d.com/index.php/MeleeWeaponTrail // // ---------------------------------------------------------------------------------- #define USE_INTERPOLATION // Unfinished // // By Anomalous Underdog, 2011 // // Based on code made by Forest Johnson (Yoggy) and xyber // using UnityEngine; using System.Collections; using System.Collections.Generic; // [RequireComponent (typeof(MeshRenderer))] public class NcTrailTexture : NcEffectBehaviour { // Attribute ------------------------------------------------------------------------ public float m_fDelayTime; public float m_fEmitTime = 0.00f; public bool m_bSmoothHide = true; protected bool m_bEmit = true; protected float m_fStartTime; protected float m_fStopTime; public float m_fLifeTime = 0.70f; public enum AXIS_TYPE {AXIS_FORWARD, AXIS_BACK, AXIS_RIGHT, AXIS_LEFT, AXIS_UP, AXIS_DOWN}; public AXIS_TYPE m_TipAxis = AXIS_TYPE.AXIS_BACK; public float m_fTipSize = 1.0f; public bool m_bCenterAlign = false; public bool m_UvFlipHorizontal = false; public bool m_UvFlipVirtical = false; public int m_nFadeHeadCount = 2; public int m_nFadeTailCount = 2; public Color[] m_Colors; public float[] m_SizeRates; #if USE_INTERPOLATION public bool m_bInterpolation = false; public int m_nMaxSmoothCount = 10; public int m_nSubdivisions = 4; protected List<Point> m_SmoothedPoints = new List<Point>(); #endif public float m_fMinVertexDistance = 0.20f; public float m_fMaxVertexDistance = 10.00f; public float m_fMaxAngle = 3.00f; public bool m_bAutoDestruct = false; protected List<Point> m_Points = new List<Point>(); protected Transform m_base; protected GameObject m_TrialObject; protected Mesh m_TrailMesh; protected Vector3 m_LastPosition; protected Vector3 m_LastCameraPosition1; protected Vector3 m_LastCameraPosition2; protected bool m_bLastFrameEmit = true; public class Point { public float timeCreated = 0.00f; public Vector3 basePosition; public Vector3 tipPosition; public bool lineBreak = false; } // Property ------------------------------------------------------------------------- public void SetEmit(bool bEmit) { m_bEmit = bEmit; m_fStartTime = GetEngineTime(); m_fStopTime = 0; } #if UNITY_EDITOR public override string CheckProperty() { // if (1 < gameObject.GetComponents(GetType()).Length) // return "SCRIPT_WARRING_DUPLICATE"; if (renderer == null) return "SCRIPT_EMPTY_MESHRENDERER"; if (renderer.sharedMaterial == null) return "SCRIPT_EMPTY_MATERIAL"; return ""; // no error } #endif public override int GetAnimationState() { if ((enabled && IsActive(gameObject))) { if (GetEngineTime() < m_fStartTime + m_fDelayTime + 0.1f) return 1; return -1; } return -1; } // Event Function ------------------------------------------------------------------- void OnDisable() { if (m_TrialObject != null) NcAutoDestruct.CreateAutoDestruct(m_TrialObject, 0, m_fLifeTime/2.0f, true, true); } void Start() { if (renderer == null || renderer.sharedMaterial == null) { enabled = false; return; } if (0 < m_fDelayTime) { m_fStartTime = GetEngineTime(); } else { InitTrailObject(); } } void InitTrailObject() { m_base = transform; m_fStartTime = GetEngineTime(); m_LastPosition = transform.position; m_TrialObject = new GameObject("Trail"); m_TrialObject.transform.position = Vector3.zero; m_TrialObject.transform.rotation = Quaternion.identity; m_TrialObject.transform.localScale = transform.localScale; m_TrialObject.AddComponent(typeof(MeshFilter)); m_TrialObject.AddComponent(typeof(MeshRenderer)); // m_TrialObject.AddComponent<Nc>(); m_TrialObject.renderer.sharedMaterial = renderer.sharedMaterial; m_TrailMesh = m_TrialObject.GetComponent<MeshFilter>().mesh; CreateEditorGameObject(m_TrialObject); } Vector3 GetTipPoint() { switch (m_TipAxis) { case AXIS_TYPE.AXIS_FORWARD: return m_base.position + m_base.forward; case AXIS_TYPE.AXIS_BACK: return m_base.position + m_base.forward * -1; case AXIS_TYPE.AXIS_RIGHT: return m_base.position + m_base.right; case AXIS_TYPE.AXIS_LEFT: return m_base.position + m_base.right * -1; case AXIS_TYPE.AXIS_UP: return m_base.position + m_base.up; case AXIS_TYPE.AXIS_DOWN: return m_base.position + m_base.up * -1; } return m_base.position + m_base.forward; } void Update() { if (renderer == null || renderer.sharedMaterial == null) { enabled = false; return; } if (0 < m_fDelayTime) { if (GetEngineTime() < m_fStartTime + m_fDelayTime) return; m_fDelayTime = 0; m_fStartTime = 0; InitTrailObject(); } if (m_bEmit && 0 < m_fEmitTime && m_fStopTime == 0) { if (m_fStartTime + m_fEmitTime < GetEngineTime()) { if (m_bSmoothHide) m_fStopTime = GetEngineTime(); else m_bEmit = false; } } if (0 < m_fStopTime && m_fLifeTime < (GetEngineTime() - m_fStopTime)) m_bEmit = false; if (!m_bEmit && m_Points.Count == 0 && m_bAutoDestruct) { Destroy(m_TrialObject); Destroy(gameObject); } // // early out if there is no camera // if (!Camera.main) return; // if we have moved enough, create a new vertex and make sure we rebuild the mesh float theDistance = (m_LastPosition - transform.position).magnitude; if (m_bEmit) { if (theDistance > m_fMinVertexDistance) { bool make = false; if (m_Points.Count < 3) { make = true; } else { //Vector3 l1 = m_Points[m_Points.Count - 2].basePosition - m_Points[m_Points.Count - 3].basePosition; //Vector3 l2 = m_Points[m_Points.Count - 1].basePosition - m_Points[m_Points.Count - 2].basePosition; Vector3 l1 = m_Points[m_Points.Count - 2].basePosition - m_Points[m_Points.Count - 3].basePosition; Vector3 l2 = m_Points[m_Points.Count - 1].basePosition - m_Points[m_Points.Count - 2].basePosition; if (Vector3.Angle(l1, l2) > m_fMaxAngle || theDistance > m_fMaxVertexDistance) make = true; } if (make) { Point p = new Point(); p.basePosition = m_base.position; p.tipPosition = GetTipPoint(); if (0 < m_fStopTime) { p.timeCreated = GetEngineTime() - (GetEngineTime() - m_fStopTime); } else { p.timeCreated = GetEngineTime(); } m_Points.Add(p); m_LastPosition = transform.position; if (m_bInterpolation) { if (m_Points.Count == 1) { m_SmoothedPoints.Add(p); } else if (1 < m_Points.Count) { // add 1+m_nSubdivisions for every possible pair in the m_Points for (int n = 0; n < 1+m_nSubdivisions; ++n) m_SmoothedPoints.Add(p); } // we use 4 control points for the smoothing int nMinSmoothCount = 2; if (nMinSmoothCount <= m_Points.Count) { int nSampleCount = Mathf.Min(m_nMaxSmoothCount, m_Points.Count); Vector3[] tipPoints = new Vector3[nSampleCount]; for (int n = 0; n < nSampleCount; n++) tipPoints[n] = m_Points[m_Points.Count - (nSampleCount - n)].basePosition; // IEnumerable<Vector3> smoothTip = NcInterpolate.NewBezier(NcInterpolate.Ease(NcInterpolate.EaseType.Linear), tipPoints, m_nSubdivisions); IEnumerable<Vector3> smoothTip = NgInterpolate.NewCatmullRom(tipPoints, m_nSubdivisions, false); Vector3[] basePoints = new Vector3[nSampleCount]; for (int n = 0; n < nSampleCount; n++) basePoints[n] = m_Points[m_Points.Count - (nSampleCount - n)].tipPosition; // IEnumerable<Vector3> smoothBase = NcInterpolate.NewBezier(NcInterpolate.Ease(NcInterpolate.EaseType.Linear), basePoints, m_nSubdivisions); IEnumerable<Vector3> smoothBase = NgInterpolate.NewCatmullRom(basePoints, m_nSubdivisions, false); List<Vector3> smoothTipList = new List<Vector3>(smoothTip); List<Vector3> smoothBaseList = new List<Vector3>(smoothBase); float firstTime = m_Points[m_Points.Count - nSampleCount].timeCreated; float secondTime = m_Points[m_Points.Count - 1].timeCreated; //Debug.Log(" smoothTipList.Count: " + smoothTipList.Count); for (int n = 0; n < smoothTipList.Count; ++n) { int idx = m_SmoothedPoints.Count - (smoothTipList.Count-n); // there are moments when the m_SmoothedPoints are lesser // than what is required, when elements from it are removed if (-1 < idx && idx < m_SmoothedPoints.Count) { Point sp = new Point(); sp.tipPosition = smoothBaseList[n]; sp.basePosition = smoothTipList[n]; sp.timeCreated = Mathf.Lerp(firstTime, secondTime, n/(float)(smoothTipList.Count)); m_SmoothedPoints[idx] = sp; } //else //{ // Debug.LogError(idx + "/" + m_SmoothedPoints.Count); //} } } } } else { m_Points[m_Points.Count - 1].tipPosition = GetTipPoint(); m_Points[m_Points.Count - 1].basePosition = m_base.position; //m_Points[m_Points.Count - 1].timeCreated = GetEngineTime(); if (m_bInterpolation) { m_SmoothedPoints[m_SmoothedPoints.Count - 1].tipPosition = GetTipPoint(); m_SmoothedPoints[m_SmoothedPoints.Count - 1].basePosition = m_base.position; } } } else { if (m_Points.Count > 0) { m_Points[m_Points.Count - 1].tipPosition = GetTipPoint(); m_Points[m_Points.Count - 1].basePosition = m_base.position; //m_Points[m_Points.Count - 1].timeCreated = GetEngineTime(); } if (m_bInterpolation) { if (m_SmoothedPoints.Count > 0) { m_SmoothedPoints[m_SmoothedPoints.Count - 1].tipPosition = GetTipPoint(); m_SmoothedPoints[m_SmoothedPoints.Count - 1].basePosition = m_base.position; } } } } if (!m_bEmit && m_bLastFrameEmit && m_Points.Count > 0) m_Points[m_Points.Count - 1].lineBreak = true; m_bLastFrameEmit = m_bEmit; List<Point> remove = new List<Point>(); foreach (Point p in m_Points) { // cull old points first if (GetEngineTime() - p.timeCreated > m_fLifeTime) { remove.Add(p); } } foreach (Point p in remove) { m_Points.Remove(p); } if (m_bInterpolation) { remove = new List<Point>(); foreach (Point p in m_SmoothedPoints) { // cull old points first if (GetEngineTime() - p.timeCreated > m_fLifeTime) { remove.Add(p); } } foreach (Point p in remove) { m_SmoothedPoints.Remove(p); } } List<Point> pointsToUse; if (m_bInterpolation) pointsToUse = m_SmoothedPoints; else pointsToUse = m_Points; if (pointsToUse.Count > 1) { Vector3[] newVertices = new Vector3[pointsToUse.Count * 2]; Vector2[] newUV = new Vector2[pointsToUse.Count * 2]; int[] newTriangles = new int[(pointsToUse.Count - 1) * 6]; Color[] newColors = new Color[pointsToUse.Count * 2]; for (int n = 0; n < pointsToUse.Count; ++n) { Point p = pointsToUse[n]; float time = (GetEngineTime() - p.timeCreated) / m_fLifeTime; Color color = Color.Lerp(Color.white, Color.clear, time); if (m_Colors != null && m_Colors.Length > 0) { float colorTime = time * (m_Colors.Length - 1); float min = Mathf.Floor(colorTime); float max = Mathf.Clamp(Mathf.Ceil(colorTime), 1, m_Colors.Length - 1); float lerp = Mathf.InverseLerp(min, max, colorTime); if (min >= m_Colors.Length) min = m_Colors.Length - 1; if (min < 0) min = 0; if (max >= m_Colors.Length) max = m_Colors.Length - 1; if (max < 0) max = 0; color = Color.Lerp(m_Colors[(int)min], m_Colors[(int)max], lerp); } Vector3 lineDirection = p.basePosition - p.tipPosition; float size = m_fTipSize; if (m_SizeRates != null && m_SizeRates.Length > 0) { float sizeTime = time * (m_SizeRates.Length - 1); float min = Mathf.Floor(sizeTime); float max = Mathf.Clamp(Mathf.Ceil(sizeTime), 1, m_SizeRates.Length - 1); float lerp = Mathf.InverseLerp(min, max, sizeTime); if (min >= m_SizeRates.Length) min = m_SizeRates.Length - 1; if (min < 0) min = 0; if (max >= m_SizeRates.Length) max = m_SizeRates.Length - 1; if (max < 0) max = 0; size *= Mathf.Lerp(m_SizeRates[(int)min], m_SizeRates[(int)max], lerp); } if (m_bCenterAlign) { newVertices[n * 2] = p.basePosition - (lineDirection * (size * 0.5f)); newVertices[(n * 2) + 1] = p.basePosition + (lineDirection * (size * 0.5f)); } else { newVertices[n * 2] = p.basePosition - (lineDirection * size); newVertices[(n * 2) + 1] = p.basePosition; } // FadeInOut int nFadeTailCount = (m_bInterpolation ? m_nFadeTailCount * m_nSubdivisions : m_nFadeTailCount); int nFadeHeadCount = (m_bInterpolation ? m_nFadeHeadCount * m_nSubdivisions : m_nFadeHeadCount); if (0 < nFadeTailCount && n <= nFadeTailCount) color.a = color.a * n / (float)nFadeTailCount; if (0 < nFadeHeadCount && pointsToUse.Count-(n+1) <= nFadeHeadCount) color.a = color.a * (pointsToUse.Count-(n+1)) / (float)nFadeHeadCount; newColors[n * 2] = newColors[(n * 2) + 1] = color; float uvRatio = (float)n/pointsToUse.Count; newUV[n * 2] = new Vector2((m_UvFlipHorizontal ? 1-uvRatio : uvRatio), (m_UvFlipVirtical ? 1 : 0)); newUV[(n * 2) + 1] = new Vector2((m_UvFlipHorizontal ? 1-uvRatio : uvRatio), (m_UvFlipVirtical ? 0 : 1)); if (n > 0 /*&& !pointsToUse[n - 1].lineBreak*/) { newTriangles[(n - 1) * 6] = (n * 2) - 2; newTriangles[((n - 1) * 6) + 1] = (n * 2) - 1; newTriangles[((n - 1) * 6) + 2] = n * 2; newTriangles[((n - 1) * 6) + 3] = (n * 2) + 1; newTriangles[((n - 1) * 6) + 4] = n * 2; newTriangles[((n - 1) * 6) + 5] = (n * 2) - 1; } } m_TrailMesh.Clear(); m_TrailMesh.vertices = newVertices; m_TrailMesh.colors = newColors; m_TrailMesh.uv = newUV; m_TrailMesh.triangles = newTriangles; } else { m_TrailMesh.Clear(); } } // Event Function ------------------------------------------------------------------- public override void OnUpdateEffectSpeed(float fSpeedRate, bool bRuntime) { m_fDelayTime /= fSpeedRate; m_fEmitTime /= fSpeedRate; m_fLifeTime /= fSpeedRate; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osuTK; using osuTK.Input; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Graphics.Sprites; using osu.Game.Rulesets.Mods; using System; using System.Linq; using System.Collections.Generic; using System.Threading; using Humanizer; using osu.Framework.Input.Events; using osu.Game.Graphics; namespace osu.Game.Overlays.Mods { public class ModSection : CompositeDrawable { private readonly Drawable header; public FillFlowContainer<ModButtonEmpty> ButtonsContainer { get; } protected IReadOnlyList<ModButton> Buttons { get; private set; } = Array.Empty<ModButton>(); public Action<Mod> Action; public Key[] ToggleKeys; public readonly ModType ModType; public IEnumerable<Mod> SelectedMods => Buttons.Select(b => b.SelectedMod).Where(m => m != null); private CancellationTokenSource modsLoadCts; protected bool SelectionAnimationRunning => pendingSelectionOperations.Count > 0; /// <summary> /// True when all mod icons have completed loading. /// </summary> public bool ModIconsLoaded { get; private set; } = true; public IEnumerable<Mod> Mods { set { var modContainers = value.Select(m => { if (m == null) return new ModButtonEmpty(); return CreateModButton(m).With(b => { b.SelectionChanged = mod => { ModButtonStateChanged(mod); Action?.Invoke(mod); }; }); }).ToArray(); modsLoadCts?.Cancel(); if (modContainers.Length == 0) { ModIconsLoaded = true; header.Hide(); Hide(); return; } ModIconsLoaded = false; LoadComponentsAsync(modContainers, c => { ModIconsLoaded = true; ButtonsContainer.ChildrenEnumerable = c; }, (modsLoadCts = new CancellationTokenSource()).Token); Buttons = modContainers.OfType<ModButton>().ToArray(); header.FadeIn(200); this.FadeIn(200); } } protected virtual void ModButtonStateChanged(Mod mod) { } protected override bool OnKeyDown(KeyDownEvent e) { if (e.ControlPressed) return false; if (ToggleKeys != null) { var index = Array.IndexOf(ToggleKeys, e.Key); if (index > -1 && index < Buttons.Count) Buttons[index].SelectNext(e.ShiftPressed ? -1 : 1); } return base.OnKeyDown(e); } private const double initial_multiple_selection_delay = 120; private double selectionDelay = initial_multiple_selection_delay; private double lastSelection; private readonly Queue<Action> pendingSelectionOperations = new Queue<Action>(); protected override void Update() { base.Update(); if (selectionDelay == initial_multiple_selection_delay || Time.Current - lastSelection >= selectionDelay) { if (pendingSelectionOperations.TryDequeue(out var dequeuedAction)) { dequeuedAction(); // each time we play an animation, we decrease the time until the next animation (to ramp the visual and audible elements). selectionDelay = Math.Max(30, selectionDelay * 0.8f); lastSelection = Time.Current; } else { // reset the selection delay after all animations have been completed. // this will cause the next action to be immediately performed. selectionDelay = initial_multiple_selection_delay; } } } /// <summary> /// Selects all mods. /// </summary> public void SelectAll() { pendingSelectionOperations.Clear(); foreach (var button in Buttons.Where(b => !b.Selected)) pendingSelectionOperations.Enqueue(() => button.SelectAt(0)); } /// <summary> /// Deselects all mods. /// </summary> public void DeselectAll() { pendingSelectionOperations.Clear(); DeselectTypes(Buttons.Select(b => b.SelectedMod?.GetType()).Where(t => t != null)); } /// <summary> /// Deselect one or more mods in this section. /// </summary> /// <param name="modTypes">The types of <see cref="Mod"/>s which should be deselected.</param> /// <param name="immediate">Whether the deselection should happen immediately. Should only be used when required to ensure correct selection flow.</param> /// <param name="newSelection">If this deselection is triggered by a user selection, this should contain the newly selected type. This type will never be deselected, even if it matches one provided in <paramref name="modTypes"/>.</param> public void DeselectTypes(IEnumerable<Type> modTypes, bool immediate = false, Mod newSelection = null) { foreach (var button in Buttons) { if (button.SelectedMod == null) continue; if (button.SelectedMod == newSelection) continue; foreach (var type in modTypes) { if (type.IsInstanceOfType(button.SelectedMod)) { if (immediate) button.Deselect(); else pendingSelectionOperations.Enqueue(button.Deselect); } } } } /// <summary> /// Updates all buttons with the given list of selected mods. /// </summary> /// <param name="newSelectedMods">The new list of selected mods to select.</param> public void UpdateSelectedButtons(IReadOnlyList<Mod> newSelectedMods) { foreach (var button in Buttons) updateButtonSelection(button, newSelectedMods); } private void updateButtonSelection(ModButton button, IReadOnlyList<Mod> newSelectedMods) { foreach (var mod in newSelectedMods) { var index = Array.FindIndex(button.Mods, m1 => mod.GetType() == m1.GetType()); if (index < 0) continue; var buttonMod = button.Mods[index]; // as this is likely coming from an external change, ensure the settings of the mod are in sync. buttonMod.CopyFrom(mod); button.SelectAt(index, false); return; } button.Deselect(); } public ModSection(ModType type) { ModType = type; AutoSizeAxes = Axes.Y; RelativeSizeAxes = Axes.X; Origin = Anchor.TopCentre; Anchor = Anchor.TopCentre; InternalChildren = new[] { header = CreateHeader(type.Humanize(LetterCasing.Title)), ButtonsContainer = new FillFlowContainer<ModButtonEmpty> { AutoSizeAxes = Axes.Y, RelativeSizeAxes = Axes.X, Origin = Anchor.BottomLeft, Anchor = Anchor.BottomLeft, Spacing = new Vector2(50f, 0f), Margin = new MarginPadding { Top = 20, }, AlwaysPresent = true }, }; } protected virtual Drawable CreateHeader(string text) => new OsuSpriteText { Font = OsuFont.GetFont(weight: FontWeight.Bold), Text = text }; protected virtual ModButton CreateModButton(Mod mod) => new ModButton(mod); /// <summary> /// Play out all remaining animations immediately to leave mods in a good (final) state. /// </summary> public void FlushAnimation() { while (pendingSelectionOperations.TryDequeue(out var dequeuedAction)) dequeuedAction(); } } }
// <copyright file="WishartTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2016 Math.NET // // 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. // </copyright> using System; using MathNet.Numerics.Distributions; using MathNet.Numerics.LinearAlgebra; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.DistributionTests.Multivariate { /// <summary> /// <c>Wishart</c> distribution tests. /// </summary> [TestFixture, Category("Distributions")] public class WishartTests { /// <summary> /// Set-up parameters. /// </summary> [SetUp] public void SetUp() { Control.CheckDistributionParameters = true; } /// <summary> /// Can create wishart. /// </summary> /// <param name="nu">DegreesOfFreedom parameter.</param> /// <param name="order">Scale matrix order.</param> [TestCase(0.1, 2)] [TestCase(1.0, 5)] [TestCase(5.0, 5)] public void CanCreateWishart(double nu, int order) { var matrix = Matrix<double>.Build.RandomPositiveDefinite(order, 1); var d = new Wishart(nu, matrix); Assert.AreEqual(nu, d.DegreesOfFreedom); for (var i = 0; i < d.Scale.RowCount; i++) { for (var j = 0; j < d.Scale.ColumnCount; j++) { Assert.AreEqual(matrix[i, j], d.Scale[i, j]); } } } /// <summary> /// Fail create Wishart with bad parameters. /// </summary> /// <param name="nu">DegreesOfFreedom parameter.</param> /// <param name="order">Scale matrix order.</param> [TestCase(0.0, 2)] [TestCase(0.1, 5)] [TestCase(1.0, 2)] [TestCase(5.0, 5)] public void FailSCreateWishart(double nu, int order) { var matrix = Matrix<double>.Build.RandomPositiveDefinite(order, 1); matrix[0, 0] = 0.0; Assert.That(() => new Wishart(nu, matrix), Throws.ArgumentException); } /// <summary> /// Fail create Wishart with bad parameters. /// </summary> /// <param name="nu">DegreesOfFreedom parameter.</param> /// <param name="order">Scale matrix order.</param> [TestCase(-1.0, 2)] [TestCase(Double.NaN, 5)] public void FailNuCreateWishart(double nu, int order) { var matrix = Matrix<double>.Build.RandomPositiveDefinite(order, 1); Assert.That(() => new InverseWishart(nu, matrix), Throws.ArgumentException); } /// <summary> /// Has random source. /// </summary> [Test] public void HasRandomSource() { var d = new Wishart(1.0, Matrix<double>.Build.RandomPositiveDefinite(2, 1)); Assert.IsNotNull(d.RandomSource); } /// <summary> /// Can set random source. /// </summary> [Test] public void CanSetRandomSource() { GC.KeepAlive(new Wishart(1.0, Matrix<double>.Build.RandomPositiveDefinite(2, 1)) { RandomSource = new System.Random(0) }); } /// <summary> /// Validate ToString. /// </summary> [Test] public void ValidateToString() { var d = new Wishart(1.0, Matrix<double>.Build.RandomPositiveDefinite(2, 1)); Assert.AreEqual("Wishart(DegreesOfFreedom = 1, Rows = 2, Columns = 2)", d.ToString()); } /// <summary> /// Can get DegreesOfFreedom. /// </summary> /// <param name="nu">DegreesOfFreedom parameter.</param> [TestCase(1.0)] [TestCase(2.0)] [TestCase(5.0)] public void CanGetNu(double nu) { var d = new Wishart(nu, Matrix<double>.Build.RandomPositiveDefinite(2, 1)); Assert.AreEqual(nu, d.DegreesOfFreedom); } /// <summary> /// Can get scale matrix. /// </summary> [Test] public void CanGetS() { const int Order = 2; var matrix = Matrix<double>.Build.RandomPositiveDefinite(Order, 1); var d = new Wishart(1.0, matrix); for (var i = 0; i < Order; i++) { for (var j = 0; j < Order; j++) { Assert.AreEqual(matrix[i, j], d.Scale[i, j]); } } } /// <summary> /// Validate mean. /// </summary> /// <param name="nu">DegreesOfFreedom parameter.</param> /// <param name="order">Scale matrix order.</param> [TestCase(0.1, 2)] [TestCase(1.0, 5)] [TestCase(5.0, 5)] public void ValidateMean(double nu, int order) { var d = new Wishart(nu, Matrix<double>.Build.RandomPositiveDefinite(order, 1)); var mean = d.Mean; for (var i = 0; i < d.Scale.RowCount; i++) { for (var j = 0; j < d.Scale.ColumnCount; j++) { Assert.AreEqual(nu * d.Scale[i, j], mean[i, j]); } } } /// <summary> /// Validate mode. /// </summary> /// <param name="nu">DegreesOfFreedom parameter.</param> /// <param name="order">Scale matrix order.</param> [TestCase(0.1, 2)] [TestCase(1.0, 5)] [TestCase(5.0, 5)] public void ValidateMode(double nu, int order) { var d = new Wishart(nu, Matrix<double>.Build.RandomPositiveDefinite(order, 1)); var mode = d.Mode; for (var i = 0; i < d.Scale.RowCount; i++) { for (var j = 0; j < d.Scale.ColumnCount; j++) { Assert.AreEqual((nu - d.Scale.RowCount - 1.0) * d.Scale[i, j], mode[i, j]); } } } /// <summary> /// Validate variance. /// </summary> /// <param name="nu">DegreesOfFreedom parameter.</param> /// <param name="order">Scale matrix order.</param> [TestCase(0.1, 2)] [TestCase(1.0, 5)] [TestCase(5.0, 5)] public void ValidateVariance(double nu, int order) { var d = new Wishart(nu, Matrix<double>.Build.RandomPositiveDefinite(order, 1)); var variance = d.Variance; for (var i = 0; i < d.Scale.RowCount; i++) { for (var j = 0; j < d.Scale.ColumnCount; j++) { Assert.AreEqual(nu * ((d.Scale[i, j] * d.Scale[i, j]) + (d.Scale[i, i] * d.Scale[j, j])), variance[i, j]); } } } /// <summary> /// Validate density. /// </summary> /// <param name="nu">DegreesOfFreedom parameter.</param> /// <param name="density">Expected value.</param> [TestCase(1.0, 0.014644982561926487)] [TestCase(2.0, 0.041042499311949421)] [TestCase(5.0, 0.12204152134938706)] public void ValidateDensity(double nu, double density) { var matrix = Matrix<double>.Build.Dense(1, 1, 1.0); var x = Matrix<double>.Build.Dense(1, 1, 5.0); var d = new Wishart(nu, matrix); AssertHelpers.AlmostEqualRelative(density, d.Density(x), 16); } /// <summary> /// Can sample. /// </summary> [Test] public void CanSample() { var d = new Wishart(1.0, Matrix<double>.Build.RandomPositiveDefinite(2, 1)); d.Sample(); } /// <summary> /// Can sample static. /// </summary> [Test] public void CanSampleStatic() { Wishart.Sample(new System.Random(0), 1.0, Matrix<double>.Build.RandomPositiveDefinite(2, 1)); } /// <summary> /// Fail sample static with bad parameters. /// </summary> [Test] public void FailSampleStatic() { Assert.That(() => Wishart.Sample(new System.Random(0), -1.0, Matrix<double>.Build.RandomPositiveDefinite(2, 1)), Throws.ArgumentException); } } }
using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.OleDb; using System.Data.OracleClient; //using Oracle.DataAccess.Client; using System.Data.Sql; using System.Data.SqlClient; namespace DataAccess { public class CDataSet { //members/fields private DataSet m_DataSet; private string m_strStatus; private long m_lStatusCode; /// <summary> /// get status /// </summary> public string Status { get { return m_strStatus; } } /// <summary> /// get status code /// </summary> public long StatusCode { get { return m_lStatusCode; } } /// <summary> /// constructor /// </summary> public CDataSet() { m_DataSet = null; m_strStatus = ""; m_lStatusCode = -1; } /// <summary> /// destructor /// </summary> ~CDataSet() { if (m_DataSet != null) { m_DataSet = null; } } /// <summary> /// append all the columns and data from one ds (dsfrom) to another ds (dsto) /// </summary> /// <param name="conn"></param> /// <param name="dsFrom"></param> /// <param name="dsTo"></param> /// <returns></returns> public bool AppendData( CDataConnection conn, DataSet dsFrom, DataSet dsTo ) { //keep the offeset of where the new columns start int nStartIndex = dsTo.Tables[0].Columns.Count; //loop over all the tables in the new ds and the cols to the original ds foreach (System.Data.DataTable table in dsFrom.Tables) { foreach (System.Data.DataColumn col in table.Columns) { try { //add the new cols to the original dataset System.Data.DataColumn colnew = new System.Data.DataColumn(); colnew.AllowDBNull = col.AllowDBNull; colnew.AutoIncrement = col.AutoIncrement; colnew.AutoIncrementSeed = col.AutoIncrementSeed; colnew.AutoIncrementStep = col.AutoIncrementStep; colnew.Caption = col.Caption; colnew.ColumnMapping = col.ColumnMapping; colnew.ColumnName = col.ColumnName; //colnew.Container = col.Container; colnew.DataType = col.DataType; colnew.DateTimeMode = col.DateTimeMode; colnew.DefaultValue = col.DefaultValue; //colnew.DesignMode = col.DesignMode; colnew.Expression = col.Expression; //colnew.ExtendedProperties = col.ExtendedProperties; colnew.MaxLength = col.MaxLength; colnew.Namespace = col.Namespace; //colnew.Ordinal = col.Ordinal; colnew.Prefix = col.Prefix; colnew.ReadOnly = col.ReadOnly; colnew.Site = col.Site; //colnew.Table = col.Table; colnew.Unique = col.Unique; //add the new column to the table dsTo.Tables[0].Columns.Add(colnew); } catch (Exception ee) { string strError = ee.Message; //ignore is already there } } //accept any changes made dsTo.AcceptChanges(); } //loop over all the rows in the table of the new ds //and add to original dataset foreach (System.Data.DataTable table in dsFrom.Tables) { foreach (System.Data.DataRow row in table.Rows) { //loop over all the column values for (int i = 0; i < row.ItemArray.Length; i++) { //loop over the "to" table and set the new col value = this col value foreach (System.Data.DataTable table1 in dsTo.Tables) { foreach (System.Data.DataRow row1 in table1.Rows) { //loop over all the rows in the "to" table to find the new one for (int ii = nStartIndex; ii < row1.ItemArray.Length; ii++) { if (row1.Table.Columns[ii].ColumnName == row.Table.Columns[i].ColumnName) { //set the rows value row1[ii] = row[i]; //increment the start index to make the loop execute faster nStartIndex++; //break the for break; } } } } //accept any changes made dsTo.AcceptChanges(); } } } return true; } /// <summary> /// get a dataset from the connection and a stored proc /// </summary> /// <param name="conn"></param> /// <param name="strSPName"></param> /// <param name="ParamList"></param> /// <param name="lStatusCode"></param> /// <param name="strStatus"></param> /// <returns></returns> /* public DataSet GetOracleDataSet(CDataConnection conn, string strSPName, CDataParameterList ParamList, out long lStatusCode, out string strStatus) { lStatusCode = 0; strStatus = ""; m_lStatusCode = 0; m_strStatus = ""; CDataUtils utils = new CDataUtils(); string strAuditXML = ""; strAuditXML += "<sp_name>" + strSPName + "</sp_name>"; //return null if no conn if (conn == null) { m_lStatusCode = 1; m_strStatus = "Unable to connect to data source, CDataConnection is null"; lStatusCode = m_lStatusCode; strStatus = m_strStatus; return null; } //create a new command object and set the command objects connection, text and type //must use OracleCommand or you cannot get back a ref cur out param which is how //we do things in medbase OracleCommand cmd = new OracleCommand(); // OleDbCommand(); cmd.Connection = conn.GetOracleConnection(); cmd.CommandText = strSPName; cmd.CommandType = CommandType.StoredProcedure; //add the parameters from the parameter list to the command parameter list for (int i = 0; i < ParamList.Count; i++) { CDataParameter parameter = ParamList.GetItemByIndex(i); if (parameter != null) { //create a new oledb param from our param and add it to the list //this follows how we currently do it in medbase //TODO: get direction, length etc from the parameter not hard coded below OracleParameter oraParameter = new OracleParameter(); oraParameter.ParameterName = parameter.ParameterName; strAuditXML += "<" + oraParameter.ParameterName + ">"; //set the parameter value, default to string. Probably a better way than the //if then else, but this works and we can find it later, if (parameter.ParameterType == (int)DataParameterType.StringParameter) { oraParameter.Value = parameter.StringParameterValue; //audit value strAuditXML += parameter.StringParameterValue; } else if (parameter.ParameterType == (int)DataParameterType.LongParameter) { oraParameter.Value = parameter.LongParameterValue; //audit value strAuditXML += Convert.ToString(parameter.LongParameterValue); } else if (parameter.ParameterType == (int)DataParameterType.DateParameter) { oraParameter.Value = parameter.DateParameterValue; //audit value strAuditXML += utils.GetDateAsString(parameter.DateParameterValue); } else if (parameter.ParameterType == (int)DataParameterType.CLOBParameter) { oraParameter.Value = parameter.CLOBParameterValue; //audit value strAuditXML += parameter.CLOBParameterValue; } else { oraParameter.Value = parameter.StringParameterValue; //audit value strAuditXML += parameter.StringParameterValue; } strAuditXML += "</" + oraParameter.ParameterName + ">"; oraParameter.Direction = parameter.Direction; cmd.Parameters.Add(oraParameter); } } //add in out params for stored proc, all sp's will return a status 1 = good, 0 = bad //status ParamList.AddParameter("po_nStatusCode", 0, ParameterDirection.Output); OracleParameter oraStatusParameter = new OracleParameter("po_nStatusCode", OracleType.Int32); oraStatusParameter.Direction = ParameterDirection.Output; cmd.Parameters.Add(oraStatusParameter); // //comment ParamList.AddParameter("po_vStatusComment", "", ParameterDirection.Output); OracleParameter oraCommentParameter = new OracleParameter("po_vStatusComment", OracleType.VarChar, 4000); oraCommentParameter.Direction = ParameterDirection.Output; cmd.Parameters.Add(oraCommentParameter); // //now add an out parameter to hold the ref cursor to the commands parameter list //returned ref cursor must always be named "RS" because OracleClient binds these //parameters by name, so you must name your parameter correctly //so the OracleParameter must be named the same thing. OracleParameter oraRSParameter = new OracleParameter( "RS", OracleType.Cursor); //OracleType.Cursor oraRSParameter.Direction = ParameterDirection.Output; cmd.Parameters.Add(oraRSParameter); //create a new dataset to hold the conntent of the reference cursor m_DataSet = new DataSet(); //now audit the call.... ignore audit and get/set session values or //login is audited seperately if (conn.Audit) { if (strSPName.ToUpper().IndexOf("AUDIT") > -1 || strSPName.ToUpper().IndexOf("GETSESSIONVALUE") > -1 || strSPName.ToUpper().IndexOf("SETSESSIONVALUE") > -1 || strSPName.ToUpper().IndexOf("LOGIN") > -1) { //ignore the audit } else { //audit the transaction CDataParameterList plistAudit = new CDataParameterList(); plistAudit.AddInputParameter("pi_vSessionID", ParamList.GetItemByName("pi_vSessionID").StringParameterValue); plistAudit.AddInputParameter("pi_vSessionClientIP", ParamList.GetItemByName("pi_vSessionClientIP").StringParameterValue); plistAudit.AddInputParameter("pi_nUserID", ParamList.GetItemByName("pi_nUserID").LongParameterValue); plistAudit.AddInputParameter("pi_vSPName", strSPName); plistAudit.AddInputParameterCLOB("pi_clAuditXML", strAuditXML); long lStat = 0; string strStat = ""; conn.ExecuteOracleSP("PCK_FX_SEC.AuditTransaction", plistAudit, out lStat, out strStat); } } //create an adapter and fill the dataset. I like datasets because they are completely //disconnected and provide the most flexibility for later porting to a web service etc. //It could be argued that a data reader is faster and offers easier movement back and forth //through a dataset. But for the web and the fact that we work from lists //I think a dataset is best. Concept is similar to current medbase architecture try { OracleDataAdapter dataAdapter = new OracleDataAdapter(cmd); dataAdapter.Fill(m_DataSet); } catch (InvalidOperationException e) { m_strStatus = e.Message; m_lStatusCode = 1; m_DataSet = null; lStatusCode = m_lStatusCode; strStatus = m_strStatus; } catch (OracleException e) { m_strStatus = e.Message; m_lStatusCode = 1; m_DataSet = null; lStatusCode = m_lStatusCode; strStatus = m_strStatus; } if (m_lStatusCode == 0) { //now read back out params into our list for (int i = 0; i < ParamList.Count; i++) { CDataParameter parameter = ParamList.GetItemByIndex(i); if (parameter != null) { if (parameter.Direction == ParameterDirection.Output || parameter.Direction == ParameterDirection.InputOutput) { foreach (OracleParameter oP in cmd.Parameters) { if (oP.ParameterName.Equals(parameter.ParameterName)) { if (parameter.ParameterType == (int)DataParameterType.StringParameter) { if (oP.Value != null) { parameter.StringParameterValue = oP.Value.ToString(); } } else if (parameter.ParameterType == (int)DataParameterType.LongParameter) { if (oP.Value != null) { if (!oP.Value.ToString().Equals("")) { parameter.LongParameterValue = Convert.ToInt64(oP.Value); } } } else if (parameter.ParameterType == (int)DataParameterType.DateParameter) { if (oP.Value != null) { if (!oP.Value.ToString().Equals("")) { parameter.DateParameterValue = Convert.ToDateTime(oP.Value); } } } else { parameter.StringParameterValue = oP.Value.ToString(); } } } } } } //set status code and text CDataParameter pStatusCode = ParamList.GetItemByName("po_nStatusCode"); if (pStatusCode != null) { m_lStatusCode = pStatusCode.LongParameterValue; } CDataParameter pStatusComment = ParamList.GetItemByName("po_vStatusComment"); if (pStatusComment != null) { m_strStatus = pStatusComment.StringParameterValue; } } lStatusCode = m_lStatusCode; strStatus = m_strStatus; return m_DataSet; }*/ /// <summary> /// get a dataset from the connection and a stored proc /// </summary> /// <param name="conn"></param> /// <param name="strSPName"></param> /// <param name="ParamList"></param> /// <param name="lStatusCode"></param> /// <param name="strStatus"></param> /// <returns></returns> public DataSet GetOracleDataSet(CDataConnection conn, string strSPName, CDataParameterList ParamList, out long lStatusCode, out string strStatus) { lStatusCode = 0; strStatus = ""; m_lStatusCode = 0; m_strStatus = ""; CDataUtils utils = new CDataUtils(); //return null if no conn if (conn == null) { m_lStatusCode = 1; m_strStatus = "Unable to connect to data source, CDataConnection is null"; lStatusCode = m_lStatusCode; strStatus = m_strStatus; return null; } //create a new command object and set the command objects connection, text and type //must use OracleCommand or you cannot get back a ref cur out param which is how //we do things in medbase OracleCommand cmd = new OracleCommand(); // OleDbCommand(); cmd.Connection = conn.GetOracleConnection(); cmd.CommandText = strSPName; cmd.CommandType = CommandType.StoredProcedure; //add the parameters from the parameter list to the command parameter list for (int i = 0; i < ParamList.Count; i++) { CDataParameter parameter = ParamList.GetItemByIndex(i); if (parameter != null) { //create a new oledb param from our param and add it to the list //this follows how we currently do it in medbase //TODO: get direction, length etc from the parameter not hard coded below OracleParameter oraParameter = new OracleParameter(); oraParameter.ParameterName = parameter.ParameterName; //set the parameter value, default to string. Probably a better way than the //if then else, but this works and we can find it later, if (parameter.ParameterType == (int)DataParameterType.StringParameter) { oraParameter.Value = parameter.StringParameterValue; } else if (parameter.ParameterType == (int)DataParameterType.LongParameter) { oraParameter.Value = parameter.LongParameterValue; } else if (parameter.ParameterType == (int)DataParameterType.DateParameter) { oraParameter.Value = parameter.DateParameterValue; } else if (parameter.ParameterType == (int)DataParameterType.CLOBParameter) { oraParameter.Value = parameter.CLOBParameterValue; } else { oraParameter.Value = parameter.StringParameterValue; } oraParameter.Direction = parameter.Direction; cmd.Parameters.Add(oraParameter); } } //add in out params for stored proc, all sp's will return a status 1 = good, 0 = bad //status ParamList.AddParameter("po_nStatusCode", 0, ParameterDirection.Output); OracleParameter oraStatusParameter = new OracleParameter("po_nStatusCode", OracleType.Int32); oraStatusParameter.Direction = ParameterDirection.Output; cmd.Parameters.Add(oraStatusParameter); // //comment ParamList.AddParameter("po_vStatusComment", "", ParameterDirection.Output); OracleParameter oraCommentParameter = new OracleParameter("po_vStatusComment", OracleType.VarChar, 4000); oraCommentParameter.Direction = ParameterDirection.Output; cmd.Parameters.Add(oraCommentParameter); // //now add an out parameter to hold the ref cursor to the commands parameter list //returned ref cursor must always be named "RS" because OracleClient binds these //parameters by name, so you must name your parameter correctly //so the OracleParameter must be named the same thing. OracleParameter oraRSParameter = new OracleParameter("RS", OracleType.Cursor); //OracleType.Cursor oraRSParameter.Direction = ParameterDirection.Output; cmd.Parameters.Add(oraRSParameter); //create a new dataset to hold the conntent of the reference cursor m_DataSet = new DataSet(); //create an adapter and fill the dataset. I like datasets because they are completely //disconnected and provide the most flexibility for later porting to a web service etc. //It could be argued that a data reader is faster and offers easier movement back and forth //through a dataset. But for the web and the fact that we work from lists //I think a dataset is best. Concept is similar to current medbase architecture try { OracleDataAdapter dataAdapter = new OracleDataAdapter(cmd); dataAdapter.Fill(m_DataSet); } catch (InvalidOperationException e) { m_strStatus = e.Message; m_lStatusCode = 1; m_DataSet = null; lStatusCode = m_lStatusCode; strStatus = m_strStatus; } catch (OracleException e) { m_strStatus = e.Message; m_lStatusCode = 1; m_DataSet = null; lStatusCode = m_lStatusCode; strStatus = m_strStatus; } if (m_lStatusCode == 0) { //now read back out params into our list for (int i = 0; i < ParamList.Count; i++) { CDataParameter parameter = ParamList.GetItemByIndex(i); if (parameter != null) { if (parameter.Direction == ParameterDirection.Output || parameter.Direction == ParameterDirection.InputOutput) { foreach (OracleParameter oP in cmd.Parameters) { if (oP.ParameterName.Equals(parameter.ParameterName)) { if (parameter.ParameterType == (int)DataParameterType.StringParameter) { if (oP.Value != null) { parameter.StringParameterValue = oP.Value.ToString(); } } else if (parameter.ParameterType == (int)DataParameterType.LongParameter) { if (oP.Value != null) { if (!oP.Value.ToString().Equals("")) { parameter.LongParameterValue = Convert.ToInt64(oP.Value); } } } else if (parameter.ParameterType == (int)DataParameterType.DateParameter) { if (oP.Value != null) { if (!oP.Value.ToString().Equals("")) { parameter.DateParameterValue = Convert.ToDateTime(oP.Value); } } } else { parameter.StringParameterValue = oP.Value.ToString(); } } } } } } //set status code and text CDataParameter pStatusCode = ParamList.GetItemByName("po_nStatusCode"); if (pStatusCode != null) { m_lStatusCode = pStatusCode.LongParameterValue; } CDataParameter pStatusComment = ParamList.GetItemByName("po_vStatusComment"); if (pStatusComment != null) { m_strStatus = pStatusComment.StringParameterValue; } } lStatusCode = m_lStatusCode; strStatus = m_strStatus; //now audit the call if needed.... if (conn.Audit) { long lAuditStatusCode = 0; string strAuditStatus = String.Empty; conn.AuditTransaction(strSPName, ParamList, lStatusCode, strStatus, out lAuditStatusCode, out strAuditStatus); } return m_DataSet; } } }
// 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.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Runtime.CompilerServices; using ILCompiler.DependencyAnalysis; using Internal.Text; namespace ILCompiler.PEWriter { /// <summary> /// For a given symbol, this structure represents its target section and offset /// within the containing section. /// </summary> public struct SymbolTarget { /// <summary> /// Index of the section holding the symbol target. /// </summary> public readonly int SectionIndex; /// <summary> /// Offset of the symbol within the section. /// </summary> public readonly int Offset; /// <summary> /// Initialize symbol target with section and offset. /// </summary> /// <param name="sectionIndex">Section index where the symbol target resides</param> /// <param name="offset">Offset of the target within the section</param> public SymbolTarget(int sectionIndex, int offset) { SectionIndex = sectionIndex; Offset = offset; } } /// <summary> /// After placing an ObjectData within a section, we use this helper structure to record /// its relocation information for the final relocation pass. /// </summary> public struct ObjectDataRelocations { /// <summary> /// Offset of the ObjectData block within the section /// </summary> public readonly int Offset; /// <summary> /// List of relocations for the data block /// </summary> public readonly Relocation[] Relocs; /// <summary> /// Initialize the list of relocations for a given location within the section. /// </summary> /// <param name="offset">Offset within the section</param> /// <param name="relocs">List of relocations to apply at the offset</param> public ObjectDataRelocations(int offset, Relocation[] relocs) { Offset = offset; Relocs = relocs; } } public struct SectionInfo { public readonly string SectionName; public readonly SectionCharacteristics Characteristics; public SectionInfo(string sectionName, SectionCharacteristics characteristics) { SectionName = sectionName; Characteristics = characteristics; } } /// <summary> /// Section represents a contiguous area of code or data with the same characteristics. /// </summary> public class Section { /// <summary> /// Index within the internal section table used by the section builder /// </summary> public readonly int Index; /// <summary> /// Section name /// </summary> public readonly string Name; /// <summary> /// Section characteristics /// </summary> public readonly SectionCharacteristics Characteristics; /// <summary> /// Alignment to apply when combining multiple builder sections into a single /// physical output section (typically when combining hot and cold code into /// the output code section). /// </summary> public readonly int Alignment; /// <summary> /// Blob builder representing the section content. /// </summary> public readonly BlobBuilder Content; /// <summary> /// Relocations to apply to the section /// </summary> public readonly List<ObjectDataRelocations> Relocations; /// <summary> /// RVA gets filled in during section serialization. /// </summary> public int RVAWhenPlaced; /// <summary> /// Output file position gets filled in during section serialization. /// </summary> public int FilePosWhenPlaced; /// <summary> /// Construct a new session object. /// </summary> /// <param name="index">Zero-based section index</param> /// <param name="name">Section name</param> /// <param name="characteristics">Section characteristics</param> /// <param name="alignment">Alignment for combining multiple logical sections</param> public Section(int index, string name, SectionCharacteristics characteristics, int alignment) { Index = index; Name = name; Characteristics = characteristics; Alignment = alignment; Content = new BlobBuilder(); Relocations = new List<ObjectDataRelocations>(); RVAWhenPlaced = 0; FilePosWhenPlaced = 0; } } /// <summary> /// This class represents a single export symbol in the PE file. /// </summary> public class ExportSymbol { /// <summary> /// Symbol identifier /// </summary> public readonly string Name; /// <summary> /// When placed into the export section, RVA of the symbol name gets updated. /// </summary> public int NameRVAWhenPlaced; /// <summary> /// Export symbol ordinal /// </summary> public readonly int Ordinal; /// <summary> /// Symbol to export /// </summary> public readonly ISymbolNode Symbol; /// <summary> /// Construct the export symbol instance filling in its arguments /// </summary> /// <param name="name">Export symbol identifier</param> /// <param name="ordinal">Ordinal ID of the export symbol</param> /// <param name="symbol">Symbol to export</param> public ExportSymbol(string name, int ordinal, ISymbolNode symbol) { Name = name; Ordinal = ordinal; Symbol = symbol; } } /// <summary> /// Section builder is capable of accumulating blocks, using them to lay out sections /// and relocate the produced executable according to the block relocation information. /// </summary> public class SectionBuilder { /// <summary> /// Map from symbols to their target sections and offsets. /// </summary> Dictionary<ISymbolNode, SymbolTarget> _symbolMap; /// <summary> /// List of sections defined in the builder /// </summary> List<Section> _sections; /// <summary> /// Symbols to export from the PE file. /// </summary> List<ExportSymbol> _exportSymbols; /// <summary> /// Optional symbol representing an entrypoint override. /// </summary> ISymbolNode _entryPointSymbol; /// <summary> /// Export directory entry when available. /// </summary> DirectoryEntry _exportDirectoryEntry; /// <summary> /// Directory entry representing the extra relocation records. /// </summary> DirectoryEntry _relocationDirectoryEntry; /// <summary> /// Symbol representing the ready-to-run header table. /// </summary> ISymbolNode _readyToRunHeaderSymbol; /// <summary> /// Delegate for translation of section names to section start symbols /// </summary> Func<string, ISymbolNode> _sectionStartNodeLookup; /// <summary> /// Size of the ready-to-run header table in bytes. /// </summary> int _readyToRunHeaderSize; /// <summary> /// For PE files with exports, this is the "DLL name" string to store in the export directory table. /// </summary> string _dllNameForExportDirectoryTable; /// <summary> /// Construct an empty section builder without any sections or blocks. /// </summary> public SectionBuilder() { _symbolMap = new Dictionary<ISymbolNode, SymbolTarget>(); _sections = new List<Section>(); _exportSymbols = new List<ExportSymbol>(); _entryPointSymbol = null; _exportDirectoryEntry = default(DirectoryEntry); _relocationDirectoryEntry = default(DirectoryEntry); _sectionStartNodeLookup = null; } /// <summary> /// Add a new section. Section names must be unique. /// </summary> /// <param name="name">Section name</param> /// <param name="characteristics">Section characteristics</param> /// <param name="alignment"> /// Alignment for composing multiple builder sections into one physical output section /// </param> /// <returns>Zero-based index of the added section</returns> public int AddSection(string name, SectionCharacteristics characteristics, int alignment) { int sectionIndex = _sections.Count; _sections.Add(new Section(sectionIndex, name, characteristics, alignment)); return sectionIndex; } /// <summary> /// Try to look up a pre-existing section in the builder; returns null if not found. /// </summary> public Section FindSection(string name) { return _sections.FirstOrDefault((sec) => sec.Name == name); } /// <summary> /// Look up RVA for a given symbol. This assumes the section have already been placed. /// </summary> /// <param name="symbol">Symbol to look up</param> /// <returns>RVA of the symbol</returns> public int GetSymbolRVA(ISymbolNode symbol) { SymbolTarget symbolTarget = _symbolMap[symbol]; Section section = _sections[symbolTarget.SectionIndex]; Debug.Assert(section.RVAWhenPlaced != 0); return section.RVAWhenPlaced + symbolTarget.Offset; } /// <summary> /// Attach an export symbol to the output PE file. /// </summary> /// <param name="name">Export symbol identifier</param> /// <param name="ordinal">Ordinal ID of the export symbol</param> /// <param name="symbol">Symbol to export</param> public void AddExportSymbol(string name, int ordinal, ISymbolNode symbol) { _exportSymbols.Add(new ExportSymbol( name: name, ordinal: ordinal, symbol: symbol)); } /// <summary> /// Record DLL name to emit in the export directory table. /// </summary> /// <param name="dllName">DLL name to emit</param> public void SetDllNameForExportDirectoryTable(string dllName) { _dllNameForExportDirectoryTable = dllName; } /// <summary> /// Override entry point for the app. /// </summary> /// <param name="symbol">Symbol representing the new entry point</param> public void SetEntryPoint(ISymbolNode symbol) { _entryPointSymbol = symbol; } /// <summary> /// Set up the ready-to-run header table location. /// </summary> /// <param name="symbol">Symbol representing the ready-to-run header</param> /// <param name="headerSize">Size of the ready-to-run header</param> public void SetReadyToRunHeaderTable(ISymbolNode symbol, int headerSize) { _readyToRunHeaderSymbol = symbol; _readyToRunHeaderSize = headerSize; } /// <summary> /// Set delegate translating section names to section start symbols. /// </summary> /// <param name="sectionStartNodeLookup">Section start symbol lookup delegate to install</param> public void SetSectionStartNodeLookup(Func<string, ISymbolNode> sectionStartNodeLookup) { _sectionStartNodeLookup = sectionStartNodeLookup; } private CoreRTNameMangler _nameMangler; private NameMangler GetNameMangler() { if (_nameMangler == null) { _nameMangler = new CoreRTNameMangler(new WindowsNodeMangler(), mangleForCplusPlus: false); _nameMangler.CompilationUnitPrefix = ""; } return _nameMangler; } /// <summary> /// Add an ObjectData block to a given section. /// </summary> /// <param name="data">Block to add</param> /// <param name="sectionIndex">Section index</param> /// <param name="name">Node name to emit in the map file</param> /// <param name="mapFile">Optional map file to emit</param> public void AddObjectData(ObjectNode.ObjectData objectData, int sectionIndex, string name, TextWriter mapFile) { Section section = _sections[sectionIndex]; // Calculate alignment padding - apparently ObjectDataBuilder can produce an alignment of 0 int alignedOffset = section.Content.Count; if (objectData.Alignment > 1) { alignedOffset = (section.Content.Count + objectData.Alignment - 1) & -objectData.Alignment; int padding = alignedOffset - section.Content.Count; if (padding > 0) { byte paddingByte = 0; if ((section.Characteristics & SectionCharacteristics.ContainsCode) != 0) { // TODO: only use INT3 on x86 & amd64 paddingByte = 0xCC; } section.Content.WriteBytes(paddingByte, padding); } } if (mapFile != null) { mapFile.WriteLine($@"S{sectionIndex}+0x{alignedOffset:X4}..{(alignedOffset + objectData.Data.Length):X4}: {objectData.Data.Length:X4} * {name}"); } section.Content.WriteBytes(objectData.Data); if (objectData.DefinedSymbols != null) { foreach (ISymbolDefinitionNode symbol in objectData.DefinedSymbols) { if (mapFile != null) { Utf8StringBuilder sb = new Utf8StringBuilder(); symbol.AppendMangledName(GetNameMangler(), sb); int sectionRelativeOffset = alignedOffset + symbol.Offset; mapFile.WriteLine($@" +0x{sectionRelativeOffset:X4}: {sb.ToString()}"); } _symbolMap.Add(symbol, new SymbolTarget( sectionIndex: sectionIndex, offset: alignedOffset + symbol.Offset)); } } if (objectData.Relocs != null && objectData.Relocs.Length != 0) { section.Relocations.Add(new ObjectDataRelocations(alignedOffset, objectData.Relocs)); } } /// <summary> /// Get the list of sections that need to be emitted to the output PE file. /// We filter out name duplicates as we'll end up merging builder sections with the same name /// into a single output physical section. /// </summary> public IEnumerable<SectionInfo> GetSections() { List<SectionInfo> sectionList = new List<SectionInfo>(); foreach (Section section in _sections) { if (!sectionList.Any((sc) => sc.SectionName == section.Name)) { sectionList.Add(new SectionInfo(section.Name, section.Characteristics)); } } if (_exportSymbols.Count != 0 && FindSection(".edata") == null) { sectionList.Add(new SectionInfo(".edata", SectionCharacteristics.ContainsInitializedData | SectionCharacteristics.MemRead)); } return sectionList; } /// <summary> /// Traverse blocks within a single section and use them to calculate final layout /// of the given section. /// </summary> /// <param name="name">Section to serialize</param> /// <param name="sectionLocation">Logical section address within the output PE file</param> /// <param name="sectionStartRva">Section start RVA</param> /// <returns></returns> public BlobBuilder SerializeSection(string name, SectionLocation sectionLocation, int sectionStartRva) { if (name == ".reloc") { return SerializeRelocationSection(sectionLocation); } if (name == ".edata") { return SerializeExportSection(sectionLocation); } BlobBuilder serializedSection = null; // Locate logical section index by name foreach (Section section in _sections.Where((sec) => sec.Name == name)) { // Calculate alignment padding int alignedRVA = (sectionLocation.RelativeVirtualAddress + section.Alignment - 1) & -section.Alignment; int padding = alignedRVA - sectionLocation.RelativeVirtualAddress; if (padding > 0) { if (serializedSection == null) { serializedSection = new BlobBuilder(); } serializedSection.WriteBytes(0, padding); sectionLocation = new SectionLocation( sectionLocation.RelativeVirtualAddress + padding, sectionLocation.PointerToRawData + padding); } // Place the section section.RVAWhenPlaced = sectionLocation.RelativeVirtualAddress; section.FilePosWhenPlaced = sectionLocation.PointerToRawData; // Place section start symbol node if available if (_sectionStartNodeLookup != null) { ISymbolNode sectionStartNode = _sectionStartNodeLookup(name); if (sectionStartNode != null) { // We back-compensate the start section symbol to point at the beginning of the original // section data. This is needed to access RVA field data in the embedded MSIL. _symbolMap.Add(sectionStartNode, new SymbolTarget(section.Index, sectionStartRva - section.RVAWhenPlaced)); } } if (section.Content.Count != 0) { sectionLocation = new SectionLocation( sectionLocation.RelativeVirtualAddress + section.Content.Count, sectionLocation.PointerToRawData + section.Content.Count); if (serializedSection == null) { serializedSection = section.Content; } else { serializedSection.LinkSuffix(section.Content); } } } return serializedSection; } /// <summary> /// Emit the .reloc section based on file relocation information in the individual blocks. /// We rely on the fact that the .reloc section is emitted last so that, by the time /// it's getting serialized, all other sections that may contain relocations have already /// been laid out. /// </summary> private BlobBuilder SerializeRelocationSection(SectionLocation sectionLocation) { // There are 12 bits for the relative offset const int RelocationTypeShift = 12; const int MaxRelativeOffsetInBlock = (1 << RelocationTypeShift) - 1; // Even though the format doesn't dictate it, it seems customary // to align the base RVA's on 4K boundaries. const int BaseRVAAlignment = 1 << RelocationTypeShift; BlobBuilder builder = new BlobBuilder(); int baseRVA = 0; List<ushort> offsetsAndTypes = null; // Traverse relocations in all sections in their RVA order // By now, all "normal" sections with relocations should already have been laid out foreach (Section section in _sections.OrderBy((sec) => sec.RVAWhenPlaced)) { foreach (ObjectDataRelocations objectDataRelocs in section.Relocations) { for (int relocIndex = 0; relocIndex < objectDataRelocs.Relocs.Length; relocIndex++) { RelocType relocType = objectDataRelocs.Relocs[relocIndex].RelocType; RelocType fileRelocType = GetFileRelocationType(relocType); if (fileRelocType != RelocType.IMAGE_REL_BASED_ABSOLUTE) { int relocationRVA = section.RVAWhenPlaced + objectDataRelocs.Offset + objectDataRelocs.Relocs[relocIndex].Offset; if (offsetsAndTypes != null && relocationRVA - baseRVA > MaxRelativeOffsetInBlock) { // Need to flush relocation block as the current RVA is too far from base RVA FlushRelocationBlock(builder, baseRVA, offsetsAndTypes); offsetsAndTypes = null; } if (offsetsAndTypes == null) { // Create new relocation block baseRVA = relocationRVA & -BaseRVAAlignment; offsetsAndTypes = new List<ushort>(); } ushort offsetAndType = (ushort)(((ushort)fileRelocType << RelocationTypeShift) | (relocationRVA - baseRVA)); offsetsAndTypes.Add(offsetAndType); } } } } if (offsetsAndTypes != null) { FlushRelocationBlock(builder, baseRVA, offsetsAndTypes); } _relocationDirectoryEntry = new DirectoryEntry(sectionLocation.RelativeVirtualAddress, builder.Count); return builder; } /// <summary> /// Serialize a block of relocations into the .reloc section. /// </summary> /// <param name="builder">Output blob builder to receive the serialized relocation block</param> /// <param name="baseRVA">Base RVA of the relocation block</param> /// <param name="offsetsAndTypes">16-bit entries encoding offset relative to the base RVA (low 12 bits) and relocation type (top 4 bite)</param> private static void FlushRelocationBlock(BlobBuilder builder, int baseRVA, List<ushort> offsetsAndTypes) { // First, emit the block header: 4 bytes starting RVA, builder.WriteInt32(baseRVA); // followed by the total block size comprising this header // and following 16-bit entries. builder.WriteInt32(4 + 4 + 2 * offsetsAndTypes.Count); // Now serialize out the entries foreach (ushort offsetAndType in offsetsAndTypes) { builder.WriteUInt16(offsetAndType); } } /// <summary> /// Serialize the export symbol table into the export section. /// </summary> /// <param name="location">RVA and file location of the .edata section</param> private BlobBuilder SerializeExportSection(SectionLocation sectionLocation) { _exportSymbols.Sort((es1, es2) => StringComparer.Ordinal.Compare(es1.Name, es2.Name)); BlobBuilder builder = new BlobBuilder(); int minOrdinal = int.MaxValue; int maxOrdinal = int.MinValue; // First, emit the name table and store the name RVA's for the individual export symbols // Also, record the ordinal range. foreach (ExportSymbol symbol in _exportSymbols) { symbol.NameRVAWhenPlaced = sectionLocation.RelativeVirtualAddress + builder.Count; builder.WriteUTF8(symbol.Name); builder.WriteByte(0); if (symbol.Ordinal < minOrdinal) { minOrdinal = symbol.Ordinal; } if (symbol.Ordinal > maxOrdinal) { maxOrdinal = symbol.Ordinal; } } // Emit the DLL name int dllNameRVA = sectionLocation.RelativeVirtualAddress + builder.Count; builder.WriteUTF8(_dllNameForExportDirectoryTable); builder.WriteByte(0); int[] addressTable = new int[maxOrdinal - minOrdinal + 1]; // Emit the name pointer table; it should be alphabetically sorted. // Also, we can now fill in the export address table as we've detected its size // in the previous pass. int namePointerTableRVA = sectionLocation.RelativeVirtualAddress + builder.Count; foreach (ExportSymbol symbol in _exportSymbols) { builder.WriteInt32(symbol.NameRVAWhenPlaced); SymbolTarget symbolTarget = _symbolMap[symbol.Symbol]; Section symbolSection = _sections[symbolTarget.SectionIndex]; Debug.Assert(symbolSection.RVAWhenPlaced != 0); addressTable[symbol.Ordinal - minOrdinal] = symbolSection.RVAWhenPlaced + symbolTarget.Offset; } // Emit the ordinal table int ordinalTableRVA = sectionLocation.RelativeVirtualAddress + builder.Count; foreach (ExportSymbol symbol in _exportSymbols) { builder.WriteUInt16((ushort)(symbol.Ordinal - minOrdinal)); } // Emit the address table int addressTableRVA = sectionLocation.RelativeVirtualAddress + builder.Count; foreach (int addressTableEntry in addressTable) { builder.WriteInt32(addressTableEntry); } // Emit the export directory table int exportDirectoryTableRVA = sectionLocation.RelativeVirtualAddress + builder.Count; // +0x00: reserved builder.WriteInt32(0); // +0x04: TODO: time/date stamp builder.WriteInt32(0); // +0x08: major version builder.WriteInt16(0); // +0x0A: minor version builder.WriteInt16(0); // +0x0C: DLL name RVA builder.WriteInt32(dllNameRVA); // +0x10: ordinal base builder.WriteInt32(minOrdinal); // +0x14: number of entries in the address table builder.WriteInt32(addressTable.Length); // +0x18: number of name pointers builder.WriteInt32(_exportSymbols.Count); // +0x1C: export address table RVA builder.WriteInt32(addressTableRVA); // +0x20: name pointer RVV builder.WriteInt32(namePointerTableRVA); // +0x24: ordinal table RVA builder.WriteInt32(ordinalTableRVA); int exportDirectorySize = sectionLocation.RelativeVirtualAddress + builder.Count - exportDirectoryTableRVA; _exportDirectoryEntry = new DirectoryEntry(relativeVirtualAddress: exportDirectoryTableRVA, size: exportDirectorySize); return builder; } /// <summary> /// Update the PE file directories. Currently this is used to update the export symbol table /// when export symbols have been added to the section builder. /// </summary> /// <param name="directoriesBuilder">PE directory builder to update</param> public void UpdateDirectories(PEDirectoriesBuilder directoriesBuilder) { if (_exportDirectoryEntry.Size != 0) { directoriesBuilder.ExportTable = _exportDirectoryEntry; } int relocationTableRVA = directoriesBuilder.BaseRelocationTable.RelativeVirtualAddress; if (relocationTableRVA == 0) { relocationTableRVA = _relocationDirectoryEntry.RelativeVirtualAddress; } directoriesBuilder.BaseRelocationTable = new DirectoryEntry( relocationTableRVA, directoriesBuilder.BaseRelocationTable.Size + _relocationDirectoryEntry.Size); if (_entryPointSymbol != null) { SymbolTarget symbolTarget = _symbolMap[_entryPointSymbol]; Section section = _sections[symbolTarget.SectionIndex]; Debug.Assert(section.RVAWhenPlaced != 0); directoriesBuilder.AddressOfEntryPoint = section.RVAWhenPlaced + symbolTarget.Offset; } } /// <summary> /// Update the COR header. /// </summary> /// <param name="corHeader">COR header builder to update</param> public void UpdateCorHeader(CorHeaderBuilder corHeader) { if (_readyToRunHeaderSymbol != null) { SymbolTarget headerTarget = _symbolMap[_readyToRunHeaderSymbol]; Section headerSection = _sections[headerTarget.SectionIndex]; Debug.Assert(headerSection.RVAWhenPlaced != 0); int r2rHeaderRVA = headerSection.RVAWhenPlaced + headerTarget.Offset; corHeader.ManagedNativeHeaderDirectory = new DirectoryEntry(r2rHeaderRVA, _readyToRunHeaderSize); } } /// <summary> /// Relocate the produced PE file and output the result into a given stream. /// </summary> /// <param name="peFile">Blob builder representing the complete PE file</param> /// <param name="defaultImageBase">Default load address for the image</param> /// <param name="corHeaderBuilder">COR header</param> /// <param name="corHeaderFileOffset">File position of the COR header</param> /// <param name="outputStream">Stream to receive the relocated PE file</param> public void RelocateOutputFile( BlobBuilder peFile, ulong defaultImageBase, CorHeaderBuilder corHeaderBuilder, int corHeaderFileOffset, Stream outputStream) { RelocationHelper relocationHelper = new RelocationHelper(outputStream, defaultImageBase, peFile); if (corHeaderBuilder != null) { relocationHelper.CopyToFilePosition(corHeaderFileOffset); UpdateCorHeader(corHeaderBuilder); BlobBuilder corHeaderBlob = new BlobBuilder(); corHeaderBuilder.WriteTo(corHeaderBlob); int writtenSize = corHeaderBlob.Count; corHeaderBlob.WriteContentTo(outputStream); relocationHelper.AdvanceOutputPos(writtenSize); // Just skip the bytes that were emitted by the COR header writer byte[] skipBuffer = new byte[writtenSize]; relocationHelper.CopyBytesToBuffer(skipBuffer, writtenSize); } // Traverse relocations in all sections in their RVA order foreach (Section section in _sections.OrderBy((sec) => sec.RVAWhenPlaced)) { int rvaToFilePosDelta = section.FilePosWhenPlaced - section.RVAWhenPlaced; foreach (ObjectDataRelocations objectDataRelocs in section.Relocations) { foreach (Relocation relocation in objectDataRelocs.Relocs) { // Process a single relocation int relocationRVA = section.RVAWhenPlaced + objectDataRelocs.Offset + relocation.Offset; int relocationFilePos = relocationRVA + rvaToFilePosDelta; // Flush parts of PE file before the relocation to the output stream relocationHelper.CopyToFilePosition(relocationFilePos); // Look up relocation target SymbolTarget relocationTarget = _symbolMap[relocation.Target]; Section targetSection = _sections[relocationTarget.SectionIndex]; int targetRVA = targetSection.RVAWhenPlaced + relocationTarget.Offset; // Apply the relocation relocationHelper.ProcessRelocation(relocation.RelocType, relocationRVA, targetRVA); } } } // Flush remaining PE file blocks after the last relocation relocationHelper.CopyRestOfFile(); } /// <summary> /// Return file relocation type for the given relocation type. If the relocation /// doesn't require a file-level relocation entry in the .reloc section, 0 is returned /// corresponding to the IMAGE_REL_BASED_ABSOLUTE no-op relocation record. /// </summary> /// <param name="relocationType">Relocation type</param> /// <returns>File-level relocation type or 0 (IMAGE_REL_BASED_ABSOLUTE) if none is required</returns> private static RelocType GetFileRelocationType(RelocType relocationType) { switch (relocationType) { case RelocType.IMAGE_REL_BASED_HIGHLOW: case RelocType.IMAGE_REL_BASED_DIR64: case RelocType.IMAGE_REL_BASED_THUMB_MOV32: return relocationType; default: return RelocType.IMAGE_REL_BASED_ABSOLUTE; } } } /// <summary> /// This class has been mostly copied over from corefx as the corefx CorHeader class /// is well protected against being useful in more general scenarios as its only /// constructor is internal. /// </summary> public sealed class CorHeaderBuilder { public int CorHeaderSize; public ushort MajorRuntimeVersion; public ushort MinorRuntimeVersion; public DirectoryEntry MetadataDirectory; public CorFlags Flags; public int EntryPointTokenOrRelativeVirtualAddress; public DirectoryEntry ResourcesDirectory; public DirectoryEntry StrongNameSignatureDirectory; public DirectoryEntry CodeManagerTableDirectory; public DirectoryEntry VtableFixupsDirectory; public DirectoryEntry ExportAddressTableJumpsDirectory; public DirectoryEntry ManagedNativeHeaderDirectory; public CorHeaderBuilder(ref BlobReader reader) { // byte count CorHeaderSize = reader.ReadInt32(); MajorRuntimeVersion = reader.ReadUInt16(); MinorRuntimeVersion = reader.ReadUInt16(); MetadataDirectory = ReadDirectoryEntry(ref reader); Flags = (CorFlags)reader.ReadUInt32(); EntryPointTokenOrRelativeVirtualAddress = reader.ReadInt32(); ResourcesDirectory = ReadDirectoryEntry(ref reader); StrongNameSignatureDirectory = ReadDirectoryEntry(ref reader); CodeManagerTableDirectory = ReadDirectoryEntry(ref reader); VtableFixupsDirectory = ReadDirectoryEntry(ref reader); ExportAddressTableJumpsDirectory = ReadDirectoryEntry(ref reader); ManagedNativeHeaderDirectory = ReadDirectoryEntry(ref reader); } /// <summary> /// Helper method to serialize CorHeader into a BlobBuilder. /// </summary> /// <param name="builder">Target blob builder to receive the serialized data</param> public void WriteTo(BlobBuilder builder) { builder.WriteInt32(CorHeaderSize); builder.WriteUInt16(MajorRuntimeVersion); builder.WriteUInt16(MinorRuntimeVersion); WriteDirectoryEntry(MetadataDirectory, builder); builder.WriteUInt32((uint)Flags); builder.WriteInt32(EntryPointTokenOrRelativeVirtualAddress); WriteDirectoryEntry(ResourcesDirectory, builder); WriteDirectoryEntry(StrongNameSignatureDirectory, builder); WriteDirectoryEntry(CodeManagerTableDirectory, builder); WriteDirectoryEntry(VtableFixupsDirectory, builder); WriteDirectoryEntry(ExportAddressTableJumpsDirectory, builder); WriteDirectoryEntry(ManagedNativeHeaderDirectory, builder); } /// <summary> /// Deserialize a directory entry from a blob reader. /// </summary> /// <param name="reader">Reader to deserialize directory entry from</param> private static DirectoryEntry ReadDirectoryEntry(ref BlobReader reader) { int rva = reader.ReadInt32(); int size = reader.ReadInt32(); return new DirectoryEntry(rva, size); } /// <summary> /// Serialize a directory entry into an output blob builder. /// </summary> /// <param name="directoryEntry">Directory entry to serialize</param> /// <param name="builder">Output blob builder to receive the serialized entry</param> private static void WriteDirectoryEntry(DirectoryEntry directoryEntry, BlobBuilder builder) { builder.WriteInt32(directoryEntry.RelativeVirtualAddress); builder.WriteInt32(directoryEntry.Size); } } /// <summary> /// Section builder extensions for R2R PE builder. /// </summary> public static class SectionBuilderExtensions { /// <summary> /// Emit built sections using the R2R PE writer. /// </summary> /// <param name="builder">Section builder to emit</param> /// <param name="machine">Target machine architecture</param> /// <param name="inputReader">Input MSIL reader</param> /// <param name="outputStream">Output stream for the final R2R PE file</param> public static void EmitR2R( this SectionBuilder builder, Machine machine, PEReader inputReader, Action<PEDirectoriesBuilder> directoriesUpdater, Stream outputStream) { R2RPEBuilder r2rBuilder = new R2RPEBuilder( machine: machine, peReader: inputReader, sectionNames: builder.GetSections(), sectionSerializer: builder.SerializeSection, directoriesUpdater: (PEDirectoriesBuilder directoriesBuilder) => { builder.UpdateDirectories(directoriesBuilder); if (directoriesUpdater != null) { directoriesUpdater(directoriesBuilder); } }); BlobBuilder outputPeFile = new BlobBuilder(); r2rBuilder.Serialize(outputPeFile); CorHeaderBuilder corHeader = r2rBuilder.CorHeader; if (corHeader != null) { corHeader.Flags = (r2rBuilder.CorHeader.Flags & ~CorFlags.ILOnly) | CorFlags.ILLibrary; corHeader.MetadataDirectory = r2rBuilder.RelocateDirectoryEntry(corHeader.MetadataDirectory); corHeader.ResourcesDirectory = r2rBuilder.RelocateDirectoryEntry(corHeader.ResourcesDirectory); corHeader.StrongNameSignatureDirectory = r2rBuilder.RelocateDirectoryEntry(corHeader.StrongNameSignatureDirectory); corHeader.CodeManagerTableDirectory = r2rBuilder.RelocateDirectoryEntry(corHeader.CodeManagerTableDirectory); corHeader.VtableFixupsDirectory = r2rBuilder.RelocateDirectoryEntry(corHeader.VtableFixupsDirectory); corHeader.ExportAddressTableJumpsDirectory = r2rBuilder.RelocateDirectoryEntry(corHeader.ExportAddressTableJumpsDirectory); corHeader.ManagedNativeHeaderDirectory = r2rBuilder.RelocateDirectoryEntry(corHeader.ManagedNativeHeaderDirectory); builder.UpdateCorHeader(corHeader); } builder.RelocateOutputFile( outputPeFile, inputReader.PEHeaders.PEHeader.ImageBase, corHeader, r2rBuilder.CorHeaderFileOffset, outputStream); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; namespace GG{ public class Tile { //Type of tile and its location in space /// <summary> /// /// Type 0 wall /// Type 1 Room /// Type 2 Player /// Type 3 AI /// More types likely to come /// /// </summary> public int type; /// <summary> /// The location in 2d Space. /// </summary> public Vector2 location; /// <summary> /// Initializes a new instance of the <see cref="GG.Tile"/> class. /// </summary> /// <param name='x'> /// X. /// </param> /// <param name='y'> /// Y. /// </param> /// <param name='type'> /// Type. /// </param> public Tile(int x, int y, int type) { location.x = x; location.y = y; this.type = type; } } public class Room { //TODO Fix This Class. public Tile[] roomTiles; public int connected = 0; } public class GridGenerator{ private Tile[][] tiles; private Room[] rooms; private int size; private int numRooms; private int maxFails; private int count =0; public GridGenerator(int size,int numRooms,int maxFails,int numAI, int numHealth) { this.size = size; this.numRooms = numRooms; this.maxFails = maxFails; initializeGrid(); createRooms(numRooms); int aicount = 0; while (aicount < numAI) { if (placeAI()) { aicount++;} } int healthcount = 0; while (healthcount < numHealth) { if (placeHealth()) { healthcount++;} } bool placed = false; while(placed != true) { placed = placePlayer(); } createPaths(); } void initializeGrid() { tiles = new Tile[size][]; for(int i=0;i<size;i++) { tiles[i] = new Tile[size]; for(int j=0;j<size;j++) { tiles[i][j] = new Tile(i,j,0); } } rooms = new Room[numRooms]; } void createRooms(int numRooms) { int fails = 0; while(count < numRooms) { if(placeRoom(count)) { count++; }else{ fails++; if (fails > maxFails) { break; } } } } bool placeRoom(int roomIndex) { //Position and Size of the room to be created int posX, posY, roomX, roomY; bool valid = true; //find a location for a room. posX = Random.Range (1, (size-1)); posY = Random.Range (1, (size-1)); //Set Room size roomX = Random.Range (2, 6); roomY = Random.Range (2, 6); //check to see if Location is valid. by adding the room size to the position to make sure it wont be larger than the array-1 if (((posX+roomX) < (size-1))&&((posY+roomY)<(size-1))) { for (int i=-1; i<(roomX+1); i++) { for (int j=-1; j<(roomY+1); j++) { //this must be lower than size - 1 or index out of range error. if (tiles[(posX + i)][(posY + j)].type == 1) { Debug.Log ("Room pressent invalid "); return false; } } } } else { Debug.Log ("Location invalid "); return false; } //If Vaild Delete the cubes from the room array and create a new room object if (valid) { //int tileCount=0; for(int i=0; i<roomX; i++) { for (int j=0; j<roomY; j++) { tiles[(posX+i)][(posY+j)].type=1; } } return(true); } Debug.Log("Thats Not Right Error 1 Failed to place room"); return(false); } bool placeAI() { //Position where to place tank int posX, posY; bool valid = true; //find a location for a room. posX = Random.Range(1, (size - 1)); posY = Random.Range(1, (size - 1)); if (tiles[(posX)][(posY)].type == 1) { Debug.Log("Room pressent invalid "); return false; } //If Vaild Delete the cubes from the room array and set the tile type if (valid) { tiles[posX][posY].type = 3; return (true); } Debug.Log("Thats Not Right Error 1 Failed to place room"); return (false); } bool placeHealth() { //Position where to place tank int posX, posY; bool valid = true; //find a location for a room. posX = Random.Range(1, (size - 1)); posY = Random.Range(1, (size - 1)); if (tiles[(posX)][(posY)].type == 1) { Debug.Log("Room pressent invalid "); return false; } //If Vaild Delete the cubes from the room array and set the tile type if (valid) { tiles[posX][posY].type = 4; return (true); } Debug.Log("Thats Not Right Error 1 Failed to place room"); return (false); } bool placePlayer(){ //Position where to place tank int posX, posY; bool valid = true; //find a location for a room. posX = Random.Range(1, (size - 1)); posY = Random.Range(1, (size - 1)); if (tiles[(posX)][(posY)].type == 1) { Debug.Log("Room pressent invalid "); return false; } //If Vaild Delete the cubes from the room array and set the tile type if(valid) { tiles[posX][posY].type = 2; return (true); } Debug.Log("Thats Not Right Error 1 Failed to place room"); return (false); } /// <summary> /// Creates the paths. /// </summary> void createPaths() { /* for (int i=0;i<count;i++){ if (rooms[i].connected==0) { ///TODO //Find near room, start pathing //Need Lists //Use Shortest List } }*/ } void createPath(Room start,Room end) { //Get list of Tiles around starting room. List<Tile> tiles = new List<Tile>(); foreach (Tile t in start.roomTiles) { tiles.Add(t); } foreach(Tile t in tiles) { //Get the nort south east and west tile that does not exist in this set already //add is not null //North } } /// <summary> /// Gets the tiles. /// </summary> /// <returns> /// The tiles. /// </returns> public Tile[][] getTiles() { return(tiles); } /// <summary> /// Gets the rooms. /// </summary> /// <param name='x'> /// X. /// </param> public void getRooms(out Room[] x) { x = rooms; } public Tile[][] Dijkstra() { Tile[][] x = tiles; return(x); } } }
// 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.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsHead { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; /// <summary> /// Test Infrastructure for AutoRest /// </summary> public partial class AutoRestHeadTestService : ServiceClient<AutoRestHeadTestService>, IAutoRestHeadTestService, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// The management credentials for Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// The retry timeout for Long Running Operations. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } public virtual IHttpSuccessOperations HttpSuccess { get; private set; } /// <summary> /// Initializes a new instance of the AutoRestHeadTestService class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestHeadTestService(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestHeadTestService class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestHeadTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestHeadTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestHeadTestService(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestHeadTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestHeadTestService(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestHeadTestService class. /// </summary> /// <param name='credentials'> /// Required. The management credentials for Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestHeadTestService(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestHeadTestService class. /// </summary> /// <param name='credentials'> /// Required. The management credentials for Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestHeadTestService(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestHeadTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. The management credentials for Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestHeadTestService(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestHeadTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. The management credentials for Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestHeadTestService(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.HttpSuccess = new HttpSuccessOperations(this); this.BaseUri = new Uri("http://localhost"); this.AcceptLanguage = "en-US"; SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new ResourceJsonConverter()); DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings.Converters.Add(new ResourceJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
/** * Copyright (c) 2017 Enzien Audio, Ltd. * * 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 phrase "powered by heavy", * the heavy logo, and a hyperlink to https://enzienaudio.com, all in a visible * form. * * 2.1 If the Application is distributed in a store system (for example, * the Apple "App Store" or "Google Play"), the phrase "powered by heavy" * shall be included in the app description or the copyright text as well as * the in the app itself. The heavy logo will shall be visible in the app * itself as well. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ using System; using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEngine; using UnityEngine.Assertions; using AOT; #if UNITY_EDITOR using UnityEditor; [CustomEditor(typeof(Hv_fireancestor_poofer_audio_AudioLib))] public class Hv_fireancestor_poofer_audio_Editor : Editor { [MenuItem("Heavy/fireancestor_poofer_audio")] static void CreateHv_fireancestor_poofer_audio() { GameObject target = Selection.activeGameObject; if (target != null) { target.AddComponent<Hv_fireancestor_poofer_audio_AudioLib>(); } } private Hv_fireancestor_poofer_audio_AudioLib _dsp; private void OnEnable() { _dsp = target as Hv_fireancestor_poofer_audio_AudioLib; } public override void OnInspectorGUI() { bool isEnabled = _dsp.IsInstantiated(); if (!isEnabled) { EditorGUILayout.LabelField("Press Play!", EditorStyles.centeredGreyMiniLabel); } // events GUI.enabled = isEnabled; EditorGUILayout.Space(); // poof if (GUILayout.Button("poof")) { _dsp.SendEvent(Hv_fireancestor_poofer_audio_AudioLib.Event.Poof); } GUILayout.EndVertical(); // parameters GUI.enabled = true; GUILayout.BeginVertical(); EditorGUILayout.Space(); EditorGUI.indentLevel++; // decay GUILayout.BeginHorizontal(); float decay = _dsp.GetFloatParameter(Hv_fireancestor_poofer_audio_AudioLib.Parameter.Decay); float newDecay = EditorGUILayout.Slider("decay", decay, 5.0f, 10000.0f); if (decay != newDecay) { _dsp.SetFloatParameter(Hv_fireancestor_poofer_audio_AudioLib.Parameter.Decay, newDecay); } GUILayout.EndHorizontal(); // filter_freq GUILayout.BeginHorizontal(); float filter_freq = _dsp.GetFloatParameter(Hv_fireancestor_poofer_audio_AudioLib.Parameter.Filter_freq); float newFilter_freq = EditorGUILayout.Slider("filter_freq", filter_freq, 0.0f, 20000.0f); if (filter_freq != newFilter_freq) { _dsp.SetFloatParameter(Hv_fireancestor_poofer_audio_AudioLib.Parameter.Filter_freq, newFilter_freq); } GUILayout.EndHorizontal(); // hold GUILayout.BeginHorizontal(); float hold = _dsp.GetFloatParameter(Hv_fireancestor_poofer_audio_AudioLib.Parameter.Hold); float newHold = EditorGUILayout.Slider("hold", hold, 5.0f, 10000.0f); if (hold != newHold) { _dsp.SetFloatParameter(Hv_fireancestor_poofer_audio_AudioLib.Parameter.Hold, newHold); } GUILayout.EndHorizontal(); EditorGUI.indentLevel--; } } #endif // UNITY_EDITOR [RequireComponent (typeof (AudioSource))] public class Hv_fireancestor_poofer_audio_AudioLib : MonoBehaviour { // Events are used to trigger bangs in the patch context (thread-safe). // Example usage: /* void Start () { Hv_fireancestor_poofer_audio_AudioLib script = GetComponent<Hv_fireancestor_poofer_audio_AudioLib>(); script.SendEvent(Hv_fireancestor_poofer_audio_AudioLib.Event.Poof); } */ public enum Event : uint { Poof = 0x6233E0EF, } // Parameters are used to send float messages into the patch context (thread-safe). // Example usage: /* void Start () { Hv_fireancestor_poofer_audio_AudioLib script = GetComponent<Hv_fireancestor_poofer_audio_AudioLib>(); // Get and set a parameter float decay = script.GetFloatParameter(Hv_fireancestor_poofer_audio_AudioLib.Parameter.Decay); script.SetFloatParameter(Hv_fireancestor_poofer_audio_AudioLib.Parameter.Decay, decay + 0.1f); } */ public enum Parameter : uint { Decay = 0x4F49BFDF, Filter_freq = 0x86998B8, Hold = 0x380FF91E, } // Delegate method for receiving float messages from the patch context (thread-safe). // Example usage: /* void Start () { Hv_fireancestor_poofer_audio_AudioLib script = GetComponent<Hv_fireancestor_poofer_audio_AudioLib>(); script.RegisterSendHook(); script.FloatReceivedCallback += OnFloatMessage; } void OnFloatMessage(Hv_fireancestor_poofer_audio_AudioLib.FloatMessage message) { Debug.Log(message.receiverName + ": " + message.value); } */ public class FloatMessage { public string receiverName; public float value; public FloatMessage(string name, float x) { receiverName = name; value = x; } } public delegate void FloatMessageReceived(FloatMessage message); public FloatMessageReceived FloatReceivedCallback; public float decay = 100.0f; public float filter_freq = 5000.0f; public float hold = 100.0f; // internal state private Hv_fireancestor_poofer_audio_Context _context; public bool IsInstantiated() { return (_context != null); } public void RegisterSendHook() { _context.RegisterSendHook(); } // see Hv_fireancestor_poofer_audio_AudioLib.Event for definitions public void SendEvent(Hv_fireancestor_poofer_audio_AudioLib.Event e) { if (IsInstantiated()) _context.SendBangToReceiver((uint) e); } // see Hv_fireancestor_poofer_audio_AudioLib.Parameter for definitions public float GetFloatParameter(Hv_fireancestor_poofer_audio_AudioLib.Parameter param) { switch (param) { case Parameter.Decay: return decay; case Parameter.Filter_freq: return filter_freq; case Parameter.Hold: return hold; default: return 0.0f; } } public void SetFloatParameter(Hv_fireancestor_poofer_audio_AudioLib.Parameter param, float x) { switch (param) { case Parameter.Decay: { x = Mathf.Clamp(x, 5.0f, 10000.0f); decay = x; break; } case Parameter.Filter_freq: { x = Mathf.Clamp(x, 0.0f, 20000.0f); filter_freq = x; break; } case Parameter.Hold: { x = Mathf.Clamp(x, 5.0f, 10000.0f); hold = x; break; } default: return; } if (IsInstantiated()) _context.SendFloatToReceiver((uint) param, x); } public void FillTableWithMonoAudioClip(string tableName, AudioClip clip) { if (clip.channels > 1) { Debug.LogWarning("Hv_fireancestor_poofer_audio_AudioLib: Only loading first channel of '" + clip.name + "' into table '" + tableName + "'. Multi-channel files are not supported."); } float[] buffer = new float[clip.samples]; // copy only the 1st channel clip.GetData(buffer, 0); _context.FillTableWithFloatBuffer(tableName, buffer); } public void FillTableWithFloatBuffer(string tableName, float[] buffer) { _context.FillTableWithFloatBuffer(tableName, buffer); } private void Awake() { _context = new Hv_fireancestor_poofer_audio_Context((double) AudioSettings.outputSampleRate); } private void Start() { _context.SendFloatToReceiver((uint) Parameter.Decay, decay); _context.SendFloatToReceiver((uint) Parameter.Filter_freq, filter_freq); _context.SendFloatToReceiver((uint) Parameter.Hold, hold); } private void Update() { // retreive sent messages if (_context.IsSendHookRegistered()) { Hv_fireancestor_poofer_audio_AudioLib.FloatMessage tempMessage; while ((tempMessage = _context.msgQueue.GetNextMessage()) != null) { FloatReceivedCallback(tempMessage); } } } private void OnAudioFilterRead(float[] buffer, int numChannels) { Assert.AreEqual(numChannels, _context.GetNumOutputChannels()); // invalid channel configuration _context.Process(buffer, buffer.Length / numChannels); // process dsp } } class Hv_fireancestor_poofer_audio_Context { #if UNITY_IOS && !UNITY_EDITOR private const string _dllName = "__Internal"; #else private const string _dllName = "Hv_fireancestor_poofer_audio_AudioLib"; #endif // Thread-safe message queue public class SendMessageQueue { private readonly object _msgQueueSync = new object(); private readonly Queue<Hv_fireancestor_poofer_audio_AudioLib.FloatMessage> _msgQueue = new Queue<Hv_fireancestor_poofer_audio_AudioLib.FloatMessage>(); public Hv_fireancestor_poofer_audio_AudioLib.FloatMessage GetNextMessage() { lock (_msgQueueSync) { return (_msgQueue.Count != 0) ? _msgQueue.Dequeue() : null; } } public void AddMessage(string receiverName, float value) { Hv_fireancestor_poofer_audio_AudioLib.FloatMessage msg = new Hv_fireancestor_poofer_audio_AudioLib.FloatMessage(receiverName, value); lock (_msgQueueSync) { _msgQueue.Enqueue(msg); } } } public readonly SendMessageQueue msgQueue = new SendMessageQueue(); private readonly GCHandle gch; private readonly IntPtr _context; // handle into unmanaged memory private SendHook _sendHook = null; [DllImport (_dllName)] private static extern IntPtr hv_fireancestor_poofer_audio_new_with_options(double sampleRate, int poolKb, int inQueueKb, int outQueueKb); [DllImport (_dllName)] private static extern int hv_processInlineInterleaved(IntPtr ctx, [In] float[] inBuffer, [Out] float[] outBuffer, int numSamples); [DllImport (_dllName)] private static extern void hv_delete(IntPtr ctx); [DllImport (_dllName)] private static extern double hv_getSampleRate(IntPtr ctx); [DllImport (_dllName)] private static extern int hv_getNumInputChannels(IntPtr ctx); [DllImport (_dllName)] private static extern int hv_getNumOutputChannels(IntPtr ctx); [DllImport (_dllName)] private static extern void hv_setSendHook(IntPtr ctx, SendHook sendHook); [DllImport (_dllName)] private static extern void hv_setPrintHook(IntPtr ctx, PrintHook printHook); [DllImport (_dllName)] private static extern int hv_setUserData(IntPtr ctx, IntPtr userData); [DllImport (_dllName)] private static extern IntPtr hv_getUserData(IntPtr ctx); [DllImport (_dllName)] private static extern void hv_sendBangToReceiver(IntPtr ctx, uint receiverHash); [DllImport (_dllName)] private static extern void hv_sendFloatToReceiver(IntPtr ctx, uint receiverHash, float x); [DllImport (_dllName)] private static extern uint hv_msg_getTimestamp(IntPtr message); [DllImport (_dllName)] private static extern bool hv_msg_hasFormat(IntPtr message, string format); [DllImport (_dllName)] private static extern float hv_msg_getFloat(IntPtr message, int index); [DllImport (_dllName)] private static extern bool hv_table_setLength(IntPtr ctx, uint tableHash, uint newSampleLength); [DllImport (_dllName)] private static extern IntPtr hv_table_getBuffer(IntPtr ctx, uint tableHash); [DllImport (_dllName)] private static extern float hv_samplesToMilliseconds(IntPtr ctx, uint numSamples); [DllImport (_dllName)] private static extern uint hv_stringToHash(string s); private delegate void PrintHook(IntPtr context, string printName, string str, IntPtr message); private delegate void SendHook(IntPtr context, string sendName, uint sendHash, IntPtr message); public Hv_fireancestor_poofer_audio_Context(double sampleRate, int poolKb=10, int inQueueKb=2, int outQueueKb=2) { gch = GCHandle.Alloc(msgQueue); _context = hv_fireancestor_poofer_audio_new_with_options(sampleRate, poolKb, inQueueKb, outQueueKb); hv_setPrintHook(_context, new PrintHook(OnPrint)); hv_setUserData(_context, GCHandle.ToIntPtr(gch)); } ~Hv_fireancestor_poofer_audio_Context() { hv_delete(_context); GC.KeepAlive(_context); GC.KeepAlive(_sendHook); gch.Free(); } public void RegisterSendHook() { // Note: send hook functionality only applies to messages containing a single float value if (_sendHook == null) { _sendHook = new SendHook(OnMessageSent); hv_setSendHook(_context, _sendHook); } } public bool IsSendHookRegistered() { return (_sendHook != null); } public double GetSampleRate() { return hv_getSampleRate(_context); } public int GetNumInputChannels() { return hv_getNumInputChannels(_context); } public int GetNumOutputChannels() { return hv_getNumOutputChannels(_context); } public void SendBangToReceiver(uint receiverHash) { hv_sendBangToReceiver(_context, receiverHash); } public void SendFloatToReceiver(uint receiverHash, float x) { hv_sendFloatToReceiver(_context, receiverHash, x); } public void FillTableWithFloatBuffer(string tableName, float[] buffer) { uint tableHash = hv_stringToHash(tableName); if (hv_table_getBuffer(_context, tableHash) != IntPtr.Zero) { hv_table_setLength(_context, tableHash, (uint) buffer.Length); Marshal.Copy(buffer, 0, hv_table_getBuffer(_context, tableHash), buffer.Length); } else { Debug.Log(string.Format("Table '{0}' doesn't exist in the patch context.", tableName)); } } public uint StringToHash(string s) { return hv_stringToHash(s); } public int Process(float[] buffer, int numFrames) { return hv_processInlineInterleaved(_context, buffer, buffer, numFrames); } [MonoPInvokeCallback(typeof(PrintHook))] private static void OnPrint(IntPtr context, string printName, string str, IntPtr message) { float timeInSecs = hv_samplesToMilliseconds(context, hv_msg_getTimestamp(message)) / 1000.0f; Debug.Log(string.Format("{0} [{1:0.000}]: {2}", printName, timeInSecs, str)); } [MonoPInvokeCallback(typeof(SendHook))] private static void OnMessageSent(IntPtr context, string sendName, uint sendHash, IntPtr message) { if (hv_msg_hasFormat(message, "f")) { SendMessageQueue msgQueue = (SendMessageQueue) GCHandle.FromIntPtr(hv_getUserData(context)).Target; msgQueue.AddMessage(sendName, hv_msg_getFloat(message, 0)); } } }
// // coreimage.cs: Definitions for CoreImage // // Copyright 2010, Novell, Inc. // Copyright 2011, 2012 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // // TODO: CIFilter, eliminate the use of the NSDictionary and use // strongly typed accessors. // // TODO: // CIImageProvider - informal protocol, // CIPluginInterface - informal protocol // CIRAWFilter - informal protocol // CIVector // using System; using System.Drawing; using MonoMac.Foundation; using MonoMac.ObjCRuntime; using MonoMac.CoreGraphics; using MonoMac.CoreImage; using MonoMac.CoreVideo; #if !MONOMAC using MonoTouch.OpenGLES; using MonoTouch.UIKit; #else using MonoMac.AppKit; #endif namespace MonoMac.CoreImage { [BaseType (typeof (NSObject))] [Since (5,0)] [DisableDefaultCtor] public interface CIColor { [Static] [Export ("colorWithCGColor:")] CIColor FromCGColor (CGColor c); [Static] [Export ("colorWithRed:green:blue:alpha:")] CIColor FromRgba (float red, float green, float blue, float alpha); [Static] [Export ("colorWithRed:green:blue:")] CIColor FromRgb (float red, float green, float blue); [Static] [Export ("colorWithString:")] CIColor FromString (string representation); [Export ("initWithCGColor:")] IntPtr Constructor (CGColor c); [Export ("numberOfComponents")] int NumberOfComponents { get; } // FIXME: bdining //[Export ("components")] //const CGFloat Components (); [Export ("alpha")] float Alpha { get; } [Export ("colorSpace")] CGColorSpace ColorSpace { get; } [Export ("red")] float Red { get; } [Export ("green")] float Green { get; } [Export ("blue")] float Blue { get; } [Export ("stringRepresentation")] string StringRepresentation (); #if !MONOMAC [Export ("initWithColor:")] IntPtr Constructor (UIColor color); #endif } [BaseType (typeof (NSObject))] [Since (5,0)] [DisableDefaultCtor] public interface CIContext { // When we bind OpenGL add these: //[Export ("contextWithCGLContext:pixelFormat:colorSpace:options:")] //CIContext ContextWithCGLContextpixelFormatcolorSpaceoptions (CGLContextObj ctx, CGLPixelFormatObj pf, CGColorSpaceRef cs, NSDictionary dict, ); #if MONOMAC [Internal, Static] [Export ("contextWithCGContext:options:")] CIContext FromContext (CGContext ctx, [NullAllowed] NSDictionary options); #else [Static] [Wrap ("FromOptions ((NSDictionary) null)")] CIContext Create (); [Static] [Export ("contextWithEAGLContext:")] CIContext FromContext (EAGLContext eaglContext); [Static, Internal] [Export ("contextWithOptions:")] CIContext FromOptions ([NullAllowed] NSDictionary dictionary); [Export ("render:toCVPixelBuffer:")] void Render (CIImage image, CVPixelBuffer buffer); [Export ("render:toCVPixelBuffer:bounds:colorSpace:")] void Render (CIImage image, CVPixelBuffer buffer, RectangleF rectangle, CGColorSpace cs); [Export ("inputImageMaximumSize")] SizeF InputImageMaximumSize { get; } [Export ("outputImageMaximumSize")] SizeF OutputImageMaximumSize { get; } #endif [Obsolete ("Use DrawImage (CIImage, RectangleF, RectangleF) instead")] [Export ("drawImage:atPoint:fromRect:")] void DrawImage (CIImage image, PointF atPoint, RectangleF fromRect); [Export ("drawImage:inRect:fromRect:")] void DrawImage (CIImage image, RectangleF inRectangle, RectangleF fromRectangle); [Export ("createCGImage:fromRect:")] [return: Release ()] CGImage CreateCGImage (CIImage image, RectangleF fromRectangle); [Export ("createCGImage:fromRect:format:colorSpace:")] [return: Release ()] CGImage CreateCGImage (CIImage image, RectangleF fromRect, int ciImageFormat, [NullAllowed] CGColorSpace colorSpace); [Internal, Export ("createCGLayerWithSize:info:")] CGLayer CreateCGLayer (SizeF size, [NullAllowed] NSDictionary info); [Export ("render:toBitmap:rowBytes:bounds:format:colorSpace:")] void RenderToBitmap (CIImage image, IntPtr bitmapPtr, int bytesPerRow, RectangleF bounds, int bitmapFormat, CGColorSpace colorSpace); //[Export ("render:toIOSurface:bounds:colorSpace:")] //void RendertoIOSurfaceboundscolorSpace (CIImage im, IOSurfaceRef surface, RectangleF r, CGColorSpaceRef cs, ); #if MONOMAC [Export ("reclaimResources")] void ReclaimResources (); [Export ("clearCaches")] void ClearCaches (); #endif [Internal, Field ("kCIContextOutputColorSpace", "+CoreImage")] NSString OutputColorSpace { get; } [Internal, Field ("kCIContextWorkingColorSpace", "+CoreImage")] NSString WorkingColorSpace { get; } [Internal, Field ("kCIContextUseSoftwareRenderer", "+CoreImage")] NSString UseSoftwareRenderer { get; } } [BaseType (typeof (NSObject))] [Since (5,0)] [DisableDefaultCtor] public interface CIFilter { [Export ("inputKeys")] string [] InputKeys { get; } [Export ("outputKeys")] string [] OutputKeys { get; } [Export ("setDefaults")] void SetDefaults (); [Export ("attributes")] NSDictionary Attributes { get; } [Export ("name")] string Name { get; } [Static] [Export ("filterWithName:")] CIFilter FromName (string name); [Static] [Export ("filterNamesInCategory:")] string [] FilterNamesInCategory (string category); [Static] [Export ("filterNamesInCategories:"), Internal] string [] _FilterNamesInCategories (string [] categories); #if MONOMAC [Export ("apply:arguments:options:")] CIImage Apply (CIKernel k, NSArray args, NSDictionary options); [Static] [Export ("registerFilterName:constructor:classAttributes:")] void RegisterFilterName (string name, NSObject constructorObject, NSDictionary classAttributes); [Static] [Export ("localizedNameForFilterName:")] string FilterLocalizedName (string filterName); [Static] [Export ("localizedNameForCategory:")] string CategoryLocalizedName (string category); [Static] [Export ("localizedDescriptionForFilterName:")] string FilterLocalizedDescription (string filterName); [Static] [Export ("localizedReferenceDocumentationForFilterName:")] NSUrl FilterLocalizedReferenceDocumentation (string filterName); #else [Export ("outputImage")] CIImage OutputImage { get; } [Since (6,0)] [Export ("serializedXMPFromFilters:inputImageExtent:"), Static] NSData SerializedXMP (CIFilter[] filters, RectangleF extent); [Since (6,0)] [Export ("filterArrayFromSerializedXMP:inputImageExtent:error:"), Static] CIFilter[] FromSerializedXMP (NSData xmpData, RectangleF extent, out NSError error); #endif [Export ("setValue:forKey:"), Internal] void SetValueForKey ([NullAllowed] NSObject value, NSString key); [Export ("valueForKey:"), Internal] NSObject ValueForKey (NSString key); } [Static] public interface CIFilterOutputKey { [Field ("kCIOutputImageKey", "+CoreImage")] NSString Image { get; } } [Static] public interface CIFilterInputKey { [Field ("kCIInputBackgroundImageKey", "+CoreImage")] NSString BackgroundImage { get; } [Field ("kCIInputImageKey", "+CoreImage")] NSString Image { get; } [Field ("kCIInputVersionKey", "+CoreImage")] NSString Version { get; } #if MONOMAC [Field ("kCIInputTimeKey", "+CoreImage")] NSString Time { get; } [Field ("kCIInputTransformKey", "+CoreImage")] NSString Transform { get; } [Field ("kCIInputScaleKey", "+CoreImage")] NSString Scale { get; } [Field ("kCIInputAspectRatioKey", "+CoreImage")] NSString AspectRatio { get; } [Field ("kCIInputCenterKey", "+CoreImage")] NSString Center { get; } [Field ("kCIInputRadiusKey", "+CoreImage")] NSString Radius { get; } [Field ("kCIInputAngleKey", "+CoreImage")] NSString Angle { get; } [Field ("kCIInputRefractionKey", "+CoreImage")] NSString Refraction { get; } [Field ("kCIInputWidthKey", "+CoreImage")] NSString Width { get; } [Field ("kCIInputSharpnessKey", "+CoreImage")] NSString Sharpness { get; } [Field ("kCIInputIntensityKey", "+CoreImage")] NSString Intensity { get; } [Field ("kCIInputEVKey", "+CoreImage")] NSString EV { get; } [Field ("kCIInputSaturationKey", "+CoreImage")] NSString Saturation { get; } [Field ("kCIInputColorKey", "+CoreImage")] NSString Color { get; } [Field ("kCIInputBrightnessKey", "+CoreImage")] NSString Brightness { get; } [Field ("kCIInputContrastKey", "+CoreImage")] NSString Contrast { get; } [Field ("kCIInputGradientImageKey", "+CoreImage")] NSString GradientImage { get; } [Field ("kCIInputMaskImageKey", "+CoreImage")] NSString MaskImage { get; } [Field ("kCIInputShadingImageKey", "+CoreImage")] NSString ShadingImage { get; } [Field ("kCIInputTargetImageKey", "+CoreImage")] NSString TargetImage { get; } [Field ("kCIInputExtentKey", "+CoreImage")] NSString Extent { get; } #endif } [Static] public interface CIFilterAttributes { [Field ("kCIAttributeFilterName", "+CoreImage")] NSString FilterName { get; } [Field ("kCIAttributeFilterDisplayName", "+CoreImage")] NSString FilterDisplayName { get; } #if MONOMAC [Field ("kCIAttributeDescription", "+CoreImage")] NSString Description { get; } [Field ("kCIAttributeReferenceDocumentation", "+CoreImage")] NSString ReferenceDocumentation { get; } #endif [Field ("kCIAttributeFilterCategories", "+CoreImage")] NSString FilterCategories { get; } [Field ("kCIAttributeClass", "+CoreImage")] NSString Class { get; } [Field ("kCIAttributeType", "+CoreImage")] NSString Type { get; } [Field ("kCIAttributeMin", "+CoreImage")] NSString Min { get; } [Field ("kCIAttributeMax", "+CoreImage")] NSString Max { get; } [Field ("kCIAttributeSliderMin", "+CoreImage")] NSString SliderMin { get; } [Field ("kCIAttributeSliderMax", "+CoreImage")] NSString SliderMax { get; } [Field ("kCIAttributeDefault", "+CoreImage")] NSString Default { get; } [Field ("kCIAttributeIdentity", "+CoreImage")] NSString Identity { get; } [Field ("kCIAttributeName", "+CoreImage")] NSString Name { get; } [Field ("kCIAttributeDisplayName", "+CoreImage")] NSString DisplayName { get; } #if MONOMAC [Field ("kCIUIParameterSet", "+CoreImage")] NSString UIParameterSet { get; } #endif [Field ("kCIAttributeTypeTime", "+CoreImage")] NSString TypeTime { get; } [Field ("kCIAttributeTypeScalar", "+CoreImage")] NSString TypeScalar { get; } [Field ("kCIAttributeTypeDistance", "+CoreImage")] NSString TypeDistance { get; } [Field ("kCIAttributeTypeAngle", "+CoreImage")] NSString TypeAngle { get; } [Field ("kCIAttributeTypeBoolean", "+CoreImage")] NSString TypeBoolean { get; } [Field ("kCIAttributeTypeInteger", "+CoreImage")] NSString TypeInteger { get; } [Field ("kCIAttributeTypeCount", "+CoreImage")] NSString TypeCount { get; } [Field ("kCIAttributeTypePosition", "+CoreImage")] NSString TypePosition { get; } [Field ("kCIAttributeTypeOffset", "+CoreImage")] NSString TypeOffset { get; } [Field ("kCIAttributeTypePosition3", "+CoreImage")] NSString TypePosition3 { get; } [Field ("kCIAttributeTypeRectangle", "+CoreImage")] NSString TypeRectangle { get; } #if MONOMAC [Field ("kCIAttributeTypeOpaqueColor", "+CoreImage")] NSString TypeOpaqueColor { get; } [Field ("kCIAttributeTypeGradient", "+CoreImage")] NSString TypeGradient { get; } #else [Field ("kCIAttributeTypeImage", "+CoreImage")] NSString TypeImage { get; } [Field ("kCIAttributeTypeTransform", "+CoreImage")] NSString TypeTransform { get; } #endif } [Static] public interface CIFilterCategory { [Field ("kCICategoryDistortionEffect", "+CoreImage")] NSString DistortionEffect { get; } [Field ("kCICategoryGeometryAdjustment", "+CoreImage")] NSString GeometryAdjustment { get; } [Field ("kCICategoryCompositeOperation", "+CoreImage")] NSString CompositeOperation { get; } [Field ("kCICategoryHalftoneEffect", "+CoreImage")] NSString HalftoneEffect { get; } [Field ("kCICategoryColorAdjustment", "+CoreImage")] NSString ColorAdjustment { get; } [Field ("kCICategoryColorEffect", "+CoreImage")] NSString ColorEffect { get; } [Field ("kCICategoryTransition", "+CoreImage")] NSString Transition { get; } [Field ("kCICategoryTileEffect", "+CoreImage")] NSString TileEffect { get; } [Field ("kCICategoryGenerator", "+CoreImage")] NSString Generator { get; } [Field ("kCICategoryReduction", "+CoreImage")] NSString Reduction { get; } [Field ("kCICategoryGradient", "+CoreImage")] NSString Gradient { get; } [Field ("kCICategoryStylize", "+CoreImage")] NSString Stylize { get; } [Field ("kCICategorySharpen", "+CoreImage")] NSString Sharpen { get; } [Field ("kCICategoryBlur", "+CoreImage")] NSString Blur { get; } [Field ("kCICategoryVideo", "+CoreImage")] NSString Video { get; } [Field ("kCICategoryStillImage", "+CoreImage")] NSString StillImage { get; } [Field ("kCICategoryInterlaced", "+CoreImage")] NSString Interlaced { get; } [Field ("kCICategoryNonSquarePixels", "+CoreImage")] NSString NonSquarePixels { get; } [Field ("kCICategoryHighDynamicRange", "+CoreImage")] NSString HighDynamicRange { get; } [Field ("kCICategoryBuiltIn", "+CoreImage")] NSString BuiltIn { get; } #if MONOMAC [Field ("kCICategoryFilterGenerator", "+CoreImage")] NSString FilterGenerator { get; } #endif } #if MONOMAC [Static] public interface CIUIParameterSet { [Field ("kCIUISetBasic", "+CoreImage")] NSString Basic { get; } [Field ("kCIUISetIntermediate", "+CoreImage")] NSString Intermediate { get; } [Field ("kCIUISetAdvanced", "+CoreImage")] NSString Advanced { get; } [Field ("kCIUISetDevelopment", "+CoreImage")] NSString Development { get; } } [Static] public interface CIFilterApply { [Field ("kCIApplyOptionExtent", "+CoreImage")] NSString OptionExtent { get; } [Field ("kCIApplyOptionDefinition", "+CoreImage")] NSString OptionDefinition { get; } [Field ("kCIApplyOptionUserInfo", "+CoreImage")] NSString OptionUserInfo { get; } [Field ("kCIApplyOptionColorSpace", "+CoreImage")] NSString OptionColorSpace { get; } } #endif #if MONOMAC [BaseType (typeof (NSObject))] [DisableDefaultCtor] public interface CIFilterGenerator { [Static, Export ("filterGenerator")] CIFilterGenerator Create (); [Static] [Export ("filterGeneratorWithContentsOfURL:")] CIFilterGenerator FromUrl (NSUrl aURL); [Export ("initWithContentsOfURL:")] IntPtr Constructor (NSUrl aURL); [Export ("connectObject:withKey:toObject:withKey:")] void ConnectObject (NSObject sourceObject, string withSourceKey, NSObject targetObject, string targetKey); [Export ("disconnectObject:withKey:toObject:withKey:")] void DisconnectObject (NSObject sourceObject, string sourceKey, NSObject targetObject, string targetKey); [Export ("exportKey:fromObject:withName:")] void ExportKey (string key, NSObject targetObject, string exportedKeyName); [Export ("removeExportedKey:")] void RemoveExportedKey (string exportedKeyName); [Export ("exportedKeys")] NSDictionary ExportedKeys { get; } [Export ("setAttributes:forExportedKey:")] void SetAttributesforExportedKey (NSDictionary attributes, NSString exportedKey); [Export ("filter")] CIFilter CreateFilter (); [Export ("registerFilterName:")] void RegisterFilterName (string name); [Export ("writeToURL:atomically:")] bool Save (NSUrl toUrl, bool atomically); //Detected properties [Export ("classAttributes")] NSDictionary ClassAttributes { get; set; } [Field ("kCIFilterGeneratorExportedKey", "+CoreImage")] NSString ExportedKey { get; } [Field ("kCIFilterGeneratorExportedKeyTargetObject", "+CoreImage")] NSString ExportedKeyTargetObject { get; } [Field ("kCIFilterGeneratorExportedKeyName", "+CoreImage")] NSString ExportedKeyName { get; } } [BaseType (typeof (NSObject))] [DisableDefaultCtor] public interface CIFilterShape { [Export ("shapeWithRect:")] CIFilterShape FromRect (RectangleF rect); [Export ("initWithRect:")] IntPtr Constructor (RectangleF rect); [Export ("transformBy:interior:")] CIFilterShape Transform (CGAffineTransform transformation, bool interiorFlag); [Export ("insetByX:Y:")] CIFilterShape Inset (int dx, int dy); [Export ("unionWith:")] CIFilterShape Union (CIFilterShape other); [Export ("unionWithRect:")] CIFilterShape Union (RectangleF rectangle); [Export ("intersectWith:")] CIFilterShape Intersect (CIFilterShape other); [Export ("intersectWithRect:")] CIFilterShape IntersectWithRect (Rectangle rectangle); } #endif [BaseType (typeof (NSObject))] [Since (5,0)] [DisableDefaultCtor] public interface CIImage { [Static] [Export ("imageWithCGImage:")] CIImage FromCGImage (CGImage image); [Static] [Export ("imageWithCGImage:options:")] [Obsolete ("Use FromCGImage (CGImage, CIImageInitializationOptionsWithMetadata) overload")] CIImage FromCGImage (CGImage image, [NullAllowed] NSDictionary d); [Static] [Wrap ("FromCGImage (image, options == null ? null : options.Dictionary)")] CIImage FromCGImage (CGImage image, [NullAllowed] CIImageInitializationOptionsWithMetadata options); #if MONOMAC [Static] [Export ("imageWithCGLayer:")] CIImage FromLayer (CGLayer layer); [Static] [Export ("imageWithCGLayer:options:")] CIImage FromLayer (CGLayer layer, NSDictionary options); #endif [Static] [Export ("imageWithBitmapData:bytesPerRow:size:format:colorSpace:")] // TODO: pixelFormat should be enum of kCIFormatARGB8, kCIFormatRGBA16, kCIFormatRGBAf, kCIFormatRGBAh CIImage FromData (NSData bitmapData, int bytesPerRow, SizeF size, int pixelFormat, [NullAllowed] CGColorSpace colorSpace); #if MONOMAC [Since (6,0)] [Static] [Export ("imageWithTexture:size:flipped:colorSpace:")] CIImage ImageWithTexture (uint glTextureName, SizeF size, bool flipped, CGColorSpace colorspace); #endif [Static] [Export ("imageWithContentsOfURL:")] CIImage FromUrl (NSUrl url); [Static] [Export ("imageWithContentsOfURL:options:")] [Obsolete ("Use FromUrl (NSUrl, CIImageInitializationOptions) overload")] CIImage FromUrl (NSUrl url, [NullAllowed] NSDictionary d); [Static] [Wrap ("FromUrl (url, options == null ? null : options.Dictionary)")] CIImage FromUrl (NSUrl url, [NullAllowed] CIImageInitializationOptions options); [Static] [Export ("imageWithData:")] CIImage FromData (NSData data); [Static] [Export ("imageWithData:options:")] [Obsolete ("Use FromData (NSData, CIImageInitializationOptionsWithMetadata) overload")] CIImage FromData (NSData data, [NullAllowed] NSDictionary d); [Static] [Wrap ("FromData (data, options == null ? null : options.Dictionary)")] CIImage FromData (NSData data, [NullAllowed] CIImageInitializationOptionsWithMetadata options); #if MONOMAC [Static] [Export ("imageWithCVImageBuffer:")] CIImage FromImageBuffer (CVImageBuffer imageBuffer); [Static] [Export ("imageWithCVImageBuffer:options:")] CIImage FromImageBuffer (CVImageBuffer imageBuffer, NSDictionary dict); #else [Static] [Export ("imageWithCVPixelBuffer:")] CIImage FromImageBuffer (CVPixelBuffer buffer); [Static] [Export ("imageWithCVPixelBuffer:options:")] [Obsolete ("Use FromImageBuffer (CVPixelBuffer, CIImageInitializationOptions) overload")] CIImage FromImageBuffer (CVPixelBuffer buffer, [NullAllowed] NSDictionary dict); [Static] [Wrap ("FromImageBuffer (buffer, options == null ? null : options.Dictionary)")] CIImage FromImageBuffer (CVPixelBuffer buffer, [NullAllowed] CIImageInitializationOptions options); #endif //[Export ("imageWithIOSurface:")] //CIImage ImageWithIOSurface (IOSurfaceRef surface, ); // //[Static] //[Export ("imageWithIOSurface:options:")] //CIImage ImageWithIOSurfaceoptions (IOSurfaceRef surface, NSDictionary d, ); [Static] [Export ("imageWithColor:")] CIImage ImageWithColor (CIColor color); [Static] [Export ("emptyImage")] CIImage EmptyImage { get; } [Export ("initWithCGImage:")] IntPtr Constructor (CGImage image); [Export ("initWithCGImage:options:")] [Obsolete ("Use constructor with CIImageInitializationOptionsWithMetadata")] IntPtr Constructor (CGImage image, [NullAllowed] NSDictionary d); [Wrap ("this (image, options == null ? null : options.Dictionary)")] IntPtr Constructor (CGImage image, [NullAllowed] CIImageInitializationOptionsWithMetadata options); [Export ("initWithCGLayer:")] IntPtr Constructor (CGLayer layer); [Export ("initWithCGLayer:options:")] [Obsolete ("Use constructor with CIImageInitializationOptions")] IntPtr Constructor (CGLayer layer, [NullAllowed] NSDictionary d); [Wrap ("this (layer, options == null ? null : options.Dictionary)")] IntPtr Constructor (CGLayer layer, [NullAllowed] CIImageInitializationOptions options); [Export ("initWithData:")] IntPtr Constructor (NSData data); [Export ("initWithData:options:")] [Obsolete ("Use constructor with CIImageInitializationOptionsWithMetadata")] IntPtr Constructor (NSData data, [NullAllowed] NSDictionary d); [Wrap ("this (data, options == null ? null : options.Dictionary)")] IntPtr Constructor (NSData data, [NullAllowed] CIImageInitializationOptionsWithMetadata options); [Export ("initWithBitmapData:bytesPerRow:size:format:colorSpace:")] IntPtr Constructor (NSData d, int bytesPerRow, SizeF size, int pixelFormat, CGColorSpace colorSpace); [Since (6,0)] [Export ("initWithTexture:size:flipped:colorSpace:")] IntPtr Constructor (int glTextureName, SizeF size, bool flipped, CGColorSpace colorSpace); [Export ("initWithContentsOfURL:")] IntPtr Constructor (NSUrl url); [Export ("initWithContentsOfURL:options:")] [Obsolete ("Use constructor with CIImageInitializationOptions")] IntPtr Constructor (NSUrl url, [NullAllowed] NSDictionary d); [Wrap ("this (url, options == null ? null : options.Dictionary)")] IntPtr Constructor (NSUrl url, [NullAllowed] CIImageInitializationOptions options); // FIXME: bindings //[Export ("initWithIOSurface:")] //NSObject InitWithIOSurface (IOSurfaceRef surface, ); // //[Export ("initWithIOSurface:options:")] //NSObject InitWithIOSurfaceoptions (IOSurfaceRef surface, NSDictionary d, ); // [Export ("initWithCVImageBuffer:")] IntPtr Constructor (CVImageBuffer imageBuffer); [Export ("initWithCVImageBuffer:options:")] [Obsolete ("Use constructor with CIImageInitializationOptions")] IntPtr Constructor (CVImageBuffer imageBuffer, [NullAllowed] NSDictionary dict); [Wrap ("this (imageBuffer, options == null ? null : options.Dictionary)")] IntPtr Constructor (CVImageBuffer imageBuffer, [NullAllowed] CIImageInitializationOptions options); [Export ("initWithColor:")] IntPtr Constructor (CIColor color); #if MONOMAC [Export ("initWithBitmapImageRep:")] IntPtr Constructor (NSImageRep imageRep); [Export ("drawAtPoint:fromRect:operation:fraction:")] void Draw (PointF point, RectangleF srcRect, NSCompositingOperation op, float delta); [Export ("drawInRect:fromRect:operation:fraction:")] void Draw (RectangleF dstRect, RectangleF srcRect, NSCompositingOperation op, float delta); #endif [Export ("imageByApplyingTransform:")] CIImage ImageByApplyingTransform (CGAffineTransform matrix); [Export ("imageByCroppingToRect:")] CIImage ImageByCroppingToRect (RectangleF r); [Export ("extent")] RectangleF Extent { get; } [Since (5,0)] [Export ("properties"), Internal] NSDictionary WeakProperties { get; } [Since (5,0)] [Wrap ("WeakProperties")] CGImageProperties Properties { get; } #if MONOMAC //[Export ("definition")] //CIFilterShape Definition (); [Field ("kCIFormatARGB8")] int FormatARGB8 { get; } [Field ("kCIFormatRGBA16")] int FormatRGBA16 { get; } [Field ("kCIFormatRGBAf")] int FormatRGBAf { get; } [Field ("kCIFormatRGBAh")] int FormatRGBAh { get; } #else [Field ("kCIFormatARGB8")] [Since (6,0)] int FormatARGB8 { get; } [Field ("kCIFormatRGBAh")] [Since (6,0)] int FormatRGBAh { get; } [Field ("kCIFormatBGRA8")] [Since (5,0)] int FormatBGRA8 { get; } [Field ("kCIFormatRGBA8")] [Since (5,0)] int FormatRGBA8 { get; } // UIKit extensions [Since (5,0)] [Export ("initWithImage:")] IntPtr Constructor (UIImage image); [Since (5,0)] [Export ("initWithImage:options")] [Obsolete ("Use constructor with CIImageInitializationOptions")] IntPtr Constructor (UIImage image, [NullAllowed] NSDictionary options); [Since (5,0)] [Wrap ("this (image, options == null ? null : options.Dictionary)")] IntPtr Constructor (UIImage image, [NullAllowed] CIImageInitializationOptions options); #endif [Field ("kCIImageAutoAdjustFeatures"), Internal] NSString AutoAdjustFeaturesKey { get; } [Field ("kCIImageAutoAdjustRedEye"), Internal] NSString AutoAdjustRedEyeKey { get; } [Field ("kCIImageAutoAdjustEnhance"), Internal] NSString AutoAdjustEnhanceKey { get; } [Export ("autoAdjustmentFilters"), Internal] NSArray _GetAutoAdjustmentFilters (); [Export ("autoAdjustmentFiltersWithOptions:"), Internal] NSArray _GetAutoAdjustmentFilters (NSDictionary opts); [Field ("kCGImagePropertyOrientation", "ImageIO"), Internal] NSString ImagePropertyOrientation { get; } [Field ("kCIImageColorSpace"), Internal] NSString CIImageColorSpaceKey { get; } [Field ("kCIImageProperties"), Internal] NSString CIImagePropertiesKey { get; } } #if MONOMAC [BaseType (typeof (NSObject))] public interface CIImageAccumulator { [Export ("imageAccumulatorWithExtent:format:")] CIImageAccumulator FromRectangle (RectangleF rect, int ciImageFormat); [Export ("initWithExtent:format:")] IntPtr Constructor (RectangleF rectangle, int ciImageFormat); [Export ("extent")] RectangleF Extent { get; } [Export ("format")] int CIImageFormat { get; } [Export ("setImage:dirtyRect:")] void SetImageDirty (CIImage image, RectangleF dirtyRect); [Export ("clear")] void Clear (); //Detected properties [Export ("image")] CIImage Image { get; set; } } [BaseType (typeof (NSObject))] public interface CIKernel { [Static, Export ("kernelsWithString:")] CIKernel [] FromProgram (string coreImageShaderProgram); [Export ("name")] string Name { get; } [Export ("setROISelector:")] void SetRegionOfInterestSelector (Selector aMethod); } [BaseType (typeof (NSObject))] public interface CIPlugIn { [Static] [Export ("loadAllPlugIns")] void LoadAllPlugIns (); [Static] [Export ("loadNonExecutablePlugIns")] void LoadNonExecutablePlugIns (); [Static] [Export ("loadPlugIn:allowNonExecutable:")] void LoadPlugIn (NSUrl pluginUrl, bool allowNonExecutable); } [BaseType (typeof (NSObject))] public interface CISampler { [Static, Export ("samplerWithImage:")] CISampler FromImage (CIImage sourceImage); [Internal, Static] [Export ("samplerWithImage:options:")] CISampler FromImage (CIImage sourceImag, NSDictionary options); [Export ("initWithImage:")] IntPtr Constructor (CIImage sourceImage); [Internal, Export ("initWithImage:options:")] NSObject Constructor (CIImage image, NSDictionary options); [Export ("definition")] CIFilterShape Definition { get; } [Export ("extent")] RectangleF Extent { get; } [Field ("kCISamplerAffineMatrix", "+CoreImage"), Internal] NSString AffineMatrix { get; } [Field ("kCISamplerWrapMode", "+CoreImage"), Internal] NSString WrapMode { get; } [Field ("kCISamplerFilterMode", "+CoreImage"), Internal] NSString FilterMode { get; } [Field ("kCISamplerWrapBlack", "+CoreImage"), Internal] NSString WrapBlack { get; } [Field ("kCISamplerWrapClamp", "+CoreImage"), Internal] NSString WrapClamp { get; } [Field ("kCISamplerFilterNearest", "+CoreImage"), Internal] NSString FilterNearest { get; } [Field ("kCISamplerFilterLinear", "+CoreImage"), Internal] NSString FilterLinear { get; } } #endif [BaseType (typeof (NSObject))] [Since (5,0)] [DisableDefaultCtor] interface CIVector { [Static, Internal, Export ("vectorWithValues:count:")] CIVector _FromValues (IntPtr values, int count); [Static] [Export ("vectorWithX:")] CIVector Create (float x); [Static] [Export ("vectorWithX:Y:")] CIVector Create (float x, float y); [Static] [Export ("vectorWithX:Y:Z:")] CIVector Create (float x, float y, float z); [Static] [Export ("vectorWithX:Y:Z:W:")] CIVector Create (float x, float y, float z, float w); #if !MONOMAC [Static] [Export ("vectorWithCGPoint:")] CIVector Create (PointF point); [Static] [Export ("vectorWithCGRect:")] CIVector Create (RectangleF point); [Static] [Export ("vectorWithCGAffineTransform:")] CIVector Create (CGAffineTransform affineTransform); #endif [Static] [Export ("vectorWithString:")] CIVector FromString (string representation); [Internal, Export ("initWithValues:count:")] IntPtr Constructor (IntPtr values, int count); [Export ("initWithX:")] IntPtr Constructor(float x); [Export ("initWithX:Y:")] IntPtr Constructor (float x, float y); [Export ("initWithX:Y:Z:")] IntPtr Constructor (float x, float y, float z); [Export ("initWithX:Y:Z:W:")] IntPtr Constructor (float x, float y, float z, float w); [Export ("initWithString:")] IntPtr Constructor (string representation); [Export ("valueAtIndex:"), Internal] float ValueAtIndex (int index); [Export ("count")] int Count { get; } [Export ("X")] float X { get; } [Export ("Y")] float Y { get; } [Export ("Z")] float Z { get; } [Export ("W")] float W { get; } #if !MONOMAC [Export ("CGPointValue")] PointF Point { get; } [Export ("CGRectValue")] RectangleF Rectangle { get; } [Export ("CGAffineTransformValue")] CGAffineTransform AffineTransform { get; } #endif [Export ("stringRepresentation"), Internal] string StringRepresentation (); } [BaseType (typeof (NSObject))] [Since (5,0)] [DisableDefaultCtor] interface CIDetector { [Static, Export ("detectorOfType:context:options:"), Internal] CIDetector FromType (NSString detectorType, [NullAllowed] CIContext context, [NullAllowed] NSDictionary options); [Export ("featuresInImage:")] CIFeature [] FeaturesInImage (CIImage image); [Export ("featuresInImage:options:")] CIFeature [] FeaturesInImage (CIImage image, NSDictionary options); [Field ("CIDetectorTypeFace"), Internal] NSString TypeFace { get; } [Field ("CIDetectorImageOrientation"), Internal] NSString ImageOrientation { get; } [Field ("CIDetectorAccuracy"), Internal] NSString Accuracy { get; } [Field ("CIDetectorAccuracyLow"), Internal] NSString AccuracyLow { get; } [Field ("CIDetectorAccuracyHigh"), Internal] NSString AccuracyHigh { get; } [Since (6,0)] [Field ("CIDetectorTracking"), Internal] NSString Tracking { get; } [Since (6,0)] [Field ("CIDetectorMinFeatureSize"), Internal] NSString MinFeatureSize { get; } } [BaseType (typeof (NSObject))] [Since (5,0)] [DisableDefaultCtor] interface CIFeature { [Export ("type")] NSString Type { get; } [Export ("bounds")] RectangleF Bounds { get; } [Field ("CIFeatureTypeFace")] NSString TypeFace { get; } } [BaseType (typeof (CIFeature))] [Since (5,0)] [DisableDefaultCtor] interface CIFaceFeature { [Export ("hasLeftEyePosition")] bool HasLeftEyePosition { get; } [Export ("leftEyePosition")] PointF LeftEyePosition { get; } [Export ("hasRightEyePosition")] bool HasRightEyePosition { get; } [Export ("rightEyePosition")] PointF RightEyePosition { get; } [Export ("hasMouthPosition")] bool HasMouthPosition { get; } [Export ("mouthPosition")] PointF MouthPosition { get; } [Since (6,0)] [Export ("hasTrackingID")] bool HasTrackingId { get; } [Since (6,0)] [Export ("trackingID")] int TrackingId { get; } [Since (6,0)] [Export ("hasTrackingFrameCount")] bool HasTrackingFrameCount { get; } [Since (6,0)] [Export ("trackingFrameCount")] int TrackingFrameCount { get; } } }
using System; using UnityEngine; [ExecuteInEditMode, RequireComponent(typeof(Camera))] [Serializable] public class PostEffectsBase : MonoBehaviour { protected bool supportHDRTextures; protected bool supportDX11; protected bool isSupported; public PostEffectsBase() { this.supportHDRTextures = true; this.isSupported = true; } public override Material CheckShaderAndCreateMaterial(Shader s, Material m2Create) { Material arg_CF_0; if (!s) { Debug.Log("Missing shader in " + this.ToString()); this.enabled = false; arg_CF_0 = null; } else if (s.isSupported && m2Create && m2Create.shader == s) { arg_CF_0 = m2Create; } else if (!s.isSupported) { this.NotSupported(); Debug.Log("The shader " + s.ToString() + " on effect " + this.ToString() + " is not supported on this platform!"); arg_CF_0 = null; } else { m2Create = new Material(s); m2Create.hideFlags = HideFlags.DontSave; arg_CF_0 = ((!m2Create) ? null : m2Create); } return arg_CF_0; } public override Material CreateMaterial(Shader s, Material m2Create) { Material arg_8E_0; if (!s) { Debug.Log("Missing shader in " + this.ToString()); arg_8E_0 = null; } else if (m2Create && m2Create.shader == s && s.isSupported) { arg_8E_0 = m2Create; } else if (!s.isSupported) { arg_8E_0 = null; } else { m2Create = new Material(s); m2Create.hideFlags = HideFlags.DontSave; arg_8E_0 = ((!m2Create) ? null : m2Create); } return arg_8E_0; } public override void OnEnable() { this.isSupported = true; } public override bool CheckSupport() { return this.CheckSupport(false); } public override bool CheckResources() { Debug.LogWarning("CheckResources () for " + this.ToString() + " should be overwritten."); return this.isSupported; } public override void Start() { this.CheckResources(); } public override bool CheckSupport(bool needDepth) { this.isSupported = true; this.supportHDRTextures = SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBHalf); bool arg_2C_1; if (arg_2C_1 = (SystemInfo.graphicsShaderLevel >= 50)) { arg_2C_1 = SystemInfo.supportsComputeShaders; } this.supportDX11 = arg_2C_1; bool arg_8D_0; if (!SystemInfo.supportsImageEffects || !SystemInfo.supportsRenderTextures) { this.NotSupported(); arg_8D_0 = false; } else if (needDepth && !SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.Depth)) { this.NotSupported(); arg_8D_0 = false; } else { if (needDepth) { this.camera.depthTextureMode = (this.camera.depthTextureMode | DepthTextureMode.Depth); } arg_8D_0 = true; } return arg_8D_0; } public override bool CheckSupport(bool needDepth, bool needHdr) { bool arg_30_0; if (!this.CheckSupport(needDepth)) { arg_30_0 = false; } else if (needHdr && !this.supportHDRTextures) { this.NotSupported(); arg_30_0 = false; } else { arg_30_0 = true; } return arg_30_0; } public override bool Dx11Support() { return this.supportDX11; } public override void ReportAutoDisable() { Debug.LogWarning("The image effect " + this.ToString() + " has been disabled as it's not supported on the current platform."); } public override bool CheckShader(Shader s) { Debug.Log("The shader " + s.ToString() + " on effect " + this.ToString() + " is not part of the Unity 3.2+ effects suite anymore. For best performance and quality, please ensure you are using the latest Standard Assets Image Effects (Pro only) package."); bool arg_51_0; if (!s.isSupported) { this.NotSupported(); arg_51_0 = false; } else { arg_51_0 = false; } return arg_51_0; } public override void NotSupported() { this.enabled = false; this.isSupported = false; } public override void DrawBorder(RenderTexture dest, Material material) { float x = 0f; float x2 = 0f; float y = 0f; float y2 = 0f; RenderTexture.active = dest; bool flag = true; GL.PushMatrix(); GL.LoadOrtho(); for (int i = 0; i < material.passCount; i++) { material.SetPass(i); float y3 = 0f; float y4 = 0f; if (flag) { y3 = 1f; y4 = (float)0; } else { y3 = (float)0; y4 = 1f; } x = (float)0; x2 = (float)0 + 1f / ((float)dest.width * 1f); y = (float)0; y2 = 1f; GL.Begin(7); GL.TexCoord2((float)0, y3); GL.Vertex3(x, y, 0.1f); GL.TexCoord2(1f, y3); GL.Vertex3(x2, y, 0.1f); GL.TexCoord2(1f, y4); GL.Vertex3(x2, y2, 0.1f); GL.TexCoord2((float)0, y4); GL.Vertex3(x, y2, 0.1f); x = 1f - 1f / ((float)dest.width * 1f); x2 = 1f; y = (float)0; y2 = 1f; GL.TexCoord2((float)0, y3); GL.Vertex3(x, y, 0.1f); GL.TexCoord2(1f, y3); GL.Vertex3(x2, y, 0.1f); GL.TexCoord2(1f, y4); GL.Vertex3(x2, y2, 0.1f); GL.TexCoord2((float)0, y4); GL.Vertex3(x, y2, 0.1f); x = (float)0; x2 = 1f; y = (float)0; y2 = (float)0 + 1f / ((float)dest.height * 1f); GL.TexCoord2((float)0, y3); GL.Vertex3(x, y, 0.1f); GL.TexCoord2(1f, y3); GL.Vertex3(x2, y, 0.1f); GL.TexCoord2(1f, y4); GL.Vertex3(x2, y2, 0.1f); GL.TexCoord2((float)0, y4); GL.Vertex3(x, y2, 0.1f); x = (float)0; x2 = 1f; y = 1f - 1f / ((float)dest.height * 1f); y2 = 1f; GL.TexCoord2((float)0, y3); GL.Vertex3(x, y, 0.1f); GL.TexCoord2(1f, y3); GL.Vertex3(x2, y, 0.1f); GL.TexCoord2(1f, y4); GL.Vertex3(x2, y2, 0.1f); GL.TexCoord2((float)0, y4); GL.Vertex3(x, y2, 0.1f); GL.End(); } GL.PopMatrix(); } public override void Main() { } }
namespace DeOps.Services.Plan { partial class EditBlock { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(EditBlock)); this.label1 = new System.Windows.Forms.Label(); this.TitleBox = new System.Windows.Forms.TextBox(); this.StartTime = new System.Windows.Forms.DateTimePicker(); this.EndTime = new System.Windows.Forms.DateTimePicker(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.OkButton = new System.Windows.Forms.Button(); this.ExitButton = new System.Windows.Forms.Button(); this.DescriptionInput = new DeOps.Interface.TextInput(); this.ScopeLink = new System.Windows.Forms.LinkLabel(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(9, 15); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(32, 13); this.label1.TabIndex = 0; this.label1.Text = "Title"; // // TitleBox // this.TitleBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.TitleBox.Location = new System.Drawing.Point(50, 12); this.TitleBox.Name = "TitleBox"; this.TitleBox.Size = new System.Drawing.Size(233, 20); this.TitleBox.TabIndex = 1; // // StartTime // this.StartTime.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.StartTime.CustomFormat = "h:mm tt MMMM dd, yyyy"; this.StartTime.Format = System.Windows.Forms.DateTimePickerFormat.Custom; this.StartTime.Location = new System.Drawing.Point(50, 38); this.StartTime.Name = "StartTime"; this.StartTime.Size = new System.Drawing.Size(233, 20); this.StartTime.TabIndex = 2; // // EndTime // this.EndTime.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.EndTime.CustomFormat = "h:mm tt MMMM dd, yyyy"; this.EndTime.Format = System.Windows.Forms.DateTimePickerFormat.Custom; this.EndTime.Location = new System.Drawing.Point(50, 64); this.EndTime.Name = "EndTime"; this.EndTime.Size = new System.Drawing.Size(233, 20); this.EndTime.TabIndex = 3; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(9, 42); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(34, 13); this.label2.TabIndex = 4; this.label2.Text = "Start"; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(9, 68); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(29, 13); this.label3.TabIndex = 5; this.label3.Text = "End"; // // label5 // this.label5.AutoSize = true; this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label5.Location = new System.Drawing.Point(9, 104); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(71, 13); this.label5.TabIndex = 8; this.label5.Text = "Description"; // // OkButton // this.OkButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.OkButton.Location = new System.Drawing.Point(127, 345); this.OkButton.Name = "OkButton"; this.OkButton.Size = new System.Drawing.Size(75, 23); this.OkButton.TabIndex = 10; this.OkButton.Text = "OK"; this.OkButton.UseVisualStyleBackColor = true; this.OkButton.Click += new System.EventHandler(this.OkButton_Click); // // ExitButton // this.ExitButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.ExitButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.ExitButton.Location = new System.Drawing.Point(208, 345); this.ExitButton.Name = "ExitButton"; this.ExitButton.Size = new System.Drawing.Size(75, 23); this.ExitButton.TabIndex = 11; this.ExitButton.Text = "Cancel"; this.ExitButton.UseVisualStyleBackColor = true; this.ExitButton.Click += new System.EventHandler(this.CancelButton_Click); // // DescriptionInput // this.DescriptionInput.AcceptTabs = true; this.DescriptionInput.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.DescriptionInput.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.DescriptionInput.EnterClears = false; this.DescriptionInput.Location = new System.Drawing.Point(12, 120); this.DescriptionInput.Name = "DescriptionInput"; this.DescriptionInput.ReadOnly = false; this.DescriptionInput.ShowFontStrip = false; this.DescriptionInput.Size = new System.Drawing.Size(271, 219); this.DescriptionInput.TabIndex = 9; // // ScopeLink // this.ScopeLink.AutoSize = true; this.ScopeLink.Location = new System.Drawing.Point(12, 350); this.ScopeLink.Name = "ScopeLink"; this.ScopeLink.Size = new System.Drawing.Size(52, 13); this.ScopeLink.TabIndex = 12; this.ScopeLink.TabStop = true; this.ScopeLink.Text = "Everyone"; this.ScopeLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.ScopeLink_LinkClicked); // // EditBlock // this.AcceptButton = this.OkButton; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.ExitButton; this.ClientSize = new System.Drawing.Size(295, 377); this.Controls.Add(this.ScopeLink); this.Controls.Add(this.ExitButton); this.Controls.Add(this.OkButton); this.Controls.Add(this.DescriptionInput); this.Controls.Add(this.label5); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.EndTime); this.Controls.Add(this.StartTime); this.Controls.Add(this.TitleBox); this.Controls.Add(this.label1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "EditBlock"; this.ShowInTaskbar = false; this.Text = "BlockView"; this.Load += new System.EventHandler(this.BlockView_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox TitleBox; private System.Windows.Forms.DateTimePicker StartTime; private System.Windows.Forms.DateTimePicker EndTime; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label5; private DeOps.Interface.TextInput DescriptionInput; private System.Windows.Forms.Button OkButton; private System.Windows.Forms.Button ExitButton; private System.Windows.Forms.LinkLabel ScopeLink; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Net; using System.Threading; using System.Windows.Forms; namespace Rawr { public static class ItemIconsPet { private static ImageList _talentIcons = null; public static ImageList TalentIcons { get { if (_talentIcons == null) { _talentIcons = new ImageList(); _talentIcons.ImageSize = new Size(45, 47); _talentIcons.ColorDepth = ColorDepth.Depth24Bit; //_talentIcons.Images.Add("temp",*/ GetTalentIcon(CharacterClass.Hunter, "Ferocity", "invalid", "temp")//) ; } return _talentIcons; } } public static Image GetItemIcon(string iconName, bool small) { Image returnImage = null; iconName = iconName.Replace(".png", "").Replace(".jpg", "").ToLower(); if (small && TalentIcons.Images.ContainsKey(iconName)) { returnImage = TalentIcons.Images[iconName]; } else if (!small && TalentIcons.Images.ContainsKey(iconName)) { returnImage = TalentIcons.Images[iconName]; } else { string pathToIcon = null; WebRequestWrapper wrapper = null; try { wrapper = new WebRequestWrapper(); if (!String.IsNullOrEmpty(iconName)) { pathToIcon = wrapper.DownloadItemIcon(iconName); //just in case the network code is in a disconnected mode. (e.g. no network traffic sent, so no network exception) } if (pathToIcon == null) { pathToIcon = wrapper.DownloadTempImage(); } } catch (Exception) { try { pathToIcon = wrapper.DownloadTempImage(); } catch (Exception) { } //Log.Write(ex.Message); //Log.Write(ex.StackTrace); //log.Error("Exception trying to retrieve an icon from the armory", ex); } if (!String.IsNullOrEmpty(pathToIcon)) { int retry = 0; do { try { using (Stream fileStream = File.Open(pathToIcon, FileMode.Open, FileAccess.Read, FileShare.Read)) { returnImage = Image.FromStream(fileStream); } } catch { returnImage = null; //possibly still downloading, give it a second Thread.Sleep(TimeSpan.FromSeconds(1)); if (retry >= 3) { //log.Error("Exception trying to load an icon from local", ex); MessageBox.Show( "Rawr encountered an error while attempting to load a saved image. If you encounter this error multiple times, please ensure that Rawr is unzipped in a location that you have full file read/write access, such as your Desktop, or My Documents."); //Log.Write(ex.Message); //Log.Write(ex.StackTrace); #if DEBUG throw; #endif } } retry++; } while (returnImage == null && retry < 5); if (returnImage != null) { if (small) { returnImage = ScaleByPercent(returnImage, 50); } TalentIcons.Images.Add(iconName, returnImage); } } } return returnImage; } public static Image GetTalentIcon(CharacterClass charClass, string talentTree, string talentName, string icon) { Image returnImage = null; string key = string.Format("{0}-{1}-{2}", charClass, talentTree, talentName); if (key != "Hunter-Ferocity-invalid" && TalentIcons.Images.ContainsKey(key) && TalentIcons.Images[key] == TalentIcons.Images["Hunter-Ferocity-invalid"]) { return null; } if (key != "Hunter-Ferocity-invalid" && TalentIcons.Images.ContainsKey(key)) { returnImage = TalentIcons.Images[key]; } else { string pathToIcon = null; WebRequestWrapper wrapper = new WebRequestWrapper(); try { if (!string.IsNullOrEmpty(talentTree) && !string.IsNullOrEmpty(talentName)) { pathToIcon = wrapper.DownloadTalentIcon(charClass, talentTree, talentName, icon); //just in case the network code is in a disconnected mode. (e.g. no network traffic sent, so no network exception) } if (pathToIcon == null) { // Try the Item method pathToIcon = wrapper.DownloadItemIcon(icon); } if (pathToIcon == null) { pathToIcon = wrapper.DownloadTempImage(); } } catch (Exception) { pathToIcon = wrapper.DownloadTempImage(); //Log.Write(ex.Message); //Log.Write(ex.StackTrace); //log.Error("Exception trying to retrieve an icon from the armory", ex); } if (!string.IsNullOrEmpty(pathToIcon)) { int retry = 0; do { try { using (Stream fileStream = File.Open(pathToIcon, FileMode.Open, FileAccess.Read, FileShare.Read)) { returnImage = Image.FromStream(fileStream); } } catch { returnImage = null; //possibly still downloading, give it a second Thread.Sleep(TimeSpan.FromSeconds(1)); if (retry >= 3) { //log.Error("Exception trying to load an icon from local", ex); MessageBox.Show("Rawr encountered an error while attempting to load " + "a saved image. If you encounter this error multiple " + "times, please ensure that Rawr is unzipped in a " + "location that you have full file read/write access, " + "such as your Desktop, or My Documents." + "\r\n\r\n" + pathToIcon, "Image Loader"); //Log.Write(ex.Message); //Log.Write(ex.StackTrace); #if DEBUG throw; #endif } } retry++; } while (returnImage == null && retry < 5); if (returnImage != null) { returnImage = Offset(returnImage, new Size(2, 2)); TalentIcons.Images.Add(key, returnImage); } } } return returnImage; } private static Image Offset(Image img, Size offset) { Bitmap bmp = new Bitmap(img.Width + offset.Width, img.Height + offset.Height, PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(bmp); g.DrawImageUnscaled(img, offset.Width, offset.Height); g.Dispose(); return bmp; } private static Image ScaleByPercent(Image img, int Percent) { float nPercent = ((float) Percent/100); int sourceWidth = img.Width; int sourceHeight = img.Height; int sourceX = 0; int sourceY = 0; int destX = 0; int destY = 0; int destWidth = (int) (sourceWidth*nPercent); int destHeight = (int) (sourceHeight*nPercent); Bitmap bmPhoto = new Bitmap(destWidth, destHeight, PixelFormat.Format24bppRgb); if(Type.GetType("Mono.Runtime") == null){ // Only run this on .NET platforms. It breaks Mono 2.4+ bmPhoto.SetResolution(img.HorizontalResolution, img.VerticalResolution); } Graphics grPhoto = Graphics.FromImage(bmPhoto); grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic; grPhoto.DrawImage(img, new Rectangle(destX, destY, destWidth, destHeight), new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight), GraphicsUnit.Pixel); grPhoto.Dispose(); return bmPhoto; } } }
namespace android.webkit { [global::MonoJavaBridge.JavaClass()] public partial class WebChromeClient : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected WebChromeClient(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaInterface(typeof(global::android.webkit.WebChromeClient.CustomViewCallback_))] public partial interface CustomViewCallback : global::MonoJavaBridge.IJavaObject { void onCustomViewHidden(); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.webkit.WebChromeClient.CustomViewCallback))] internal sealed partial class CustomViewCallback_ : java.lang.Object, CustomViewCallback { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal CustomViewCallback_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; void android.webkit.WebChromeClient.CustomViewCallback.onCustomViewHidden() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.webkit.WebChromeClient.CustomViewCallback_.staticClass, "onCustomViewHidden", "()V", ref global::android.webkit.WebChromeClient.CustomViewCallback_._m0); } static CustomViewCallback_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.webkit.WebChromeClient.CustomViewCallback_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/webkit/WebChromeClient$CustomViewCallback")); } } public delegate void CustomViewCallbackDelegate(); internal partial class CustomViewCallbackDelegateWrapper : java.lang.Object, CustomViewCallback { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected CustomViewCallbackDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public CustomViewCallbackDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.webkit.WebChromeClient.CustomViewCallbackDelegateWrapper._m0.native == global::System.IntPtr.Zero) global::android.webkit.WebChromeClient.CustomViewCallbackDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.webkit.WebChromeClient.CustomViewCallbackDelegateWrapper.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.webkit.WebChromeClient.CustomViewCallbackDelegateWrapper.staticClass, global::android.webkit.WebChromeClient.CustomViewCallbackDelegateWrapper._m0); Init(@__env, handle); } static CustomViewCallbackDelegateWrapper() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.webkit.WebChromeClient.CustomViewCallbackDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/webkit/WebChromeClient_CustomViewCallbackDelegateWrapper")); } } internal partial class CustomViewCallbackDelegateWrapper { private CustomViewCallbackDelegate myDelegate; public void onCustomViewHidden() { myDelegate(); } public static implicit operator CustomViewCallbackDelegateWrapper(CustomViewCallbackDelegate d) { global::android.webkit.WebChromeClient.CustomViewCallbackDelegateWrapper ret = new global::android.webkit.WebChromeClient.CustomViewCallbackDelegateWrapper(); ret.myDelegate = d; global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret); return ret; } } private static global::MonoJavaBridge.MethodId _m0; public virtual void onReceivedIcon(android.webkit.WebView arg0, android.graphics.Bitmap arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.webkit.WebChromeClient.staticClass, "onReceivedIcon", "(Landroid/webkit/WebView;Landroid/graphics/Bitmap;)V", ref global::android.webkit.WebChromeClient._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m1; public virtual void onProgressChanged(android.webkit.WebView arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.webkit.WebChromeClient.staticClass, "onProgressChanged", "(Landroid/webkit/WebView;I)V", ref global::android.webkit.WebChromeClient._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m2; public virtual void onReceivedTitle(android.webkit.WebView arg0, java.lang.String arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.webkit.WebChromeClient.staticClass, "onReceivedTitle", "(Landroid/webkit/WebView;Ljava/lang/String;)V", ref global::android.webkit.WebChromeClient._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m3; public virtual void onReceivedTouchIconUrl(android.webkit.WebView arg0, java.lang.String arg1, bool arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.webkit.WebChromeClient.staticClass, "onReceivedTouchIconUrl", "(Landroid/webkit/WebView;Ljava/lang/String;Z)V", ref global::android.webkit.WebChromeClient._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m4; public virtual void onShowCustomView(android.view.View arg0, android.webkit.WebChromeClient.CustomViewCallback arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.webkit.WebChromeClient.staticClass, "onShowCustomView", "(Landroid/view/View;Landroid/webkit/WebChromeClient$CustomViewCallback;)V", ref global::android.webkit.WebChromeClient._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } public void onShowCustomView(android.view.View arg0, global::android.webkit.WebChromeClient.CustomViewCallbackDelegate arg1) { onShowCustomView(arg0, (global::android.webkit.WebChromeClient.CustomViewCallbackDelegateWrapper)arg1); } private static global::MonoJavaBridge.MethodId _m5; public virtual void onHideCustomView() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.webkit.WebChromeClient.staticClass, "onHideCustomView", "()V", ref global::android.webkit.WebChromeClient._m5); } private static global::MonoJavaBridge.MethodId _m6; public virtual bool onCreateWindow(android.webkit.WebView arg0, bool arg1, bool arg2, android.os.Message arg3) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.webkit.WebChromeClient.staticClass, "onCreateWindow", "(Landroid/webkit/WebView;ZZLandroid/os/Message;)Z", ref global::android.webkit.WebChromeClient._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m7; public virtual void onRequestFocus(android.webkit.WebView arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.webkit.WebChromeClient.staticClass, "onRequestFocus", "(Landroid/webkit/WebView;)V", ref global::android.webkit.WebChromeClient._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m8; public virtual void onCloseWindow(android.webkit.WebView arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.webkit.WebChromeClient.staticClass, "onCloseWindow", "(Landroid/webkit/WebView;)V", ref global::android.webkit.WebChromeClient._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m9; public virtual bool onJsAlert(android.webkit.WebView arg0, java.lang.String arg1, java.lang.String arg2, android.webkit.JsResult arg3) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.webkit.WebChromeClient.staticClass, "onJsAlert", "(Landroid/webkit/WebView;Ljava/lang/String;Ljava/lang/String;Landroid/webkit/JsResult;)Z", ref global::android.webkit.WebChromeClient._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m10; public virtual bool onJsConfirm(android.webkit.WebView arg0, java.lang.String arg1, java.lang.String arg2, android.webkit.JsResult arg3) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.webkit.WebChromeClient.staticClass, "onJsConfirm", "(Landroid/webkit/WebView;Ljava/lang/String;Ljava/lang/String;Landroid/webkit/JsResult;)Z", ref global::android.webkit.WebChromeClient._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m11; public virtual bool onJsPrompt(android.webkit.WebView arg0, java.lang.String arg1, java.lang.String arg2, java.lang.String arg3, android.webkit.JsPromptResult arg4) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.webkit.WebChromeClient.staticClass, "onJsPrompt", "(Landroid/webkit/WebView;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Landroid/webkit/JsPromptResult;)Z", ref global::android.webkit.WebChromeClient._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); } private static global::MonoJavaBridge.MethodId _m12; public virtual bool onJsBeforeUnload(android.webkit.WebView arg0, java.lang.String arg1, java.lang.String arg2, android.webkit.JsResult arg3) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.webkit.WebChromeClient.staticClass, "onJsBeforeUnload", "(Landroid/webkit/WebView;Ljava/lang/String;Ljava/lang/String;Landroid/webkit/JsResult;)Z", ref global::android.webkit.WebChromeClient._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m13; public virtual void onExceededDatabaseQuota(java.lang.String arg0, java.lang.String arg1, long arg2, long arg3, long arg4, android.webkit.WebStorage.QuotaUpdater arg5) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.webkit.WebChromeClient.staticClass, "onExceededDatabaseQuota", "(Ljava/lang/String;Ljava/lang/String;JJJLandroid/webkit/WebStorage$QuotaUpdater;)V", ref global::android.webkit.WebChromeClient._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5)); } public void onExceededDatabaseQuota(java.lang.String arg0, java.lang.String arg1, long arg2, long arg3, long arg4, global::android.webkit.WebStorage.QuotaUpdaterDelegate arg5) { onExceededDatabaseQuota(arg0, arg1, arg2, arg3, arg4, (global::android.webkit.WebStorage.QuotaUpdaterDelegateWrapper)arg5); } private static global::MonoJavaBridge.MethodId _m14; public virtual void onReachedMaxAppCacheSize(long arg0, long arg1, android.webkit.WebStorage.QuotaUpdater arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.webkit.WebChromeClient.staticClass, "onReachedMaxAppCacheSize", "(JJLandroid/webkit/WebStorage$QuotaUpdater;)V", ref global::android.webkit.WebChromeClient._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } public void onReachedMaxAppCacheSize(long arg0, long arg1, global::android.webkit.WebStorage.QuotaUpdaterDelegate arg2) { onReachedMaxAppCacheSize(arg0, arg1, (global::android.webkit.WebStorage.QuotaUpdaterDelegateWrapper)arg2); } private static global::MonoJavaBridge.MethodId _m15; public virtual void onGeolocationPermissionsShowPrompt(java.lang.String arg0, android.webkit.GeolocationPermissions.Callback arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.webkit.WebChromeClient.staticClass, "onGeolocationPermissionsShowPrompt", "(Ljava/lang/String;Landroid/webkit/GeolocationPermissions$Callback;)V", ref global::android.webkit.WebChromeClient._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } public void onGeolocationPermissionsShowPrompt(java.lang.String arg0, global::android.webkit.GeolocationPermissions.CallbackDelegate arg1) { onGeolocationPermissionsShowPrompt(arg0, (global::android.webkit.GeolocationPermissions.CallbackDelegateWrapper)arg1); } private static global::MonoJavaBridge.MethodId _m16; public virtual void onGeolocationPermissionsHidePrompt() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.webkit.WebChromeClient.staticClass, "onGeolocationPermissionsHidePrompt", "()V", ref global::android.webkit.WebChromeClient._m16); } private static global::MonoJavaBridge.MethodId _m17; public virtual bool onJsTimeout() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.webkit.WebChromeClient.staticClass, "onJsTimeout", "()Z", ref global::android.webkit.WebChromeClient._m17); } private static global::MonoJavaBridge.MethodId _m18; public virtual void onConsoleMessage(java.lang.String arg0, int arg1, java.lang.String arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.webkit.WebChromeClient.staticClass, "onConsoleMessage", "(Ljava/lang/String;ILjava/lang/String;)V", ref global::android.webkit.WebChromeClient._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m19; public virtual bool onConsoleMessage(android.webkit.ConsoleMessage arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.webkit.WebChromeClient.staticClass, "onConsoleMessage", "(Landroid/webkit/ConsoleMessage;)Z", ref global::android.webkit.WebChromeClient._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new global::android.graphics.Bitmap DefaultVideoPoster { get { return getDefaultVideoPoster(); } } private static global::MonoJavaBridge.MethodId _m20; public virtual global::android.graphics.Bitmap getDefaultVideoPoster() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<android.graphics.Bitmap>(this, global::android.webkit.WebChromeClient.staticClass, "getDefaultVideoPoster", "()Landroid/graphics/Bitmap;", ref global::android.webkit.WebChromeClient._m20) as android.graphics.Bitmap; } public new global::android.view.View VideoLoadingProgressView { get { return getVideoLoadingProgressView(); } } private static global::MonoJavaBridge.MethodId _m21; public virtual global::android.view.View getVideoLoadingProgressView() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.webkit.WebChromeClient.staticClass, "getVideoLoadingProgressView", "()Landroid/view/View;", ref global::android.webkit.WebChromeClient._m21) as android.view.View; } private static global::MonoJavaBridge.MethodId _m22; public virtual void getVisitedHistory(android.webkit.ValueCallback arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.webkit.WebChromeClient.staticClass, "getVisitedHistory", "(Landroid/webkit/ValueCallback;)V", ref global::android.webkit.WebChromeClient._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void getVisitedHistory(global::android.webkit.ValueCallbackDelegate arg0) { getVisitedHistory((global::android.webkit.ValueCallbackDelegateWrapper)arg0); } private static global::MonoJavaBridge.MethodId _m23; public WebChromeClient() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.webkit.WebChromeClient._m23.native == global::System.IntPtr.Zero) global::android.webkit.WebChromeClient._m23 = @__env.GetMethodIDNoThrow(global::android.webkit.WebChromeClient.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.webkit.WebChromeClient.staticClass, global::android.webkit.WebChromeClient._m23); Init(@__env, handle); } static WebChromeClient() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.webkit.WebChromeClient.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/webkit/WebChromeClient")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Xunit; namespace System.Threading.Channels.Tests { public class ChannelTests { [Fact] public void ChannelOptimizations_Properties_Roundtrip() { var co = new UnboundedChannelOptions(); Assert.False(co.SingleReader); Assert.False(co.SingleWriter); co.SingleReader = true; Assert.True(co.SingleReader); Assert.False(co.SingleWriter); co.SingleReader = false; Assert.False(co.SingleReader); co.SingleWriter = true; Assert.False(co.SingleReader); Assert.True(co.SingleWriter); co.SingleWriter = false; Assert.False(co.SingleWriter); co.SingleReader = true; co.SingleWriter = true; Assert.True(co.SingleReader); Assert.True(co.SingleWriter); Assert.False(co.AllowSynchronousContinuations); co.AllowSynchronousContinuations = true; Assert.True(co.AllowSynchronousContinuations); co.AllowSynchronousContinuations = false; Assert.False(co.AllowSynchronousContinuations); } [Fact] public void Create_ValidInputs_ProducesValidChannels() { Assert.NotNull(Channel.CreateBounded<int>(1)); Assert.NotNull(Channel.CreateBounded<int>(new BoundedChannelOptions(1))); Assert.NotNull(Channel.CreateUnbounded<int>()); Assert.NotNull(Channel.CreateUnbounded<int>(new UnboundedChannelOptions())); } [Fact] public void Create_NullOptions_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentNullException>("options", () => Channel.CreateUnbounded<int>(null)); AssertExtensions.Throws<ArgumentNullException>("options", () => Channel.CreateBounded<int>(null)); } [Theory] [InlineData(0)] [InlineData(-2)] public void CreateBounded_InvalidBufferSizes_ThrowArgumentExceptions(int capacity) { AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => Channel.CreateBounded<int>(capacity)); AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new BoundedChannelOptions(capacity)); } [Theory] [InlineData((BoundedChannelFullMode)(-1))] [InlineData((BoundedChannelFullMode)(4))] public void BoundedChannelOptions_InvalidModes_ThrowArgumentExceptions(BoundedChannelFullMode mode) => AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => new BoundedChannelOptions(1) { FullMode = mode }); [Theory] [InlineData(0)] [InlineData(-2)] public void BoundedChannelOptions_InvalidCapacity_ThrowArgumentExceptions(int capacity) => AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => new BoundedChannelOptions(1) { Capacity = capacity }); [Theory] [InlineData(1)] public void CreateBounded_ValidBufferSizes_Success(int bufferedCapacity) => Assert.NotNull(Channel.CreateBounded<int>(bufferedCapacity)); [Fact] public async Task DefaultWriteAsync_UsesWaitToWriteAsyncAndTryWrite() { var c = new TestChannelWriter<int>(10); Assert.False(c.TryComplete()); Assert.Equal(TaskStatus.Canceled, c.WriteAsync(42, new CancellationToken(true)).Status); int count = 0; try { while (true) { await c.WriteAsync(count++); } } catch (ChannelClosedException) { } Assert.Equal(11, count); } [Fact] public void DefaultCompletion_NeverCompletes() { Task t = new TestChannelReader<int>(Enumerable.Empty<int>()).Completion; Assert.False(t.IsCompleted); } [Fact] public async Task DefaultWriteAsync_CatchesTryWriteExceptions() { var w = new TryWriteThrowingWriter<int>(); Task t = w.WriteAsync(42); Assert.Equal(TaskStatus.Faulted, t.Status); await Assert.ThrowsAsync<FormatException>(() => t); } [Fact] public async Task DefaultReadAsync_CatchesTryWriteExceptions() { var r = new TryReadThrowingReader<int>(); Task<int> t = r.ReadAsync().AsTask(); Assert.Equal(TaskStatus.Faulted, t.Status); await Assert.ThrowsAsync<FieldAccessException>(() => t); } [Fact] public async void TestBaseClassReadAsync() { WrapperChannel<int> channel = new WrapperChannel<int>(10); ChannelReader<int> reader = channel.Reader; ChannelWriter<int> writer = channel.Writer; // 1- do it through synchronous TryRead() writer.TryWrite(50); Assert.Equal(50, await reader.ReadAsync()); // 2- do it through async ValueTask<int> readTask = reader.ReadAsync(); writer.TryWrite(100); Assert.Equal(100, await readTask); // 3- use cancellation token CancellationToken ct = new CancellationToken(true); // cancelled token await Assert.ThrowsAsync<TaskCanceledException>(() => reader.ReadAsync(ct).AsTask()); // 4- throw during reading readTask = reader.ReadAsync(); ((WrapperChannelReader<int>)reader).ForceThrowing = true; writer.TryWrite(200); await Assert.ThrowsAsync<InvalidOperationException>(() => readTask.AsTask()); // 5- close the channel while waiting reading ((WrapperChannelReader<int>)reader).ForceThrowing = false; Assert.Equal(200, await reader.ReadAsync()); readTask = reader.ReadAsync(); channel.Writer.TryComplete(); await Assert.ThrowsAsync<ChannelClosedException>(() => readTask.AsTask()); } // This reader doesn't override ReadAsync to force using the base class ReadAsync method private sealed class WrapperChannelReader<T> : ChannelReader<T> { private ChannelReader<T> _reader; internal bool ForceThrowing { get; set; } public WrapperChannelReader(Channel<T> channel) {_reader = channel.Reader; } public override bool TryRead(out T item) { if (ForceThrowing) throw new InvalidOperationException(); return _reader.TryRead(out item); } public override Task<bool> WaitToReadAsync(CancellationToken cancellationToken) { return _reader.WaitToReadAsync(cancellationToken); } } public class WrapperChannel<T> : Channel<T> { public WrapperChannel(int capacity) { Channel<T> channel = Channel.CreateBounded<T>(capacity); Writer = channel.Writer; Reader = new WrapperChannelReader<T>(channel); } } private sealed class TestChannelWriter<T> : ChannelWriter<T> { private readonly Random _rand = new Random(42); private readonly int _max; private int _count; public TestChannelWriter(int max) => _max = max; public override bool TryWrite(T item) => _rand.Next(0, 2) == 0 && _count++ < _max; // succeed if we're under our limit, and add random failures public override Task<bool> WaitToWriteAsync(CancellationToken cancellationToken) => _count >= _max ? Task.FromResult(false) : _rand.Next(0, 2) == 0 ? Task.Delay(1).ContinueWith(_ => true) : // randomly introduce delays Task.FromResult(true); } private sealed class TestChannelReader<T> : ChannelReader<T> { private Random _rand = new Random(42); private IEnumerator<T> _enumerator; private int _count; private bool _closed; public TestChannelReader(IEnumerable<T> enumerable) => _enumerator = enumerable.GetEnumerator(); public override bool TryRead(out T item) { // Randomly fail to read if (_rand.Next(0, 2) == 0) { item = default; return false; } // If the enumerable is closed, fail the read. if (!_enumerator.MoveNext()) { _enumerator.Dispose(); _closed = true; item = default; return false; } // Otherwise return the next item. _count++; item = _enumerator.Current; return true; } public override Task<bool> WaitToReadAsync(CancellationToken cancellationToken) => _closed ? Task.FromResult(false) : _rand.Next(0, 2) == 0 ? Task.Delay(1).ContinueWith(_ => true) : // randomly introduce delays Task.FromResult(true); } private sealed class TryWriteThrowingWriter<T> : ChannelWriter<T> { public override bool TryWrite(T item) => throw new FormatException(); public override Task<bool> WaitToWriteAsync(CancellationToken cancellationToken = default) => throw new InvalidDataException(); } private sealed class TryReadThrowingReader<T> : ChannelReader<T> { public override bool TryRead(out T item) => throw new FieldAccessException(); public override Task<bool> WaitToReadAsync(CancellationToken cancellationToken = default) => throw new DriveNotFoundException(); } private sealed class CanReadFalseStream : MemoryStream { public override bool CanRead => false; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace WebApp170603.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
/* * UltraCart Rest API V2 * * UltraCart REST API Version 2 * * OpenAPI spec version: 2.0.0 * Contact: support@ultracart.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter; namespace com.ultracart.admin.v2.Model { /// <summary> /// OrderTrackingNumberDetails /// </summary> [DataContract] public partial class OrderTrackingNumberDetails : IEquatable<OrderTrackingNumberDetails>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="OrderTrackingNumberDetails" /> class. /// </summary> /// <param name="actualDeliveryDate">actualDeliveryDate.</param> /// <param name="actualDeliveryDateFormatted">actualDeliveryDateFormatted.</param> /// <param name="details">details.</param> /// <param name="easypostTrackerId">easypostTrackerId.</param> /// <param name="expectedDeliveryDate">expectedDeliveryDate.</param> /// <param name="expectedDeliveryDateFormatted">expectedDeliveryDateFormatted.</param> /// <param name="mapUrl">mapUrl.</param> /// <param name="orderPlacedDate">orderPlacedDate.</param> /// <param name="orderPlacedDateFormatted">orderPlacedDateFormatted.</param> /// <param name="paymentProcessedDate">paymentProcessedDate.</param> /// <param name="paymentProcessedDateFormatted">paymentProcessedDateFormatted.</param> /// <param name="shippedDate">shippedDate.</param> /// <param name="shippedDateFormatted">shippedDateFormatted.</param> /// <param name="shippingMethod">shippingMethod.</param> /// <param name="status">status.</param> /// <param name="statusDescription">statusDescription.</param> /// <param name="trackingNumber">trackingNumber.</param> /// <param name="trackingUrl">trackingUrl.</param> public OrderTrackingNumberDetails(string actualDeliveryDate = default(string), string actualDeliveryDateFormatted = default(string), List<OrderTrackingNumberDetail> details = default(List<OrderTrackingNumberDetail>), string easypostTrackerId = default(string), string expectedDeliveryDate = default(string), string expectedDeliveryDateFormatted = default(string), string mapUrl = default(string), string orderPlacedDate = default(string), string orderPlacedDateFormatted = default(string), string paymentProcessedDate = default(string), string paymentProcessedDateFormatted = default(string), string shippedDate = default(string), string shippedDateFormatted = default(string), string shippingMethod = default(string), string status = default(string), string statusDescription = default(string), string trackingNumber = default(string), string trackingUrl = default(string)) { this.ActualDeliveryDate = actualDeliveryDate; this.ActualDeliveryDateFormatted = actualDeliveryDateFormatted; this.Details = details; this.EasypostTrackerId = easypostTrackerId; this.ExpectedDeliveryDate = expectedDeliveryDate; this.ExpectedDeliveryDateFormatted = expectedDeliveryDateFormatted; this.MapUrl = mapUrl; this.OrderPlacedDate = orderPlacedDate; this.OrderPlacedDateFormatted = orderPlacedDateFormatted; this.PaymentProcessedDate = paymentProcessedDate; this.PaymentProcessedDateFormatted = paymentProcessedDateFormatted; this.ShippedDate = shippedDate; this.ShippedDateFormatted = shippedDateFormatted; this.ShippingMethod = shippingMethod; this.Status = status; this.StatusDescription = statusDescription; this.TrackingNumber = trackingNumber; this.TrackingUrl = trackingUrl; } /// <summary> /// Gets or Sets ActualDeliveryDate /// </summary> [DataMember(Name="actual_delivery_date", EmitDefaultValue=false)] public string ActualDeliveryDate { get; set; } /// <summary> /// Gets or Sets ActualDeliveryDateFormatted /// </summary> [DataMember(Name="actual_delivery_date_formatted", EmitDefaultValue=false)] public string ActualDeliveryDateFormatted { get; set; } /// <summary> /// Gets or Sets Details /// </summary> [DataMember(Name="details", EmitDefaultValue=false)] public List<OrderTrackingNumberDetail> Details { get; set; } /// <summary> /// Gets or Sets EasypostTrackerId /// </summary> [DataMember(Name="easypost_tracker_id", EmitDefaultValue=false)] public string EasypostTrackerId { get; set; } /// <summary> /// Gets or Sets ExpectedDeliveryDate /// </summary> [DataMember(Name="expected_delivery_date", EmitDefaultValue=false)] public string ExpectedDeliveryDate { get; set; } /// <summary> /// Gets or Sets ExpectedDeliveryDateFormatted /// </summary> [DataMember(Name="expected_delivery_date_formatted", EmitDefaultValue=false)] public string ExpectedDeliveryDateFormatted { get; set; } /// <summary> /// Gets or Sets MapUrl /// </summary> [DataMember(Name="map_url", EmitDefaultValue=false)] public string MapUrl { get; set; } /// <summary> /// Gets or Sets OrderPlacedDate /// </summary> [DataMember(Name="order_placed_date", EmitDefaultValue=false)] public string OrderPlacedDate { get; set; } /// <summary> /// Gets or Sets OrderPlacedDateFormatted /// </summary> [DataMember(Name="order_placed_date_formatted", EmitDefaultValue=false)] public string OrderPlacedDateFormatted { get; set; } /// <summary> /// Gets or Sets PaymentProcessedDate /// </summary> [DataMember(Name="payment_processed_date", EmitDefaultValue=false)] public string PaymentProcessedDate { get; set; } /// <summary> /// Gets or Sets PaymentProcessedDateFormatted /// </summary> [DataMember(Name="payment_processed_date_formatted", EmitDefaultValue=false)] public string PaymentProcessedDateFormatted { get; set; } /// <summary> /// Gets or Sets ShippedDate /// </summary> [DataMember(Name="shipped_date", EmitDefaultValue=false)] public string ShippedDate { get; set; } /// <summary> /// Gets or Sets ShippedDateFormatted /// </summary> [DataMember(Name="shipped_date_formatted", EmitDefaultValue=false)] public string ShippedDateFormatted { get; set; } /// <summary> /// Gets or Sets ShippingMethod /// </summary> [DataMember(Name="shipping_method", EmitDefaultValue=false)] public string ShippingMethod { get; set; } /// <summary> /// Gets or Sets Status /// </summary> [DataMember(Name="status", EmitDefaultValue=false)] public string Status { get; set; } /// <summary> /// Gets or Sets StatusDescription /// </summary> [DataMember(Name="status_description", EmitDefaultValue=false)] public string StatusDescription { get; set; } /// <summary> /// Gets or Sets TrackingNumber /// </summary> [DataMember(Name="tracking_number", EmitDefaultValue=false)] public string TrackingNumber { get; set; } /// <summary> /// Gets or Sets TrackingUrl /// </summary> [DataMember(Name="tracking_url", EmitDefaultValue=false)] public string TrackingUrl { 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 OrderTrackingNumberDetails {\n"); sb.Append(" ActualDeliveryDate: ").Append(ActualDeliveryDate).Append("\n"); sb.Append(" ActualDeliveryDateFormatted: ").Append(ActualDeliveryDateFormatted).Append("\n"); sb.Append(" Details: ").Append(Details).Append("\n"); sb.Append(" EasypostTrackerId: ").Append(EasypostTrackerId).Append("\n"); sb.Append(" ExpectedDeliveryDate: ").Append(ExpectedDeliveryDate).Append("\n"); sb.Append(" ExpectedDeliveryDateFormatted: ").Append(ExpectedDeliveryDateFormatted).Append("\n"); sb.Append(" MapUrl: ").Append(MapUrl).Append("\n"); sb.Append(" OrderPlacedDate: ").Append(OrderPlacedDate).Append("\n"); sb.Append(" OrderPlacedDateFormatted: ").Append(OrderPlacedDateFormatted).Append("\n"); sb.Append(" PaymentProcessedDate: ").Append(PaymentProcessedDate).Append("\n"); sb.Append(" PaymentProcessedDateFormatted: ").Append(PaymentProcessedDateFormatted).Append("\n"); sb.Append(" ShippedDate: ").Append(ShippedDate).Append("\n"); sb.Append(" ShippedDateFormatted: ").Append(ShippedDateFormatted).Append("\n"); sb.Append(" ShippingMethod: ").Append(ShippingMethod).Append("\n"); sb.Append(" Status: ").Append(Status).Append("\n"); sb.Append(" StatusDescription: ").Append(StatusDescription).Append("\n"); sb.Append(" TrackingNumber: ").Append(TrackingNumber).Append("\n"); sb.Append(" TrackingUrl: ").Append(TrackingUrl).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as OrderTrackingNumberDetails); } /// <summary> /// Returns true if OrderTrackingNumberDetails instances are equal /// </summary> /// <param name="input">Instance of OrderTrackingNumberDetails to be compared</param> /// <returns>Boolean</returns> public bool Equals(OrderTrackingNumberDetails input) { if (input == null) return false; return ( this.ActualDeliveryDate == input.ActualDeliveryDate || (this.ActualDeliveryDate != null && this.ActualDeliveryDate.Equals(input.ActualDeliveryDate)) ) && ( this.ActualDeliveryDateFormatted == input.ActualDeliveryDateFormatted || (this.ActualDeliveryDateFormatted != null && this.ActualDeliveryDateFormatted.Equals(input.ActualDeliveryDateFormatted)) ) && ( this.Details == input.Details || this.Details != null && this.Details.SequenceEqual(input.Details) ) && ( this.EasypostTrackerId == input.EasypostTrackerId || (this.EasypostTrackerId != null && this.EasypostTrackerId.Equals(input.EasypostTrackerId)) ) && ( this.ExpectedDeliveryDate == input.ExpectedDeliveryDate || (this.ExpectedDeliveryDate != null && this.ExpectedDeliveryDate.Equals(input.ExpectedDeliveryDate)) ) && ( this.ExpectedDeliveryDateFormatted == input.ExpectedDeliveryDateFormatted || (this.ExpectedDeliveryDateFormatted != null && this.ExpectedDeliveryDateFormatted.Equals(input.ExpectedDeliveryDateFormatted)) ) && ( this.MapUrl == input.MapUrl || (this.MapUrl != null && this.MapUrl.Equals(input.MapUrl)) ) && ( this.OrderPlacedDate == input.OrderPlacedDate || (this.OrderPlacedDate != null && this.OrderPlacedDate.Equals(input.OrderPlacedDate)) ) && ( this.OrderPlacedDateFormatted == input.OrderPlacedDateFormatted || (this.OrderPlacedDateFormatted != null && this.OrderPlacedDateFormatted.Equals(input.OrderPlacedDateFormatted)) ) && ( this.PaymentProcessedDate == input.PaymentProcessedDate || (this.PaymentProcessedDate != null && this.PaymentProcessedDate.Equals(input.PaymentProcessedDate)) ) && ( this.PaymentProcessedDateFormatted == input.PaymentProcessedDateFormatted || (this.PaymentProcessedDateFormatted != null && this.PaymentProcessedDateFormatted.Equals(input.PaymentProcessedDateFormatted)) ) && ( this.ShippedDate == input.ShippedDate || (this.ShippedDate != null && this.ShippedDate.Equals(input.ShippedDate)) ) && ( this.ShippedDateFormatted == input.ShippedDateFormatted || (this.ShippedDateFormatted != null && this.ShippedDateFormatted.Equals(input.ShippedDateFormatted)) ) && ( this.ShippingMethod == input.ShippingMethod || (this.ShippingMethod != null && this.ShippingMethod.Equals(input.ShippingMethod)) ) && ( this.Status == input.Status || (this.Status != null && this.Status.Equals(input.Status)) ) && ( this.StatusDescription == input.StatusDescription || (this.StatusDescription != null && this.StatusDescription.Equals(input.StatusDescription)) ) && ( this.TrackingNumber == input.TrackingNumber || (this.TrackingNumber != null && this.TrackingNumber.Equals(input.TrackingNumber)) ) && ( this.TrackingUrl == input.TrackingUrl || (this.TrackingUrl != null && this.TrackingUrl.Equals(input.TrackingUrl)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.ActualDeliveryDate != null) hashCode = hashCode * 59 + this.ActualDeliveryDate.GetHashCode(); if (this.ActualDeliveryDateFormatted != null) hashCode = hashCode * 59 + this.ActualDeliveryDateFormatted.GetHashCode(); if (this.Details != null) hashCode = hashCode * 59 + this.Details.GetHashCode(); if (this.EasypostTrackerId != null) hashCode = hashCode * 59 + this.EasypostTrackerId.GetHashCode(); if (this.ExpectedDeliveryDate != null) hashCode = hashCode * 59 + this.ExpectedDeliveryDate.GetHashCode(); if (this.ExpectedDeliveryDateFormatted != null) hashCode = hashCode * 59 + this.ExpectedDeliveryDateFormatted.GetHashCode(); if (this.MapUrl != null) hashCode = hashCode * 59 + this.MapUrl.GetHashCode(); if (this.OrderPlacedDate != null) hashCode = hashCode * 59 + this.OrderPlacedDate.GetHashCode(); if (this.OrderPlacedDateFormatted != null) hashCode = hashCode * 59 + this.OrderPlacedDateFormatted.GetHashCode(); if (this.PaymentProcessedDate != null) hashCode = hashCode * 59 + this.PaymentProcessedDate.GetHashCode(); if (this.PaymentProcessedDateFormatted != null) hashCode = hashCode * 59 + this.PaymentProcessedDateFormatted.GetHashCode(); if (this.ShippedDate != null) hashCode = hashCode * 59 + this.ShippedDate.GetHashCode(); if (this.ShippedDateFormatted != null) hashCode = hashCode * 59 + this.ShippedDateFormatted.GetHashCode(); if (this.ShippingMethod != null) hashCode = hashCode * 59 + this.ShippingMethod.GetHashCode(); if (this.Status != null) hashCode = hashCode * 59 + this.Status.GetHashCode(); if (this.StatusDescription != null) hashCode = hashCode * 59 + this.StatusDescription.GetHashCode(); if (this.TrackingNumber != null) hashCode = hashCode * 59 + this.TrackingNumber.GetHashCode(); if (this.TrackingUrl != null) hashCode = hashCode * 59 + this.TrackingUrl.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.ComponentModel; namespace System.Collections.Immutable { internal sealed partial class SortedInt32KeyNode<TValue> { /// <summary> /// Enumerates the contents of a binary tree. /// </summary> /// <remarks> /// This struct can and should be kept in exact sync with the other binary tree enumerators: /// <see cref="ImmutableList{T}.Enumerator"/>, <see cref="ImmutableSortedDictionary{TKey, TValue}.Enumerator"/>, and <see cref="ImmutableSortedSet{T}.Enumerator"/>. /// /// CAUTION: when this enumerator is actually used as a valuetype (not boxed) do NOT copy it by assigning to a second variable /// or by passing it to another method. When this enumerator is disposed of it returns a mutable reference type stack to a resource pool, /// and if the value type enumerator is copied (which can easily happen unintentionally if you pass the value around) there is a risk /// that a stack that has already been returned to the resource pool may still be in use by one of the enumerator copies, leading to data /// corruption and/or exceptions. /// </remarks> [EditorBrowsable(EditorBrowsableState.Advanced)] public struct Enumerator : IEnumerator<KeyValuePair<int, TValue>>, ISecurePooledObjectUser { /// <summary> /// The resource pool of reusable mutable stacks for purposes of enumeration. /// </summary> /// <remarks> /// We utilize this resource pool to make "allocation free" enumeration achievable. /// </remarks> private static readonly SecureObjectPool<Stack<RefAsValueType<SortedInt32KeyNode<TValue>>>, Enumerator> s_enumeratingStacks = new SecureObjectPool<Stack<RefAsValueType<SortedInt32KeyNode<TValue>>>, Enumerator>(); /// <summary> /// A unique ID for this instance of this enumerator. /// Used to protect pooled objects from use after they are recycled. /// </summary> private readonly int _poolUserId; /// <summary> /// The set being enumerated. /// </summary> private SortedInt32KeyNode<TValue> _root; /// <summary> /// The stack to use for enumerating the binary tree. /// </summary> private SecurePooledObject<Stack<RefAsValueType<SortedInt32KeyNode<TValue>>>> _stack; /// <summary> /// The node currently selected. /// </summary> private SortedInt32KeyNode<TValue> _current; /// <summary> /// Initializes an <see cref="Enumerator"/> structure. /// </summary> /// <param name="root">The root of the set to be enumerated.</param> internal Enumerator(SortedInt32KeyNode<TValue> root) { Requires.NotNull(root, nameof(root)); _root = root; _current = null; _poolUserId = SecureObjectPool.NewId(); _stack = null; if (!_root.IsEmpty) { if (!s_enumeratingStacks.TryTake(this, out _stack)) { _stack = s_enumeratingStacks.PrepNew(this, new Stack<RefAsValueType<SortedInt32KeyNode<TValue>>>(root.Height)); } this.PushLeft(_root); } } /// <summary> /// The current element. /// </summary> public KeyValuePair<int, TValue> Current { get { this.ThrowIfDisposed(); if (_current != null) { return _current.Value; } throw new InvalidOperationException(); } } /// <inheritdoc/> int ISecurePooledObjectUser.PoolUserId { get { return _poolUserId; } } /// <summary> /// The current element. /// </summary> object IEnumerator.Current { get { return this.Current; } } /// <summary> /// Disposes of this enumerator and returns the stack reference to the resource pool. /// </summary> public void Dispose() { _root = null; _current = null; Stack<RefAsValueType<SortedInt32KeyNode<TValue>>> stack; if (_stack != null && _stack.TryUse(ref this, out stack)) { stack.ClearFastWhenEmpty(); s_enumeratingStacks.TryAdd(this, _stack); } _stack = null; } /// <summary> /// Advances enumeration to the next element. /// </summary> /// <returns>A value indicating whether there is another element in the enumeration.</returns> public bool MoveNext() { this.ThrowIfDisposed(); if (_stack != null) { var stack = _stack.Use(ref this); if (stack.Count > 0) { SortedInt32KeyNode<TValue> n = stack.Pop().Value; _current = n; this.PushLeft(n.Right); return true; } } _current = null; return false; } /// <summary> /// Restarts enumeration. /// </summary> public void Reset() { this.ThrowIfDisposed(); _current = null; if (_stack != null) { var stack = _stack.Use(ref this); stack.ClearFastWhenEmpty(); this.PushLeft(_root); } } /// <summary> /// Throws an <see cref="ObjectDisposedException"/> if this enumerator has been disposed. /// </summary> internal void ThrowIfDisposed() { // Since this is a struct, copies might not have been marked as disposed. // But the stack we share across those copies would know. // This trick only works when we have a non-null stack. // For enumerators of empty collections, there isn't any natural // way to know when a copy of the struct has been disposed of. if (_root == null || (_stack != null && !_stack.IsOwned(ref this))) { Requires.FailObjectDisposed(this); } } /// <summary> /// Pushes this node and all its Left descendants onto the stack. /// </summary> /// <param name="node">The starting node to push onto the stack.</param> private void PushLeft(SortedInt32KeyNode<TValue> node) { Requires.NotNull(node, nameof(node)); var stack = _stack.Use(ref this); while (!node.IsEmpty) { stack.Push(new RefAsValueType<SortedInt32KeyNode<TValue>>(node)); node = node.Left; } } } } }
using System; using NUnit.Framework; namespace Xamarin.Forms.Core.UnitTests { [TestFixture] public class CommandTests : BaseTestFixture { [Test] public void Constructor () { var cmd = new Command (() => { }); Assert.True (cmd.CanExecute (null)); } [Test] public void ThrowsWithNullConstructor () { Assert.Throws<ArgumentNullException> (() => new Command ((Action)null)); } [Test] public void ThrowsWithNullParameterizedConstructor () { Assert.Throws<ArgumentNullException> (() => new Command ((Action<object>)null)); } [Test] public void ThrowsWithNullCanExecute () { Assert.Throws<ArgumentNullException> (() => new Command (() => { }, null)); } [Test] public void ThrowsWithNullParameterizedCanExecute () { Assert.Throws<ArgumentNullException> (() => new Command (o => { }, null)); } [Test] public void ThrowsWithNullExecuteValidCanExecute () { Assert.Throws<ArgumentNullException> (() => new Command (null, () => true)); } [Test] public void Execute () { bool executed = false; var cmd = new Command (() => executed = true); cmd.Execute (null); Assert.True (executed); } [Test] public void ExecuteParameterized () { object executed = null; var cmd = new Command (o => executed = o); var expected = new object (); cmd.Execute (expected); Assert.AreEqual (expected, executed); } [Test] public void ExecuteWithCanExecute () { bool executed = false; var cmd = new Command (() => executed = true, () => true); cmd.Execute (null); Assert.True (executed); } [Test] public void CanExecute ([Values (true, false)] bool expected) { bool canExecuteRan = false; var cmd = new Command (() => { }, () => { canExecuteRan = true; return expected; }); Assert.AreEqual(expected, cmd.CanExecute (null)); Assert.True (canExecuteRan); } [Test] public void ChangeCanExecute () { bool signaled = false; var cmd = new Command (() => { }); cmd.CanExecuteChanged += (sender, args) => signaled = true; cmd.ChangeCanExecute (); Assert.True (signaled); } [Test] public void GenericThrowsWithNullExecute () { Assert.Throws<ArgumentNullException> (() => new Command<string> (null)); } [Test] public void GenericThrowsWithNullExecuteAndCanExecuteValid () { Assert.Throws<ArgumentNullException> (() => new Command<string> (null, s => true)); } [Test] public void GenericThrowsWithValidExecuteAndCanExecuteNull () { Assert.Throws<ArgumentNullException> (() => new Command<string> (s => { }, null)); } [Test] public void GenericExecute () { string result = null; var cmd = new Command<string> (s => result = s); cmd.Execute ("Foo"); Assert.AreEqual ("Foo", result); } [Test] public void GenericExecuteWithCanExecute () { string result = null; var cmd = new Command<string> (s => result = s, s => true); cmd.Execute ("Foo"); Assert.AreEqual ("Foo", result); } [Test] public void GenericCanExecute ([Values (true, false)] bool expected) { string result = null; var cmd = new Command<string> (s => { }, s => { result = s; return expected; }); Assert.AreEqual (expected, cmd.CanExecute ("Foo")); Assert.AreEqual ("Foo", result); } class FakeParentContext { } // ReSharper disable once ClassNeverInstantiated.Local class FakeChildContext { } [Test] public void CanExecuteReturnsFalseIfParameterIsWrongReferenceType() { var command = new Command<FakeChildContext>(context => { }, context => true); Assert.IsFalse(command.CanExecute(new FakeParentContext()), "the parameter is of the wrong type"); } [Test] public void CanExecuteReturnsFalseIfParameterIsWrongValueType() { var command = new Command<int>(context => { }, context => true); Assert.IsFalse(command.CanExecute(10.5), "the parameter is of the wrong type"); } [Test] public void CanExecuteUsesParameterIfReferenceTypeAndSetToNull() { var command = new Command<FakeChildContext>(context => { }, context => true); Assert.IsTrue(command.CanExecute(null), "null is a valid value for a reference type"); } [Test] public void CanExecuteUsesParameterIfNullableAndSetToNull() { var command = new Command<int?>(context => { }, context => true); Assert.IsTrue(command.CanExecute(null), "null is a valid value for a Nullable<int> type"); } [Test] public void CanExecuteIgnoresParameterIfValueTypeAndSetToNull() { var command = new Command<int>(context => { }, context => true); Assert.IsFalse(command.CanExecute(null), "null is not a valid valid for int"); } [Test] public void ExecuteDoesNotRunIfParameterIsWrongReferenceType() { int executions = 0; var command = new Command<FakeChildContext>(context => executions += 1); Assert.DoesNotThrow(() => command.Execute(new FakeParentContext()), "the command should not execute, so no exception should be thrown"); Assert.IsTrue(executions == 0, "the command should not have executed"); } [Test] public void ExecuteDoesNotRunIfParameterIsWrongValueType() { int executions = 0; var command = new Command<int>(context => executions += 1); Assert.DoesNotThrow(() => command.Execute(10.5), "the command should not execute, so no exception should be thrown"); Assert.IsTrue(executions == 0, "the command should not have executed"); } [Test] public void ExecuteRunsIfReferenceTypeAndSetToNull() { int executions = 0; var command = new Command<FakeChildContext>(context => executions += 1); Assert.DoesNotThrow(() => command.Execute(null), "null is a valid value for a reference type"); Assert.IsTrue(executions == 1, "the command should have executed"); } [Test] public void ExecuteRunsIfNullableAndSetToNull() { int executions = 0; var command = new Command<int?>(context => executions += 1); Assert.DoesNotThrow(() => command.Execute(null), "null is a valid value for a Nullable<int> type"); Assert.IsTrue(executions == 1, "the command should have executed"); } [Test] public void ExecuteDoesNotRunIfValueTypeAndSetToNull() { int executions = 0; var command = new Command<int>(context => executions += 1); Assert.DoesNotThrow(() => command.Execute(null), "null is not a valid value for int"); Assert.IsTrue(executions == 0, "the command should not have executed"); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Text; using Microsoft.DiaSymReader; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Utilities; using Roslyn.Utilities; using ShellInterop = Microsoft.VisualStudio.Shell.Interop; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; using VsThreading = Microsoft.VisualStudio.Threading; using Document = Microsoft.CodeAnalysis.Document; using Microsoft.CodeAnalysis.Debugging; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Interop; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue { internal sealed class VsENCRebuildableProjectImpl { private readonly AbstractProject _vsProject; // number of projects that are in the debug state: private static int s_debugStateProjectCount; // number of projects that are in the break state: private static int s_breakStateProjectCount; // projects that entered the break state: private static readonly List<KeyValuePair<ProjectId, ProjectReadOnlyReason>> s_breakStateEnteredProjects = new List<KeyValuePair<ProjectId, ProjectReadOnlyReason>>(); // active statements of projects that entered the break state: private static readonly List<VsActiveStatement> s_pendingActiveStatements = new List<VsActiveStatement>(); private static VsReadOnlyDocumentTracker s_readOnlyDocumentTracker; internal static readonly TraceLog log = new TraceLog(2048, "EnC"); private static Solution s_breakStateEntrySolution; private static EncDebuggingSessionInfo s_encDebuggingSessionInfo; private readonly IEditAndContinueWorkspaceService _encService; private readonly IActiveStatementTrackingService _trackingService; private readonly EditAndContinueDiagnosticUpdateSource _diagnosticProvider; private readonly IDebugEncNotify _debugEncNotify; private readonly INotificationService _notifications; private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService; #region Per Project State private bool _changesApplied; // maps VS Active Statement Id, which is unique within this project, to our id private Dictionary<uint, ActiveStatementId> _activeStatementIds; private ProjectAnalysisSummary _lastEditSessionSummary = ProjectAnalysisSummary.NoChanges; private HashSet<uint> _activeMethods; private List<VsExceptionRegion> _exceptionRegions; private EmitBaseline _committedBaseline; private EmitBaseline _pendingBaseline; private Project _projectBeingEmitted; private ImmutableArray<DocumentId> _documentsWithEmitError = ImmutableArray<DocumentId>.Empty; /// <summary> /// Initialized when the project switches to debug state. /// Null if the project has no output file or we can't read the MVID. /// </summary> private ModuleMetadata _metadata; private ISymUnmanagedReader3 _pdbReader; private IntPtr _pdbReaderObjAsStream; #endregion private bool IsDebuggable { get { return _metadata != null; } } internal VsENCRebuildableProjectImpl(AbstractProject project) { _vsProject = project; _encService = _vsProject.Workspace.Services.GetService<IEditAndContinueWorkspaceService>(); _trackingService = _vsProject.Workspace.Services.GetService<IActiveStatementTrackingService>(); _notifications = _vsProject.Workspace.Services.GetService<INotificationService>(); _debugEncNotify = (IDebugEncNotify)project.ServiceProvider.GetService(typeof(ShellInterop.SVsShellDebugger)); var componentModel = (IComponentModel)project.ServiceProvider.GetService(typeof(SComponentModel)); _diagnosticProvider = componentModel.GetService<EditAndContinueDiagnosticUpdateSource>(); _editorAdaptersFactoryService = componentModel.GetService<IVsEditorAdaptersFactoryService>(); Debug.Assert(_encService != null); Debug.Assert(_trackingService != null); Debug.Assert(_diagnosticProvider != null); Debug.Assert(_editorAdaptersFactoryService != null); } // called from an edit filter if an edit of a read-only buffer is attempted: internal bool OnEdit(DocumentId documentId) { if (_encService.IsProjectReadOnly(documentId.ProjectId, out var sessionReason, out var projectReason)) { OnReadOnlyDocumentEditAttempt(documentId, sessionReason, projectReason); return true; } return false; } private void OnReadOnlyDocumentEditAttempt( DocumentId documentId, SessionReadOnlyReason sessionReason, ProjectReadOnlyReason projectReason) { if (sessionReason == SessionReadOnlyReason.StoppedAtException) { _debugEncNotify.NotifyEncEditAttemptedAtInvalidStopState(); return; } var visualStudioWorkspace = _vsProject.Workspace as VisualStudioWorkspaceImpl; var hostProject = visualStudioWorkspace?.GetHostProject(documentId.ProjectId) as AbstractProject; if (hostProject?.EditAndContinueImplOpt?._metadata != null) { _debugEncNotify.NotifyEncEditDisallowedByProject(hostProject.Hierarchy); return; } // NotifyEncEditDisallowedByProject is broken if the project isn't built at the time the debugging starts (debugger bug 877586). // TODO: localize messages https://github.com/dotnet/roslyn/issues/16656 string message; if (sessionReason == SessionReadOnlyReason.Running) { message = "Changes are not allowed while code is running."; } else { Debug.Assert(sessionReason == SessionReadOnlyReason.None); switch (projectReason) { case ProjectReadOnlyReason.MetadataNotAvailable: // TODO: Remove once https://github.com/dotnet/roslyn/issues/16657 is addressed bool deferredLoad = (_vsProject.ServiceProvider.GetService(typeof(SVsSolution)) as IVsSolution7)?.IsSolutionLoadDeferred() == true; if (deferredLoad) { message = "Changes are not allowed if the project wasn't loaded and built when debugging started." + Environment.NewLine + Environment.NewLine + "'Lightweight solution load' is enabled for the current solution. " + "Disable it to ensure that all projects are loaded when debugging starts."; s_encDebuggingSessionInfo?.LogReadOnlyEditAttemptedProjectNotBuiltOrLoaded(); } else { message = "Changes are not allowed if the project wasn't built when debugging started."; } break; case ProjectReadOnlyReason.NotLoaded: message = "Changes are not allowed if the assembly has not been loaded."; break; default: throw ExceptionUtilities.UnexpectedValue(projectReason); } } _notifications.SendNotification(message, title: FeaturesResources.Edit_and_Continue1, severity: NotificationSeverity.Error); } /// <summary> /// Since we can't await asynchronous operations we need to wait for them to complete. /// The default SynchronizationContext.Wait pumps messages giving the debugger a chance to /// reenter our EnC implementation. To avoid that we use a specialized SynchronizationContext /// that doesn't pump messages. We need to make sure though that the async methods we wait for /// don't dispatch to foreground thread, otherwise we would end up in a deadlock. /// </summary> private static VsThreading.SpecializedSyncContext NonReentrantContext { get { return VsThreading.ThreadingTools.Apply(VsThreading.NoMessagePumpSyncContext.Default); } } public bool HasCustomMetadataEmitter() { return true; } /// <summary> /// Invoked when the debugger transitions from Design mode to Run mode or Break mode. /// </summary> public int StartDebuggingPE() { try { log.Write("Enter Debug Mode: project '{0}'", _vsProject.DisplayName); // EnC service is global (per solution), but the debugger calls this for each project. // Avoid starting the debug session if it has already been started. if (_encService.DebuggingSession == null) { Debug.Assert(s_debugStateProjectCount == 0); Debug.Assert(s_breakStateProjectCount == 0); Debug.Assert(s_breakStateEnteredProjects.Count == 0); _encService.OnBeforeDebuggingStateChanged(DebuggingState.Design, DebuggingState.Run); _encService.StartDebuggingSession(_vsProject.Workspace.CurrentSolution); s_encDebuggingSessionInfo = new EncDebuggingSessionInfo(); s_readOnlyDocumentTracker = new VsReadOnlyDocumentTracker(_encService, _editorAdaptersFactoryService, _vsProject); } string outputPath = _vsProject.ObjOutputPath; // The project doesn't produce a debuggable binary or we can't read it. // Continue on since the debugger ignores HResults and we need to handle subsequent calls. if (outputPath != null) { try { InjectFault_MvidRead(); _metadata = ModuleMetadata.CreateFromStream(new FileStream(outputPath, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)); _metadata.GetModuleVersionId(); } catch (FileNotFoundException) { // If the project isn't referenced by the project being debugged it might not be built. // In that case EnC is never allowed for the project, and thus we can assume the project hasn't entered debug state. log.Write("StartDebuggingPE: '{0}' metadata file not found: '{1}'", _vsProject.DisplayName, outputPath); _metadata = null; } catch (Exception e) { log.Write("StartDebuggingPE: error reading MVID of '{0}' ('{1}'): {2}", _vsProject.DisplayName, outputPath, e.Message); _metadata = null; var descriptor = new DiagnosticDescriptor("Metadata", "Metadata", ServicesVSResources.Error_while_reading_0_colon_1, DiagnosticCategory.EditAndContinue, DiagnosticSeverity.Error, isEnabledByDefault: true, customTags: DiagnosticCustomTags.EditAndContinue); _diagnosticProvider.ReportDiagnostics( new EncErrorId(_encService.DebuggingSession, EditAndContinueDiagnosticUpdateSource.DebuggerErrorId), _encService.DebuggingSession.InitialSolution, _vsProject.Id, new[] { Diagnostic.Create(descriptor, Location.None, outputPath, e.Message) }); } } else { log.Write("StartDebuggingPE: project has no output path '{0}'", _vsProject.DisplayName); _metadata = null; } if (_metadata != null) { // The debugger doesn't call EnterBreakStateOnPE for projects that don't have MVID. // However a project that's initially not loaded (but it might be in future) enters // both the debug and break states. s_debugStateProjectCount++; } _activeMethods = new HashSet<uint>(); _exceptionRegions = new List<VsExceptionRegion>(); _activeStatementIds = new Dictionary<uint, ActiveStatementId>(); // The HResult is ignored by the debugger. return VSConstants.S_OK; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } public int StopDebuggingPE() { try { log.Write("Exit Debug Mode: project '{0}'", _vsProject.DisplayName); Debug.Assert(s_breakStateEnteredProjects.Count == 0); // Clear the solution stored while projects were entering break mode. // It should be cleared as soon as all tracked projects enter the break mode // but if the entering break mode fails for some projects we should avoid leaking the solution. Debug.Assert(s_breakStateEntrySolution == null); s_breakStateEntrySolution = null; // EnC service is global (per solution), but the debugger calls this for each project. // Avoid ending the debug session if it has already been ended. if (_encService.DebuggingSession != null) { _encService.OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Design); _encService.EndDebuggingSession(); LogEncSession(); s_encDebuggingSessionInfo = null; s_readOnlyDocumentTracker.Dispose(); s_readOnlyDocumentTracker = null; } if (_metadata != null) { _metadata.Dispose(); _metadata = null; s_debugStateProjectCount--; } else { // an error might have been reported: var errorId = new EncErrorId(_encService.DebuggingSession, EditAndContinueDiagnosticUpdateSource.DebuggerErrorId); _diagnosticProvider.ClearDiagnostics(errorId, _vsProject.Workspace.CurrentSolution, _vsProject.Id, documentIdOpt: null); } _activeMethods = null; _exceptionRegions = null; _committedBaseline = null; _activeStatementIds = null; _projectBeingEmitted = null; Debug.Assert(_pdbReaderObjAsStream == IntPtr.Zero || _pdbReader == null); if (_pdbReader != null) { if (Marshal.IsComObject(_pdbReader)) { Marshal.ReleaseComObject(_pdbReader); } _pdbReader = null; } // The HResult is ignored by the debugger. return VSConstants.S_OK; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } private static void LogEncSession() { var sessionId = DebugLogMessage.GetNextId(); Logger.Log(FunctionId.Debugging_EncSession, DebugLogMessage.Create(sessionId, s_encDebuggingSessionInfo)); foreach (var editSession in s_encDebuggingSessionInfo.EditSessions) { var editSessionId = DebugLogMessage.GetNextId(); Logger.Log(FunctionId.Debugging_EncSession_EditSession, DebugLogMessage.Create(sessionId, editSessionId, editSession)); if (editSession.EmitDeltaErrorIds != null) { foreach (var error in editSession.EmitDeltaErrorIds) { Logger.Log(FunctionId.Debugging_EncSession_EditSession_EmitDeltaErrorId, DebugLogMessage.Create(sessionId, editSessionId, error)); } } foreach (var rudeEdit in editSession.RudeEdits) { Logger.Log(FunctionId.Debugging_EncSession_EditSession_RudeEdit, DebugLogMessage.Create(sessionId, editSessionId, rudeEdit, blocking: editSession.HadRudeEdits)); } } } /// <summary> /// Get MVID and file name of the project's output file. /// </summary> /// <remarks> /// The MVID is used by the debugger to identify modules loaded into debuggee that correspond to this project. /// The path seems to be unused. /// /// The output file path might be different from the path of the module loaded into the process. /// For example, the binary produced by the C# compiler is stores in obj directory, /// and then copied to bin directory from which it is loaded to the debuggee. /// /// The binary produced by the compiler can also be rewritten by post-processing tools. /// The debugger assumes that the MVID of the compiler's output file at the time we start debugging session /// is the same as the MVID of the module loaded into debuggee. The original MVID might be different though. /// </remarks> public int GetPEidentity(Guid[] pMVID, string[] pbstrPEName) { Debug.Assert(_encService.DebuggingSession != null); if (_metadata == null) { return VSConstants.E_FAIL; } if (pMVID != null && pMVID.Length != 0) { pMVID[0] = _metadata.GetModuleVersionId(); } if (pbstrPEName != null && pbstrPEName.Length != 0) { var outputPath = _vsProject.ObjOutputPath; Debug.Assert(outputPath != null); pbstrPEName[0] = Path.GetFileName(outputPath); } return VSConstants.S_OK; } /// <summary> /// Called by the debugger when entering a Break state. /// </summary> /// <param name="encBreakReason">Reason for transition to Break state.</param> /// <param name="pActiveStatements">Statements active when the debuggee is stopped.</param> /// <param name="cActiveStatements">Length of <paramref name="pActiveStatements"/>.</param> public int EnterBreakStateOnPE(Interop.ENC_BREAKSTATE_REASON encBreakReason, ShellInterop.ENC_ACTIVE_STATEMENT[] pActiveStatements, uint cActiveStatements) { try { using (NonReentrantContext) { log.Write("Enter {2}Break Mode: project '{0}', AS#: {1}", _vsProject.DisplayName, pActiveStatements != null ? pActiveStatements.Length : -1, encBreakReason == ENC_BREAKSTATE_REASON.ENC_BREAK_EXCEPTION ? "Exception " : ""); Debug.Assert(cActiveStatements == (pActiveStatements != null ? pActiveStatements.Length : 0)); Debug.Assert(s_breakStateProjectCount < s_debugStateProjectCount); Debug.Assert(s_breakStateProjectCount > 0 || _exceptionRegions.Count == 0); Debug.Assert(s_breakStateProjectCount == s_breakStateEnteredProjects.Count); Debug.Assert(IsDebuggable); if (s_breakStateEntrySolution == null) { _encService.OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Break); s_breakStateEntrySolution = _vsProject.Workspace.CurrentSolution; // TODO: This is a workaround for a debugger bug in which not all projects exit the break state. // Reset the project count. s_breakStateProjectCount = 0; } ProjectReadOnlyReason state; if (pActiveStatements != null) { AddActiveStatements(s_breakStateEntrySolution, pActiveStatements); state = ProjectReadOnlyReason.None; } else { // unfortunately the debugger doesn't provide details: state = ProjectReadOnlyReason.NotLoaded; } // If pActiveStatements is null the EnC Manager failed to retrieve the module corresponding // to the project in the debuggee. We won't include such projects in the edit session. s_breakStateEnteredProjects.Add(KeyValuePair.Create(_vsProject.Id, state)); s_breakStateProjectCount++; // EnC service is global, but the debugger calls this for each project. // Avoid starting the edit session until all projects enter break state. if (s_breakStateEnteredProjects.Count == s_debugStateProjectCount) { Debug.Assert(_encService.EditSession == null); Debug.Assert(s_pendingActiveStatements.TrueForAll(s => s.Owner._activeStatementIds.Count == 0)); var byDocument = new Dictionary<DocumentId, ImmutableArray<ActiveStatementSpan>>(); // note: fills in activeStatementIds of projects that own the active statements: GroupActiveStatements(s_pendingActiveStatements, byDocument); // When stopped at exception: All documents are read-only, but the files might be changed outside of VS. // So we start an edit session as usual and report a rude edit for all changes we see. bool stoppedAtException = encBreakReason == ENC_BREAKSTATE_REASON.ENC_BREAK_EXCEPTION; var projectStates = ImmutableDictionary.CreateRange(s_breakStateEnteredProjects); _encService.StartEditSession(s_breakStateEntrySolution, byDocument, projectStates, stoppedAtException); _trackingService.StartTracking(_encService.EditSession); s_readOnlyDocumentTracker.UpdateWorkspaceDocuments(); // When tracking is started the tagger is notified and the active statements are highlighted. // Add the handler that notifies the debugger *after* that initial tagger notification, // so that it's not triggered unless an actual change in leaf AS occurs. _trackingService.TrackingSpansChanged += TrackingSpansChanged; } } // The debugger ignores the result. return VSConstants.S_OK; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } finally { // TODO: This is a workaround for a debugger bug. // Ensure that the state gets reset even if if `GroupActiveStatements` throws an exception. if (s_breakStateEnteredProjects.Count == s_debugStateProjectCount) { // we don't need these anymore: s_pendingActiveStatements.Clear(); s_breakStateEnteredProjects.Clear(); s_breakStateEntrySolution = null; } } } private void TrackingSpansChanged(bool leafChanged) { //log.Write("Tracking spans changed: {0}", leafChanged); //if (leafChanged) //{ // // fire and forget: // Application.Current.Dispatcher.InvokeAsync(() => // { // log.Write("Notifying debugger of active statement change."); // var debugNotify = (IDebugEncNotify)_vsProject.ServiceProvider.GetService(typeof(ShellInterop.SVsShellDebugger)); // debugNotify.NotifyEncUpdateCurrentStatement(); // }); //} } private struct VsActiveStatement { public readonly DocumentId DocumentId; public readonly uint StatementId; public readonly ActiveStatementSpan Span; public readonly VsENCRebuildableProjectImpl Owner; public VsActiveStatement(VsENCRebuildableProjectImpl owner, uint statementId, DocumentId documentId, ActiveStatementSpan span) { this.Owner = owner; this.StatementId = statementId; this.DocumentId = documentId; this.Span = span; } } private struct VsExceptionRegion { public readonly uint ActiveStatementId; public readonly int Ordinal; public readonly uint MethodToken; public readonly LinePositionSpan Span; public VsExceptionRegion(uint activeStatementId, int ordinal, uint methodToken, LinePositionSpan span) { this.ActiveStatementId = activeStatementId; this.Span = span; this.MethodToken = methodToken; this.Ordinal = ordinal; } } // See InternalApis\vsl\inc\encbuild.idl private const int TEXT_POSITION_ACTIVE_STATEMENT = 1; private void AddActiveStatements(Solution solution, ShellInterop.ENC_ACTIVE_STATEMENT[] vsActiveStatements) { Debug.Assert(_activeMethods.Count == 0); Debug.Assert(_exceptionRegions.Count == 0); foreach (var vsActiveStatement in vsActiveStatements) { log.DebugWrite("+AS[{0}]: {1} {2} {3} {4} '{5}'", vsActiveStatement.id, vsActiveStatement.tsPosition.iStartLine, vsActiveStatement.tsPosition.iStartIndex, vsActiveStatement.tsPosition.iEndLine, vsActiveStatement.tsPosition.iEndIndex, vsActiveStatement.filename); // TODO (tomat): // Active statement is in user hidden code. The only information that we have from the debugger // is the method token. We don't need to track the statement (it's not in user code anyways), // but we should probably track the list of such methods in order to preserve their local variables. // Not sure what's exactly the scenario here, perhaps modifying async method/iterator? // Dev12 just ignores these. if (vsActiveStatement.posType != TEXT_POSITION_ACTIVE_STATEMENT) { continue; } var flags = (ActiveStatementFlags)vsActiveStatement.ASINFO; // Finds a document id in the solution with the specified file path. DocumentId documentId = solution.GetDocumentIdsWithFilePath(vsActiveStatement.filename) .Where(dId => dId.ProjectId == _vsProject.Id).SingleOrDefault(); if (documentId != null) { var document = solution.GetDocument(documentId); Debug.Assert(document != null); SourceText source = document.GetTextAsync(default(CancellationToken)).Result; LinePositionSpan lineSpan = vsActiveStatement.tsPosition.ToLinePositionSpan(); // If the PDB is out of sync with the source we might get bad spans. var sourceLines = source.Lines; if (lineSpan.End.Line >= sourceLines.Count || sourceLines.GetPosition(lineSpan.End) > sourceLines[sourceLines.Count - 1].EndIncludingLineBreak) { log.Write("AS out of bounds (line count is {0})", source.Lines.Count); continue; } SyntaxNode syntaxRoot = document.GetSyntaxRootAsync(default(CancellationToken)).Result; var analyzer = document.Project.LanguageServices.GetService<IEditAndContinueAnalyzer>(); s_pendingActiveStatements.Add(new VsActiveStatement( this, vsActiveStatement.id, document.Id, new ActiveStatementSpan(flags, lineSpan))); bool isLeaf = (flags & ActiveStatementFlags.LeafFrame) != 0; var ehRegions = analyzer.GetExceptionRegions(source, syntaxRoot, lineSpan, isLeaf); for (int i = 0; i < ehRegions.Length; i++) { _exceptionRegions.Add(new VsExceptionRegion( vsActiveStatement.id, i, vsActiveStatement.methodToken, ehRegions[i])); } } _activeMethods.Add(vsActiveStatement.methodToken); } } private static void GroupActiveStatements( IEnumerable<VsActiveStatement> activeStatements, Dictionary<DocumentId, ImmutableArray<ActiveStatementSpan>> byDocument) { var spans = new List<ActiveStatementSpan>(); foreach (var grouping in activeStatements.GroupBy(s => s.DocumentId)) { var documentId = grouping.Key; foreach (var activeStatement in grouping.OrderBy(s => s.Span.Span.Start)) { int ordinal = spans.Count; // register vsid with the project that owns the active statement: activeStatement.Owner._activeStatementIds.Add(activeStatement.StatementId, new ActiveStatementId(documentId, ordinal)); spans.Add(activeStatement.Span); } byDocument.Add(documentId, spans.AsImmutable()); spans.Clear(); } } /// <summary> /// Returns the number of exception regions around current active statements. /// This is called when the project is entering a break right after /// <see cref="EnterBreakStateOnPE"/> and prior to <see cref="GetExceptionSpans"/>. /// </summary> /// <remarks> /// Called by EnC manager. /// </remarks> public int GetExceptionSpanCount(out uint pcExceptionSpan) { pcExceptionSpan = (uint)_exceptionRegions.Count; return VSConstants.S_OK; } /// <summary> /// Returns information about exception handlers in the source. /// </summary> /// <remarks> /// Called by EnC manager. /// </remarks> public int GetExceptionSpans(uint celt, ShellInterop.ENC_EXCEPTION_SPAN[] rgelt, ref uint pceltFetched) { Debug.Assert(celt == rgelt.Length); Debug.Assert(celt == _exceptionRegions.Count); for (int i = 0; i < _exceptionRegions.Count; i++) { rgelt[i] = new ShellInterop.ENC_EXCEPTION_SPAN() { id = (uint)i, methodToken = _exceptionRegions[i].MethodToken, tsPosition = _exceptionRegions[i].Span.ToVsTextSpan() }; } pceltFetched = celt; return VSConstants.S_OK; } /// <summary> /// Called by the debugger whenever it needs to determine a position of an active statement. /// E.g. the user clicks on a frame in a call stack. /// </summary> /// <remarks> /// Called when applying change, when setting current IP, a notification is received from /// <see cref="IDebugEncNotify.NotifyEncUpdateCurrentStatement"/>, etc. /// In addition this API is exposed on IDebugENC2 COM interface so it can be used anytime by other components. /// </remarks> public int GetCurrentActiveStatementPosition(uint vsId, VsTextSpan[] ptsNewPosition) { try { using (NonReentrantContext) { Debug.Assert(IsDebuggable); var session = _encService.EditSession; var ids = _activeStatementIds; // Can be called anytime, even outside of an edit/debug session. // We might not have an active statement available if PDB got out of sync with the source. if (session == null || ids == null || !ids.TryGetValue(vsId, out var id)) { log.Write("GetCurrentActiveStatementPosition failed for AS {0}.", vsId); return VSConstants.E_FAIL; } Document document = _vsProject.Workspace.CurrentSolution.GetDocument(id.DocumentId); SourceText text = document.GetTextAsync(default(CancellationToken)).Result; LinePositionSpan lineSpan; // Try to get spans from the tracking service first. // We might get an imprecise result if the document analysis hasn't been finished yet and // the active statement has structurally changed, but that's ok. The user won't see an updated tag // for the statement until the analysis finishes anyways. if (_trackingService.TryGetSpan(id, text, out var span) && span.Length > 0) { lineSpan = text.Lines.GetLinePositionSpan(span); } else { var activeSpans = session.GetDocumentAnalysis(document).GetValue(default(CancellationToken)).ActiveStatements; if (activeSpans.IsDefault) { // The document has syntax errors and the tracking span is gone. log.Write("Position not available for AS {0} due to syntax errors", vsId); return VSConstants.E_FAIL; } lineSpan = activeSpans[id.Ordinal]; } ptsNewPosition[0] = lineSpan.ToVsTextSpan(); log.DebugWrite("AS position: {0} {1} {2}", vsId, lineSpan, session.BaseActiveStatements[id.DocumentId][id.Ordinal].Flags); return VSConstants.S_OK; } } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } /// <summary> /// Returns the state of the changes made to the source. /// The EnC manager calls this to determine whether there are any changes to the source /// and if so whether there are any rude edits. /// </summary> public int GetENCBuildState(ShellInterop.ENC_BUILD_STATE[] pENCBuildState) { try { using (NonReentrantContext) { Debug.Assert(pENCBuildState != null && pENCBuildState.Length == 1); // GetENCBuildState is called outside of edit session (at least) in following cases: // 1) when the debugger is determining whether a source file checksum matches the one in PDB. // 2) when the debugger is setting the next statement and a change is pending // See CDebugger::SetNextStatement(CTextPos* pTextPos, bool WarnOnFunctionChange): // // pENC2->ExitBreakState(); // >>> hr = GetCodeContextOfPosition(pTextPos, &pCodeContext, &pProgram, true, true); // pENC2->EnterBreakState(m_pSession, GetEncBreakReason()); // // The debugger seem to expect ENC_NOT_MODIFIED in these cases, otherwise errors occur. if (_changesApplied || _encService.EditSession == null) { _lastEditSessionSummary = ProjectAnalysisSummary.NoChanges; } else { // Fetch the latest snapshot of the project and get an analysis summary for any changes // made since the break mode was entered. var currentProject = _vsProject.Workspace.CurrentSolution.GetProject(_vsProject.Id); if (currentProject == null) { // If the project has yet to be loaded into the solution (which may be the case, // since they are loaded on-demand), then it stands to reason that it has not yet // been modified. // TODO (https://github.com/dotnet/roslyn/issues/1204): this check should be unnecessary. _lastEditSessionSummary = ProjectAnalysisSummary.NoChanges; log.Write($"Project '{_vsProject.DisplayName}' has not yet been loaded into the solution"); } else { _projectBeingEmitted = currentProject; _lastEditSessionSummary = GetProjectAnalysisSummary(_projectBeingEmitted); } _encService.EditSession.LogBuildState(_lastEditSessionSummary); } switch (_lastEditSessionSummary) { case ProjectAnalysisSummary.NoChanges: pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_NOT_MODIFIED; break; case ProjectAnalysisSummary.CompilationErrors: pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_COMPILE_ERRORS; break; case ProjectAnalysisSummary.RudeEdits: pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_NONCONTINUABLE_ERRORS; break; case ProjectAnalysisSummary.ValidChanges: case ProjectAnalysisSummary.ValidInsignificantChanges: // The debugger doesn't distinguish between these two. pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_APPLY_READY; break; default: throw ExceptionUtilities.Unreachable; } log.Write("EnC state of '{0}' queried: {1}{2}", _vsProject.DisplayName, pENCBuildState[0], _encService.EditSession != null ? "" : " (no session)"); return VSConstants.S_OK; } } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } private ProjectAnalysisSummary GetProjectAnalysisSummary(Project project) { if (!IsDebuggable) { return ProjectAnalysisSummary.NoChanges; } var cancellationToken = default(CancellationToken); return _encService.EditSession.GetProjectAnalysisSummaryAsync(project, cancellationToken).Result; } public int ExitBreakStateOnPE() { try { using (NonReentrantContext) { // The debugger calls Exit without previously calling Enter if the project's MVID isn't available. if (!IsDebuggable) { return VSConstants.S_OK; } log.Write("Exit Break Mode: project '{0}'", _vsProject.DisplayName); // EnC service is global, but the debugger calls this for each project. // Avoid ending the edit session if it has already been ended. if (_encService.EditSession != null) { Debug.Assert(s_breakStateProjectCount == s_debugStateProjectCount); _encService.OnBeforeDebuggingStateChanged(DebuggingState.Break, DebuggingState.Run); _encService.EditSession.LogEditSession(s_encDebuggingSessionInfo); _encService.EndEditSession(); _trackingService.EndTracking(); s_readOnlyDocumentTracker.UpdateWorkspaceDocuments(); _trackingService.TrackingSpansChanged -= TrackingSpansChanged; } _exceptionRegions.Clear(); _activeMethods.Clear(); _activeStatementIds.Clear(); s_breakStateProjectCount--; Debug.Assert(s_breakStateProjectCount >= 0); _changesApplied = false; _diagnosticProvider.ClearDiagnostics( new EncErrorId(_encService.DebuggingSession, EditAndContinueDiagnosticUpdateSource.EmitErrorId), _vsProject.Workspace.CurrentSolution, _vsProject.Id, _documentsWithEmitError); _documentsWithEmitError = ImmutableArray<DocumentId>.Empty; } // HResult ignored by the debugger return VSConstants.S_OK; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } public unsafe int BuildForEnc(object pUpdatePE) { try { log.Write("Applying changes to {0}", _vsProject.DisplayName); Debug.Assert(_encService.EditSession != null); Debug.Assert(!_encService.EditSession.StoppedAtException); // Non-debuggable project has no changes. Debug.Assert(IsDebuggable); if (_changesApplied) { log.Write("Changes already applied to {0}, can't apply again", _vsProject.DisplayName); throw ExceptionUtilities.Unreachable; } // The debugger always calls GetENCBuildState right before BuildForEnc. Debug.Assert(_projectBeingEmitted != null); Debug.Assert(_lastEditSessionSummary == GetProjectAnalysisSummary(_projectBeingEmitted)); // The debugger should have called GetENCBuildState before calling BuildForEnc. // Unfortunately, there is no way how to tell the debugger that the changes were not significant, // so we'll to emit an empty delta. See bug 839558. Debug.Assert(_lastEditSessionSummary == ProjectAnalysisSummary.ValidInsignificantChanges || _lastEditSessionSummary == ProjectAnalysisSummary.ValidChanges); var updater = (IDebugUpdateInMemoryPE2)pUpdatePE; if (_committedBaseline == null) { var hr = MarshalPdbReader(updater, out _pdbReaderObjAsStream, out _pdbReader); if (hr != VSConstants.S_OK) { return hr; } _committedBaseline = EmitBaseline.CreateInitialBaseline(_metadata, GetBaselineEncDebugInfo); } // ISymUnmanagedReader can only be accessed from an MTA thread, // so dispatch it to one of thread pool threads, which are MTA. var emitTask = Task.Factory.SafeStartNew(EmitProjectDelta, CancellationToken.None, TaskScheduler.Default); Deltas delta; using (NonReentrantContext) { delta = emitTask.Result; if (delta == null) { // Non-fatal Watson has already been reported by the emit task return VSConstants.E_FAIL; } } var errorId = new EncErrorId(_encService.DebuggingSession, EditAndContinueDiagnosticUpdateSource.EmitErrorId); // Clear diagnostics, in case the project was built before and failed due to errors. _diagnosticProvider.ClearDiagnostics(errorId, _projectBeingEmitted.Solution, _vsProject.Id, _documentsWithEmitError); if (!delta.EmitResult.Success) { var errors = delta.EmitResult.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error); _documentsWithEmitError = _diagnosticProvider.ReportDiagnostics(errorId, _projectBeingEmitted.Solution, _vsProject.Id, errors); _encService.EditSession.LogEmitProjectDeltaErrors(errors.Select(e => e.Id)); return VSConstants.E_FAIL; } _documentsWithEmitError = ImmutableArray<DocumentId>.Empty; SetFileUpdates(updater, delta.LineEdits); updater.SetDeltaIL(delta.IL.Value, (uint)delta.IL.Value.Length); updater.SetDeltaPdb(SymUnmanagedStreamFactory.CreateStream(delta.Pdb.Stream)); updater.SetRemapMethods(delta.Pdb.UpdatedMethods, (uint)delta.Pdb.UpdatedMethods.Length); updater.SetDeltaMetadata(delta.Metadata.Bytes, (uint)delta.Metadata.Bytes.Length); _pendingBaseline = delta.EmitResult.Baseline; #if DEBUG fixed (byte* deltaMetadataPtr = &delta.Metadata.Bytes[0]) { var reader = new System.Reflection.Metadata.MetadataReader(deltaMetadataPtr, delta.Metadata.Bytes.Length); var moduleDef = reader.GetModuleDefinition(); log.DebugWrite("Gen {0}: MVID={1}, BaseId={2}, EncId={3}", moduleDef.Generation, reader.GetGuid(moduleDef.Mvid), reader.GetGuid(moduleDef.BaseGenerationId), reader.GetGuid(moduleDef.GenerationId)); } #endif return VSConstants.S_OK; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } private unsafe void SetFileUpdates( IDebugUpdateInMemoryPE2 updater, List<KeyValuePair<DocumentId, ImmutableArray<LineChange>>> edits) { int totalEditCount = edits.Sum(e => e.Value.Length); if (totalEditCount == 0) { return; } var lineUpdates = new LINEUPDATE[totalEditCount]; fixed (LINEUPDATE* lineUpdatesPtr = lineUpdates) { int index = 0; var fileUpdates = new FILEUPDATE[edits.Count]; for (int f = 0; f < fileUpdates.Length; f++) { var documentId = edits[f].Key; var deltas = edits[f].Value; fileUpdates[f].FileName = _vsProject.GetDocumentOrAdditionalDocument(documentId).FilePath; fileUpdates[f].LineUpdateCount = (uint)deltas.Length; fileUpdates[f].LineUpdates = (IntPtr)(lineUpdatesPtr + index); for (int l = 0; l < deltas.Length; l++) { lineUpdates[index + l].Line = (uint)deltas[l].OldLine; lineUpdates[index + l].UpdatedLine = (uint)deltas[l].NewLine; } index += deltas.Length; } // The updater makes a copy of all data, we can release the buffer after the call. updater.SetFileUpdates(fileUpdates, (uint)fileUpdates.Length); } } private Deltas EmitProjectDelta() { Debug.Assert(Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA); var emitTask = _encService.EditSession.EmitProjectDeltaAsync(_projectBeingEmitted, _committedBaseline, default(CancellationToken)); return emitTask.Result; } /// <summary> /// Returns EnC debug information for initial version of the specified method. /// </summary> /// <exception cref="InvalidDataException">The debug information data is corrupt or can't be retrieved from the debugger.</exception> private EditAndContinueMethodDebugInformation GetBaselineEncDebugInfo(MethodDefinitionHandle methodHandle) { Debug.Assert(Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA); InitializePdbReader(); return GetEditAndContinueMethodDebugInfo(_pdbReader, methodHandle); } private void InitializePdbReader() { Debug.Assert(Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA); if (_pdbReader == null) { // Unmarshal the symbol reader (being marshalled cross thread from STA -> MTA). Debug.Assert(_pdbReaderObjAsStream != IntPtr.Zero); var exception = Marshal.GetExceptionForHR(NativeMethods.GetObjectForStream(_pdbReaderObjAsStream, out object pdbReaderObjMta)); if (exception != null) { // likely a bug in the compiler/debugger FatalError.ReportWithoutCrash(exception); throw new InvalidDataException(exception.Message, exception); } _pdbReaderObjAsStream = IntPtr.Zero; _pdbReader = (ISymUnmanagedReader3)pdbReaderObjMta; } } private static EditAndContinueMethodDebugInformation GetEditAndContinueMethodDebugInfo(ISymUnmanagedReader3 symReader, MethodDefinitionHandle methodHandle) { return TryGetPortableEncDebugInfo(symReader, methodHandle, out var info) ? info : GetNativeEncDebugInfo(symReader, methodHandle); } private static unsafe bool TryGetPortableEncDebugInfo(ISymUnmanagedReader symReader, MethodDefinitionHandle methodHandle, out EditAndContinueMethodDebugInformation info) { if (!(symReader is ISymUnmanagedReader5 symReader5)) { info = default(EditAndContinueMethodDebugInformation); return false; } int hr = symReader5.GetPortableDebugMetadataByVersion(version: 1, metadata: out byte* metadata, size: out int size); Marshal.ThrowExceptionForHR(hr); if (hr != 0) { info = default(EditAndContinueMethodDebugInformation); return false; } var pdbReader = new System.Reflection.Metadata.MetadataReader(metadata, size); ImmutableArray<byte> GetCdiBytes(Guid kind) => TryGetCustomDebugInformation(pdbReader, methodHandle, kind, out var cdi) ? pdbReader.GetBlobContent(cdi.Value) : default(ImmutableArray<byte>); info = EditAndContinueMethodDebugInformation.Create( compressedSlotMap: GetCdiBytes(PortableCustomDebugInfoKinds.EncLocalSlotMap), compressedLambdaMap: GetCdiBytes(PortableCustomDebugInfoKinds.EncLambdaAndClosureMap)); return true; } /// <exception cref="BadImageFormatException">Invalid data format.</exception> private static bool TryGetCustomDebugInformation(System.Reflection.Metadata.MetadataReader reader, EntityHandle handle, Guid kind, out CustomDebugInformation customDebugInfo) { bool foundAny = false; customDebugInfo = default(CustomDebugInformation); foreach (var infoHandle in reader.GetCustomDebugInformation(handle)) { var info = reader.GetCustomDebugInformation(infoHandle); var id = reader.GetGuid(info.Kind); if (id == kind) { if (foundAny) { throw new BadImageFormatException(); } customDebugInfo = info; foundAny = true; } } return foundAny; } private static EditAndContinueMethodDebugInformation GetNativeEncDebugInfo(ISymUnmanagedReader3 symReader, MethodDefinitionHandle methodHandle) { int methodToken = MetadataTokens.GetToken(methodHandle); byte[] debugInfo; try { debugInfo = symReader.GetCustomDebugInfoBytes(methodToken, methodVersion: 1); } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) // likely a bug in the compiler/debugger { throw new InvalidDataException(e.Message, e); } try { ImmutableArray<byte> localSlots, lambdaMap; if (debugInfo != null) { localSlots = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(debugInfo, CustomDebugInfoKind.EditAndContinueLocalSlotMap); lambdaMap = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(debugInfo, CustomDebugInfoKind.EditAndContinueLambdaMap); } else { localSlots = lambdaMap = default(ImmutableArray<byte>); } return EditAndContinueMethodDebugInformation.Create(localSlots, lambdaMap); } catch (InvalidOperationException e) when (FatalError.ReportWithoutCrash(e)) // likely a bug in the compiler/debugger { // TODO: CustomDebugInfoReader should throw InvalidDataException throw new InvalidDataException(e.Message, e); } } public int EncApplySucceeded(int hrApplyResult) { try { log.Write("Change applied to {0}", _vsProject.DisplayName); Debug.Assert(IsDebuggable); Debug.Assert(_encService.EditSession != null); Debug.Assert(!_encService.EditSession.StoppedAtException); Debug.Assert(_pendingBaseline != null); // Since now on until exiting the break state, we consider the changes applied and the project state should be NoChanges. _changesApplied = true; _committedBaseline = _pendingBaseline; _pendingBaseline = null; return VSConstants.S_OK; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } /// <summary> /// Called when changes are being applied. /// </summary> /// <param name="exceptionRegionId"> /// The value of <see cref="ShellInterop.ENC_EXCEPTION_SPAN.id"/>. /// Set by <see cref="GetExceptionSpans(uint, ShellInterop.ENC_EXCEPTION_SPAN[], ref uint)"/> to the index into <see cref="_exceptionRegions"/>. /// </param> /// <param name="ptsNewPosition">Output value holder.</param> public int GetCurrentExceptionSpanPosition(uint exceptionRegionId, VsTextSpan[] ptsNewPosition) { try { using (NonReentrantContext) { Debug.Assert(IsDebuggable); Debug.Assert(_encService.EditSession != null); Debug.Assert(!_encService.EditSession.StoppedAtException); Debug.Assert(ptsNewPosition.Length == 1); var exceptionRegion = _exceptionRegions[(int)exceptionRegionId]; var session = _encService.EditSession; var asid = _activeStatementIds[exceptionRegion.ActiveStatementId]; var document = _projectBeingEmitted.GetDocument(asid.DocumentId); var analysis = session.GetDocumentAnalysis(document).GetValue(default(CancellationToken)); var regions = analysis.ExceptionRegions; // the method shouldn't be called in presence of errors: Debug.Assert(!analysis.HasChangesAndErrors); Debug.Assert(!regions.IsDefault); // Absence of rude edits guarantees that the exception regions around AS haven't semantically changed. // Only their spans might have changed. ptsNewPosition[0] = regions[asid.Ordinal][exceptionRegion.Ordinal].ToVsTextSpan(); } return VSConstants.S_OK; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } private static int MarshalPdbReader(IDebugUpdateInMemoryPE2 updater, out IntPtr pdbReaderPointer, out ISymUnmanagedReader3 managedSymReader) { // ISymUnmanagedReader can only be accessed from an MTA thread, however, we need // fetch the IUnknown instance (call IENCSymbolReaderProvider.GetSymbolReader) here // in the STA. To further complicate things, we need to return synchronously from // this method. Waiting for the MTA thread to complete so we can return synchronously // blocks the STA thread, so we need to make sure the CLR doesn't try to marshal // ISymUnmanagedReader calls made in an MTA back to the STA for execution (if this // happens we'll be deadlocked). We'll use CoMarshalInterThreadInterfaceInStream to // achieve this. First, we'll marshal the object in a Stream and pass a Stream pointer // over to the MTA. In the MTA, we'll get the Stream from the pointer and unmarshal // the object. The reader object was originally created on an MTA thread, and the // instance we retrieved in the STA was a proxy. When we unmarshal the Stream in the // MTA, it "unwraps" the proxy, allowing us to directly call the implementation. // Another way to achieve this would be for the symbol reader to implement IAgileObject, // but the symbol reader we use today does not. If that changes, we should consider // removing this marshal/unmarshal code. updater.GetENCDebugInfo(out IENCDebugInfo debugInfo); var symbolReaderProvider = (IENCSymbolReaderProvider)debugInfo; symbolReaderProvider.GetSymbolReader(out object pdbReaderObjSta); if (Marshal.IsComObject(pdbReaderObjSta)) { int hr = NativeMethods.GetStreamForObject(pdbReaderObjSta, out pdbReaderPointer); Marshal.ReleaseComObject(pdbReaderObjSta); managedSymReader = null; return hr; } else { pdbReaderPointer = IntPtr.Zero; managedSymReader = (ISymUnmanagedReader3)pdbReaderObjSta; return 0; } } #region Testing #if DEBUG // Fault injection: // If set we'll fail to read MVID of specified projects to test error reporting. internal static ImmutableArray<string> InjectMvidReadingFailure; private void InjectFault_MvidRead() { if (!InjectMvidReadingFailure.IsDefault && InjectMvidReadingFailure.Contains(_vsProject.DisplayName)) { throw new IOException("Fault injection"); } } #else [Conditional("DEBUG")] private void InjectFault_MvidRead() { } #endif #endregion } }
// // TransientGraphUtility.cs // MSAGL class to manage transient vertices and edges for Rectilinear Edge Routing. // // Copyright Microsoft Corporation. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.Msagl.Core.Geometry; using Microsoft.Msagl.Core.Geometry.Curves; using Microsoft.Msagl.Routing.Visibility; namespace Microsoft.Msagl.Routing.Rectilinear { using DebugHelpers; internal class TransientGraphUtility { // Vertices added to the graph for routing. internal List<VisibilityVertexRectilinear> AddedVertices = new List<VisibilityVertexRectilinear>(); // Edges added to the graph for routing. internal List<TollFreeVisibilityEdge> AddedEdges = new List<TollFreeVisibilityEdge>(); // Edges joining two non-transient vertices; these must be replaced. readonly List<VisibilityEdge> edgesToRestore = new List<VisibilityEdge>(); internal bool LimitPortVisibilitySpliceToEndpointBoundingBox { get; set; } // Owned by creator of this class. VisibilityGraphGenerator GraphGenerator { get; set; } internal ObstacleTree ObstacleTree { get { return GraphGenerator.ObstacleTree; } } internal VisibilityGraph VisGraph { get { return GraphGenerator.VisibilityGraph; } } private bool IsSparseVg { get { return this.GraphGenerator is SparseVisibilityGraphGenerator; } } internal TransientGraphUtility(VisibilityGraphGenerator graphGen) { GraphGenerator = graphGen; } internal VisibilityVertex AddVertex(Point location) { var vertex = this.VisGraph.AddVertex(location); AddedVertices.Add((VisibilityVertexRectilinear)vertex); return vertex; } internal VisibilityVertex FindOrAddVertex(Point location) { var vertex = VisGraph.FindVertex(location); return vertex ?? AddVertex(location); } internal VisibilityEdge FindOrAddEdge(VisibilityVertex sourceVertex, VisibilityVertex targetVertex) { return FindOrAddEdge(sourceVertex, targetVertex, ScanSegment.NormalWeight); } internal VisibilityEdge FindOrAddEdge(VisibilityVertex sourceVertex, VisibilityVertex targetVertex, double weight) { // Since we're adding transient edges into the graph, we're not doing full intersection // evaluation; thus there may already be an edge from the source vertex in the direction // of the target vertex, but ending before or after the target vertex. Directions dirToTarget = PointComparer.GetPureDirection(sourceVertex, targetVertex); VisibilityVertex bracketSource, bracketTarget; // Is there an edge in the chain from sourceVertex in the direction of targetVertex // that brackets targetvertex? // <sourceVertex> -> ..1.. -> ..2.. <end> 3 // Yes if targetVertex is at the x above 1 or 2, No if it is at 3. If false, bracketSource // will be set to the vertex at <end> (if there are any edges in that direction at all). VisibilityVertex splitVertex = targetVertex; if (!FindBracketingVertices(sourceVertex, targetVertex.Point, dirToTarget , out bracketSource, out bracketTarget)) { // No bracketing of targetVertex from sourceVertex but bracketSource has been updated. // Is there a bracket of bracketSource from the targetVertex direction? // 3 <end> ..2.. <- ..1.. <targetVertex> // Yes if bracketSource is at the x above 1 or 2, No if it is at 3. If false, bracketTarget // will be set to the vertex at <end> (if there are any edges in that direction at all). // If true, then bracketSource and splitVertex must be updated. VisibilityVertex tempSource; if (FindBracketingVertices(targetVertex, sourceVertex.Point, CompassVector.OppositeDir(dirToTarget) , out bracketTarget, out tempSource)) { Debug.Assert(bracketSource == sourceVertex, "Mismatched bracketing detection"); bracketSource = tempSource; splitVertex = sourceVertex; } } // If null != edge then targetVertex is between bracketSource and bracketTarget and SplitEdge returns the // first half-edge (and weight is ignored as the split uses the edge weight). var edge = VisGraph.FindEdge(bracketSource.Point, bracketTarget.Point); edge = (null != edge) ? this.SplitEdge(edge, splitVertex) : CreateEdge(bracketSource, bracketTarget, weight); DevTrace_VerifyEdge(edge); return edge; } internal static bool FindBracketingVertices(VisibilityVertex sourceVertex, Point targetPoint, Directions dirToTarget , out VisibilityVertex bracketSource, out VisibilityVertex bracketTarget) { // Walk from the source to target until we bracket target or there is no nextVertex // in the desired direction. bracketSource = sourceVertex; for (; ; ) { bracketTarget = StaticGraphUtility.FindNextVertex(bracketSource, dirToTarget); if (null == bracketTarget) { break; } if (PointComparer.Equal(bracketTarget.Point, targetPoint)) { // Desired edge already exists. return true; } if (dirToTarget != PointComparer.GetPureDirection(bracketTarget.Point, targetPoint)) { // bracketTarget is past vertex in the traversal direction. break; } bracketSource = bracketTarget; } return null != bracketTarget; } [Conditional("DEVTRACE")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] // ReSharper disable InconsistentNaming void DevTrace_VerifyEdge(VisibilityEdge edge) { #if DEVTRACE if (transGraphVerify.IsLevel(1)) { Debug.Assert(PointComparer.IsPureLower(edge.SourcePoint, edge.TargetPoint), "non-ascending edge"); // For A -> B -> C, make sure there is no A -> C, and vice-versa. Simplest way to do // this is to ensure that there is only one edge in any given direction for each vertex. DevTrace_VerifyVertex(edge.Source); DevTrace_VerifyVertex(edge.Target); } #endif // DEVTRACE } #if DEVTRACE [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] void DevTrace_VerifyVertex(VisibilityVertex vertex) { if (transGraphVerify.IsLevel(1)) { Directions dir = Directions.North; for (int idir = 0; idir < 4; ++idir, dir = CompassVector.RotateRight(dir)) { int count = 0; int cEdges = vertex.InEdges.Count; // indexing is faster than foreach for Lists for (int ii = 0; ii < cEdges; ++ii) { var edge = vertex.InEdges[ii]; if (PointComparer.GetPureDirection(vertex.Point, edge.SourcePoint) == dir) { ++count; } } // Avoid GetEnumerator overhead. var outEdgeNode = vertex.OutEdges.IsEmpty() ? null : vertex.OutEdges.TreeMinimum(); for (; outEdgeNode != null; outEdgeNode = vertex.OutEdges.Next(outEdgeNode)) { var edge = outEdgeNode.Item; if (PointComparer.GetPureDirection(vertex.Point, edge.TargetPoint) == dir) { ++count; } } Debug.Assert(count < 2, "vertex has multiple edges in one direction"); } } } #endif // DEVTRACE [Conditional("DEVTRACE")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] internal void DevTrace_VerifyAllVertices(VisibilityGraph vg) { #if DEVTRACE if (transGraphVerify.IsLevel(4)) { foreach (var vertex in vg.Vertices()) { DevTrace_VerifyVertex(vertex); } } #endif // DEVTRACE } [Conditional("DEVTRACE")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] internal void DevTrace_VerifyAllEdgeIntersections(VisibilityGraph visibilityGraph) { #if DEVTRACE // By design, edges cross at non-vertices in SparseVg. if (this.IsSparseVg) { return; } if (transGraphVerify.IsLevel(4)) { var edges = visibilityGraph.Edges.ToArray(); for (int i = 0; i < edges.Length; i++) { var iEdge = edges[i]; for (int j = i + 1; j < edges.Length; j++) { var jEdge = edges[j]; Point x; if (LineSegment.Intersect(iEdge.SourcePoint, iEdge.TargetPoint, jEdge.SourcePoint, jEdge.TargetPoint, out x)) { if (!DevTrace_IsEndOfEdge(iEdge, x) && !DevTrace_IsEndOfEdge(jEdge, x)) { Debug.Assert(false, "VisibilityEdges cross at non-endpoints"); } } } } } #endif // DEVTRACE } #if DEVTRACE static bool DevTrace_IsEndOfEdge(VisibilityEdge e, Point x) { return PointComparer.Equal(e.SourcePoint, x) || PointComparer.Equal(e.TargetPoint, x); } #endif // DEVTRACE // ReSharper restore InconsistentNaming private VisibilityEdge CreateEdge(VisibilityVertex first, VisibilityVertex second, double weight) { // All edges in the graph are ascending. VisibilityVertex source = first; VisibilityVertex target = second; if (!PointComparer.IsPureLower(source.Point, target.Point)) { source = second; target = first; } var edge = new TollFreeVisibilityEdge(source, target, weight); VisibilityGraph.AddEdge(edge); this.AddedEdges.Add(edge); return edge; } internal void RemoveFromGraph() { RemoveAddedVertices(); RemoveAddedEdges(); RestoreRemovedEdges(); } private void RemoveAddedVertices() { foreach (var vertex in this.AddedVertices) { // Removing all transient vertices will remove all associated transient edges as well. if (null != this.VisGraph.FindVertex(vertex.Point)) { this.VisGraph.RemoveVertex(vertex); } } this.AddedVertices.Clear(); } private void RemoveAddedEdges() { foreach (var edge in this.AddedEdges) { // If either vertex was removed, so was the edge, so just check source. if (null != this.VisGraph.FindVertex(edge.SourcePoint)) { VisibilityGraph.RemoveEdge(edge); } } this.AddedEdges.Clear(); } private void RestoreRemovedEdges() { foreach (var edge in this.edgesToRestore) { // We should only put TransientVisibilityEdges in this list, and should never encounter // a non-transient edge in the graph after we've replaced it with a transient one, so // the edge should not be in the graph until we re-insert it. Debug.Assert(!(edge is TollFreeVisibilityEdge), "Unexpected Transient edge"); VisibilityGraph.AddEdge(edge); this.DevTrace_VerifyEdge(edge); } this.edgesToRestore.Clear(); } internal VisibilityEdge FindNextEdge(VisibilityVertex vertex, Directions dir) { return StaticGraphUtility.FindNextEdge(VisGraph, vertex, dir); } internal VisibilityEdge FindPerpendicularOrContainingEdge(VisibilityVertex startVertex , Directions dir, Point pointLocation) { // Return the edge in 'dir' from startVertex that is perpendicular to pointLocation. // startVertex must therefore be located such that pointLocation is in 'dir' direction from it, // or is on the same line. StaticGraphUtility.Assert(0 == (CompassVector.OppositeDir(dir) & PointComparer.GetDirections(startVertex.Point, pointLocation)) , "the ray from 'dir' is away from pointLocation", ObstacleTree, VisGraph); while (true) { VisibilityVertex nextVertex = StaticGraphUtility.FindNextVertex(startVertex, dir); if (null == nextVertex) { break; } Directions dirCheck = PointComparer.GetDirections(nextVertex.Point, pointLocation); // If the next vertex is past the intersection with pointLocation, this edge brackets it. if (0 != (CompassVector.OppositeDir(dir) & dirCheck)) { return VisGraph.FindEdge(startVertex.Point, nextVertex.Point); } startVertex = nextVertex; } return null; } internal VisibilityEdge FindNearestPerpendicularOrContainingEdge(VisibilityVertex startVertex , Directions dir, Point pointLocation) { // Similar to FindPerpendicularEdge, but first try to move closer to pointLocation, // as long as there are edges going in 'dir' that extend to pointLocation. Directions dirTowardLocation = ~dir & PointComparer.GetDirections(startVertex.Point, pointLocation); // If Directions. None then pointLocation is collinear. VisibilityVertex currentVertex = startVertex; Directions currentDirTowardLocation = dirTowardLocation; // First move toward pointLocation far as we can. while (Directions. None != currentDirTowardLocation) { VisibilityVertex nextVertex = StaticGraphUtility.FindNextVertex(currentVertex, dirTowardLocation); if (null == nextVertex) { break; } if (0 != (CompassVector.OppositeDir(dirTowardLocation) & PointComparer.GetDirections(nextVertex.Point, pointLocation))) { break; } currentVertex = nextVertex; currentDirTowardLocation = ~dir & PointComparer.GetDirections(currentVertex.Point, pointLocation); } // Now find the first vertex that has a chain that intersects pointLocation, if any, moving away // from pointLocation until we find it or arrive back at startVertex. VisibilityEdge perpEdge; while (true) { perpEdge = FindPerpendicularOrContainingEdge(currentVertex, dir, pointLocation); if ((null != perpEdge) || (currentVertex == startVertex)) { break; } currentVertex = StaticGraphUtility.FindNextVertex(currentVertex, CompassVector.OppositeDir(dirTowardLocation)); } return perpEdge; } internal void ConnectVertexToTargetVertex(VisibilityVertex sourceVertex, VisibilityVertex targetVertex, Directions finalEdgeDir, double weight) { // finalDir is the required direction of the final edge to the targetIntersect // (there will be two edges if we have to add a bend vertex). StaticGraphUtility.Assert(PointComparer.IsPureDirection(finalEdgeDir), "finalEdgeDir is not pure", ObstacleTree, VisGraph); // targetIntersect may be CenterVertex if that is on an extreme bend or a flat border. if (PointComparer.Equal(sourceVertex.Point, targetVertex.Point)) { return; } // If the target is collinear with sourceVertex we can just create one edge to it. Directions targetDirs = PointComparer.GetDirections(sourceVertex.Point, targetVertex.Point); if (PointComparer.IsPureDirection(targetDirs)) { FindOrAddEdge(sourceVertex, targetVertex); return; } // Not collinear so we need to create a bend vertex and edge if they don't yet exist. Point bendPoint = StaticGraphUtility.FindBendPointBetween(sourceVertex.Point, targetVertex.Point, finalEdgeDir); VisibilityVertex bendVertex = FindOrAddVertex(bendPoint); FindOrAddEdge(sourceVertex, bendVertex, weight); // Now create the outer target vertex if it doesn't exist. FindOrAddEdge(bendVertex, targetVertex, weight); } internal VisibilityVertex AddEdgeToTargetEdge(VisibilityVertex sourceVertex, VisibilityEdge targetEdge , Point targetIntersect) { StaticGraphUtility.Assert(PointComparer.Equal(sourceVertex.Point, targetIntersect) || PointComparer.IsPureDirection(sourceVertex.Point, targetIntersect) , "non-orthogonal edge request", ObstacleTree, VisGraph); StaticGraphUtility.Assert(StaticGraphUtility.PointIsOnSegment(targetEdge.SourcePoint, targetEdge.TargetPoint, targetIntersect) , "targetIntersect is not on targetEdge", ObstacleTree, VisGraph); // If the target vertex does not exist, we must split targetEdge to add it. VisibilityVertex targetVertex = VisGraph.FindVertex(targetIntersect); if (null == targetVertex) { targetVertex = AddVertex(targetIntersect); SplitEdge(targetEdge, targetVertex); } FindOrAddEdge(sourceVertex, targetVertex); return targetVertex; } internal VisibilityEdge SplitEdge(VisibilityEdge edge, VisibilityVertex splitVertex) { // If the edge is NULL it means we could not find an appropriate one, so do nothing. if (null == edge) { return null; } StaticGraphUtility.Assert(StaticGraphUtility.PointIsOnSegment(edge.SourcePoint, edge.TargetPoint, splitVertex.Point) , "splitVertex is not on edge", ObstacleTree, VisGraph); if (PointComparer.Equal(edge.Source.Point, splitVertex.Point) || PointComparer.Equal(edge.Target.Point, splitVertex.Point)) { // No split needed. return edge; } // Store the original edge, if needed. if (!(edge is TollFreeVisibilityEdge)) { edgesToRestore.Add(edge); } VisibilityGraph.RemoveEdge(edge); // If this is an overlapped edge, or we're in sparseVg, then it may be an unpadded->padded edge that crosses // over another obstacle's padded boundary, and then either a collinear splice from a free point or another // obstacle in the same cluster starts splicing from that leapfrogged boundary, so we have the edges: // A -> D | D is unpadded, A is padded border of sourceObstacle // B -> C -> E -> F | B and C are vertical ScanSegments between A and D // <-- splice direction is West | F is unpadded, E is padded border of targetObstacle // Now after splicing F to E to C to B we go A, calling FindOrAddEdge B->A; the bracketing process finds // A->D which we'll be splitting at B, which would wind up with A->B, B->C, B->D, having to Eastward // outEdges from B. See RectilinearTests.Reflection_Block1_Big_UseRect for overlapped, and // RectilinearTests.FreePortLocationRelativeToTransientVisibilityEdgesSparseVg for sparseVg. // To avoid this we add the edges in each direction from splitVertex with FindOrAddEdge. If we've // come here from a previous call to FindOrAddEdge, then that call has found the bracketing vertices, // which are the endpoints of 'edge', and we've removed 'edge', so we will not call SplitEdge again. if ((this.IsSparseVg || (edge.Weight == ScanSegment.OverlappedWeight)) && (splitVertex.Degree > 0)) { FindOrAddEdge(splitVertex, edge.Source, edge.Weight); return FindOrAddEdge(splitVertex, edge.Target, edge.Weight); } // Splice it into the graph in place of targetEdge. Return the first half, because // this may be called from AddEdge, in which case the split vertex is the target vertex. CreateEdge(splitVertex, edge.Target, edge.Weight); return CreateEdge(edge.Source, splitVertex, edge.Weight); } internal void ExtendEdgeChain(VisibilityVertex startVertex, Rectangle limitRect, LineSegment maxVisibilitySegment, PointAndCrossingsList pacList, bool isOverlapped) { var dir = PointComparer.GetDirections(maxVisibilitySegment.Start, maxVisibilitySegment.End); if (dir == Directions. None) { return; } Debug.Assert(CompassVector.IsPureDirection(dir), "impure max visibility segment"); // Shoot the edge chain out to the shorter of max visibility or intersection with the limitrect. StaticGraphUtility.Assert(PointComparer.Equal(maxVisibilitySegment.Start, startVertex.Point) || (PointComparer.GetPureDirection(maxVisibilitySegment.Start, startVertex.Point) == dir) , "Inconsistent direction found", ObstacleTree, VisGraph); double oppositeFarBound = StaticGraphUtility.GetRectangleBound(limitRect, dir); Point maxDesiredSplicePoint = StaticGraphUtility.IsVertical(dir) ? ApproximateComparer.Round(new Point(startVertex.Point.X, oppositeFarBound)) : ApproximateComparer.Round(new Point(oppositeFarBound, startVertex.Point.Y)); if (PointComparer.Equal(maxDesiredSplicePoint, startVertex.Point)) { // Nothing to do. return; } if (PointComparer.GetPureDirection(startVertex.Point, maxDesiredSplicePoint) != dir) { // It's in the opposite direction, so no need to do anything. return; } // If maxDesiredSplicePoint is shorter, create a new shorter segment. We have to pass both segments // through to the worker function so it knows whether it can go past maxDesiredSegment (which may be limited // by limitRect). var maxDesiredSegment = maxVisibilitySegment; if (PointComparer.GetDirections(maxDesiredSplicePoint, maxDesiredSegment.End) == dir) { maxDesiredSegment = new LineSegment(maxDesiredSegment.Start, maxDesiredSplicePoint); } ExtendEdgeChain(startVertex, dir, maxDesiredSegment, maxVisibilitySegment, pacList, isOverlapped); } private void ExtendEdgeChain(VisibilityVertex startVertex, Directions extendDir , LineSegment maxDesiredSegment, LineSegment maxVisibilitySegment , PointAndCrossingsList pacList, bool isOverlapped) { StaticGraphUtility.Assert(PointComparer.GetPureDirection(maxDesiredSegment.Start, maxDesiredSegment.End) == extendDir , "maxDesiredSegment is reversed", ObstacleTree, VisGraph); // Direction*s*, because it may return None, which is valid and means startVertex is on the // border of an obstacle and we don't want to go inside it. Directions segmentDir = PointComparer.GetDirections(startVertex.Point, maxDesiredSegment.End); if (segmentDir != extendDir) { // OppositeDir may happen on overlaps where the boundary has a gap in its ScanSegments due to other obstacles // overlapping it and each other. This works because the port has an edge connected to startVertex, // which is on a ScanSegment outside the obstacle. StaticGraphUtility.Assert(isOverlapped || (segmentDir != CompassVector.OppositeDir(extendDir)) , "obstacle encountered between prevPoint and startVertex", ObstacleTree, VisGraph); return; } // We'll find the segment to the left (or right if to the left doesn't exist), // then splice across in the opposite direction. Directions spliceSourceDir = CompassVector.RotateLeft(extendDir); VisibilityVertex spliceSource = StaticGraphUtility.FindNextVertex(startVertex, spliceSourceDir); if (null == spliceSource) { spliceSourceDir = CompassVector.OppositeDir(spliceSourceDir); spliceSource = StaticGraphUtility.FindNextVertex(startVertex, spliceSourceDir); if (null == spliceSource) { return; } } // Store this off before ExtendSpliceWorker, which overwrites it. Directions spliceTargetDir = CompassVector.OppositeDir(spliceSourceDir); VisibilityVertex spliceTarget; if (ExtendSpliceWorker(spliceSource, extendDir, spliceTargetDir, maxDesiredSegment, maxVisibilitySegment, isOverlapped, out spliceTarget)) { // We ended on the source side and may have dead-ends on the target side so reverse sides. ExtendSpliceWorker(spliceTarget, extendDir, spliceSourceDir, maxDesiredSegment, maxVisibilitySegment, isOverlapped, out spliceTarget); } SpliceGroupBoundaryCrossings(pacList, startVertex, maxDesiredSegment); } private void SpliceGroupBoundaryCrossings(PointAndCrossingsList crossingList, VisibilityVertex startVertex, LineSegment maxSegment) { if ((null == crossingList) || (0 == crossingList.Count)) { return; } crossingList.Reset(); var start = maxSegment.Start; var end = maxSegment.End; var dir = PointComparer.GetPureDirection(start, end); // Make sure we are going in the ascending direction. if (!StaticGraphUtility.IsAscending(dir)) { start = maxSegment.End; end = maxSegment.Start; dir = CompassVector.OppositeDir(dir); } // We need to back up to handle group crossings that are between a VisibilityBorderIntersect on a sloped border and the // incoming startVertex (which is on the first ScanSegment in Perpendicular(dir) that is outside that padded border). startVertex = TraverseToFirstVertexAtOrAbove(startVertex, start, CompassVector.OppositeDir(dir)); // Splice into the Vertices between and including the start/end points. for (var currentVertex = startVertex; null != currentVertex; currentVertex = StaticGraphUtility.FindNextVertex(currentVertex, dir)) { bool isFinalVertex = (PointComparer.Compare(currentVertex.Point, end) >= 0); while (crossingList.CurrentIsBeforeOrAt(currentVertex.Point)) { PointAndCrossings pac = crossingList.Pop(); // If it's past the start and at or before the end, splice in the crossings in the descending direction. if (PointComparer.Compare(pac.Location, startVertex.Point) > 0) { if (PointComparer.Compare(pac.Location, end) <= 0) { SpliceGroupBoundaryCrossing(currentVertex, pac, CompassVector.OppositeDir(dir)); } } // If it's at or past the start and before the end, splice in the crossings in the descending direction. if (PointComparer.Compare(pac.Location, startVertex.Point) >= 0) { if (PointComparer.Compare(pac.Location, end) < 0) { SpliceGroupBoundaryCrossing(currentVertex, pac, dir); } } } if (isFinalVertex) { break; } } } private static VisibilityVertex TraverseToFirstVertexAtOrAbove(VisibilityVertex startVertex, Point start, Directions dir) { var returnVertex = startVertex; var oppositeDir = CompassVector.OppositeDir(dir); for ( ; ; ) { var nextVertex = StaticGraphUtility.FindNextVertex(returnVertex, dir); // This returns Directions. None on a match. if ((null == nextVertex) || (PointComparer.GetDirections(nextVertex.Point, start) == oppositeDir)) { break; } returnVertex = nextVertex; } return returnVertex; } private void SpliceGroupBoundaryCrossing(VisibilityVertex currentVertex, PointAndCrossings pac, Directions dirToInside) { GroupBoundaryCrossing[] crossings = PointAndCrossingsList.ToCrossingArray(pac.Crossings, dirToInside); if (null != crossings) { var outerVertex = VisGraph.FindVertex(pac.Location) ?? AddVertex(pac.Location); if (currentVertex.Point != outerVertex.Point) { FindOrAddEdge(currentVertex, outerVertex); } var interiorPoint = crossings[0].GetInteriorVertexPoint(pac.Location); var interiorVertex = VisGraph.FindVertex(interiorPoint) ?? AddVertex(interiorPoint); // FindOrAddEdge splits an existing edge so may not return the portion bracketed by outerVertex and interiorVertex. FindOrAddEdge(outerVertex, interiorVertex); var edge = VisGraph.FindEdge(outerVertex.Point, interiorVertex.Point); var crossingsArray = crossings.Select(c => c.Group.InputShape).ToArray(); edge.IsPassable = delegate { return crossingsArray.Any(s => s.IsTransparent); }; } } // The return value is whether we should try a second pass if this is called on the first pass, // using spliceTarget to wrap up dead-ends on the target side. bool ExtendSpliceWorker(VisibilityVertex spliceSource, Directions extendDir, Directions spliceTargetDir , LineSegment maxDesiredSegment, LineSegment maxVisibilitySegment , bool isOverlapped, out VisibilityVertex spliceTarget) { // This is called after having created at least one extension vertex (initially, the // first one added outside the obstacle), so we know extendVertex will be there. spliceSource // is the vertex to the OppositeDir(spliceTargetDir) of that extendVertex. VisibilityVertex extendVertex = StaticGraphUtility.FindNextVertex(spliceSource, spliceTargetDir); spliceTarget = StaticGraphUtility.FindNextVertex(extendVertex, spliceTargetDir); for (; ; ) { if (!GetNextSpliceSource(ref spliceSource, spliceTargetDir, extendDir)) { break; } // spliceSource is now on the correct edge relative to the desired nextExtendPoint. // spliceTarget is in the opposite direction of the extension-line-to-spliceSource. Point nextExtendPoint = StaticGraphUtility.FindBendPointBetween(extendVertex.Point , spliceSource.Point, CompassVector.OppositeDir(spliceTargetDir)); // We test below for being on or past maxDesiredSegment; here we may be skipping // over maxDesiredSegmentEnd which is valid since we want to be sure to go to or // past limitRect, but be sure to stay within maxVisibilitySegment. if (IsPointPastSegmentEnd(maxVisibilitySegment, nextExtendPoint)) { break; } spliceTarget = GetSpliceTarget(ref spliceSource, spliceTargetDir, nextExtendPoint); //StaticGraphUtility.Test_DumpVisibilityGraph(ObstacleTree, VisGraph); if (null == spliceTarget) { // This may be because spliceSource was created just for Group boundaries. If so, // skip to the next nextExtendVertex location. if (this.IsSkippableSpliceSourceWithNullSpliceTarget(spliceSource, extendDir)) { continue; } // We're at a dead-end extending from the source side, or there is an intervening obstacle, or both. // Don't splice across lateral group boundaries. if (ObstacleTree.SegmentCrossesAnObstacle(spliceSource.Point, nextExtendPoint)) { return false; } } // We might be walking through a point where a previous chain dead-ended. VisibilityVertex nextExtendVertex = VisGraph.FindVertex(nextExtendPoint); if (null != nextExtendVertex) { if ((null == spliceTarget) || (null != this.VisGraph.FindEdge(extendVertex.Point, nextExtendPoint))) { // We are probably along a ScanSegment so visibility in this direction has already been determined. // Stop and don't try to continue extension from the opposite side. If we continue splicing here // it might go across an obstacle. if (null == spliceTarget) { Debug_VerifyNonOverlappedExtension(isOverlapped, extendVertex, nextExtendVertex, spliceSource:null, spliceTarget:null); FindOrAddEdge(extendVertex, nextExtendVertex, isOverlapped ? ScanSegment.OverlappedWeight : ScanSegment.NormalWeight); } return false; } // This should always have been found in the find-the-next-target loop above if there is // a vertex (which would be nextExtendVertex, which we just found) between spliceSource // and spliceTarget. Even for a sparse graph, an edge should not skip over a vertex. StaticGraphUtility.Assert(spliceTarget == StaticGraphUtility.FindNextVertex(nextExtendVertex, spliceTargetDir) , "no edge exists between an existing nextExtendVertex and spliceTarget" , ObstacleTree, VisGraph); } else { StaticGraphUtility.Assert((null == spliceTarget) || spliceTargetDir == PointComparer.GetPureDirection(nextExtendPoint, spliceTarget.Point) , "spliceTarget is not to spliceTargetDir of nextExtendVertex" , ObstacleTree, VisGraph); nextExtendVertex = this.AddVertex(nextExtendPoint); } FindOrAddEdge(extendVertex, nextExtendVertex, isOverlapped ? ScanSegment.OverlappedWeight : ScanSegment.NormalWeight); Debug_VerifyNonOverlappedExtension(isOverlapped, extendVertex, nextExtendVertex, spliceSource, spliceTarget); // This will split the edge if targetVertex is non-null; otherwise we are at a dead-end // on the target side so must not create a vertex as it would be inside an obstacle. FindOrAddEdge(spliceSource, nextExtendVertex, isOverlapped ? ScanSegment.OverlappedWeight : ScanSegment.NormalWeight); if (isOverlapped) { isOverlapped = this.SeeIfSpliceIsStillOverlapped(extendDir, nextExtendVertex); } extendVertex = nextExtendVertex; // Test GetDirections because it may return Directions. None. if (0 == (extendDir & PointComparer.GetDirections(nextExtendPoint, maxDesiredSegment.End))) { // At or past the desired max extension point, so we're done. spliceTarget = null; break; } } return null != spliceTarget; } [Conditional("DEBUG")] private void Debug_VerifyNonOverlappedExtension(bool isOverlapped, VisibilityVertex extendVertex, VisibilityVertex nextExtendVertex, VisibilityVertex spliceSource, VisibilityVertex spliceTarget) { if (isOverlapped) { return; } #if DEBUG StaticGraphUtility.Assert(!this.ObstacleTree.SegmentCrossesANonGroupObstacle(extendVertex.Point, nextExtendVertex.Point) , "extendDir edge crosses an obstacle", this.ObstacleTree, this.VisGraph); #endif // DEBUG if (spliceSource == null) { // Only verifying the direct extension. return; } // Verify lateral splices as well. if ((null == spliceTarget) || (null == this.VisGraph.FindEdge(spliceSource.Point, spliceTarget.Point) && (null == this.VisGraph.FindEdge(spliceSource.Point, nextExtendVertex.Point)))) { // If targetVertex isn't null and the proposed edge from nextExtendVertex -> targetVertex // edge doesn't already exist, then we assert that we're not creating a new edge that // crosses the obstacle bounds (a bounds-crossing edge may already exist, from a port // within the obstacle; in that case nextExtendPoint splits that edge). As above, don't // splice laterally across groups. StaticGraphUtility.Assert(!this.ObstacleTree.SegmentCrossesAnObstacle(spliceSource.Point, nextExtendVertex.Point) , "spliceSource->extendVertex edge crosses an obstacle", this.ObstacleTree, this.VisGraph); // Above we moved spliceTarget over when nextExtendVertex existed, so account // for that here. StaticGraphUtility.Assert((null == spliceTarget) || (null != this.VisGraph.FindEdge(nextExtendVertex.Point, spliceTarget.Point)) || !this.ObstacleTree.SegmentCrossesAnObstacle(nextExtendVertex.Point, spliceTarget.Point) , "extendVertex->spliceTarget edge crosses an obstacle", this.ObstacleTree, this.VisGraph); } } private static bool GetNextSpliceSource(ref VisibilityVertex spliceSource, Directions spliceTargetDir, Directions extendDir) { VisibilityVertex nextSpliceSource = StaticGraphUtility.FindNextVertex(spliceSource, extendDir); if (null == nextSpliceSource) { // See if there is a source further away from the extension line - we might have // been on freePoint line (or another nearby PortEntry line) that dead-ended. // Look laterally from the previous spliceSource first. nextSpliceSource = spliceSource; for (;;) { nextSpliceSource = StaticGraphUtility.FindNextVertex(nextSpliceSource, CompassVector.OppositeDir(spliceTargetDir)); if (null == nextSpliceSource) { return false; } var nextSpliceSourceExtend = StaticGraphUtility.FindNextVertex(nextSpliceSource, extendDir); if (null != nextSpliceSourceExtend) { nextSpliceSource = nextSpliceSourceExtend; break; } } } spliceSource = nextSpliceSource; return true; } private static VisibilityVertex GetSpliceTarget(ref VisibilityVertex spliceSource, Directions spliceTargetDir, Point nextExtendPoint) { // Look for the target. There may be a dead-ended edge starting at the current spliceSource // edge that has a vertex closer to the extension line; in that case keep walking until we // have the closest vertex on the Source side of the extension line as spliceSource. Directions prevDir = PointComparer.GetPureDirection(spliceSource.Point, nextExtendPoint); Directions nextDir = prevDir; var spliceTarget = spliceSource; while (nextDir == prevDir) { spliceSource = spliceTarget; spliceTarget = StaticGraphUtility.FindNextVertex(spliceSource, spliceTargetDir); if (null == spliceTarget) { break; } if (PointComparer.Equal(spliceTarget.Point, nextExtendPoint)) { // If we encountered an existing vertex for the extension chain, update spliceTarget // to be after it and we're done with this loop. spliceTarget = StaticGraphUtility.FindNextVertex(spliceTarget, spliceTargetDir); break; } nextDir = PointComparer.GetPureDirection(spliceTarget.Point, nextExtendPoint); } return spliceTarget; } private bool SeeIfSpliceIsStillOverlapped(Directions extendDir, VisibilityVertex nextExtendVertex) { // If we've spliced out of overlapped space into free space, we may be able to turn off the // overlapped state if we have a perpendicular non-overlapped edge. var edge = this.FindNextEdge(nextExtendVertex, CompassVector.RotateLeft(extendDir)); var maybeFreeSpace = (null == edge) ? false : (ScanSegment.NormalWeight == edge.Weight); if (!maybeFreeSpace) { edge = this.FindNextEdge(nextExtendVertex, CompassVector.RotateRight(extendDir)); maybeFreeSpace = (null == edge) ? false : (ScanSegment.NormalWeight == edge.Weight); } return !maybeFreeSpace || this.ObstacleTree.PointIsInsideAnObstacle(nextExtendVertex.Point, extendDir); } bool IsSkippableSpliceSourceWithNullSpliceTarget(VisibilityVertex spliceSource, Directions extendDir) { if (IsSkippableSpliceSourceEdgeWithNullTarget(StaticGraphUtility.FindNextEdge(VisGraph, spliceSource, extendDir))) { return true; } var spliceSourceEdge = StaticGraphUtility.FindNextEdge(this.VisGraph, spliceSource, CompassVector.OppositeDir(extendDir)); // Since target is null, if this is a reflection, it is bouncing off an outer side of a group or // obstacle at spliceSource. In that case, we don't want to splice from it because then we could // cut through the group and outside again; instead we should just stay outside it. return (IsSkippableSpliceSourceEdgeWithNullTarget(spliceSourceEdge) || IsReflectionEdge(spliceSourceEdge)); } static bool IsSkippableSpliceSourceEdgeWithNullTarget(VisibilityEdge spliceSourceEdge) { return (null != spliceSourceEdge) && (null != spliceSourceEdge.IsPassable) && (PointComparer.Equal(spliceSourceEdge.Length, GroupBoundaryCrossing.BoundaryWidth)); } static bool IsReflectionEdge(VisibilityEdge edge) { return (null != edge) && (edge.Weight == ScanSegment.ReflectionWeight); } static bool IsPointPastSegmentEnd(LineSegment maxSegment, Point point) { return PointComparer.GetDirections(maxSegment.Start, maxSegment.End) == PointComparer.GetDirections(maxSegment.End, point); } /// <summary> /// </summary> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object,System.Object)")] public override string ToString() { return string.Format("{0} {1}", AddedVertices.Count, edgesToRestore.Count); } #region DevTrace #if DEVTRACE readonly DevTrace transGraphTrace = new DevTrace("Rectilinear_TransGraphTrace", "TransGraph"); readonly DevTrace transGraphVerify = new DevTrace("Rectilinear_TransGraphVerify"); #endif // DEVTRACE #endregion // DevTrace } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace System.Data.SqlClient.SNI { /// <summary> /// MARS handle /// </summary> internal class SNIMarsHandle : SNIHandle { private const uint ACK_THRESHOLD = 2; private readonly SNIMarsConnection _connection; private readonly uint _status = TdsEnums.SNI_UNINITIALIZED; private readonly Queue<SNIPacket> _receivedPacketQueue = new Queue<SNIPacket>(); private readonly Queue<SNIMarsQueuedPacket> _sendPacketQueue = new Queue<SNIMarsQueuedPacket>(); private readonly object _callbackObject; private readonly Guid _connectionId = Guid.NewGuid(); private readonly ushort _sessionId; private readonly ManualResetEventSlim _packetEvent = new ManualResetEventSlim(false); private readonly ManualResetEventSlim _ackEvent = new ManualResetEventSlim(false); private readonly SNISMUXHeader _currentHeader = new SNISMUXHeader(); private uint _sendHighwater = 4; private int _asyncReceives = 0; private uint _receiveHighwater = 4; private uint _receiveHighwaterLastAck = 4; private uint _sequenceNumber; private SNIError _connectionError; /// <summary> /// Connection ID /// </summary> public override Guid ConnectionId { get { return _connectionId; } } /// <summary> /// Handle status /// </summary> public override uint Status { get { return _status; } } /// <summary> /// Dispose object /// </summary> public override void Dispose() { try { SendControlPacket(SNISMUXFlags.SMUX_FIN); } catch (Exception e) { SNICommon.ReportSNIError(SNIProviders.SMUX_PROV, SNICommon.InternalExceptionError, e); throw; } } /// <summary> /// Constructor /// </summary> /// <param name="connection">MARS connection</param> /// <param name="sessionId">MARS session ID</param> /// <param name="callbackObject">Callback object</param> /// <param name="async">true if connection is asynchronous</param> public SNIMarsHandle(SNIMarsConnection connection, ushort sessionId, object callbackObject, bool async) { _sessionId = sessionId; _connection = connection; _callbackObject = callbackObject; SendControlPacket(SNISMUXFlags.SMUX_SYN); _status = TdsEnums.SNI_SUCCESS; } /// <summary> /// Send control packet /// </summary> /// <param name="flags">SMUX header flags</param> private void SendControlPacket(SNISMUXFlags flags) { byte[] headerBytes = null; lock (this) { GetSMUXHeaderBytes(0, (byte)flags, ref headerBytes); } SNIPacket packet = new SNIPacket(null); packet.SetData(headerBytes, SNISMUXHeader.HEADER_LENGTH); _connection.Send(packet); } /// <summary> /// Generate SMUX header /// </summary> /// <param name="length">Packet length</param> /// <param name="flags">Packet flags</param> /// <param name="headerBytes">Header in bytes</param> private void GetSMUXHeaderBytes(int length, byte flags, ref byte[] headerBytes) { headerBytes = new byte[SNISMUXHeader.HEADER_LENGTH]; _currentHeader.SMID = 83; _currentHeader.flags = flags; _currentHeader.sessionId = _sessionId; _currentHeader.length = (uint)SNISMUXHeader.HEADER_LENGTH + (uint)length; _currentHeader.sequenceNumber = ((flags == (byte)SNISMUXFlags.SMUX_FIN) || (flags == (byte)SNISMUXFlags.SMUX_ACK)) ? _sequenceNumber - 1 : _sequenceNumber++; _currentHeader.highwater = _receiveHighwater; _receiveHighwaterLastAck = _currentHeader.highwater; BitConverter.GetBytes(_currentHeader.SMID).CopyTo(headerBytes, 0); BitConverter.GetBytes(_currentHeader.flags).CopyTo(headerBytes, 1); BitConverter.GetBytes(_currentHeader.sessionId).CopyTo(headerBytes, 2); BitConverter.GetBytes(_currentHeader.length).CopyTo(headerBytes, 4); BitConverter.GetBytes(_currentHeader.sequenceNumber).CopyTo(headerBytes, 8); BitConverter.GetBytes(_currentHeader.highwater).CopyTo(headerBytes, 12); } /// <summary> /// Generate a packet with SMUX header /// </summary> /// <param name="packet">SNI packet</param> /// <returns>Encapsulated SNI packet</returns> private SNIPacket GetSMUXEncapsulatedPacket(SNIPacket packet) { uint xSequenceNumber = _sequenceNumber; byte[] headerBytes = null; GetSMUXHeaderBytes(packet.Length, (byte)SNISMUXFlags.SMUX_DATA, ref headerBytes); SNIPacket smuxPacket = new SNIPacket(null); smuxPacket.Description = string.Format("({0}) SMUX packet {1}", packet.Description == null ? "" : packet.Description, xSequenceNumber); smuxPacket.Allocate(16 + packet.Length); smuxPacket.AppendData(headerBytes, 16); smuxPacket.AppendPacket(packet); return smuxPacket; } /// Send a packet synchronously /// </summary> /// <param name="packet">SNI packet</param> /// <returns>SNI error code</returns> public override uint Send(SNIPacket packet) { while (true) { lock (this) { if (_sequenceNumber < _sendHighwater) { break; } } _ackEvent.Wait(); lock (this) { _ackEvent.Reset(); } } return _connection.Send(GetSMUXEncapsulatedPacket(packet)); } /// <summary> /// Send packet asynchronously /// </summary> /// <param name="packet">SNI packet</param> /// <param name="callback">Completion callback</param> /// <returns>SNI error code</returns> private uint InternalSendAsync(SNIPacket packet, SNIAsyncCallback callback) { SNIPacket encapsulatedPacket = null; lock (this) { if (_sequenceNumber >= _sendHighwater) { return TdsEnums.SNI_QUEUE_FULL; } encapsulatedPacket = GetSMUXEncapsulatedPacket(packet); if (callback != null) { encapsulatedPacket.SetCompletionCallback(callback); } else { encapsulatedPacket.SetCompletionCallback(HandleSendComplete); } return _connection.SendAsync(encapsulatedPacket, callback); } } /// <summary> /// Send pending packets /// </summary> /// <returns>SNI error code</returns> private uint SendPendingPackets() { SNIMarsQueuedPacket packet = null; while (true) { lock (this) { if (_sequenceNumber < _sendHighwater) { if (_sendPacketQueue.Count != 0) { packet = _sendPacketQueue.Peek(); uint result = InternalSendAsync(packet.Packet, packet.Callback); if (result != TdsEnums.SNI_SUCCESS && result != TdsEnums.SNI_SUCCESS_IO_PENDING) { return result; } _sendPacketQueue.Dequeue(); continue; } else { _ackEvent.Set(); } } break; } } return TdsEnums.SNI_SUCCESS; } /// <summary> /// Send a packet asynchronously /// </summary> /// <param name="packet">SNI packet</param> /// <param name="callback">Completion callback</param> /// <returns>SNI error code</returns> public override uint SendAsync(SNIPacket packet, SNIAsyncCallback callback = null) { lock (this) { _sendPacketQueue.Enqueue(new SNIMarsQueuedPacket(packet, callback != null ? callback : HandleSendComplete)); } SendPendingPackets(); return TdsEnums.SNI_SUCCESS_IO_PENDING; } /// <summary> /// Receive a packet asynchronously /// </summary> /// <param name="packet">SNI packet</param> /// <returns>SNI error code</returns> public override uint ReceiveAsync(ref SNIPacket packet, bool isMars = true) { lock (_receivedPacketQueue) { int queueCount = _receivedPacketQueue.Count; if (_connectionError != null) { return SNICommon.ReportSNIError(_connectionError); } if (queueCount == 0) { _asyncReceives++; return TdsEnums.SNI_SUCCESS_IO_PENDING; } packet = _receivedPacketQueue.Dequeue(); if (queueCount == 1) { _packetEvent.Reset(); } } lock (this) { _receiveHighwater++; } SendAckIfNecessary(); return TdsEnums.SNI_SUCCESS; } /// <summary> /// Handle receive error /// </summary> public void HandleReceiveError(SNIPacket packet) { lock (_receivedPacketQueue) { _connectionError = SNILoadHandle.SingletonInstance.LastError; _packetEvent.Set(); } ((TdsParserStateObject)_callbackObject).ReadAsyncCallback(packet, 1); } /// <summary> /// Handle send completion /// </summary> /// <param name="packet">SNI packet</param> /// <param name="sniErrorCode">SNI error code</param> public void HandleSendComplete(SNIPacket packet, uint sniErrorCode) { lock (this) { Debug.Assert(_callbackObject != null); ((TdsParserStateObject)_callbackObject).WriteAsyncCallback(packet, sniErrorCode); } } /// <summary> /// Handle SMUX acknowledgement /// </summary> /// <param name="highwater">Send highwater mark</param> public void HandleAck(uint highwater) { lock (this) { if (_sendHighwater != highwater) { _sendHighwater = highwater; SendPendingPackets(); } } } /// <summary> /// Handle receive completion /// </summary> /// <param name="packet">SNI packet</param> /// <param name="header">SMUX header</param> public void HandleReceiveComplete(SNIPacket packet, SNISMUXHeader header) { lock (this) { if (_sendHighwater != header.highwater) { HandleAck(header.highwater); } lock (_receivedPacketQueue) { if (_asyncReceives == 0) { _receivedPacketQueue.Enqueue(packet); _packetEvent.Set(); return; } _asyncReceives--; Debug.Assert(_callbackObject != null); ((TdsParserStateObject)_callbackObject).ReadAsyncCallback(packet, 0); } } lock (this) { _receiveHighwater++; } SendAckIfNecessary(); } /// <summary> /// Send ACK if we've hit highwater threshold /// </summary> private void SendAckIfNecessary() { uint receiveHighwater; uint receiveHighwaterLastAck; lock (this) { receiveHighwater = _receiveHighwater; receiveHighwaterLastAck = _receiveHighwaterLastAck; } if (receiveHighwater - receiveHighwaterLastAck > ACK_THRESHOLD) { SendControlPacket(SNISMUXFlags.SMUX_ACK); } } /// <summary> /// Receive a packet synchronously /// </summary> /// <param name="packet">SNI packet</param> /// <param name="timeoutInMilliseconds">Timeout in Milliseconds</param> /// <returns>SNI error code</returns> public override uint Receive(out SNIPacket packet, int timeoutInMilliseconds) { packet = null; int queueCount; uint result = TdsEnums.SNI_SUCCESS_IO_PENDING; while (true) { lock (_receivedPacketQueue) { if (_connectionError != null) { return SNICommon.ReportSNIError(_connectionError); } queueCount = _receivedPacketQueue.Count; if (queueCount > 0) { packet = _receivedPacketQueue.Dequeue(); if (queueCount == 1) { _packetEvent.Reset(); } result = TdsEnums.SNI_SUCCESS; } } if (result == TdsEnums.SNI_SUCCESS) { lock (this) { _receiveHighwater++; } SendAckIfNecessary(); return result; } if (!_packetEvent.Wait(timeoutInMilliseconds)) { SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.SMUX_PROV, 0, SNICommon.ConnTimeoutError, string.Empty); return TdsEnums.SNI_WAIT_TIMEOUT; } } } /// <summary> /// Check SNI handle connection /// </summary> /// <param name="handle"></param> /// <returns>SNI error status</returns> public override uint CheckConnection() { return _connection.CheckConnection(); } /// <summary> /// Set async callbacks /// </summary> /// <param name="receiveCallback">Receive callback</param> /// <param name="sendCallback">Send callback</param> public override void SetAsyncCallbacks(SNIAsyncCallback receiveCallback, SNIAsyncCallback sendCallback) { } /// <summary> /// Set buffer size /// </summary> /// <param name="bufferSize">Buffer size</param> public override void SetBufferSize(int bufferSize) { } /// <summary> /// Enable SSL /// </summary> public override uint EnableSsl(uint options) { return _connection.EnableSsl(options); } /// <summary> /// Disable SSL /// </summary> public override void DisableSsl() { _connection.DisableSsl(); } #if DEBUG /// <summary> /// Test handle for killing underlying connection /// </summary> public override void KillConnection() { _connection.KillConnection(); } #endif } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections; using System.Globalization; using System.IO; using System.Text; using System.Web; using mshtml; using OpenLiveWriter.HtmlParser.Parser; using OpenLiveWriter.Interop.Com; using OpenLiveWriter.Interop.Com.ActiveDocuments; using OpenLiveWriter.Interop.SHDocVw; namespace OpenLiveWriter.CoreServices { public class UrlInfo { public string TagName { get { return _tagName; } } public string Url { get { return _url; } } public string Name { get { if (_name == null || _name.Trim() == string.Empty) { _name = UrlHelper.GetFileNameWithoutExtensionForUrl(Url); if (_name == string.Empty) _name = Url; } return _name; } } private string _name; private string _tagName; private string _url; public UrlInfo(string url, string tagName) : this(null, url, tagName) { } public UrlInfo(string name, string url, string tagName) { _name = name; if (_name != null) { _name = _name.Replace("\r\n", " "); _name = _name.Replace("\n", " "); _name = _name.Replace("\r", " "); } _url = url; _tagName = tagName; } } public class LightWeightTag { public LightWeightTag(BeginTag tag) { _beginTag = tag; } private BeginTag _beginTag = null; public string Name { get { return _name; } set { _name = value; } } private string _name; public BeginTag BeginTag { get { return _beginTag; } } } /// <summary> /// Summary description for LightweightHTMLDocument. /// </summary> public class LightWeightHTMLDocument : LightWeightHTMLDocumentIterator { public static LightWeightHTMLDocument FromString(string html, string baseUrl) { return LightWeightHTMLDocument.FromString(html, baseUrl, true); } public static LightWeightHTMLDocument FromString(string html, string baseUrl, bool escapePaths) { return FromString(html, baseUrl, null, escapePaths); } public static LightWeightHTMLDocument FromString(string html, string baseUrl, string name, bool escapePaths) { string escapedHtml = html; if (escapePaths) escapedHtml = LightWeightHTMLUrlToAbsolute.ConvertToAbsolute(html, baseUrl); LightWeightHTMLDocument escapedDocument = new LightWeightHTMLDocument(escapedHtml, baseUrl, name); HTMLDocumentHelper.SpecialHeaders specialHeaders = HTMLDocumentHelper.GetSpecialHeaders(escapedHtml, baseUrl); escapedDocument._docType = specialHeaders.DocType; escapedDocument._savedFrom = specialHeaders.SavedFrom; escapedDocument.Parse(); return escapedDocument; } public static LightWeightHTMLDocument FromStream(Stream stream, string url) { return FromStream(stream, url, null); } public static LightWeightHTMLDocument FromStream(Stream stream, string url, string name) { if (!stream.CanSeek) { string filePath = TempFileManager.Instance.CreateTempFile(); using (FileStream file = new FileStream(filePath, FileMode.Open)) StreamHelper.Transfer(stream, file); return LightWeightHTMLDocument.FromFile(filePath, url, name); } else { Encoding currentEncoding = Encoding.Default; LightWeightHTMLDocument lwDoc = null; using (StreamReader reader = new StreamReader(stream, currentEncoding)) { lwDoc = LightWeightHTMLDocument.FromString(reader.ReadToEnd(), url, name, true); // If there is no metadata that disagrees with our encoding, just return the DOM read with default decoding LightWeightHTMLMetaData metaData = new LightWeightHTMLMetaData(lwDoc); if (metaData != null && metaData.Charset != null) { try { // The decoding is different than the encoding used to read this document, reread it with correct encoding Encoding encoding = Encoding.GetEncoding(metaData.Charset); if (encoding != currentEncoding) { reader.DiscardBufferedData(); stream.Seek(0, SeekOrigin.Begin); using (StreamReader reader2 = new StreamReader(stream, encoding)) { lwDoc = LightWeightHTMLDocument.FromString(reader2.ReadToEnd(), url, name, true); } } } catch (NotSupportedException) { // The encoding isn't supported on this system } catch (ArgumentException) { // The encoding isn't an encoding that the OS even knows about (its probably // not well formatted or misspelled or something) } } } return lwDoc; } } public static LightWeightHTMLDocument FromFile(string filePath, string url) { return FromFile(filePath, url, null); } public static LightWeightHTMLDocument FromFile(string filePath, string url, string name) { using (Stream s = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 8192)) { return FromStream(s, url, name); } } public static LightWeightHTMLDocument FromIHTMLDocument2(IHTMLDocument2 htmlDocument, string url) { if (htmlDocument == null) return null; return LightWeightHTMLDocument.FromIHTMLDocument2(htmlDocument, url, true); } public static LightWeightHTMLDocument FromIHTMLDocument2(IHTMLDocument2 htmlDocument, string url, bool escapePaths) { if (htmlDocument == null) return null; return LightWeightHTMLDocument.FromIHTMLDocument2(htmlDocument, url, null, escapePaths); } private static LightWeightHTMLDocument FromIHTMLDocument2(IHTMLDocument2 htmlDocument, string url, string name) { return LightWeightHTMLDocument.FromIHTMLDocument2(htmlDocument, url, name, true); } public static LightWeightHTMLDocument FromIHTMLDocument2(IHTMLDocument2 htmlDocument, string url, bool escapePaths, bool escapeEmptyString) { if (htmlDocument == null) return null; return LightWeightHTMLDocument.FromIHTMLDocument2(htmlDocument, url, null, escapePaths, escapeEmptyString); } private static LightWeightHTMLDocument FromIHTMLDocument2(IHTMLDocument2 htmlDocument, string url, string name, bool escapePaths) { return LightWeightHTMLDocument.FromIHTMLDocument2(htmlDocument, url, name, escapePaths, true); } private static LightWeightHTMLDocument FromIHTMLDocument2(IHTMLDocument2 htmlDocument, string url, string name, bool escapePaths, bool escapeEmptyString) { string escapedHtml = HTMLDocumentHelper.HTMLDocToString(htmlDocument); if (escapedHtml == null) return null; if (escapePaths) escapedHtml = LightWeightHTMLUrlToAbsolute.ConvertToAbsolute(escapedHtml, url, true, escapeEmptyString); LightWeightHTMLDocument finalDocument = new LightWeightHTMLDocument(escapedHtml, url, name); // Set the Frames finalDocument.SetFrames(GetLightWeightDocumentForFrames(htmlDocument)); // Set the styles finalDocument.SetStyleReferences(HTMLDocumentHelper.GetStyleReferencesForDocument(htmlDocument, url)); // Set the DocType HTMLDocumentHelper.SpecialHeaders specialHeaders = HTMLDocumentHelper.GetSpecialHeaders(htmlDocument); finalDocument._docType = specialHeaders.DocType; finalDocument._savedFrom = specialHeaders.SavedFrom; finalDocument.Parse(); return finalDocument; } public static LightWeightHTMLDocument[] GetLightWeightDocumentForFrames(IHTMLDocument2 htmlDocument) { ArrayList frameLightWeightDocuments = new ArrayList(); // Get the IOleContainer for the for the html document (this requires that // the document is the root document in the browser) IOleContainer oleContainer = (IOleContainer)htmlDocument; IEnumUnknown enumUnknown; // Enumerate the controls in the browser oleContainer.EnumObjects(OLECONTF.EMBEDDINGS, out enumUnknown); // Iterate through the controls object unknown; for (int i = 0; HRESULT.S_OK == enumUnknown.Next(1, out unknown, IntPtr.Zero); i++) { // Only subframes should cast to IWebBrowser2 IWebBrowser2 webBrowser = unknown as IWebBrowser2; // Since it is a subframe, we can also get the base frame implementation for it IHTMLFrameBase frameBase = unknown as IHTMLFrameBase; // It's a frame, add this to the list! if (webBrowser != null) { try { IHTMLDocument2 frameDocument = webBrowser.Document as IHTMLDocument2; if (frameDocument != null) { LightWeightHTMLDocument document = LightWeightHTMLDocument.FromIHTMLDocument2(frameDocument, frameDocument.url, frameBase.name); if (document != null) frameLightWeightDocuments.Add(document); } } catch (InvalidCastException) { string html = "<HTML></HTML>"; LightWeightHTMLDocument document = LightWeightHTMLDocument.FromString(html, webBrowser.LocationURL, webBrowser.LocationURL, true); if (document != null) frameLightWeightDocuments.Add(document); } } } return (LightWeightHTMLDocument[])frameLightWeightDocuments.ToArray(typeof(LightWeightHTMLDocument)); } public LightWeightTag[] GetTagsByName(string name) { string key = name.ToUpper(CultureInfo.InvariantCulture); if (_tagTable.ContainsKey(key)) return (LightWeightTag[])_tagTable[key]; else return new LightWeightTag[0]; } private Hashtable _tagTable = new Hashtable(); public LightWeightHTMLDocument[] Frames { get { return _frames; } } public HTMLDocumentHelper.ResourceUrlInfo[] StyleResourcesUrls { get { return _styleResourceUrls; } } public string DocType { get { return _docType; } } private string _docType = null; public string ContentType { get { return _contentType; } set { _contentType = value; } } private string _contentType = null; public string SavedFrom { get { return _savedFrom; } } private string _savedFrom = null; /// Changed this from private to public public void SetFrames(LightWeightHTMLDocument[] frames) { _frames = frames; } public void UpdateBasedUponHTMLDocumentData(IHTMLDocument2 document, string baseUrl) { if (_frames == null) SetFrames(GetLightWeightDocumentForFrames(document)); if (_styleResourceUrls == null) SetStyleReferences(HTMLDocumentHelper.GetStyleReferencesForDocument(document, baseUrl)); } public void SetStyleReferences(HTMLDocumentHelper.ResourceUrlInfo[] styleResourceUrls) { _styleResourceUrls = styleResourceUrls; } private HTMLDocumentHelper.ResourceUrlInfo[] _styleResourceUrls = null; private LightWeightHTMLDocument[] _frames = null; public LightWeightHTMLDocument Clone() { return new LightWeightHTMLDocument(Html, Url); } public string Title { get { if (_title == null) _title = Url; return _title; } } private string _title = null; public string Name { get { return _name; } } private string _name = null; public bool HasFramesOrStyles { get { if (!_hasFramesOrStylesInit) { _hasFramesOrStyles = (GetTagsByName(HTMLTokens.Style).Length > 0 || GetTagsByName(HTMLTokens.Frame).Length > 0 || GetTagsByName(HTMLTokens.IFrame).Length > 0 || GetTagsByName(HTMLTokens.Link).Length > 0); _hasFramesOrStylesInit = true; } return _hasFramesOrStyles; } } private bool _hasFramesOrStyles = false; private bool _hasFramesOrStylesInit = false; public LightWeightHTMLMetaData MetaData { get { if (_metaData == null) _metaData = new LightWeightHTMLMetaData(this); return _metaData; } } private LightWeightHTMLMetaData _metaData = null; public UrlInfo[] ResourceUrlInfos { get { if (!_generated) { // Handle regular tags ArrayList urls = GetUrlInfosForTable(ResourceElements); // Handle Literals foreach (UrlInfo urlInfo in _literalUrlInfos) { urls.Add(urlInfo); } // Handle Params LightWeightTag[] paramTags = GetTagsByName(HTMLTokens.Param); foreach (LightWeightTag param in paramTags) { foreach (string paramValue in ParamsUrlElements) { Attr attr = param.BeginTag.GetAttribute(HTMLTokens.Name); if (attr != null) { if (attr.Value != null && attr.Value.ToUpperInvariant() == paramValue.ToUpperInvariant()) { Attr valueAttr = param.BeginTag.GetAttribute(HTMLTokens.Value); if (valueAttr != null) urls.Add(new UrlInfo(valueAttr.Value, HTMLTokens.Param)); } } } } // Handle Links LightWeightTag[] linkTags = GetTagsByName(HTMLTokens.Link); foreach (LightWeightTag link in linkTags) { foreach (string linkRelValue in LinksUrlElements) { Attr attr = link.BeginTag.GetAttribute(HTMLTokens.Rel); if (attr != null) { if (attr.Value != null && attr.Value.ToLower(CultureInfo.InvariantCulture) == linkRelValue.ToLower(CultureInfo.InvariantCulture)) { Attr hrefAttr = link.BeginTag.GetAttribute(HTMLTokens.Href); if (hrefAttr != null) urls.Add(new UrlInfo(hrefAttr.Value, HTMLTokens.Link)); } } } } _resourceUrlInfos.AddRange(urls); _generated = true; } return (UrlInfo[])_resourceUrlInfos.ToArray(typeof(UrlInfo)); } } private ArrayList _resourceUrlInfos = new ArrayList(); private bool _generated = false; public void AddReference(UrlInfo urlInfo) { if (!_resourceUrlInfos.Contains(urlInfo)) _resourceUrlInfos.Add(urlInfo); } public UrlInfo[] UserVisibleUrlInfos { get { if (_userVisibleUrlInfos == null) _userVisibleUrlInfos = (UrlInfo[])GetUrlInfosForTable(UserVisibleElements).ToArray(typeof(UrlInfo)); return _userVisibleUrlInfos; } } private UrlInfo[] _userVisibleUrlInfos = null; public UrlInfo[] Anchors { get { if (_anchors == null) _anchors = (UrlInfo[])GetUrlInfosForTable(AnchorElements).ToArray(typeof(UrlInfo)); return _anchors; } } private UrlInfo[] _anchors = null; public UrlInfo[] NonResourceUrlInfos { get { if (_nonResourceUrlInfos == null) _nonResourceUrlInfos = (UrlInfo[])GetUrlInfosForTable(NonResourceElements).ToArray(typeof(UrlInfo)); return _nonResourceUrlInfos; } } private UrlInfo[] _nonResourceUrlInfos = null; public string GenerateHtml() { return Generator.DoReplace(); } public string RawHtml { get { return this.Html; } } private LightWeightHTMLReplacer Generator { get { if (_generator == null) _generator = new LightWeightHTMLReplacer(Html, Url, MetaData); return _generator; } } private LightWeightHTMLReplacer _generator = null; public void AddUrlToEscape(UrlToReplace urlToReplace) { Generator.AddUrlToReplace(urlToReplace); } protected LightWeightHTMLDocument(string html, string url) : this(html, url, null) { } protected LightWeightHTMLDocument(string html, string url, string name) : base(html) { _url = url; _name = name; } public string Url { get { if (_url == null) _url = string.Empty; return _url; } set { _url = value; } } private string _url; public void AddSubstitionUrl(UrlToReplace urlToReplace) { Generator.AddUrlToReplace(urlToReplace); } private LightWeightHTMLDocument GetFrameDocumentByName(string name) { if (name == null) return null; foreach (LightWeightHTMLDocument frameDoc in _frames) if (frameDoc.Name == name) return frameDoc; return null; } protected override void OnBeginTag(BeginTag tag) { if (tag != null) { // Reset any frame urls // This is done because the HTML that is often in this document may have // incorrect urls for frames. The frames enumeration is accurate, so if the // name from the frames enumeration is the same as this frame, we should fix its // url up. if (tag.NameEquals(HTMLTokens.Frame)) { Attr name = tag.GetAttribute(HTMLTokens.Name); if (name != null && this._frames != null) { LightWeightHTMLDocument frameDoc = GetFrameDocumentByName(name.Value); if (frameDoc != null) { Attr src = tag.GetAttribute(HTMLTokens.Src); if (src != null && src.Value != frameDoc.Url) Generator.AddSubstitionUrl(new UrlToReplace(src.Value, frameDoc.Url)); } } } LightWeightTag currentTag = new LightWeightTag(tag); // The key we'll use for the table string key = tag.Name.ToUpper(CultureInfo.InvariantCulture); if (!_tagTable.ContainsKey(key)) _tagTable[key] = new LightWeightTag[0]; LightWeightTag[] currentTags = (LightWeightTag[])_tagTable[key]; LightWeightTag[] grownTags = new LightWeightTag[currentTags.Length + 1]; currentTags.CopyTo(grownTags, 0); grownTags[currentTags.Length] = currentTag; _tagTable[key] = grownTags; // Accumulate the title text if (tag.NameEquals(HTMLTokens.Title) && !tag.Complete) _nextTextIsTitleText = true; else if (tag.NameEquals(HTMLTokens.A) && !tag.Complete && tag.GetAttribute(HTMLTokens.Href) != null) { if (_collectingForTag != null) { if (tag.NameEquals(HTMLTokens.A)) _collectingForTagDepth++; } else _collectingForTag = currentTag; } } base.OnBeginTag(tag); } private bool _nextTextIsTitleText = false; private LightWeightTag _collectingForTag = null; private int _collectingForTagDepth = 0; protected override void OnEndTag(EndTag tag) { if (_collectingForTag != null) { if (tag.NameEquals(HTMLTokens.A)) { if (_collectingForTagDepth == 0) _collectingForTag = null; else _collectingForTagDepth--; } } base.OnEndTag(tag); } protected override void OnText(Text text) { if (_nextTextIsTitleText) { _title = HttpUtility.HtmlDecode(text.ToString()); _nextTextIsTitleText = false; } if (_collectingForTag != null) _collectingForTag.Name = _collectingForTag.Name + text.RawText; base.OnText(text); } protected override void OnStyleUrl(StyleUrl styleUrl) { _literalUrlInfos.Add(new UrlInfo(styleUrl.LiteralText, HTMLTokens.Style)); base.OnStyleUrl(styleUrl); } private ArrayList _literalUrlInfos = new ArrayList(); protected override void OnStyleImport(StyleImport styleImport) { _styleImports.Add(new UrlInfo(styleImport.LiteralText, HTMLTokens.Import)); base.OnStyleImport(styleImport); } private ArrayList _styleImports = new ArrayList(); private ArrayList GetUrlInfosForTable(Hashtable elementTable) { ArrayList urlInfos = new ArrayList(); foreach (string tagName in elementTable.Keys) { LightWeightTag[] tags = GetTagsByName(tagName); foreach (LightWeightTag tag in tags) { string attrValue = tag.BeginTag.GetAttributeValue((string)elementTable[tagName]); if (attrValue != null) { if (!UrlHelper.IsUrl(attrValue)) attrValue = UrlHelper.EscapeRelativeURL(_url, attrValue); urlInfos.Add(new UrlInfo(tag.Name, attrValue, tag.BeginTag.Name)); } } } return urlInfos; } static LightWeightHTMLDocument() { m_resourceElements = new Hashtable(); m_resourceElements.Add(HTMLTokens.Img, HTMLTokens.Src); m_resourceElements.Add(HTMLTokens.Object, HTMLTokens.Src); m_resourceElements.Add(HTMLTokens.Embed, HTMLTokens.Src); m_resourceElements.Add(HTMLTokens.Param, HTMLTokens.Value); //required for movies embeded using object tag m_resourceElements.Add(HTMLTokens.Script, HTMLTokens.Src); m_resourceElements.Add(HTMLTokens.Body, HTMLTokens.Background); m_resourceElements.Add(HTMLTokens.Input, HTMLTokens.Src); m_resourceElements.Add(HTMLTokens.Td, HTMLTokens.Background); m_resourceElements.Add(HTMLTokens.Tr, HTMLTokens.Background); m_resourceElements.Add(HTMLTokens.Table, HTMLTokens.Background); m_anchors = new Hashtable(); m_anchors.Add(HTMLTokens.A, HTMLTokens.Href); m_anchors.Add(HTMLTokens.Area, HTMLTokens.Href); m_userVisibleElements = new Hashtable(); m_userVisibleElements.Add(HTMLTokens.Img, HTMLTokens.Src); m_userVisibleElements.Add(HTMLTokens.Object, HTMLTokens.Src); m_userVisibleElements.Add(HTMLTokens.Embed, HTMLTokens.Src); m_userVisibleElements.Add(HTMLTokens.Body, HTMLTokens.Background); m_userVisibleElements.Add(HTMLTokens.Input, HTMLTokens.Src); m_userVisibleElements.Add(HTMLTokens.Td, HTMLTokens.Background); m_userVisibleElements.Add(HTMLTokens.Tr, HTMLTokens.Background); m_userVisibleElements.Add(HTMLTokens.Table, HTMLTokens.Background); m_nonResourceElements = new Hashtable(); m_nonResourceElements.Add(HTMLTokens.Form, HTMLTokens.Action); m_nonResourceElements.Add(HTMLTokens.A, HTMLTokens.Href); m_nonResourceElements.Add(HTMLTokens.Link, HTMLTokens.Href); m_nonResourceElements.Add(HTMLTokens.Area, HTMLTokens.Href); _frameElements = new Hashtable(); _frameElements.Add(HTMLTokens.IFrame, HTMLTokens.Src); _frameElements.Add(HTMLTokens.Frame, HTMLTokens.Src); _paramsUrlElements = new ArrayList(); _paramsUrlElements.Add(HTMLTokens.Movie); _paramsUrlElements.Add(HTMLTokens.Src); _linkUrlElements = new ArrayList(); _linkUrlElements.Add("Stylesheet"); _allUrlElements = new Hashtable(); foreach (string token in FrameElements.Keys) _allUrlElements.Add(token, FrameElements[token]); foreach (string token in NonResourceElements.Keys) _allUrlElements.Add(token, NonResourceElements[token]); foreach (string token in ResourceElements.Keys) _allUrlElements.Add(token, ResourceElements[token]); } /// <summary> /// Resource Elements are elements that can be downloaded when a page or snippet is captured /// </summary> public static Hashtable ResourceElements { get { return m_resourceElements; } } private static Hashtable m_resourceElements = null; public static Hashtable AnchorElements { get { return m_anchors; } } private static Hashtable m_anchors = null; /// <summary> /// User visible elements are references in a page that are visible to a user /// </summary> public static Hashtable UserVisibleElements { get { return m_userVisibleElements; } } private static Hashtable m_userVisibleElements = null; /// <summary> /// Non resource elements are elements that cannot be downloaded when a page or snippet is captured /// </summary> public static Hashtable NonResourceElements { get { return m_nonResourceElements; } } private static Hashtable m_nonResourceElements = null; public static Hashtable FrameElements { get { return _frameElements; } } private static Hashtable _frameElements = null; public static ArrayList ParamsUrlElements { get { return _paramsUrlElements; } } private static ArrayList _paramsUrlElements = null; public static ArrayList LinksUrlElements { get { return _linkUrlElements; } } private static ArrayList _linkUrlElements = null; public static Hashtable AllUrlElements { get { return _allUrlElements; } } private static Hashtable _allUrlElements = null; } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Xml.XPath; using Examine; using Examine.LuceneEngine.SearchCriteria; using Examine.Providers; using Lucene.Net.Documents; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Dynamics; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Xml; using Umbraco.Web.Models; using UmbracoExamine; using umbraco; using umbraco.cms.businesslogic; using ContentType = umbraco.cms.businesslogic.ContentType; namespace Umbraco.Web.PublishedCache.XmlPublishedCache { /// <summary> /// An IPublishedMediaStore that first checks for the media in Examine, and then reverts to the database /// </summary> /// <remarks> /// NOTE: In the future if we want to properly cache all media this class can be extended or replaced when these classes/interfaces are exposed publicly. /// </remarks> internal class PublishedMediaCache : IPublishedMediaCache { public PublishedMediaCache() { } /// <summary> /// Generally used for unit testing to use an explicit examine searcher /// </summary> /// <param name="searchProvider"></param> /// <param name="indexProvider"></param> internal PublishedMediaCache(BaseSearchProvider searchProvider, BaseIndexProvider indexProvider) { _searchProvider = searchProvider; _indexProvider = indexProvider; } private readonly BaseSearchProvider _searchProvider; private readonly BaseIndexProvider _indexProvider; public virtual IPublishedContent GetById(UmbracoContext umbracoContext, bool preview, int nodeId) { return GetUmbracoMedia(nodeId); } public virtual IEnumerable<IPublishedContent> GetAtRoot(UmbracoContext umbracoContext, bool preview) { var rootMedia = global::umbraco.cms.businesslogic.media.Media.GetRootMedias(); var result = new List<IPublishedContent>(); //TODO: need to get a ConvertFromMedia method but we'll just use this for now. foreach (var media in rootMedia .Select(m => global::umbraco.library.GetMedia(m.Id, true)) .Where(media => media != null && media.Current != null)) { media.MoveNext(); result.Add(ConvertFromXPathNavigator(media.Current)); } return result; } public virtual IPublishedContent GetSingleByXPath(UmbracoContext umbracoContext, bool preview, string xpath, XPathVariable[] vars) { throw new NotImplementedException("PublishedMediaCache does not support XPath."); } public virtual IPublishedContent GetSingleByXPath(UmbracoContext umbracoContext, bool preview, XPathExpression xpath, XPathVariable[] vars) { throw new NotImplementedException("PublishedMediaCache does not support XPath."); } public virtual IEnumerable<IPublishedContent> GetByXPath(UmbracoContext umbracoContext, bool preview, string xpath, XPathVariable[] vars) { throw new NotImplementedException("PublishedMediaCache does not support XPath."); } public virtual IEnumerable<IPublishedContent> GetByXPath(UmbracoContext umbracoContext, bool preview, XPathExpression xpath, XPathVariable[] vars) { throw new NotImplementedException("PublishedMediaCache does not support XPath."); } public virtual XPathNavigator GetXPathNavigator(UmbracoContext umbracoContext, bool preview) { throw new NotImplementedException("PublishedMediaCache does not support XPath."); } public bool XPathNavigatorIsNavigable { get { return false; } } public virtual bool HasContent(UmbracoContext context, bool preview) { throw new NotImplementedException(); } private ExamineManager GetExamineManagerSafe() { try { return ExamineManager.Instance; } catch (TypeInitializationException) { return null; } } private BaseIndexProvider GetIndexProviderSafe() { if (_indexProvider != null) return _indexProvider; var eMgr = GetExamineManagerSafe(); if (eMgr != null) { try { //by default use the InternalSearcher return eMgr.IndexProviderCollection["InternalIndexer"]; } catch (Exception ex) { LogHelper.Error<PublishedMediaCache>("Could not retrieve the InternalIndexer", ex); //something didn't work, continue returning null. } } return null; } private BaseSearchProvider GetSearchProviderSafe() { if (_searchProvider != null) return _searchProvider; var eMgr = GetExamineManagerSafe(); if (eMgr != null) { try { //by default use the InternalSearcher return eMgr.SearchProviderCollection["InternalSearcher"]; } catch (FileNotFoundException) { //Currently examine is throwing FileNotFound exceptions when we have a loadbalanced filestore and a node is published in umbraco //See this thread: http://examine.cdodeplex.com/discussions/264341 //Catch the exception here for the time being, and just fallback to GetMedia //TODO: Need to fix examine in LB scenarios! } } return null; } private IPublishedContent GetUmbracoMedia(int id) { var searchProvider = GetSearchProviderSafe(); if (searchProvider != null) { try { //first check in Examine as this is WAY faster var criteria = searchProvider.CreateSearchCriteria("media"); var filter = criteria.Id(id).Not().Field(UmbracoContentIndexer.IndexPathFieldName, "-1,-21,".MultipleCharacterWildcard()); //the above filter will create a query like this, NOTE: That since the use of the wildcard, it automatically escapes it in Lucene. //+(+__NodeId:3113 -__Path:-1,-21,*) +__IndexType:media var results = searchProvider.Search(filter.Compile()); if (results.Any()) { return ConvertFromSearchResult(results.First()); } } catch (FileNotFoundException) { //Currently examine is throwing FileNotFound exceptions when we have a loadbalanced filestore and a node is published in umbraco //See this thread: http://examine.cdodeplex.com/discussions/264341 //Catch the exception here for the time being, and just fallback to GetMedia //TODO: Need to fix examine in LB scenarios! } } var media = global::umbraco.library.GetMedia(id, true); if (media != null && media.Current != null) { media.MoveNext(); var moved = media.Current.MoveToFirstChild(); //first check if we have an error if (moved) { if (media.Current.Name.InvariantEquals("error")) { return null; } } if (moved) { //move back to the parent and return media.Current.MoveToParent(); } return ConvertFromXPathNavigator(media.Current); } return null; } internal IPublishedContent ConvertFromSearchResult(SearchResult searchResult) { //NOTE: Some fields will not be included if the config section for the internal index has been //mucked around with. It should index everything and so the index definition should simply be: // <IndexSet SetName="InternalIndexSet" IndexPath="~/App_Data/TEMP/ExamineIndexes/Internal/" /> var values = new Dictionary<string, string>(searchResult.Fields); //we need to ensure some fields exist, because of the above issue if (!new []{"template", "templateId"}.Any(values.ContainsKey)) values.Add("template", 0.ToString()); if (!new[] { "sortOrder" }.Any(values.ContainsKey)) values.Add("sortOrder", 0.ToString()); if (!new[] { "urlName" }.Any(values.ContainsKey)) values.Add("urlName", ""); if (!new[] { "nodeType" }.Any(values.ContainsKey)) values.Add("nodeType", 0.ToString()); if (!new[] { "creatorName" }.Any(values.ContainsKey)) values.Add("creatorName", ""); if (!new[] { "writerID" }.Any(values.ContainsKey)) values.Add("writerID", 0.ToString()); if (!new[] { "creatorID" }.Any(values.ContainsKey)) values.Add("creatorID", 0.ToString()); if (!new[] { "createDate" }.Any(values.ContainsKey)) values.Add("createDate", default(DateTime).ToString("yyyy-MM-dd HH:mm:ss")); if (!new[] { "level" }.Any(values.ContainsKey)) { values.Add("level", values["__Path"].Split(',').Length.ToString()); } var content = new DictionaryPublishedContent(values, d => d.ParentId != -1 //parent should be null if -1 ? GetUmbracoMedia(d.ParentId) : null, //callback to return the children of the current node d => GetChildrenMedia(d.Id), GetProperty, true); return PublishedContentModelFactory.CreateModel(content); } internal IPublishedContent ConvertFromXPathNavigator(XPathNavigator xpath) { if (xpath == null) throw new ArgumentNullException("xpath"); var values = new Dictionary<string, string> {{"nodeName", xpath.GetAttribute("nodeName", "")}}; if (!UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema) { values.Add("nodeTypeAlias", xpath.Name); } var result = xpath.SelectChildren(XPathNodeType.Element); //add the attributes e.g. id, parentId etc if (result.Current != null && result.Current.HasAttributes) { if (result.Current.MoveToFirstAttribute()) { //checking for duplicate keys because of the 'nodeTypeAlias' might already be added above. if (!values.ContainsKey(result.Current.Name)) { values.Add(result.Current.Name, result.Current.Value); } while (result.Current.MoveToNextAttribute()) { if (!values.ContainsKey(result.Current.Name)) { values.Add(result.Current.Name, result.Current.Value); } } result.Current.MoveToParent(); } } //add the user props while (result.MoveNext()) { if (result.Current != null && !result.Current.HasAttributes) { string value = result.Current.Value; if (string.IsNullOrEmpty(value)) { if (result.Current.HasAttributes || result.Current.SelectChildren(XPathNodeType.Element).Count > 0) { value = result.Current.OuterXml; } } values.Add(result.Current.Name, value); } } var content = new DictionaryPublishedContent(values, d => d.ParentId != -1 //parent should be null if -1 ? GetUmbracoMedia(d.ParentId) : null, //callback to return the children of the current node based on the xml structure already found d => GetChildrenMedia(d.Id, xpath), GetProperty, false); return PublishedContentModelFactory.CreateModel(content); } /// <summary> /// We will need to first check if the document was loaded by Examine, if so we'll need to check if this property exists /// in the results, if it does not, then we'll have to revert to looking up in the db. /// </summary> /// <param name="dd"> </param> /// <param name="alias"></param> /// <returns></returns> private IPublishedProperty GetProperty(DictionaryPublishedContent dd, string alias) { if (dd.LoadedFromExamine) { //if this is from Examine, lets check if the alias does not exist on the document if (dd.Properties.All(x => x.PropertyTypeAlias != alias)) { //ok it doesn't exist, we might assume now that Examine didn't index this property because the index is not set up correctly //so before we go loading this from the database, we can check if the alias exists on the content type at all, this information //is cached so will be quicker to look up. if (dd.Properties.Any(x => x.PropertyTypeAlias == UmbracoContentIndexer.NodeTypeAliasFieldName)) { // so in dd.Properties, there is an IPublishedProperty with property type alias "__NodeTypeAlias" and // that special property would contain the node type alias, which we use to get "aliases & names". That // special property is going to be a PropertyResult (with Value == DataValue) and we // want its value in the most simple way = it is OK to use DataValue here. var aliasesAndNames = ContentType.GetAliasesAndNames(dd.Properties.First(x => x.PropertyTypeAlias.InvariantEquals(UmbracoContentIndexer.NodeTypeAliasFieldName)).DataValue.ToString()); if (aliasesAndNames != null) { if (!aliasesAndNames.ContainsKey(alias)) { //Ok, now we know it doesn't exist on this content type anyways return null; } } } //if we've made it here, that means it does exist on the content type but not in examine, we'll need to query the db :( var media = global::umbraco.library.GetMedia(dd.Id, true); if (media != null && media.Current != null) { media.MoveNext(); var mediaDoc = ConvertFromXPathNavigator(media.Current); return mediaDoc.Properties.FirstOrDefault(x => x.PropertyTypeAlias.InvariantEquals(alias)); } } } //We've made it here which means that the value is stored in the Examine index. //We are going to check for a special field however, that is because in some cases we store a 'Raw' //value in the index such as for xml/html. var rawValue = dd.Properties.FirstOrDefault(x => x.PropertyTypeAlias.InvariantEquals(UmbracoContentIndexer.RawFieldPrefix + alias)); return rawValue ?? dd.Properties.FirstOrDefault(x => x.PropertyTypeAlias.InvariantEquals(alias)); } /// <summary> /// A Helper methods to return the children for media whther it is based on examine or xml /// </summary> /// <param name="parentId"></param> /// <param name="xpath"></param> /// <returns></returns> private IEnumerable<IPublishedContent> GetChildrenMedia(int parentId, XPathNavigator xpath = null) { //if there is no navigator, try examine first, then re-look it up if (xpath == null) { var searchProvider = GetSearchProviderSafe(); if (searchProvider != null) { try { //first check in Examine as this is WAY faster var criteria = searchProvider.CreateSearchCriteria("media"); var filter = criteria.ParentId(parentId); ISearchResults results; //we want to check if the indexer for this searcher has "sortOrder" flagged as sortable. //if so, we'll use Lucene to do the sorting, if not we'll have to manually sort it (slower). var indexer = GetIndexProviderSafe(); var useLuceneSort = indexer != null && indexer.IndexerData.StandardFields.Any(x => x.Name.InvariantEquals("sortOrder") && x.EnableSorting); if (useLuceneSort) { //we have a sortOrder field declared to be sorted, so we'll use Examine results = searchProvider.Search( filter.And().OrderBy(new SortableField("sortOrder", SortType.Int)).Compile()); } else { results = searchProvider.Search(filter.Compile()); } if (results.Any()) { return useLuceneSort ? results.Select(ConvertFromSearchResult) //will already be sorted by lucene : results.Select(ConvertFromSearchResult).OrderBy(x => x.SortOrder); } else { //if there's no result then return null. Previously we defaulted back to library.GetMedia below //but this will always get called for when we are getting descendents since many items won't have //children and then we are hitting the database again! //So instead we're going to rely on Examine to have the correct results like it should. return Enumerable.Empty<IPublishedContent>(); } } catch (FileNotFoundException) { //Currently examine is throwing FileNotFound exceptions when we have a loadbalanced filestore and a node is published in umbraco //See this thread: http://examine.cdodeplex.com/discussions/264341 //Catch the exception here for the time being, and just fallback to GetMedia } } //falling back to get media var media = library.GetMedia(parentId, true); if (media != null && media.Current != null) { media.MoveNext(); xpath = media.Current; } else { return Enumerable.Empty<IPublishedContent>(); } } //The xpath might be the whole xpath including the current ones ancestors so we need to select the current node var item = xpath.Select("//*[@id='" + parentId + "']"); if (item.Current == null) { return Enumerable.Empty<IPublishedContent>(); } var children = item.Current.SelectChildren(XPathNodeType.Element); var mediaList = new List<IPublishedContent>(); foreach(XPathNavigator x in children) { //NOTE: I'm not sure why this is here, it is from legacy code of ExamineBackedMedia, but // will leave it here as it must have done something! if (x.Name != "contents") { //make sure it's actually a node, not a property if (!string.IsNullOrEmpty(x.GetAttribute("path", "")) && !string.IsNullOrEmpty(x.GetAttribute("id", ""))) { mediaList.Add(ConvertFromXPathNavigator(x)); } } } return mediaList; } /// <summary> /// An IPublishedContent that is represented all by a dictionary. /// </summary> /// <remarks> /// This is a helper class and definitely not intended for public use, it expects that all of the values required /// to create an IPublishedContent exist in the dictionary by specific aliases. /// </remarks> internal class DictionaryPublishedContent : PublishedContentBase { // note: I'm not sure this class fully complies with IPublishedContent rules especially // I'm not sure that _properties contains all properties including those without a value, // neither that GetProperty will return a property without a value vs. null... @zpqrtbnk // List of properties that will appear in the XML and do not match // anything in the ContentType, so they must be ignored. private static readonly string[] IgnoredKeys = { "version", "isDoc", "key" }; public DictionaryPublishedContent( IDictionary<string, string> valueDictionary, Func<DictionaryPublishedContent, IPublishedContent> getParent, Func<DictionaryPublishedContent, IEnumerable<IPublishedContent>> getChildren, Func<DictionaryPublishedContent, string, IPublishedProperty> getProperty, bool fromExamine) { if (valueDictionary == null) throw new ArgumentNullException("valueDictionary"); if (getParent == null) throw new ArgumentNullException("getParent"); if (getProperty == null) throw new ArgumentNullException("getProperty"); _getParent = getParent; _getChildren = getChildren; _getProperty = getProperty; LoadedFromExamine = fromExamine; ValidateAndSetProperty(valueDictionary, val => _id = int.Parse(val), "id", "nodeId", "__NodeId"); //should validate the int! ValidateAndSetProperty(valueDictionary, val => _templateId = int.Parse(val), "template", "templateId"); ValidateAndSetProperty(valueDictionary, val => _sortOrder = int.Parse(val), "sortOrder"); ValidateAndSetProperty(valueDictionary, val => _name = val, "nodeName", "__nodeName"); ValidateAndSetProperty(valueDictionary, val => _urlName = val, "urlName"); ValidateAndSetProperty(valueDictionary, val => _documentTypeAlias = val, "nodeTypeAlias", UmbracoContentIndexer.NodeTypeAliasFieldName); ValidateAndSetProperty(valueDictionary, val => _documentTypeId = int.Parse(val), "nodeType"); ValidateAndSetProperty(valueDictionary, val => _writerName = val, "writerName"); ValidateAndSetProperty(valueDictionary, val => _creatorName = val, "creatorName", "writerName"); //this is a bit of a hack fix for: U4-1132 ValidateAndSetProperty(valueDictionary, val => _writerId = int.Parse(val), "writerID"); ValidateAndSetProperty(valueDictionary, val => _creatorId = int.Parse(val), "creatorID", "writerID"); //this is a bit of a hack fix for: U4-1132 ValidateAndSetProperty(valueDictionary, val => _path = val, "path", "__Path"); ValidateAndSetProperty(valueDictionary, val => _createDate = ParseDateTimeValue(val), "createDate"); ValidateAndSetProperty(valueDictionary, val => _updateDate = ParseDateTimeValue(val), "updateDate"); ValidateAndSetProperty(valueDictionary, val => _level = int.Parse(val), "level"); ValidateAndSetProperty(valueDictionary, val => { int pId; ParentId = -1; if (int.TryParse(val, out pId)) { ParentId = pId; } }, "parentID"); _contentType = PublishedContentType.Get(PublishedItemType.Media, _documentTypeAlias); _properties = new Collection<IPublishedProperty>(); //loop through remaining values that haven't been applied foreach (var i in valueDictionary.Where(x => !_keysAdded.Contains(x.Key))) { IPublishedProperty property = null; // must ignore those if (IgnoredKeys.Contains(i.Key)) continue; if (i.Key.InvariantStartsWith("__")) { // no type for that one, dunno how to convert property = new PropertyResult(i.Key, i.Value, PropertyResultType.CustomProperty); } else { // use property type to ensure proper conversion var propertyType = _contentType.GetPropertyType(i.Key); // note: this is where U4-4144 and -3665 were born // // because propertyType is null, the XmlPublishedProperty ctor will throw // it's null because i.Key is not a valid property alias for the type... // the alias is case insensitive (verified) so it means it really is not // a correct alias. // // in every cases this is after a ConvertFromXPathNavigator, so it means // that we get some properties from the XML that are not valid properties. // no idea which property. could come from the cache in library, could come // from so many places really. // workaround: just ignore that property if (propertyType == null) { LogHelper.Warn<PublishedMediaCache>("Dropping property \"" + i.Key + "\" because it does not belong to the content type."); continue; } property = new XmlPublishedProperty(propertyType, false, i.Value); // false :: never preview a media } _properties.Add(property); } } private DateTime ParseDateTimeValue(string val) { if (LoadedFromExamine) { try { //we might need to parse the date time using Lucene converters return DateTools.StringToDate(val); } catch (FormatException) { //swallow exception, its not formatted correctly so revert to just trying to parse } } return DateTime.Parse(val); } /// <summary> /// Flag to get/set if this was laoded from examine cache /// </summary> internal bool LoadedFromExamine { get; private set; } private readonly Func<DictionaryPublishedContent, IPublishedContent> _getParent; private readonly Func<DictionaryPublishedContent, IEnumerable<IPublishedContent>> _getChildren; private readonly Func<DictionaryPublishedContent, string, IPublishedProperty> _getProperty; /// <summary> /// Returns 'Media' as the item type /// </summary> public override PublishedItemType ItemType { get { return PublishedItemType.Media; } } public override IPublishedContent Parent { get { return _getParent(this); } } public int ParentId { get; private set; } public override int Id { get { return _id; } } public override int TemplateId { get { //TODO: should probably throw a not supported exception since media doesn't actually support this. return _templateId; } } public override int SortOrder { get { return _sortOrder; } } public override string Name { get { return _name; } } public override string UrlName { get { return _urlName; } } public override string DocumentTypeAlias { get { return _documentTypeAlias; } } public override int DocumentTypeId { get { return _documentTypeId; } } public override string WriterName { get { return _writerName; } } public override string CreatorName { get { return _creatorName; } } public override int WriterId { get { return _writerId; } } public override int CreatorId { get { return _creatorId; } } public override string Path { get { return _path; } } public override DateTime CreateDate { get { return _createDate; } } public override DateTime UpdateDate { get { return _updateDate; } } public override Guid Version { get { return _version; } } public override int Level { get { return _level; } } public override bool IsDraft { get { return false; } } public override ICollection<IPublishedProperty> Properties { get { return _properties; } } public override IEnumerable<IPublishedContent> Children { get { return _getChildren(this); } } public override IPublishedProperty GetProperty(string alias) { return _getProperty(this, alias); } public override PublishedContentType ContentType { get { return _contentType; } } // override to implement cache // cache at context level, ie once for the whole request // but cache is not shared by requests because we wouldn't know how to clear it public override IPublishedProperty GetProperty(string alias, bool recurse) { if (recurse == false) return GetProperty(alias); IPublishedProperty property; string key = null; var cache = UmbracoContextCache.Current; if (cache != null) { key = string.Format("RECURSIVE_PROPERTY::{0}::{1}", Id, alias.ToLowerInvariant()); object o; if (cache.TryGetValue(key, out o)) { property = o as IPublishedProperty; if (property == null) throw new InvalidOperationException("Corrupted cache."); return property; } } // else get it for real, no cache property = base.GetProperty(alias, true); if (cache != null) cache[key] = property; return property; } private readonly List<string> _keysAdded = new List<string>(); private int _id; private int _templateId; private int _sortOrder; private string _name; private string _urlName; private string _documentTypeAlias; private int _documentTypeId; private string _writerName; private string _creatorName; private int _writerId; private int _creatorId; private string _path; private DateTime _createDate; private DateTime _updateDate; private Guid _version; private int _level; private readonly ICollection<IPublishedProperty> _properties; private readonly PublishedContentType _contentType; private void ValidateAndSetProperty(IDictionary<string, string> valueDictionary, Action<string> setProperty, params string[] potentialKeys) { var key = potentialKeys.FirstOrDefault(x => valueDictionary.ContainsKey(x) && valueDictionary[x] != null); if (key == null) { throw new FormatException("The valueDictionary is not formatted correctly and is missing any of the '" + string.Join(",", potentialKeys) + "' elements"); } setProperty(valueDictionary[key]); _keysAdded.Add(key); } } } }
// *********************************************************************** // Copyright (c) 2014 Charlie Poole // // 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. // *********************************************************************** #if !SILVERLIGHT && !PORTABLE #region Using Directives using System; using System.IO; using NUnit.TestUtilities; #endregion namespace NUnit.Framework.Assertions { [TestFixture] public class DirectoryAssertTests { private TestDirectory _goodDir1; private TestDirectory _goodDir2; private const string BAD_DIRECTORY = @"\I\hope\this\is\garbage"; [SetUp] public void SetUp() { _goodDir1 = new TestDirectory(); _goodDir2 = new TestDirectory(); Assume.That(_goodDir1.Directory, Is.Not.EqualTo(_goodDir2.Directory), "The two good directories are the same"); Assume.That(BAD_DIRECTORY, Does.Not.Exist, BAD_DIRECTORY + " exists"); } [TearDown] public void TearDown() { if (_goodDir1 != null) _goodDir1.Dispose(); if (_goodDir2 != null) _goodDir2.Dispose(); } #region AreEqual #region Success Tests [Test] public void AreEqualPassesWithDirectoryInfos() { var expected = new DirectoryInfo(_goodDir1.ToString()); var actual = new DirectoryInfo(_goodDir1.ToString()); DirectoryAssert.AreEqual(expected, actual); DirectoryAssert.AreEqual(expected, actual); } #endregion #region Failure Tests [Test] public void AreEqualFailsWithDirectoryInfos() { var expected = _goodDir1.Directory; var actual = _goodDir2.Directory; var expectedMessage = string.Format(" Expected: <{0}>{2} But was: <{1}>{2}", expected.FullName, actual.FullName, Environment.NewLine); var ex = Assert.Throws<AssertionException>(() => DirectoryAssert.AreEqual(expected, actual)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } #endregion #endregion #region AreNotEqual #region Success Tests [Test] public void AreNotEqualPassesIfExpectedIsNull() { DirectoryAssert.AreNotEqual(_goodDir1.Directory, null); } [Test] public void AreNotEqualPassesIfActualIsNull() { DirectoryAssert.AreNotEqual(null, _goodDir1.Directory); } [Test] public void AreNotEqualPassesWithDirectoryInfos() { var expected = _goodDir1.Directory; var actual = _goodDir2.Directory; DirectoryAssert.AreNotEqual(expected, actual); } #endregion #region Failure Tests [Test] public void AreNotEqualFailsWithDirectoryInfos() { var expected = new DirectoryInfo(_goodDir1.ToString()); var actual = new DirectoryInfo(_goodDir1.ToString()); var expectedMessage = string.Format( " Expected: not equal to <{0}>{2} But was: <{1}>{2}", expected.FullName, actual.FullName, Environment.NewLine ); var ex = Assert.Throws<AssertionException>(() => DirectoryAssert.AreNotEqual(expected, actual)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } #endregion #endregion #region Exists [Test] public void ExistsPassesWhenDirectoryInfoExists() { DirectoryAssert.Exists(_goodDir1.Directory); } [Test] public void ExistsPassesWhenStringExists() { DirectoryAssert.Exists(_goodDir1.ToString()); } [Test] public void ExistsFailsWhenDirectoryInfoDoesNotExist() { var ex = Assert.Throws<AssertionException>(() => DirectoryAssert.Exists(new DirectoryInfo(BAD_DIRECTORY))); Assert.That(ex.Message, Does.StartWith(" Expected: directory exists")); } [Test] public void ExistsFailsWhenStringDoesNotExist() { var ex = Assert.Throws<AssertionException>(() => DirectoryAssert.Exists(BAD_DIRECTORY)); Assert.That(ex.Message, Does.StartWith(" Expected: directory exists")); } [Test] public void ExistsFailsWhenDirectoryInfoIsNull() { var ex = Assert.Throws<ArgumentNullException>(() => DirectoryAssert.Exists((DirectoryInfo)null)); Assert.That(ex.Message, Does.StartWith("The actual value must be a non-null string or DirectoryInfo")); } [Test] public void ExistsFailsWhenStringIsNull() { var ex = Assert.Throws<ArgumentNullException>(() => DirectoryAssert.Exists((string)null)); Assert.That(ex.Message, Does.StartWith("The actual value must be a non-null string or DirectoryInfo")); } [Test] public void ExistsFailsWhenStringIsEmpty() { var ex = Assert.Throws<ArgumentException>(() => DirectoryAssert.Exists(string.Empty)); Assert.That(ex.Message, Does.StartWith("The actual value cannot be an empty string")); } #endregion #region DoesNotExist [Test] public void DoesNotExistFailsWhenDirectoryInfoExists() { var ex = Assert.Throws<AssertionException>(() => DirectoryAssert.DoesNotExist(_goodDir1.Directory)); Assert.That(ex.Message, Does.StartWith(" Expected: not directory exists")); } [Test] public void DoesNotExistFailsWhenStringExists() { var ex = Assert.Throws<AssertionException>(() => DirectoryAssert.DoesNotExist(_goodDir1.ToString())); Assert.That(ex.Message, Does.StartWith(" Expected: not directory exists")); } [Test] public void DoesNotExistPassesWhenDirectoryInfoDoesNotExist() { DirectoryAssert.DoesNotExist(new DirectoryInfo(BAD_DIRECTORY)); } [Test] public void DoesNotExistPassesWhenStringDoesNotExist() { DirectoryAssert.DoesNotExist(BAD_DIRECTORY); } [Test] public void DoesNotExistFailsWhenDirectoryInfoIsNull() { var ex = Assert.Throws<ArgumentNullException>(() => DirectoryAssert.DoesNotExist((DirectoryInfo)null)); Assert.That(ex.Message, Does.StartWith("The actual value must be a non-null string or DirectoryInfo")); } [Test] public void DoesNotExistFailsWhenStringIsNull() { var ex = Assert.Throws<ArgumentNullException>(() => DirectoryAssert.DoesNotExist((string)null)); Assert.That(ex.Message, Does.StartWith("The actual value must be a non-null string or DirectoryInfo")); } [Test] public void DoesNotExistFailsWhenStringIsEmpty() { var ex = Assert.Throws<ArgumentException>(() => DirectoryAssert.DoesNotExist(string.Empty)); Assert.That(ex.Message, Does.StartWith("The actual value cannot be an empty string")); } #endregion } } #endif
// leveldb-sharp // // Copyright (c) 2011 The LevelDB Authors // Copyright (c) 2012-2013, Mirco Bauer <meebey@meebey.net> // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Text; using System.Runtime.InteropServices; namespace LevelDB { /// <summary> /// Native method P/Invoke declarations for LevelDB /// </summary> public static class Native { public static void CheckError(string error) { if (String.IsNullOrEmpty(error)) { return; } throw new ApplicationException(error); } public static void CheckError(IntPtr error) { if (error == IntPtr.Zero) { return; } CheckError(GetAndReleaseString(error)); } public static UIntPtr GetStringLength(string value) { if (value == null || value.Length == 0) { return UIntPtr.Zero; } return new UIntPtr((uint) Encoding.UTF8.GetByteCount(value)); } public static string GetAndReleaseString(IntPtr ptr) { if (ptr == IntPtr.Zero) { return null; } var str = Marshal.PtrToStringAnsi(ptr); leveldb_free(ptr); return str; } #region DB operations #region leveldb_open // extern leveldb_t* leveldb_open(const leveldb_options_t* options, const char* name, char** errptr); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr leveldb_open(IntPtr options, string name, out IntPtr error); public static IntPtr leveldb_open(IntPtr options, string name, out string error) { IntPtr errorPtr; var db = leveldb_open(options, name, out errorPtr); error = GetAndReleaseString(errorPtr); return db; } public static IntPtr leveldb_open(IntPtr options, string name) { string error; var db = leveldb_open(options, name, out error); CheckError(error); return db; } #endregion // extern void leveldb_close(leveldb_t* db); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_close(IntPtr db); #region leveldb_put // extern void leveldb_put(leveldb_t* db, const leveldb_writeoptions_t* options, const char* key, size_t keylen, const char* val, size_t vallen, char** errptr); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_put(IntPtr db, IntPtr writeOptions, string key, UIntPtr keyLength, string value, UIntPtr valueLength, out IntPtr error); public static void leveldb_put(IntPtr db, IntPtr writeOptions, string key, UIntPtr keyLength, string value, UIntPtr valueLength, out string error) { IntPtr errorPtr; leveldb_put(db, writeOptions, key, keyLength, value, valueLength, out errorPtr); error = GetAndReleaseString(errorPtr); } public static void leveldb_put(IntPtr db, IntPtr writeOptions, string key, string value) { string error; var keyLength = GetStringLength(key); var valueLength = GetStringLength(value); Native.leveldb_put(db, writeOptions, key, keyLength, value, valueLength, out error); CheckError(error); } #endregion #region leveldb_delete // extern void leveldb_delete(leveldb_t* db, const leveldb_writeoptions_t* options, const char* key, size_t keylen, char** errptr); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_delete(IntPtr db, IntPtr writeOptions, string key, UIntPtr keylen, out IntPtr error); public static void leveldb_delete(IntPtr db, IntPtr writeOptions, string key, UIntPtr keylen, out string error) { IntPtr errorPtr; leveldb_delete(db, writeOptions, key, keylen, out errorPtr); error = GetAndReleaseString(errorPtr); } public static void leveldb_delete(IntPtr db, IntPtr writeOptions, string key) { string error; var keyLength = GetStringLength(key); leveldb_delete(db, writeOptions, key, keyLength, out error); CheckError(error); } #endregion #region leveldb_write // extern void leveldb_write(leveldb_t* db, const leveldb_writeoptions_t* options, leveldb_writebatch_t* batch, char** errptr); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_write(IntPtr db, IntPtr writeOptions, IntPtr writeBatch, out IntPtr error); public static void leveldb_write(IntPtr db, IntPtr writeOptions, IntPtr writeBatch, out string error) { IntPtr errorPtr; leveldb_write(db, writeOptions, writeBatch, out errorPtr); error = GetAndReleaseString(errorPtr); } public static void leveldb_write(IntPtr db, IntPtr writeOptions, IntPtr writeBatch) { string error; leveldb_write(db, writeOptions, writeBatch, out error); CheckError(error); } #endregion #region leveldb_get // extern char* leveldb_get(leveldb_t* db, const leveldb_readoptions_t* options, const char* key, size_t keylen, size_t* vallen, char** errptr); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr leveldb_get(IntPtr db, IntPtr readOptions, string key, UIntPtr keyLength, out UIntPtr valueLength, out IntPtr error); public static IntPtr leveldb_get(IntPtr db, IntPtr readOptions, string key, UIntPtr keyLength, out UIntPtr valueLength, out string error) { IntPtr errorPtr; var valuePtr = leveldb_get(db, readOptions, key, keyLength, out valueLength, out errorPtr); error = GetAndReleaseString(errorPtr); return valuePtr; } public static string leveldb_get(IntPtr db, IntPtr readOptions, string key) { UIntPtr valueLength; string error; var keyLength = GetStringLength(key); var valuePtr = leveldb_get(db, readOptions, key, keyLength, out valueLength, out error); CheckError(error); if (valuePtr == IntPtr.Zero || valueLength == UIntPtr.Zero) { return null; } var value = Marshal.PtrToStringAnsi(valuePtr, (int) valueLength); leveldb_free(valuePtr); return value; } #endregion // extern leveldb_iterator_t* leveldb_create_iterator(leveldb_t* db, const leveldb_readoptions_t* options); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr leveldb_create_iterator(IntPtr db, IntPtr readOptions); // extern const leveldb_snapshot_t* leveldb_create_snapshot(leveldb_t* db); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr leveldb_create_snapshot(IntPtr db); // extern void leveldb_release_snapshot(leveldb_t* db, const leveldb_snapshot_t* snapshot); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_release_snapshot(IntPtr db, IntPtr snapshot); /// <summary> /// Returns NULL if property name is unknown. /// Else returns a pointer to a malloc()-ed null-terminated value. /// </summary> // extern char* leveldb_property_value(leveldb_t* db, const char* propname); [DllImport("leveldb", EntryPoint="leveldb_property_value", CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr leveldb_property_value_native(IntPtr db, string propname); public static string leveldb_property_value(IntPtr db, string propname) { var valuePtr = leveldb_property_value_native(db, propname); if (valuePtr == IntPtr.Zero) { return null; } var value = Marshal.PtrToStringAnsi(valuePtr); leveldb_free(valuePtr); return value; } // extern void leveldb_approximate_sizes( // leveldb_t* db, int num_ranges, // const char* const* range_start_key, // const size_t* range_start_key_len, // const char* const* range_limit_key, // const size_t* range_limit_key_len, // uint64_t* sizes); /// <summary> /// Compact the underlying storage for the key range [startKey,limitKey]. /// In particular, deleted and overwritten versions are discarded, /// and the data is rearranged to reduce the cost of operations /// needed to access the data. This operation should typically only /// be invoked by users who understand the underlying implementation. /// /// startKey==null is treated as a key before all keys in the database. /// limitKey==null is treated as a key after all keys in the database. /// Therefore the following call will compact the entire database: /// leveldb_compact_range(db, null, null); /// </summary> // extern void leveldb_compact_range(leveldb_t* db, // const char* start_key, size_t start_key_len, // const char* limit_key, size_t limit_key_len); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_compact_range(IntPtr db, string startKey, UIntPtr startKeyLen, string limitKey, UIntPtr limitKeyLen); public static void leveldb_compact_range(IntPtr db, string startKey, string limitKey) { leveldb_compact_range(db, startKey, GetStringLength(startKey), limitKey, GetStringLength(limitKey)); } #endregion #region Management operations #region leveldb_destroy_db // extern void leveldb_destroy_db(const leveldb_options_t* options, const char* name, char** errptr); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_destroy_db(IntPtr options, string path, out IntPtr error); public static void leveldb_destroy_db(IntPtr options, string path, out string error) { IntPtr errorPtr; leveldb_destroy_db(options, path, out errorPtr); error = GetAndReleaseString(errorPtr); } public static void leveldb_destroy_db(IntPtr options, string path) { string error; leveldb_destroy_db(options, path, out error); CheckError(error); } #endregion #region leveldb_repair_db // extern void leveldb_repair_db(const leveldb_options_t* options, const char* name, char** errptr); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_repair_db(IntPtr options, string path, out IntPtr error); public static void leveldb_repair_db(IntPtr options, string path, out string error) { IntPtr errorPtr; leveldb_repair_db(options, path, out errorPtr); error = GetAndReleaseString(errorPtr); } public static void leveldb_repair_db(IntPtr options, string path) { string error; leveldb_repair_db(options, path, out error); CheckError(error); } #endregion #endregion #region Write batch // extern leveldb_writebatch_t* leveldb_writebatch_create(); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr leveldb_writebatch_create(); // extern void leveldb_writebatch_destroy(leveldb_writebatch_t*); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_writebatch_destroy(IntPtr writeBatch); // extern void leveldb_writebatch_clear(leveldb_writebatch_t*); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_writebatch_clear(IntPtr writeBatch); // extern void leveldb_writebatch_put(leveldb_writebatch_t*, const char* key, size_t klen, const char* val, size_t vlen); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_writebatch_put(IntPtr writeBatch, string key, UIntPtr keyLength, string value, UIntPtr valueLength); public static void leveldb_writebatch_put(IntPtr writeBatch, string key, string value) { var keyLength = GetStringLength(key); var valueLength = GetStringLength(value); Native.leveldb_writebatch_put(writeBatch, key, keyLength, value, valueLength); } // extern void leveldb_writebatch_delete(leveldb_writebatch_t*, const char* key, size_t klen); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_writebatch_delete(IntPtr writeBatch, string key, UIntPtr keylen); public static void leveldb_writebatch_delete(IntPtr writeBatch, string key) { var keyLength = GetStringLength(key); leveldb_writebatch_delete(writeBatch, key, keyLength); } // TODO: // extern void leveldb_writebatch_iterate(leveldb_writebatch_t*, void* state, void (*put)(void*, const char* k, size_t klen, const char* v, size_t vlen), void (*deleted)(void*, const char* k, size_t klen)); #endregion #region Options // extern leveldb_options_t* leveldb_options_create(); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr leveldb_options_create(); // extern void leveldb_options_destroy(leveldb_options_t*); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_options_destroy(IntPtr options); // extern void leveldb_options_set_comparator(leveldb_options_t*, leveldb_comparator_t*); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_options_set_comparator(IntPtr options, IntPtr comparator); /// <summary> /// If true, the database will be created if it is missing. /// Default: false /// </summary> // extern void leveldb_options_set_create_if_missing(leveldb_options_t*, unsigned char); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_options_set_create_if_missing(IntPtr options, bool value); /// <summary> /// If true, an error is raised if the database already exists. /// Default: false /// </summary> // extern void leveldb_options_set_error_if_exists(leveldb_options_t*, unsigned char); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_options_set_error_if_exists(IntPtr options, bool value); /// <summary> /// If true, the implementation will do aggressive checking of the /// data it is processing and will stop early if it detects any /// errors. This may have unforeseen ramifications: for example, a /// corruption of one DB entry may cause a large number of entries to /// become unreadable or for the entire DB to become unopenable. /// Default: false /// </summary> // extern void leveldb_options_set_paranoid_checks(leveldb_options_t*, unsigned char); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_options_set_paranoid_checks(IntPtr options, bool value); /// <summary> /// Number of open files that can be used by the DB. You may need to /// increase this if your database has a large working set (budget /// one open file per 2MB of working set). /// Default: 1000 /// </summary> // extern void leveldb_options_set_max_open_files(leveldb_options_t*, int); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_options_set_max_open_files(IntPtr options, int value); /// <summary> /// Each block is individually compressed before being written to /// persistent storage. Compression is on by default since the default /// compression method is very fast, and is automatically disabled for /// uncompressible data. In rare cases, applications may want to /// disable compression entirely, but should only do so if benchmarks /// show a performance improvement. /// Default: 1 (SnappyCompression) /// </summary> /// <seealso cref="T:CompressionType"/> // extern void leveldb_options_set_compression(leveldb_options_t*, int); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_options_set_compression(IntPtr options, int value); /// <summary> /// Control over blocks (user data is stored in a set of blocks, and /// a block is the unit of reading from disk). /// /// If non-NULL, use the specified cache for blocks. /// If NULL, leveldb will automatically create and use an 8MB internal cache. /// Default: NULL /// </summary> // extern void leveldb_options_set_cache(leveldb_options_t*, leveldb_cache_t*); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_options_set_cache(IntPtr options, IntPtr cache); public static void leveldb_options_set_cache_size(IntPtr options, int capacity) { var cache = leveldb_cache_create_lru((UIntPtr) capacity); leveldb_options_set_cache(options, cache); } /// <summary> /// Approximate size of user data packed per block. Note that the /// block size specified here corresponds to uncompressed data. The /// actual size of the unit read from disk may be smaller if /// compression is enabled. This parameter can be changed dynamically. /// /// Default: 4K /// </summary> // extern void leveldb_options_set_block_size(leveldb_options_t*, size_t); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_options_set_block_size(IntPtr options, UIntPtr size); public static void leveldb_options_set_block_size(IntPtr options, int size) { leveldb_options_set_block_size(options, (UIntPtr) size); } /// <summary> /// Amount of data to build up in memory (backed by an unsorted log /// on disk) before converting to a sorted on-disk file. /// /// Larger values increase performance, especially during bulk loads. /// Up to two write buffers may be held in memory at the same time, /// so you may wish to adjust this parameter to control memory usage. /// Also, a larger write buffer will result in a longer recovery time /// the next time the database is opened. /// /// Default: 4MB /// </summary> // extern void leveldb_options_set_write_buffer_size(leveldb_options_t*, size_t); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_options_set_write_buffer_size(IntPtr options, UIntPtr size); public static void leveldb_options_set_write_buffer_size(IntPtr options, int size) { leveldb_options_set_write_buffer_size(options, (UIntPtr) size); } /// <summary> /// Number of keys between restart points for delta encoding of keys. /// This parameter can be changed dynamically. Most clients should /// leave this parameter alone. /// Default: 16 /// </summary> // extern void leveldb_options_set_block_restart_interval(leveldb_options_t*, int); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_options_set_block_restart_interval(IntPtr options, int interval); #endregion #region Read Options // extern leveldb_readoptions_t* leveldb_readoptions_create(); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr leveldb_readoptions_create(); // extern void leveldb_readoptions_destroy(leveldb_readoptions_t*); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_readoptions_destroy(IntPtr readOptions); // extern void leveldb_readoptions_set_verify_checksums(leveldb_readoptions_t*, unsigned char); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_readoptions_set_verify_checksums(IntPtr readOptions, bool value); // extern void leveldb_readoptions_set_fill_cache(leveldb_readoptions_t*, unsigned char); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_readoptions_set_fill_cache(IntPtr readOptions, bool value); // extern void leveldb_readoptions_set_snapshot(leveldb_readoptions_t*, const leveldb_snapshot_t*); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_readoptions_set_snapshot(IntPtr readOptions, IntPtr snapshot); #endregion #region Write Options // extern leveldb_writeoptions_t* leveldb_writeoptions_create(); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr leveldb_writeoptions_create(); // extern void leveldb_writeoptions_destroy(leveldb_writeoptions_t*); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_writeoptions_destroy(IntPtr writeOptions); // extern void leveldb_writeoptions_set_sync(leveldb_writeoptions_t*, unsigned char); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_writeoptions_set_sync(IntPtr writeOptions, bool value); #endregion #region Iterator // extern void leveldb_iter_seek_to_first(leveldb_iterator_t*); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_iter_seek_to_first(IntPtr iter); // extern void leveldb_iter_seek_to_last(leveldb_iterator_t*); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_iter_seek_to_last(IntPtr iter); // extern void leveldb_iter_seek(leveldb_iterator_t*, const char* k, size_t klen); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_iter_seek(IntPtr iter, string key, UIntPtr keyLength); public static void leveldb_iter_seek(IntPtr iter, string key) { var keyLength = GetStringLength(key); leveldb_iter_seek(iter, key, keyLength); } // extern unsigned char leveldb_iter_valid(const leveldb_iterator_t*); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern byte leveldb_iter_valid(IntPtr iter); // extern void leveldb_iter_prev(leveldb_iterator_t*); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_iter_prev(IntPtr iter); // extern void leveldb_iter_next(leveldb_iterator_t*); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_iter_next(IntPtr iter); // extern const char* leveldb_iter_key(const leveldb_iterator_t*, size_t* klen); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr leveldb_iter_key(IntPtr iter, out UIntPtr keyLength); public static string leveldb_iter_key(IntPtr iter) { UIntPtr keyLength; var keyPtr = leveldb_iter_key(iter, out keyLength); if (keyPtr == IntPtr.Zero || keyLength == UIntPtr.Zero) { return null; } var key = Marshal.PtrToStringAnsi(keyPtr, (int) keyLength); return key; } // extern const char* leveldb_iter_value(const leveldb_iterator_t*, size_t* vlen); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr leveldb_iter_value(IntPtr iter, out UIntPtr valueLength); public static string leveldb_iter_value(IntPtr iter) { UIntPtr valueLength; var valuePtr = leveldb_iter_value(iter, out valueLength); if (valuePtr == IntPtr.Zero || valueLength == UIntPtr.Zero) { return null; } var value = Marshal.PtrToStringAnsi(valuePtr, (int) valueLength); return value; } // extern void leveldb_iter_destroy(leveldb_iterator_t*); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_iter_destroy(IntPtr iter); // TODO: // extern void leveldb_iter_get_error(const leveldb_iterator_t*, char** errptr); #endregion #region Cache // extern leveldb_cache_t* leveldb_cache_create_lru(size_t capacity); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr leveldb_cache_create_lru(UIntPtr capacity); // extern void leveldb_cache_destroy(leveldb_cache_t* cache); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_cache_destroy(IntPtr cache); #endregion #region Env // TODO: // extern leveldb_env_t* leveldb_create_default_env(); // extern void leveldb_env_destroy(leveldb_env_t*); #endregion #region Utility /// <summary> /// Calls free(ptr). /// REQUIRES: ptr was malloc()-ed and returned by one of the routines /// in this file. Note that in certain cases (typically on Windows), /// you may need to call this routine instead of free(ptr) to dispose /// of malloc()-ed memory returned by this library. /// </summary> // extern void leveldb_free(void* ptr); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern void leveldb_free(IntPtr ptr); /// <summary> /// Return the major version number for this release. /// </summary> // extern int leveldb_major_version(); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern int leveldb_major_version(); /// <summary> /// Return the minor version number for this release. /// </summary> // extern int leveldb_minor_version(); [DllImport("leveldb", CallingConvention = CallingConvention.Cdecl)] public static extern int leveldb_minor_version(); #endregion public static void Dump(IntPtr db) { var options = Native.leveldb_readoptions_create(); IntPtr iter = Native.leveldb_create_iterator(db, options); for (Native.leveldb_iter_seek_to_first(iter); (int)Native.leveldb_iter_valid(iter) != 0; Native.leveldb_iter_next(iter)) { string key = Native.leveldb_iter_key(iter); string value = Native.leveldb_iter_value(iter); Console.WriteLine("'{0}' => '{1}'", key, value); } Native.leveldb_iter_destroy(iter); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.NetAnalyzers; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.NetCore.Analyzers.Runtime { using static MicrosoftNetCoreAnalyzersResources; /// <summary> /// CA1305: Specify IFormatProvider /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class SpecifyIFormatProviderAnalyzer : AbstractGlobalizationDiagnosticAnalyzer { internal const string RuleId = "CA1305"; private static readonly LocalizableString s_localizableTitle = CreateLocalizableResourceString(nameof(SpecifyIFormatProviderTitle)); private static readonly LocalizableString s_localizableDescription = CreateLocalizableResourceString(nameof(SpecifyIFormatProviderDescription)); internal static readonly DiagnosticDescriptor IFormatProviderAlternateStringRule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, CreateLocalizableResourceString(nameof(SpecifyIFormatProviderMessageIFormatProviderAlternateString)), DiagnosticCategory.Globalization, RuleLevel.IdeHidden_BulkConfigurable, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static readonly DiagnosticDescriptor IFormatProviderAlternateRule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, CreateLocalizableResourceString(nameof(SpecifyIFormatProviderMessageIFormatProviderAlternate)), DiagnosticCategory.Globalization, RuleLevel.IdeHidden_BulkConfigurable, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static readonly DiagnosticDescriptor UICultureStringRule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, CreateLocalizableResourceString(nameof(SpecifyIFormatProviderMessageUICultureString)), DiagnosticCategory.Globalization, RuleLevel.IdeHidden_BulkConfigurable, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static readonly DiagnosticDescriptor UICultureRule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, CreateLocalizableResourceString(nameof(SpecifyIFormatProviderMessageUICulture)), DiagnosticCategory.Globalization, RuleLevel.IdeHidden_BulkConfigurable, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); private static readonly ImmutableArray<string> s_dateInvariantFormats = ImmutableArray.Create("o", "O", "r", "R", "s", "u"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(IFormatProviderAlternateStringRule, IFormatProviderAlternateRule, UICultureStringRule, UICultureRule); protected override void InitializeWorker(CompilationStartAnalysisContext context) { #region "Get All the WellKnown Types and Members" var iformatProviderType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemIFormatProvider); var cultureInfoType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemGlobalizationCultureInfo); if (iformatProviderType == null || cultureInfoType == null) { return; } var objectType = context.Compilation.GetSpecialType(SpecialType.System_Object); var stringType = context.Compilation.GetSpecialType(SpecialType.System_String); var charType = context.Compilation.GetSpecialType(SpecialType.System_Char); var boolType = context.Compilation.GetSpecialType(SpecialType.System_Boolean); var guidType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemGuid); var builder = ImmutableHashSet.CreateBuilder<INamedTypeSymbol>(); builder.AddIfNotNull(charType); builder.AddIfNotNull(boolType); builder.AddIfNotNull(stringType); builder.AddIfNotNull(guidType); var invariantToStringTypes = builder.ToImmutableHashSet(); var dateTimeType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDateTime); var dateTimeOffsetType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDateTimeOffset); var timeSpanType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemTimeSpan); var stringFormatMembers = stringType.GetMembers("Format").OfType<IMethodSymbol>(); var stringFormatMemberWithStringAndObjectParameter = stringFormatMembers.GetFirstOrDefaultMemberWithParameterInfos( GetParameterInfo(stringType), GetParameterInfo(objectType)); var stringFormatMemberWithStringObjectAndObjectParameter = stringFormatMembers.GetFirstOrDefaultMemberWithParameterInfos( GetParameterInfo(stringType), GetParameterInfo(objectType), GetParameterInfo(objectType)); var stringFormatMemberWithStringObjectObjectAndObjectParameter = stringFormatMembers.GetFirstOrDefaultMemberWithParameterInfos( GetParameterInfo(stringType), GetParameterInfo(objectType), GetParameterInfo(objectType), GetParameterInfo(objectType)); var stringFormatMemberWithStringAndParamsObjectParameter = stringFormatMembers.GetFirstOrDefaultMemberWithParameterInfos( GetParameterInfo(stringType), GetParameterInfo(objectType, isArray: true, arrayRank: 1, isParams: true)); var stringFormatMemberWithIFormatProviderStringAndParamsObjectParameter = stringFormatMembers.GetFirstOrDefaultMemberWithParameterInfos( GetParameterInfo(iformatProviderType), GetParameterInfo(stringType), GetParameterInfo(objectType, isArray: true, arrayRank: 1, isParams: true)); var currentCultureProperty = cultureInfoType.GetMembers("CurrentCulture").OfType<IPropertySymbol>().FirstOrDefault(); var invariantCultureProperty = cultureInfoType.GetMembers("InvariantCulture").OfType<IPropertySymbol>().FirstOrDefault(); var currentUICultureProperty = cultureInfoType.GetMembers("CurrentUICulture").OfType<IPropertySymbol>().FirstOrDefault(); var installedUICultureProperty = cultureInfoType.GetMembers("InstalledUICulture").OfType<IPropertySymbol>().FirstOrDefault(); var threadType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingThread); var currentThreadCurrentUICultureProperty = threadType?.GetMembers("CurrentUICulture").OfType<IPropertySymbol>().FirstOrDefault(); var activatorType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemActivator); var resourceManagerType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemResourcesResourceManager); var computerInfoType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualBasicDevicesComputerInfo); var installedUICulturePropertyOfComputerInfoType = computerInfoType?.GetMembers("InstalledUICulture").OfType<IPropertySymbol>().FirstOrDefault(); var obsoleteAttributeType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemObsoleteAttribute); #endregion context.RegisterOperationAction(oaContext => { var invocationExpression = (IInvocationOperation)oaContext.Operation; var targetMethod = invocationExpression.TargetMethod; #region "Exceptions" if (targetMethod.IsGenericMethod || targetMethod.ContainingType.IsErrorType() || (activatorType != null && activatorType.Equals(targetMethod.ContainingType)) || (resourceManagerType != null && resourceManagerType.Equals(targetMethod.ContainingType)) || IsValidToStringCall(invocationExpression, invariantToStringTypes, dateTimeType, dateTimeOffsetType, timeSpanType)) { return; } #endregion #region "IFormatProviderAlternateStringRule Only" if (stringFormatMemberWithIFormatProviderStringAndParamsObjectParameter != null && !oaContext.Options.IsConfiguredToSkipAnalysis(IFormatProviderAlternateStringRule, targetMethod, oaContext.ContainingSymbol, oaContext.Compilation) && (targetMethod.Equals(stringFormatMemberWithStringAndObjectParameter) || targetMethod.Equals(stringFormatMemberWithStringObjectAndObjectParameter) || targetMethod.Equals(stringFormatMemberWithStringObjectObjectAndObjectParameter) || targetMethod.Equals(stringFormatMemberWithStringAndParamsObjectParameter))) { // Sample message for IFormatProviderAlternateStringRule: Because the behavior of string.Format(string, object) could vary based on the current user's locale settings, // replace this call in IFormatProviderStringTest.M() with a call to string.Format(IFormatProvider, string, params object[]). oaContext.ReportDiagnostic( invocationExpression.Syntax.CreateDiagnostic( IFormatProviderAlternateStringRule, targetMethod.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat), oaContext.ContainingSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat), stringFormatMemberWithIFormatProviderStringAndParamsObjectParameter.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat))); return; } #endregion #region "IFormatProviderAlternateStringRule & IFormatProviderAlternateRule" var iformatProviderAlternateRule = targetMethod.ReturnType.Equals(stringType) ? IFormatProviderAlternateStringRule : IFormatProviderAlternateRule; if (!oaContext.Options.IsConfiguredToSkipAnalysis(iformatProviderAlternateRule, targetMethod, oaContext.ContainingSymbol, oaContext.Compilation)) { IEnumerable<IMethodSymbol> methodsWithSameNameAsTargetMethod = targetMethod.ContainingType.GetMembers(targetMethod.Name).OfType<IMethodSymbol>().WhereMethodDoesNotContainAttribute(obsoleteAttributeType); if (methodsWithSameNameAsTargetMethod.HasMoreThan(1)) { var correctOverloads = methodsWithSameNameAsTargetMethod.GetMethodOverloadsWithDesiredParameterAtLeadingOrTrailing(targetMethod, iformatProviderType); // If there are two matching overloads, one with CultureInfo as the first parameter and one with CultureInfo as the last parameter, // report the diagnostic on the overload with CultureInfo as the last parameter, to match the behavior of FxCop. var correctOverload = correctOverloads.FirstOrDefault(overload => overload.Parameters.Last().Type.Equals(iformatProviderType)) ?? correctOverloads.FirstOrDefault(); // Sample message for IFormatProviderAlternateRule: Because the behavior of Convert.ToInt64(string) could vary based on the current user's locale settings, // replace this call in IFormatProviderStringTest.TestMethod() with a call to Convert.ToInt64(string, IFormatProvider). if (correctOverload != null) { oaContext.ReportDiagnostic( invocationExpression.Syntax.CreateDiagnostic( iformatProviderAlternateRule, targetMethod.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat), oaContext.ContainingSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat), correctOverload.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat))); } } } #endregion #region "UICultureStringRule & UICultureRule" var uiCultureRule = targetMethod.ReturnType.Equals(stringType) ? UICultureStringRule : UICultureRule; if (!oaContext.Options.IsConfiguredToSkipAnalysis(uiCultureRule, targetMethod, oaContext.ContainingSymbol, oaContext.Compilation)) { IEnumerable<int> IformatProviderParameterIndices = GetIndexesOfParameterType(targetMethod, iformatProviderType); foreach (var index in IformatProviderParameterIndices) { var argument = invocationExpression.Arguments[index]; if (argument != null && currentUICultureProperty != null && installedUICultureProperty != null && currentThreadCurrentUICultureProperty != null) { var semanticModel = argument.SemanticModel; var symbol = semanticModel.GetSymbolInfo(argument.Value.Syntax, oaContext.CancellationToken).Symbol; if (symbol != null && (symbol.Equals(currentUICultureProperty) || symbol.Equals(installedUICultureProperty) || symbol.Equals(currentThreadCurrentUICultureProperty) || (installedUICulturePropertyOfComputerInfoType != null && symbol.Equals(installedUICulturePropertyOfComputerInfoType)))) { // Sample message // 1. UICultureStringRule - 'TestClass.TestMethod()' passes 'Thread.CurrentUICulture' as the 'IFormatProvider' parameter to 'TestClass.CalleeMethod(string, IFormatProvider)'. // This property returns a culture that is inappropriate for formatting methods. // 2. UICultureRule -'TestClass.TestMethod()' passes 'CultureInfo.CurrentUICulture' as the 'IFormatProvider' parameter to 'TestClass.Callee(IFormatProvider, string)'. // This property returns a culture that is inappropriate for formatting methods. oaContext.ReportDiagnostic( invocationExpression.Syntax.CreateDiagnostic( uiCultureRule, oaContext.ContainingSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat), symbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat), targetMethod.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat))); } } } } #endregion }, OperationKind.Invocation); } private static IEnumerable<int> GetIndexesOfParameterType(IMethodSymbol targetMethod, INamedTypeSymbol formatProviderType) { return targetMethod.Parameters .Select((Parameter, Index) => (Parameter, Index)) .Where(x => x.Parameter.Type.Equals(formatProviderType)) .Select(x => x.Index); } private static ParameterInfo GetParameterInfo(INamedTypeSymbol type, bool isArray = false, int arrayRank = 0, bool isParams = false) { return ParameterInfo.GetParameterInfo(type, isArray, arrayRank, isParams); } private static bool IsValidToStringCall(IInvocationOperation invocationOperation, ImmutableHashSet<INamedTypeSymbol> invariantToStringTypes, INamedTypeSymbol? dateTimeType, INamedTypeSymbol? dateTimeOffsetType, INamedTypeSymbol? timeSpanType) { var targetMethod = invocationOperation.TargetMethod; if (targetMethod.Name != "ToString") { return false; } if (invariantToStringTypes.Contains(UnwrapNullableValueTypes(targetMethod.ContainingType))) { return true; } if (invocationOperation.Arguments.Length != 1 || !invocationOperation.Arguments[0].Value.ConstantValue.HasValue || invocationOperation.Arguments[0].Value.ConstantValue.Value is not string format) { return false; } // Handle invariant format specifiers, see https://github.com/dotnet/roslyn-analyzers/issues/3507 if ((dateTimeType != null && targetMethod.ContainingType.Equals(dateTimeType)) || (dateTimeOffsetType != null && targetMethod.ContainingType.Equals(dateTimeOffsetType))) { return s_dateInvariantFormats.Contains(format); } if (timeSpanType != null && targetMethod.ContainingType.Equals(timeSpanType)) { return format == "c"; } return false; // Local functions static INamedTypeSymbol UnwrapNullableValueTypes(INamedTypeSymbol typeSymbol) { if (typeSymbol.IsNullableValueType() && typeSymbol.TypeArguments[0] is INamedTypeSymbol nullableTypeArgument) return nullableTypeArgument; return typeSymbol; } } } }
// 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.IO; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; namespace System.Data.SqlClient.SNI { /// <summary> /// TCP connection handle /// </summary> internal class SNITCPHandle : SNIHandle { private readonly string _targetServer; private readonly object _callbackObject; private readonly Socket _socket; private NetworkStream _tcpStream; private readonly TaskScheduler _writeScheduler; private readonly TaskFactory _writeTaskFactory; private Stream _stream; private SslStream _sslStream; private SslOverTdsStream _sslOverTdsStream; private SNIAsyncCallback _receiveCallback; private SNIAsyncCallback _sendCallback; private bool _validateCert = true; private int _bufferSize = TdsEnums.DEFAULT_LOGIN_PACKET_SIZE; private uint _status = TdsEnums.SNI_UNINITIALIZED; private Guid _connectionId = Guid.NewGuid(); private const int MaxParallelIpAddresses = 64; /// <summary> /// Dispose object /// </summary> public override void Dispose() { lock (this) { if (_sslOverTdsStream != null) { _sslOverTdsStream.Dispose(); _sslOverTdsStream = null; } if (_sslStream != null) { _sslStream.Dispose(); _sslStream = null; } if (_tcpStream != null) { _tcpStream.Dispose(); _tcpStream = null; } //Release any references held by _stream. _stream = null; } } /// <summary> /// Connection ID /// </summary> public override Guid ConnectionId { get { return _connectionId; } } /// <summary> /// Connection status /// </summary> public override uint Status { get { return _status; } } /// <summary> /// Constructor /// </summary> /// <param name="serverName">Server name</param> /// <param name="port">TCP port number</param> /// <param name="timerExpire">Connection timer expiration</param> /// <param name="callbackObject">Callback object</param> public SNITCPHandle(string serverName, int port, long timerExpire, object callbackObject, bool parallel) { _writeScheduler = new ConcurrentExclusiveSchedulerPair().ExclusiveScheduler; _writeTaskFactory = new TaskFactory(_writeScheduler); _callbackObject = callbackObject; _targetServer = serverName; try { TimeSpan ts = default(TimeSpan); // In case the Timeout is Infinite, we will receive the max value of Int64 as the tick count // The infinite Timeout is a function of ConnectionString Timeout=0 bool isInfiniteTimeOut = long.MaxValue == timerExpire; if (!isInfiniteTimeOut) { ts = DateTime.FromFileTime(timerExpire) - DateTime.Now; ts = ts.Ticks < 0 ? TimeSpan.FromTicks(0) : ts; } Task<Socket> connectTask; if (parallel) { Task<IPAddress[]> serverAddrTask = Dns.GetHostAddressesAsync(serverName); serverAddrTask.Wait(ts); IPAddress[] serverAddresses = serverAddrTask.Result; if (serverAddresses.Length > MaxParallelIpAddresses) { // Fail if above 64 to match legacy behavior ReportTcpSNIError(0, SNICommon.MultiSubnetFailoverWithMoreThan64IPs, string.Empty); return; } connectTask = ParallelConnectAsync(serverAddresses, port); } else { connectTask = ConnectAsync(serverName, port); } if (!(isInfiniteTimeOut ? connectTask.Wait(-1) : connectTask.Wait(ts))) { ReportTcpSNIError(0, SNICommon.ConnOpenFailedError, string.Empty); return; } _socket = connectTask.Result; if (_socket == null || !_socket.Connected) { if (_socket != null) { _socket.Dispose(); _socket = null; } ReportTcpSNIError(0, SNICommon.ConnOpenFailedError, string.Empty); return; } _socket.NoDelay = true; _tcpStream = new NetworkStream(_socket, true); _sslOverTdsStream = new SslOverTdsStream(_tcpStream); _sslStream = new SslStream(_sslOverTdsStream, true, new RemoteCertificateValidationCallback(ValidateServerCertificate), null); } catch (SocketException se) { ReportTcpSNIError(se); return; } catch (Exception e) { ReportTcpSNIError(e); return; } _stream = _tcpStream; _status = TdsEnums.SNI_SUCCESS; } private static async Task<Socket> ConnectAsync(string serverName, int port) { IPAddress[] addresses = await Dns.GetHostAddressesAsync(serverName).ConfigureAwait(false); IPAddress targetAddrV4 = Array.Find(addresses, addr => (addr.AddressFamily == AddressFamily.InterNetwork)); IPAddress targetAddrV6 = Array.Find(addresses, addr => (addr.AddressFamily == AddressFamily.InterNetworkV6)); if (targetAddrV4 != null && targetAddrV6 != null) { return await ParallelConnectAsync(new IPAddress[] { targetAddrV4, targetAddrV6 }, port).ConfigureAwait(false); } else { IPAddress targetAddr = (targetAddrV4 != null) ? targetAddrV4 : targetAddrV6; var socket = new Socket(targetAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { await socket.ConnectAsync(targetAddr, port).ConfigureAwait(false); } catch { socket.Dispose(); throw; } return socket; } } private static Task<Socket> ParallelConnectAsync(IPAddress[] serverAddresses, int port) { if (serverAddresses == null) { throw new ArgumentNullException(nameof(serverAddresses)); } if (serverAddresses.Length == 0) { throw new ArgumentOutOfRangeException(nameof(serverAddresses)); } var sockets = new List<Socket>(serverAddresses.Length); var connectTasks = new List<Task>(serverAddresses.Length); var tcs = new TaskCompletionSource<Socket>(); var lastError = new StrongBox<Exception>(); var pendingCompleteCount = new StrongBox<int>(serverAddresses.Length); foreach (IPAddress address in serverAddresses) { var socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); sockets.Add(socket); // Start all connection tasks now, to prevent possible race conditions with // calling ConnectAsync on disposed sockets. try { connectTasks.Add(socket.ConnectAsync(address, port)); } catch (Exception e) { connectTasks.Add(Task.FromException(e)); } } for (int i = 0; i < sockets.Count; i++) { ParallelConnectHelper(sockets[i], connectTasks[i], tcs, pendingCompleteCount, lastError, sockets); } return tcs.Task; } private static async void ParallelConnectHelper( Socket socket, Task connectTask, TaskCompletionSource<Socket> tcs, StrongBox<int> pendingCompleteCount, StrongBox<Exception> lastError, List<Socket> sockets) { bool success = false; try { // Try to connect. If we're successful, store this task into the result task. await connectTask.ConfigureAwait(false); success = tcs.TrySetResult(socket); if (success) { // Whichever connection completes the return task is responsible for disposing // all of the sockets (except for whichever one is stored into the result task). // This ensures that only one thread will attempt to dispose of a socket. // This is also the closest thing we have to canceling connect attempts. foreach (Socket otherSocket in sockets) { if (otherSocket != socket) { otherSocket.Dispose(); } } } } catch (Exception e) { // Store an exception to be published if no connection succeeds Interlocked.Exchange(ref lastError.Value, e); } finally { // If we didn't successfully transition the result task to completed, // then someone else did and they would have cleaned up, so there's nothing // more to do. Otherwise, no one completed it yet or we failed; either way, // see if we're the last outstanding connection, and if we are, try to complete // the task, and if we're successful, it's our responsibility to dispose all of the sockets. if (!success && Interlocked.Decrement(ref pendingCompleteCount.Value) == 0) { if (lastError.Value != null) { tcs.TrySetException(lastError.Value); } else { tcs.TrySetCanceled(); } foreach (Socket s in sockets) { s.Dispose(); } } } } /// <summary> /// Enable SSL /// </summary> public override uint EnableSsl(uint options) { _validateCert = (options & TdsEnums.SNI_SSL_VALIDATE_CERTIFICATE) != 0; try { _sslStream.AuthenticateAsClientAsync(_targetServer).GetAwaiter().GetResult(); _sslOverTdsStream.FinishHandshake(); } catch (AuthenticationException aue) { return ReportTcpSNIError(aue); } catch (InvalidOperationException ioe) { return ReportTcpSNIError(ioe); } _stream = _sslStream; return TdsEnums.SNI_SUCCESS; } /// <summary> /// Disable SSL /// </summary> public override void DisableSsl() { _sslStream.Dispose(); _sslStream = null; _sslOverTdsStream.Dispose(); _sslOverTdsStream = null; _stream = _tcpStream; } /// <summary> /// Validate server certificate callback /// </summary> /// <param name="sender">Sender object</param> /// <param name="cert">X.509 certificate</param> /// <param name="chain">X.509 chain</param> /// <param name="policyErrors">Policy errors</param> /// <returns>True if certificate is valid</returns> private bool ValidateServerCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors policyErrors) { if (!_validateCert) { return true; } return SNICommon.ValidateSslServerCertificate(_targetServer, sender, cert, chain, policyErrors); } /// <summary> /// Set buffer size /// </summary> /// <param name="bufferSize">Buffer size</param> public override void SetBufferSize(int bufferSize) { _bufferSize = bufferSize; _socket.SendBufferSize = bufferSize; _socket.ReceiveBufferSize = bufferSize; } /// <summary> /// Send a packet synchronously /// </summary> /// <param name="packet">SNI packet</param> /// <returns>SNI error code</returns> public override uint Send(SNIPacket packet) { lock (this) { try { packet.WriteToStream(_stream); return TdsEnums.SNI_SUCCESS; } catch (ObjectDisposedException ode) { return ReportTcpSNIError(ode); } catch (SocketException se) { return ReportTcpSNIError(se); } catch (IOException ioe) { return ReportTcpSNIError(ioe); } } } /// <summary> /// Receive a packet synchronously /// </summary> /// <param name="packet">SNI packet</param> /// <param name="timeoutInMilliseconds">Timeout in Milliseconds</param> /// <returns>SNI error code</returns> public override uint Receive(out SNIPacket packet, int timeoutInMilliseconds) { lock (this) { packet = null; try { if (timeoutInMilliseconds > 0) { _socket.ReceiveTimeout = timeoutInMilliseconds; } else if (timeoutInMilliseconds == -1) { // SqlCient internally represents infinite timeout by -1, and for TcpClient this is translated to a timeout of 0 _socket.ReceiveTimeout = 0; } else { // otherwise it is timeout for 0 or less than -1 ReportTcpSNIError(0, SNICommon.ConnTimeoutError, string.Empty); return TdsEnums.SNI_WAIT_TIMEOUT; } packet = new SNIPacket(null); packet.Allocate(_bufferSize); packet.ReadFromStream(_stream); if (packet.Length == 0) { return ReportErrorAndReleasePacket(packet, 0, SNICommon.ConnTerminatedError, string.Empty); } return TdsEnums.SNI_SUCCESS; } catch (ObjectDisposedException ode) { return ReportErrorAndReleasePacket(packet, ode); } catch (SocketException se) { return ReportErrorAndReleasePacket(packet, se); } catch (IOException ioe) { uint errorCode = ReportErrorAndReleasePacket(packet, ioe); if (ioe.InnerException is SocketException && ((SocketException)(ioe.InnerException)).SocketErrorCode == SocketError.TimedOut) { errorCode = TdsEnums.SNI_WAIT_TIMEOUT; } return errorCode; } finally { _socket.ReceiveTimeout = 0; } } } /// <summary> /// Set async callbacks /// </summary> /// <param name="receiveCallback">Receive callback</param> /// <param name="sendCallback">Send callback</param> /// <summary> public override void SetAsyncCallbacks(SNIAsyncCallback receiveCallback, SNIAsyncCallback sendCallback) { _receiveCallback = receiveCallback; _sendCallback = sendCallback; } /// <summary> /// Send a packet asynchronously /// </summary> /// <param name="packet">SNI packet</param> /// <param name="callback">Completion callback</param> /// <returns>SNI error code</returns> public override uint SendAsync(SNIPacket packet, SNIAsyncCallback callback = null) { SNIPacket newPacket = packet; _writeTaskFactory.StartNew(() => { try { lock (this) { packet.WriteToStream(_stream); } } catch (Exception e) { SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.TCP_PROV, SNICommon.InternalExceptionError, e); if (callback != null) { callback(packet, TdsEnums.SNI_ERROR); } else { _sendCallback(packet, TdsEnums.SNI_ERROR); } return; } if (callback != null) { callback(packet, TdsEnums.SNI_SUCCESS); } else { _sendCallback(packet, TdsEnums.SNI_SUCCESS); } }); return TdsEnums.SNI_SUCCESS_IO_PENDING; } /// <summary> /// Receive a packet asynchronously /// </summary> /// <param name="packet">SNI packet</param> /// <returns>SNI error code</returns> public override uint ReceiveAsync(ref SNIPacket packet) { lock (this) { packet = new SNIPacket(null); packet.Allocate(_bufferSize); try { packet.ReadFromStreamAsync(_stream, _receiveCallback); return TdsEnums.SNI_SUCCESS_IO_PENDING; } catch (ObjectDisposedException ode) { return ReportErrorAndReleasePacket(packet, ode); } catch (SocketException se) { return ReportErrorAndReleasePacket(packet, se); } catch (IOException ioe) { return ReportErrorAndReleasePacket(packet, ioe); } } } /// <summary> /// Check SNI handle connection /// </summary> /// <param name="handle"></param> /// <returns>SNI error status</returns> public override uint CheckConnection() { try { if (!_socket.Connected || _socket.Poll(0, SelectMode.SelectError)) { return TdsEnums.SNI_ERROR; } } catch (SocketException se) { return ReportTcpSNIError(se); } catch (ObjectDisposedException ode) { return ReportTcpSNIError(ode); } return TdsEnums.SNI_SUCCESS; } private uint ReportTcpSNIError(Exception sniException) { _status = TdsEnums.SNI_ERROR; return SNICommon.ReportSNIError(SNIProviders.TCP_PROV, SNICommon.InternalExceptionError, sniException); } private uint ReportTcpSNIError(uint nativeError, uint sniError, string errorMessage) { _status = TdsEnums.SNI_ERROR; return SNICommon.ReportSNIError(SNIProviders.TCP_PROV, nativeError, sniError, errorMessage); } private uint ReportErrorAndReleasePacket(SNIPacket packet, Exception sniException) { if (packet != null) { packet.Release(); } return ReportTcpSNIError(sniException); } private uint ReportErrorAndReleasePacket(SNIPacket packet, uint nativeError, uint sniError, string errorMessage) { if (packet != null) { packet.Release(); } return ReportTcpSNIError(nativeError, sniError, errorMessage); } #if DEBUG /// <summary> /// Test handle for killing underlying connection /// </summary> public override void KillConnection() { _socket.Shutdown(SocketShutdown.Both); } #endif } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using LibGit2Sharp.Core; using LibGit2Sharp.Core.Handles; namespace LibGit2Sharp { /// <summary> /// Provides helper overloads to a <see cref="ReferenceCollection"/>. /// </summary> public static class ReferenceCollectionExtensions { private enum RefState { Exists, DoesNotExistButLooksValid, DoesNotLookValid, } private static RefState TryResolveReference(out Reference reference, ReferenceCollection refsColl, string canonicalName) { if (!Reference.IsValidName(canonicalName)) { reference = null; return RefState.DoesNotLookValid; } reference = refsColl[canonicalName]; return reference != null ? RefState.Exists : RefState.DoesNotExistButLooksValid; } /// <summary> /// Creates a direct or symbolic reference with the specified name and target /// </summary> /// <param name="refsColl">The <see cref="ReferenceCollection"/> being worked with.</param> /// <param name="name">The name of the reference to create.</param> /// <param name="canonicalRefNameOrObjectish">The target which can be either the canonical name of a reference or a revparse spec.</param> /// <param name="signature">The identity used for updating the reflog</param> /// <param name="logMessage">The optional message to log in the <see cref="ReflogCollection"/> when adding the <see cref="Reference"/></param> /// <param name="allowOverwrite">True to allow silent overwriting a potentially existing reference, false otherwise.</param> /// <returns>A new <see cref="Reference"/>.</returns> public static Reference Add(this ReferenceCollection refsColl, string name, string canonicalRefNameOrObjectish, Signature signature, string logMessage, bool allowOverwrite = false) { Ensure.ArgumentNotNullOrEmptyString(name, "name"); Ensure.ArgumentNotNullOrEmptyString(canonicalRefNameOrObjectish, "canonicalRefNameOrObjectish"); Reference reference; RefState refState = TryResolveReference(out reference, refsColl, canonicalRefNameOrObjectish); var gitObject = refsColl.repo.Lookup(canonicalRefNameOrObjectish, GitObjectType.Any, LookUpOptions.None); if (refState == RefState.Exists) { return refsColl.Add(name, reference, signature, logMessage, allowOverwrite); } if (refState == RefState.DoesNotExistButLooksValid && gitObject == null) { using (ReferenceSafeHandle handle = Proxy.git_reference_symbolic_create(refsColl.repo.Handle, name, canonicalRefNameOrObjectish, allowOverwrite, signature.OrDefault(refsColl.repo.Config), logMessage)) { return Reference.BuildFromPtr<Reference>(handle, refsColl.repo); } } Ensure.GitObjectIsNotNull(gitObject, canonicalRefNameOrObjectish); if (logMessage == null) { logMessage = string.Format(CultureInfo.InvariantCulture, "{0}: Created from {1}", name.LooksLikeLocalBranch() ? "branch" : "reference", canonicalRefNameOrObjectish); } refsColl.EnsureHasLog(name); return refsColl.Add(name, gitObject.Id, signature, logMessage, allowOverwrite); } /// <summary> /// Creates a direct or symbolic reference with the specified name and target /// </summary> /// <param name="refsColl">The <see cref="ReferenceCollection"/> being worked with.</param> /// <param name="name">The name of the reference to create.</param> /// <param name="canonicalRefNameOrObjectish">The target which can be either the canonical name of a reference or a revparse spec.</param> /// <param name="allowOverwrite">True to allow silent overwriting a potentially existing reference, false otherwise.</param> /// <returns>A new <see cref="Reference"/>.</returns> public static Reference Add(this ReferenceCollection refsColl, string name, string canonicalRefNameOrObjectish, bool allowOverwrite = false) { return Add(refsColl, name, canonicalRefNameOrObjectish, null, null, allowOverwrite); } /// <summary> /// Updates the target of a direct reference. /// </summary> /// <param name="refsColl">The <see cref="ReferenceCollection"/> being worked with.</param> /// <param name="directRef">The direct reference which target should be updated.</param> /// <param name="objectish">The revparse spec of the target.</param> /// <param name="signature">The identity used for updating the reflog</param> /// <param name="logMessage">The optional message to log in the <see cref="ReflogCollection"/></param> /// <returns>A new <see cref="Reference"/>.</returns> public static Reference UpdateTarget(this ReferenceCollection refsColl, Reference directRef, string objectish, Signature signature, string logMessage) { Ensure.ArgumentNotNull(directRef, "directRef"); Ensure.ArgumentNotNull(objectish, "objectish"); GitObject target = refsColl.repo.Lookup(objectish); Ensure.GitObjectIsNotNull(target, objectish); return refsColl.UpdateTarget(directRef, target.Id, signature, logMessage); } /// <summary> /// Updates the target of a direct reference /// </summary> /// <param name="refsColl">The <see cref="ReferenceCollection"/> being worked with.</param> /// <param name="directRef">The direct reference which target should be updated.</param> /// <param name="objectish">The revparse spec of the target.</param> /// <returns>A new <see cref="Reference"/>.</returns> public static Reference UpdateTarget(this ReferenceCollection refsColl, Reference directRef, string objectish) { return UpdateTarget(refsColl, directRef, objectish, null, null); } /// <summary> /// Rename an existing reference with a new name /// </summary> /// <param name="currentName">The canonical name of the reference to rename.</param> /// <param name="newName">The new canonical name.</param> /// <param name="signature">The identity used for updating the reflog</param> /// <param name="logMessage">The optional message to log in the <see cref="ReflogCollection"/></param> /// <param name="allowOverwrite">True to allow silent overwriting a potentially existing reference, false otherwise.</param> /// <param name="refsColl">The <see cref="ReferenceCollection"/> being worked with.</param> /// <returns>A new <see cref="Reference"/>.</returns> public static Reference Rename(this ReferenceCollection refsColl, string currentName, string newName, Signature signature = null, string logMessage = null, bool allowOverwrite = false) { Ensure.ArgumentNotNullOrEmptyString(currentName, "currentName"); Reference reference = refsColl[currentName]; if (reference == null) { throw new LibGit2SharpException( string.Format(CultureInfo.InvariantCulture, "Reference '{0}' doesn't exist. One cannot move a non existing reference.", currentName)); } return refsColl.Rename(reference, newName, signature, logMessage, allowOverwrite); } /// <summary> /// Updates the target of a reference /// </summary> /// <param name="refsColl">The <see cref="ReferenceCollection"/> being worked with.</param> /// <param name="name">The canonical name of the reference.</param> /// <param name="canonicalRefNameOrObjectish">The target which can be either the canonical name of a reference or a revparse spec.</param> /// <param name="signature">The identity used for updating the reflog</param> /// <param name="logMessage">The optional message to log in the <see cref="ReflogCollection"/> of the <paramref name="name"/> reference.</param> /// <returns>A new <see cref="Reference"/>.</returns> public static Reference UpdateTarget(this ReferenceCollection refsColl, string name, string canonicalRefNameOrObjectish, Signature signature, string logMessage) { Ensure.ArgumentNotNullOrEmptyString(name, "name"); Ensure.ArgumentNotNullOrEmptyString(canonicalRefNameOrObjectish, "canonicalRefNameOrObjectish"); signature = signature.OrDefault(refsColl.repo.Config); if (name == "HEAD") { return refsColl.UpdateHeadTarget(canonicalRefNameOrObjectish, signature, logMessage); } Reference reference = refsColl[name]; var directReference = reference as DirectReference; if (directReference != null) { return refsColl.UpdateTarget(directReference, canonicalRefNameOrObjectish, signature, logMessage); } var symbolicReference = reference as SymbolicReference; if (symbolicReference != null) { Reference targetRef; RefState refState = TryResolveReference(out targetRef, refsColl, canonicalRefNameOrObjectish); if (refState == RefState.DoesNotLookValid) { throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "The reference specified by {0} is a Symbolic reference, you must provide a reference canonical name as the target.", name), "canonicalRefNameOrObjectish"); } return refsColl.UpdateTarget(symbolicReference, targetRef, signature, logMessage); } throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture, "Reference '{0}' has an unexpected type ('{1}').", name, reference.GetType())); } /// <summary> /// Updates the target of a reference /// </summary> /// <param name="refsColl">The <see cref="ReferenceCollection"/> being worked with.</param> /// <param name="name">The canonical name of the reference.</param> /// <param name="canonicalRefNameOrObjectish">The target which can be either the canonical name of a reference or a revparse spec.</param> /// <returns>A new <see cref="Reference"/>.</returns> public static Reference UpdateTarget(this ReferenceCollection refsColl, string name, string canonicalRefNameOrObjectish) { return UpdateTarget(refsColl, name, canonicalRefNameOrObjectish, null, null); } /// <summary> /// Delete a reference with the specified name /// </summary> /// <param name="refsColl">The <see cref="ReferenceCollection"/> being worked with.</param> /// <param name="name">The canonical name of the reference to delete.</param> public static void Remove(this ReferenceCollection refsColl, string name) { Ensure.ArgumentNotNullOrEmptyString(name, "name"); Reference reference = refsColl[name]; if (reference == null) { return; } refsColl.Remove(reference); } /// <summary> /// Find the <see cref="Reference"/>s among <paramref name="refSubset"/> /// that can reach at least one <see cref="Commit"/> in the specified <paramref name="targets"/>. /// </summary> /// <param name="refsColl">The <see cref="ReferenceCollection"/> being worked with.</param> /// <param name="refSubset">The set of <see cref="Reference"/>s to examine.</param> /// <param name="targets">The set of <see cref="Commit"/>s that are interesting.</param> /// <returns>A subset of <paramref name="refSubset"/> that can reach at least one <see cref="Commit"/> within <paramref name="targets"/>.</returns> public static IEnumerable<Reference> ReachableFrom( this ReferenceCollection refsColl, IEnumerable<Reference> refSubset, IEnumerable<Commit> targets) { Ensure.ArgumentNotNull(refSubset, "refSubset"); Ensure.ArgumentNotNull(targets, "targets"); var refs = new List<Reference>(refSubset); if (refs.Count == 0) { return Enumerable.Empty<Reference>(); } List<ObjectId> targetsSet = targets.Select(c => c.Id).Distinct().ToList(); if (targetsSet.Count == 0) { return Enumerable.Empty<Reference>(); } var result = new List<Reference>(); foreach (var reference in refs) { var peeledTargetCommit = reference .ResolveToDirectReference() .Target.DereferenceToCommit(false); if (peeledTargetCommit == null) { continue; } var commitId = peeledTargetCommit.Id; foreach (var potentialAncestorId in targetsSet) { if (potentialAncestorId == commitId) { result.Add(reference); break; } if (Proxy.git_graph_descendant_of(refsColl.repo.Handle, commitId, potentialAncestorId)) { result.Add(reference); break; } } } return result; } /// <summary> /// Find the <see cref="Reference"/>s /// that can reach at least one <see cref="Commit"/> in the specified <paramref name="targets"/>. /// </summary> /// <param name="refsColl">The <see cref="ReferenceCollection"/> being worked with.</param> /// <param name="targets">The set of <see cref="Commit"/>s that are interesting.</param> /// <returns>The list of <see cref="Reference"/> that can reach at least one <see cref="Commit"/> within <paramref name="targets"/>.</returns> public static IEnumerable<Reference> ReachableFrom( this ReferenceCollection refsColl, IEnumerable<Commit> targets) { return ReachableFrom(refsColl, refsColl, targets); } } }
/*! @file License.cs @author Woong Gyu La a.k.a Chris. <juhgiyo@gmail.com> <http://github.com/juhgiyo/eplibrary.cs> @date April 01, 2014 @brief License Interface @version 2.0 @section LICENSE The MIT License (MIT) Copyright (c) 2014 Woong Gyu La <juhgiyo@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. @section DESCRIPTION A License Class. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.Net.NetworkInformation; using System.Text.RegularExpressions; using System.IO; namespace EpLibrary.cs { /// <summary> /// License type /// </summary> [Flags] public enum LicenseType { /// <summary> /// Mac Address Checking /// </summary> MacAddress=0x1, /// <summary> /// Date Checking /// </summary> ExpireDate=0x2 } /// <summary> /// License Result /// </summary> public enum LicenseResult { /// <summary> /// Success /// </summary> Success, /// <summary> /// Date Expired /// </summary> Expired, /// <summary> /// Mac Address Mismatch /// </summary> MacAddressMisMatch, /// <summary> /// License Corrupted /// </summary> CorruptedLicense } /// <summary> /// A class that handles the license. /// </summary> public class License { /// <summary> /// Create License and return as string /// </summary> /// <param name="macAddress">mac address which licensed</param> /// <param name="dateTime">expiration date</param> /// <returns></returns> public static String CreateLicense(String password,LicenseType licenseType,String macAddress=null, DateTime? expirationDate=null) { String licenseData = ""; if ((licenseType & LicenseType.MacAddress) == LicenseType.MacAddress) { licenseData += Crypt.GetCrypt(CryptAlgo.Rijndael, "macaddress:" + macAddress, password, CryptType.Encrypt); licenseData += "\r\n"; } if ((licenseType & LicenseType.ExpireDate) == LicenseType.ExpireDate && expirationDate.HasValue) { licenseData += Crypt.GetCrypt(CryptAlgo.Rijndael, "expirationdate:" + expirationDate.Value.ToString("d"), password, CryptType.Encrypt); licenseData += "\r\n"; } return licenseData; } /// <summary> /// Return encrypted Mac Address /// </summary> /// <param name="password">password</param> /// <param name="licenseData">license data</param> /// <returns>decrypted Mac Address</returns> public static String GetDecryptedMacAddr(String password, String licenseData) { String[] lines = Regex.Split(licenseData, "\r\n"); String licensedMacAddress = null; foreach (String line in lines) { String decryptedData = Crypt.GetCrypt(CryptAlgo.Rijndael, line, password, CryptType.Decrypt); if (decryptedData!=null && decryptedData.Contains("macaddress:")) { decryptedData=decryptedData.Remove(0, "macaddress:".Length); licensedMacAddress = decryptedData; } } return licensedMacAddress; } /// <summary> /// Get Decrypted Expiration Date with license data /// </summary> /// <param name="password">password</param> /// <param name="licenseData">license data</param> /// <returns>retrieved expiration date</returns> public static DateTime? GetDecryptedExpirationDate(String password, String licenseData) { DateTime? expirationDate = null; String[] lines = Regex.Split(licenseData, "\r\n"); foreach (String line in lines) { String decryptedData = Crypt.GetCrypt(CryptAlgo.Rijndael, line, password, CryptType.Decrypt); if (decryptedData != null && decryptedData.Contains("expirationdate:")) { decryptedData = decryptedData.Remove(0, "expirationdate:".Length); expirationDate = Convert.ToDateTime(decryptedData); } } return expirationDate; } /// <summary> /// Get license data from the stream /// </summary> /// <param name="reader">stream reader</param> /// <returns>retrieved license data</returns> public static string GetLicenseDataFromStream(StringReader reader) { string licenseData = null; string tmpData = null; while ((tmpData = reader.ReadLine()) != null) { licenseData += tmpData + "\r\n"; } return licenseData; } /// <summary> /// Check License with given license string /// </summary> /// <param name="licenseData">license string</param> /// <returns>result of checking</returns> public static LicenseResult CheckLicense(String password, LicenseType licenseType, String licenseData) { String licensedMacAddress = null; DateTime? expirationDate=null; String[] lines=Regex.Split(licenseData,"\r\n"); foreach (String line in lines) { if(line.Trim().Equals("")) continue; String decryptedData = Crypt.GetCrypt(CryptAlgo.Rijndael, line, password, CryptType.Decrypt); if (decryptedData != null && decryptedData.Contains("macaddress:")) { decryptedData = decryptedData.Remove(0, "macaddress:".Length); licensedMacAddress = decryptedData; } else if (decryptedData != null && decryptedData.Contains("expirationdate:")) { decryptedData = decryptedData.Remove(0, "expirationdate:".Length); expirationDate = Convert.ToDateTime(decryptedData); } } if ((licenseType & LicenseType.MacAddress) == LicenseType.MacAddress) { if (licensedMacAddress == null) return LicenseResult.CorruptedLicense; if (!checkMacAddress(licensedMacAddress)) return LicenseResult.MacAddressMisMatch; } if ((licenseType & LicenseType.ExpireDate) == LicenseType.ExpireDate) { if (!expirationDate.HasValue) return LicenseResult.CorruptedLicense; if (!checkDate(expirationDate.Value)) return LicenseResult.Expired; } return LicenseResult.Success; } /// <summary> /// Return the list of MAC Addresses /// </summary> /// <returns>the list of MAC Addresses</returns> public static List<String> GetMacAddress() { List<String> macAddresses = new List<String>(); foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { if(nic.GetPhysicalAddress().ToString().Length>0) macAddresses.Add(nic.GetPhysicalAddress().ToString()); } return macAddresses; } /// <summary> /// Check if current mac address matches licensed mac address /// </summary> /// <param name="licenesedMacAddress">licensed mac address</param> /// <returns>true if matched otherwise false</returns> private static bool checkMacAddress(String licenesedMacAddress) { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { if (licenesedMacAddress.CompareTo(nic.GetPhysicalAddress().ToString()) == 0) return true; } return false; } /// <summary> /// Check if license is expired with current date /// </summary> /// <param name="expirationDate">expiration date</param> /// <returns>true if not expired otherwise false</returns> private static bool checkDate(DateTime expirationDate) { DateTime curTime= DateTime.Now; if (curTime.Year > expirationDate.Year) { return false; } if (curTime.Year == expirationDate.Year) { if (curTime.Month > expirationDate.Month) return false; if (curTime.Month == expirationDate.Month) { if (curTime.Day > expirationDate.Day) return false; } } return true; } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Workflows.Executions.V1Beta.Snippets { using Google.Api.Gax; using Google.Cloud.Workflows.Common.V1Beta; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class GeneratedExecutionsClientSnippets { /// <summary>Snippet for ListExecutions</summary> public void ListExecutionsRequestObject() { // Snippet: ListExecutions(ListExecutionsRequest, CallSettings) // Create client ExecutionsClient executionsClient = ExecutionsClient.Create(); // Initialize request argument(s) ListExecutionsRequest request = new ListExecutionsRequest { ParentAsWorkflowName = WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"), View = ExecutionView.Unspecified, }; // Make the request PagedEnumerable<ListExecutionsResponse, Execution> response = executionsClient.ListExecutions(request); // Iterate over all response items, lazily performing RPCs as required foreach (Execution item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListExecutionsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Execution item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Execution> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Execution item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListExecutionsAsync</summary> public async Task ListExecutionsRequestObjectAsync() { // Snippet: ListExecutionsAsync(ListExecutionsRequest, CallSettings) // Create client ExecutionsClient executionsClient = await ExecutionsClient.CreateAsync(); // Initialize request argument(s) ListExecutionsRequest request = new ListExecutionsRequest { ParentAsWorkflowName = WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"), View = ExecutionView.Unspecified, }; // Make the request PagedAsyncEnumerable<ListExecutionsResponse, Execution> response = executionsClient.ListExecutionsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Execution item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListExecutionsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Execution item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Execution> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Execution item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListExecutions</summary> public void ListExecutions() { // Snippet: ListExecutions(string, string, int?, CallSettings) // Create client ExecutionsClient executionsClient = ExecutionsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/workflows/[WORKFLOW]"; // Make the request PagedEnumerable<ListExecutionsResponse, Execution> response = executionsClient.ListExecutions(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Execution item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListExecutionsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Execution item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Execution> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Execution item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListExecutionsAsync</summary> public async Task ListExecutionsAsync() { // Snippet: ListExecutionsAsync(string, string, int?, CallSettings) // Create client ExecutionsClient executionsClient = await ExecutionsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/workflows/[WORKFLOW]"; // Make the request PagedAsyncEnumerable<ListExecutionsResponse, Execution> response = executionsClient.ListExecutionsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Execution item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListExecutionsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Execution item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Execution> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Execution item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListExecutions</summary> public void ListExecutionsResourceNames() { // Snippet: ListExecutions(WorkflowName, string, int?, CallSettings) // Create client ExecutionsClient executionsClient = ExecutionsClient.Create(); // Initialize request argument(s) WorkflowName parent = WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"); // Make the request PagedEnumerable<ListExecutionsResponse, Execution> response = executionsClient.ListExecutions(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Execution item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListExecutionsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Execution item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Execution> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Execution item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListExecutionsAsync</summary> public async Task ListExecutionsResourceNamesAsync() { // Snippet: ListExecutionsAsync(WorkflowName, string, int?, CallSettings) // Create client ExecutionsClient executionsClient = await ExecutionsClient.CreateAsync(); // Initialize request argument(s) WorkflowName parent = WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"); // Make the request PagedAsyncEnumerable<ListExecutionsResponse, Execution> response = executionsClient.ListExecutionsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Execution item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListExecutionsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Execution item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Execution> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Execution item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for CreateExecution</summary> public void CreateExecutionRequestObject() { // Snippet: CreateExecution(CreateExecutionRequest, CallSettings) // Create client ExecutionsClient executionsClient = ExecutionsClient.Create(); // Initialize request argument(s) CreateExecutionRequest request = new CreateExecutionRequest { ParentAsWorkflowName = WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"), Execution = new Execution(), }; // Make the request Execution response = executionsClient.CreateExecution(request); // End snippet } /// <summary>Snippet for CreateExecutionAsync</summary> public async Task CreateExecutionRequestObjectAsync() { // Snippet: CreateExecutionAsync(CreateExecutionRequest, CallSettings) // Additional: CreateExecutionAsync(CreateExecutionRequest, CancellationToken) // Create client ExecutionsClient executionsClient = await ExecutionsClient.CreateAsync(); // Initialize request argument(s) CreateExecutionRequest request = new CreateExecutionRequest { ParentAsWorkflowName = WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"), Execution = new Execution(), }; // Make the request Execution response = await executionsClient.CreateExecutionAsync(request); // End snippet } /// <summary>Snippet for CreateExecution</summary> public void CreateExecution() { // Snippet: CreateExecution(string, Execution, CallSettings) // Create client ExecutionsClient executionsClient = ExecutionsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/workflows/[WORKFLOW]"; Execution execution = new Execution(); // Make the request Execution response = executionsClient.CreateExecution(parent, execution); // End snippet } /// <summary>Snippet for CreateExecutionAsync</summary> public async Task CreateExecutionAsync() { // Snippet: CreateExecutionAsync(string, Execution, CallSettings) // Additional: CreateExecutionAsync(string, Execution, CancellationToken) // Create client ExecutionsClient executionsClient = await ExecutionsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/workflows/[WORKFLOW]"; Execution execution = new Execution(); // Make the request Execution response = await executionsClient.CreateExecutionAsync(parent, execution); // End snippet } /// <summary>Snippet for CreateExecution</summary> public void CreateExecutionResourceNames() { // Snippet: CreateExecution(WorkflowName, Execution, CallSettings) // Create client ExecutionsClient executionsClient = ExecutionsClient.Create(); // Initialize request argument(s) WorkflowName parent = WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"); Execution execution = new Execution(); // Make the request Execution response = executionsClient.CreateExecution(parent, execution); // End snippet } /// <summary>Snippet for CreateExecutionAsync</summary> public async Task CreateExecutionResourceNamesAsync() { // Snippet: CreateExecutionAsync(WorkflowName, Execution, CallSettings) // Additional: CreateExecutionAsync(WorkflowName, Execution, CancellationToken) // Create client ExecutionsClient executionsClient = await ExecutionsClient.CreateAsync(); // Initialize request argument(s) WorkflowName parent = WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"); Execution execution = new Execution(); // Make the request Execution response = await executionsClient.CreateExecutionAsync(parent, execution); // End snippet } /// <summary>Snippet for GetExecution</summary> public void GetExecutionRequestObject() { // Snippet: GetExecution(GetExecutionRequest, CallSettings) // Create client ExecutionsClient executionsClient = ExecutionsClient.Create(); // Initialize request argument(s) GetExecutionRequest request = new GetExecutionRequest { ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"), View = ExecutionView.Unspecified, }; // Make the request Execution response = executionsClient.GetExecution(request); // End snippet } /// <summary>Snippet for GetExecutionAsync</summary> public async Task GetExecutionRequestObjectAsync() { // Snippet: GetExecutionAsync(GetExecutionRequest, CallSettings) // Additional: GetExecutionAsync(GetExecutionRequest, CancellationToken) // Create client ExecutionsClient executionsClient = await ExecutionsClient.CreateAsync(); // Initialize request argument(s) GetExecutionRequest request = new GetExecutionRequest { ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"), View = ExecutionView.Unspecified, }; // Make the request Execution response = await executionsClient.GetExecutionAsync(request); // End snippet } /// <summary>Snippet for GetExecution</summary> public void GetExecution() { // Snippet: GetExecution(string, CallSettings) // Create client ExecutionsClient executionsClient = ExecutionsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/workflows/[WORKFLOW]/executions/[EXECUTION]"; // Make the request Execution response = executionsClient.GetExecution(name); // End snippet } /// <summary>Snippet for GetExecutionAsync</summary> public async Task GetExecutionAsync() { // Snippet: GetExecutionAsync(string, CallSettings) // Additional: GetExecutionAsync(string, CancellationToken) // Create client ExecutionsClient executionsClient = await ExecutionsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/workflows/[WORKFLOW]/executions/[EXECUTION]"; // Make the request Execution response = await executionsClient.GetExecutionAsync(name); // End snippet } /// <summary>Snippet for GetExecution</summary> public void GetExecutionResourceNames() { // Snippet: GetExecution(ExecutionName, CallSettings) // Create client ExecutionsClient executionsClient = ExecutionsClient.Create(); // Initialize request argument(s) ExecutionName name = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"); // Make the request Execution response = executionsClient.GetExecution(name); // End snippet } /// <summary>Snippet for GetExecutionAsync</summary> public async Task GetExecutionResourceNamesAsync() { // Snippet: GetExecutionAsync(ExecutionName, CallSettings) // Additional: GetExecutionAsync(ExecutionName, CancellationToken) // Create client ExecutionsClient executionsClient = await ExecutionsClient.CreateAsync(); // Initialize request argument(s) ExecutionName name = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"); // Make the request Execution response = await executionsClient.GetExecutionAsync(name); // End snippet } /// <summary>Snippet for CancelExecution</summary> public void CancelExecutionRequestObject() { // Snippet: CancelExecution(CancelExecutionRequest, CallSettings) // Create client ExecutionsClient executionsClient = ExecutionsClient.Create(); // Initialize request argument(s) CancelExecutionRequest request = new CancelExecutionRequest { ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"), }; // Make the request Execution response = executionsClient.CancelExecution(request); // End snippet } /// <summary>Snippet for CancelExecutionAsync</summary> public async Task CancelExecutionRequestObjectAsync() { // Snippet: CancelExecutionAsync(CancelExecutionRequest, CallSettings) // Additional: CancelExecutionAsync(CancelExecutionRequest, CancellationToken) // Create client ExecutionsClient executionsClient = await ExecutionsClient.CreateAsync(); // Initialize request argument(s) CancelExecutionRequest request = new CancelExecutionRequest { ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"), }; // Make the request Execution response = await executionsClient.CancelExecutionAsync(request); // End snippet } /// <summary>Snippet for CancelExecution</summary> public void CancelExecution() { // Snippet: CancelExecution(string, CallSettings) // Create client ExecutionsClient executionsClient = ExecutionsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/workflows/[WORKFLOW]/executions/[EXECUTION]"; // Make the request Execution response = executionsClient.CancelExecution(name); // End snippet } /// <summary>Snippet for CancelExecutionAsync</summary> public async Task CancelExecutionAsync() { // Snippet: CancelExecutionAsync(string, CallSettings) // Additional: CancelExecutionAsync(string, CancellationToken) // Create client ExecutionsClient executionsClient = await ExecutionsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/workflows/[WORKFLOW]/executions/[EXECUTION]"; // Make the request Execution response = await executionsClient.CancelExecutionAsync(name); // End snippet } /// <summary>Snippet for CancelExecution</summary> public void CancelExecutionResourceNames() { // Snippet: CancelExecution(ExecutionName, CallSettings) // Create client ExecutionsClient executionsClient = ExecutionsClient.Create(); // Initialize request argument(s) ExecutionName name = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"); // Make the request Execution response = executionsClient.CancelExecution(name); // End snippet } /// <summary>Snippet for CancelExecutionAsync</summary> public async Task CancelExecutionResourceNamesAsync() { // Snippet: CancelExecutionAsync(ExecutionName, CallSettings) // Additional: CancelExecutionAsync(ExecutionName, CancellationToken) // Create client ExecutionsClient executionsClient = await ExecutionsClient.CreateAsync(); // Initialize request argument(s) ExecutionName name = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"); // Make the request Execution response = await executionsClient.CancelExecutionAsync(name); // End snippet } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Globalization; using System.Reflection; namespace System.Net { internal enum CookieToken { // State types Nothing, NameValuePair, // X=Y Attribute, // X EndToken, // ';' EndCookie, // ',' End, // EOLN Equals, // Value types Comment, CommentUrl, CookieName, Discard, Domain, Expires, MaxAge, Path, Port, Secure, HttpOnly, Unknown, Version } // CookieTokenizer // // Used to split a single or multi-cookie (header) string into individual // tokens. internal class CookieTokenizer { private bool _eofCookie; private int _index; private readonly int _length; private string _name; private bool _quoted; private int _start; private CookieToken _token; private int _tokenLength; private readonly string _tokenStream; private string _value; private int _cookieStartIndex; private int _cookieLength; internal CookieTokenizer(string tokenStream) { _length = tokenStream.Length; _tokenStream = tokenStream; } internal bool EndOfCookie { get { return _eofCookie; } set { _eofCookie = value; } } internal bool Eof { get { return _index >= _length; } } internal string Name { get { return _name; } set { _name = value; } } internal bool Quoted { get { return _quoted; } set { _quoted = value; } } internal CookieToken Token { get { return _token; } set { _token = value; } } internal string Value { get { return _value; } set { _value = value; } } // Extract // // Extracts the current token internal string Extract() { string tokenString = string.Empty; if (_tokenLength != 0) { tokenString = Quoted ? _tokenStream.Substring(_start, _tokenLength) : _tokenStream.SubstringTrim(_start, _tokenLength); } return tokenString; } // FindNext // // Find the start and length of the next token. The token is terminated // by one of: // - end-of-line // - end-of-cookie: unquoted comma separates multiple cookies // - end-of-token: unquoted semi-colon // - end-of-name: unquoted equals // // Inputs: // <argument> ignoreComma // true if parsing doesn't stop at a comma. This is only true when // we know we're parsing an original cookie that has an expires= // attribute, because the format of the time/date used in expires // is: // Wdy, dd-mmm-yyyy HH:MM:SS GMT // // <argument> ignoreEquals // true if parsing doesn't stop at an equals sign. The LHS of the // first equals sign is an attribute name. The next token may // include one or more equals signs. For example: // SESSIONID=ID=MSNx45&q=33 // // Outputs: // <member> _index // incremented to the last position in _tokenStream contained by // the current token // // <member> _start // incremented to the start of the current token // // <member> _tokenLength // set to the length of the current token // // Assumes: Nothing // // Returns: // type of CookieToken found: // // End - end of the cookie string // EndCookie - end of current cookie in (potentially) a // multi-cookie string // EndToken - end of name=value pair, or end of an attribute // Equals - end of name= // // Throws: Nothing internal CookieToken FindNext(bool ignoreComma, bool ignoreEquals) { _tokenLength = 0; _start = _index; while ((_index < _length) && char.IsWhiteSpace(_tokenStream[_index])) { ++_index; ++_start; } CookieToken token = CookieToken.End; int increment = 1; if (!Eof) { if (_tokenStream[_index] == '"') { Quoted = true; ++_index; bool quoteOn = false; while (_index < _length) { char currChar = _tokenStream[_index]; if (!quoteOn && currChar == '"') { break; } if (quoteOn) { quoteOn = false; } else if (currChar == '\\') { quoteOn = true; } ++_index; } if (_index < _length) { ++_index; } _tokenLength = _index - _start; increment = 0; // If we are here, reset ignoreComma. // In effect, we ignore everything after quoted string until the next delimiter. ignoreComma = false; } while ((_index < _length) && (_tokenStream[_index] != ';') && (ignoreEquals || (_tokenStream[_index] != '=')) && (ignoreComma || (_tokenStream[_index] != ','))) { // Fixing 2 things: // 1) ignore day of week in cookie string // 2) revert ignoreComma once meet it, so won't miss the next cookie) if (_tokenStream[_index] == ',') { _start = _index + 1; _tokenLength = -1; ignoreComma = false; } ++_index; _tokenLength += increment; } if (!Eof) { switch (_tokenStream[_index]) { case ';': token = CookieToken.EndToken; break; case '=': token = CookieToken.Equals; break; default: _cookieLength = _index - _cookieStartIndex; token = CookieToken.EndCookie; break; } ++_index; } if (Eof) { _cookieLength = _index - _cookieStartIndex; } } return token; } // Next // // Get the next cookie name/value or attribute // // Cookies come in the following formats: // // 1. Version0 // Set-Cookie: [<name>][=][<value>] // [; expires=<date>] // [; path=<path>] // [; domain=<domain>] // [; secure] // Cookie: <name>=<value> // // Notes: <name> and/or <value> may be blank // <date> is the RFC 822/1123 date format that // incorporates commas, e.g. // "Wednesday, 09-Nov-99 23:12:40 GMT" // // 2. RFC 2109 // Set-Cookie: 1#{ // <name>=<value> // [; comment=<comment>] // [; domain=<domain>] // [; max-age=<seconds>] // [; path=<path>] // [; secure] // ; Version=<version> // } // Cookie: $Version=<version> // 1#{ // ; <name>=<value> // [; path=<path>] // [; domain=<domain>] // } // // 3. RFC 2965 // Set-Cookie2: 1#{ // <name>=<value> // [; comment=<comment>] // [; commentURL=<comment>] // [; discard] // [; domain=<domain>] // [; max-age=<seconds>] // [; path=<path>] // [; ports=<portlist>] // [; secure] // ; Version=<version> // } // Cookie: $Version=<version> // 1#{ // ; <name>=<value> // [; path=<path>] // [; domain=<domain>] // [; port="<port>"] // } // [Cookie2: $Version=<version>] // // Inputs: // <argument> first // true if this is the first name/attribute that we have looked for // in the cookie stream // // Outputs: // // Assumes: // Nothing // // Returns: // type of CookieToken found: // // - Attribute // - token was single-value. May be empty. Caller should check // Eof or EndCookie to determine if any more action needs to // be taken // // - NameValuePair // - Name and Value are meaningful. Either may be empty // // Throws: // Nothing internal CookieToken Next(bool first, bool parseResponseCookies) { Reset(); if (first) { _cookieStartIndex = _index; _cookieLength = 0; } CookieToken terminator = FindNext(false, false); if (terminator == CookieToken.EndCookie) { EndOfCookie = true; } if ((terminator == CookieToken.End) || (terminator == CookieToken.EndCookie)) { if ((Name = Extract()).Length != 0) { Token = TokenFromName(parseResponseCookies); return CookieToken.Attribute; } return terminator; } Name = Extract(); if (first) { Token = CookieToken.CookieName; } else { Token = TokenFromName(parseResponseCookies); } if (terminator == CookieToken.Equals) { terminator = FindNext(!first && (Token == CookieToken.Expires), true); if (terminator == CookieToken.EndCookie) { EndOfCookie = true; } Value = Extract(); return CookieToken.NameValuePair; } else { return CookieToken.Attribute; } } // Reset // // Sets this tokenizer up for finding the next name/value pair, // attribute, or end-of-{token,cookie,line}. internal void Reset() { _eofCookie = false; _name = string.Empty; _quoted = false; _start = _index; _token = CookieToken.Nothing; _tokenLength = 0; _value = string.Empty; } private struct RecognizedAttribute { private readonly string _name; private readonly CookieToken _token; internal RecognizedAttribute(string name, CookieToken token) { _name = name; _token = token; } internal CookieToken Token { get { return _token; } } internal bool IsEqualTo(string value) { return string.Equals(_name, value, StringComparison.OrdinalIgnoreCase); } } // Recognized attributes in order of expected frequency. private static readonly RecognizedAttribute[] s_recognizedAttributes = { new RecognizedAttribute(CookieFields.PathAttributeName, CookieToken.Path), new RecognizedAttribute(CookieFields.MaxAgeAttributeName, CookieToken.MaxAge), new RecognizedAttribute(CookieFields.ExpiresAttributeName, CookieToken.Expires), new RecognizedAttribute(CookieFields.VersionAttributeName, CookieToken.Version), new RecognizedAttribute(CookieFields.DomainAttributeName, CookieToken.Domain), new RecognizedAttribute(CookieFields.SecureAttributeName, CookieToken.Secure), new RecognizedAttribute(CookieFields.DiscardAttributeName, CookieToken.Discard), new RecognizedAttribute(CookieFields.PortAttributeName, CookieToken.Port), new RecognizedAttribute(CookieFields.CommentAttributeName, CookieToken.Comment), new RecognizedAttribute(CookieFields.CommentUrlAttributeName, CookieToken.CommentUrl), new RecognizedAttribute(CookieFields.HttpOnlyAttributeName, CookieToken.HttpOnly), }; private static readonly RecognizedAttribute[] s_recognizedServerAttributes = { new RecognizedAttribute('$' + CookieFields.PathAttributeName, CookieToken.Path), new RecognizedAttribute('$' + CookieFields.VersionAttributeName, CookieToken.Version), new RecognizedAttribute('$' + CookieFields.DomainAttributeName, CookieToken.Domain), new RecognizedAttribute('$' + CookieFields.PortAttributeName, CookieToken.Port), new RecognizedAttribute('$' + CookieFields.HttpOnlyAttributeName, CookieToken.HttpOnly), }; internal CookieToken TokenFromName(bool parseResponseCookies) { if (!parseResponseCookies) { for (int i = 0; i < s_recognizedServerAttributes.Length; ++i) { if (s_recognizedServerAttributes[i].IsEqualTo(Name)) { return s_recognizedServerAttributes[i].Token; } } } else { for (int i = 0; i < s_recognizedAttributes.Length; ++i) { if (s_recognizedAttributes[i].IsEqualTo(Name)) { return s_recognizedAttributes[i].Token; } } } return CookieToken.Unknown; } } // CookieParser // // Takes a cookie header, makes cookies. internal class CookieParser { private readonly CookieTokenizer _tokenizer; private Cookie _savedCookie; internal CookieParser(string cookieString) { _tokenizer = new CookieTokenizer(cookieString); } #if SYSTEM_NET_PRIMITIVES_DLL private static bool InternalSetNameMethod(Cookie cookie, string value) { return cookie.InternalSetName(value); } #else private static Func<Cookie, string, bool> s_internalSetNameMethod; private static Func<Cookie, string, bool> InternalSetNameMethod { get { if (s_internalSetNameMethod == null) { // TODO: #13607 // We need to use Cookie.InternalSetName instead of the Cookie.set_Name wrapped in a try catch block, as // Cookie.set_Name keeps the original name if the string is empty or null. // Unfortunately this API is internal so we use reflection to access it. The method is cached for performance reasons. MethodInfo method = typeof(Cookie).GetMethod("InternalSetName", BindingFlags.Instance | BindingFlags.NonPublic); Debug.Assert(method != null, "We need to use an internal method named InternalSetName that is declared on Cookie."); s_internalSetNameMethod = (Func<Cookie, string, bool>)Delegate.CreateDelegate(typeof(Func<Cookie, string, bool>), method); } return s_internalSetNameMethod; } } #endif private static FieldInfo s_isQuotedDomainField = null; private static FieldInfo IsQuotedDomainField { get { if (s_isQuotedDomainField == null) { // TODO: #13607 FieldInfo field = typeof(Cookie).GetField("IsQuotedDomain", BindingFlags.Instance | BindingFlags.NonPublic); Debug.Assert(field != null, "We need to use an internal field named IsQuotedDomain that is declared on Cookie."); s_isQuotedDomainField = field; } return s_isQuotedDomainField; } } private static FieldInfo s_isQuotedVersionField = null; private static FieldInfo IsQuotedVersionField { get { if (s_isQuotedVersionField == null) { // TODO: #13607 FieldInfo field = typeof(Cookie).GetField("IsQuotedVersion", BindingFlags.Instance | BindingFlags.NonPublic); Debug.Assert(field != null, "We need to use an internal field named IsQuotedVersion that is declared on Cookie."); s_isQuotedVersionField = field; } return s_isQuotedVersionField; } } // Get // // Gets the next cookie or null if there are no more cookies. internal Cookie Get() { Cookie cookie = null; // Only the first occurrence of an attribute value must be counted. bool commentSet = false; bool commentUriSet = false; bool domainSet = false; bool expiresSet = false; bool pathSet = false; bool portSet = false; // Special case: may have no value in header. bool versionSet = false; bool secureSet = false; bool discardSet = false; do { CookieToken token = _tokenizer.Next(cookie == null, true); if (cookie == null && (token == CookieToken.NameValuePair || token == CookieToken.Attribute)) { cookie = new Cookie(); InternalSetNameMethod(cookie, _tokenizer.Name); cookie.Value = _tokenizer.Value; } else { switch (token) { case CookieToken.NameValuePair: switch (_tokenizer.Token) { case CookieToken.Comment: if (!commentSet) { commentSet = true; cookie.Comment = _tokenizer.Value; } break; case CookieToken.CommentUrl: if (!commentUriSet) { commentUriSet = true; if (Uri.TryCreate(CheckQuoted(_tokenizer.Value), UriKind.Absolute, out Uri parsed)) { cookie.CommentUri = parsed; } } break; case CookieToken.Domain: if (!domainSet) { domainSet = true; cookie.Domain = CheckQuoted(_tokenizer.Value); IsQuotedDomainField.SetValue(cookie, _tokenizer.Quoted); } break; case CookieToken.Expires: if (!expiresSet) { expiresSet = true; if (DateTime.TryParse(CheckQuoted(_tokenizer.Value), CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out DateTime expires)) { cookie.Expires = expires; } else { // This cookie will be rejected InternalSetNameMethod(cookie, string.Empty); } } break; case CookieToken.MaxAge: if (!expiresSet) { expiresSet = true; if (int.TryParse(CheckQuoted(_tokenizer.Value), out int parsed)) { cookie.Expires = DateTime.Now.AddSeconds(parsed); } else { // This cookie will be rejected InternalSetNameMethod(cookie, string.Empty); } } break; case CookieToken.Path: if (!pathSet) { pathSet = true; cookie.Path = _tokenizer.Value; } break; case CookieToken.Port: if (!portSet) { portSet = true; try { cookie.Port = _tokenizer.Value; } catch { // This cookie will be rejected InternalSetNameMethod(cookie, string.Empty); } } break; case CookieToken.Version: if (!versionSet) { versionSet = true; int parsed; if (int.TryParse(CheckQuoted(_tokenizer.Value), out parsed)) { cookie.Version = parsed; IsQuotedVersionField.SetValue(cookie, _tokenizer.Quoted); } else { // This cookie will be rejected InternalSetNameMethod(cookie, string.Empty); } } break; } break; case CookieToken.Attribute: switch (_tokenizer.Token) { case CookieToken.Discard: if (!discardSet) { discardSet = true; cookie.Discard = true; } break; case CookieToken.Secure: if (!secureSet) { secureSet = true; cookie.Secure = true; } break; case CookieToken.HttpOnly: cookie.HttpOnly = true; break; case CookieToken.Port: if (!portSet) { portSet = true; cookie.Port = string.Empty; } break; } break; } } } while (!_tokenizer.Eof && !_tokenizer.EndOfCookie); return cookie; } internal Cookie GetServer() { Cookie cookie = _savedCookie; _savedCookie = null; // Only the first occurrence of an attribute value must be counted. bool domainSet = false; bool pathSet = false; bool portSet = false; // Special case: may have no value in header. do { bool first = cookie == null || string.IsNullOrEmpty(cookie.Name); CookieToken token = _tokenizer.Next(first, false); if (first && (token == CookieToken.NameValuePair || token == CookieToken.Attribute)) { if (cookie == null) { cookie = new Cookie(); } InternalSetNameMethod(cookie, _tokenizer.Name); cookie.Value = _tokenizer.Value; } else { switch (token) { case CookieToken.NameValuePair: switch (_tokenizer.Token) { case CookieToken.Domain: if (!domainSet) { domainSet = true; cookie.Domain = CheckQuoted(_tokenizer.Value); IsQuotedDomainField.SetValue(cookie, _tokenizer.Quoted); } break; case CookieToken.Path: if (!pathSet) { pathSet = true; cookie.Path = _tokenizer.Value; } break; case CookieToken.Port: if (!portSet) { portSet = true; try { cookie.Port = _tokenizer.Value; } catch (CookieException) { // This cookie will be rejected InternalSetNameMethod(cookie, string.Empty); } } break; case CookieToken.Version: // this is a new cookie, this token is for the next cookie. _savedCookie = new Cookie(); if (int.TryParse(_tokenizer.Value, out int parsed)) { _savedCookie.Version = parsed; } return cookie; case CookieToken.Unknown: // this is a new cookie, the token is for the next cookie. _savedCookie = new Cookie(); InternalSetNameMethod(_savedCookie, _tokenizer.Name); _savedCookie.Value = _tokenizer.Value; return cookie; } break; case CookieToken.Attribute: if (_tokenizer.Token == CookieToken.Port && !portSet) { portSet = true; cookie.Port = string.Empty; } break; } } } while (!_tokenizer.Eof && !_tokenizer.EndOfCookie); return cookie; } internal static string CheckQuoted(string value) { if (value.Length < 2 || value[0] != '\"' || value[value.Length - 1] != '\"') return value; return value.Length == 2 ? string.Empty : value.Substring(1, value.Length - 2); } internal bool EndofHeader() { return _tokenizer.Eof; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Runtime.InteropServices; using System.Threading; using Microsoft.Win32.SafeHandles; namespace System.Diagnostics { internal static partial class ProcessManager { /// <summary>Gets whether the process with the specified ID is currently running.</summary> /// <param name="processId">The process ID.</param> /// <returns>true if the process is running; otherwise, false.</returns> public static bool IsProcessRunning(int processId) { return IsProcessRunning(processId, "."); } /// <summary>Gets whether the process with the specified ID on the specified machine is currently running.</summary> /// <param name="processId">The process ID.</param> /// <param name="machineName">The machine name.</param> /// <returns>true if the process is running; otherwise, false.</returns> public static bool IsProcessRunning(int processId, string machineName) { // Performance optimization for the local machine: // First try to OpenProcess by id, if valid handle is returned, the process is definitely running // Otherwise enumerate all processes and compare ids if (!IsRemoteMachine(machineName)) { using (SafeProcessHandle processHandle = Interop.Kernel32.OpenProcess(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION, false, processId)) { if (!processHandle.IsInvalid) { return true; } } } return Array.IndexOf(GetProcessIds(machineName), processId) >= 0; } /// <summary>Gets process infos for each process on the specified machine.</summary> /// <param name="machineName">The target machine.</param> /// <returns>An array of process infos, one per found process.</returns> public static ProcessInfo[] GetProcessInfos(string machineName) { return IsRemoteMachine(machineName) ? NtProcessManager.GetProcessInfos(machineName, isRemoteMachine: true) : NtProcessInfoHelper.GetProcessInfos(); } /// <summary>Gets the ProcessInfo for the specified process ID on the specified machine.</summary> /// <param name="processId">The process ID.</param> /// <param name="machineName">The machine name.</param> /// <returns>The ProcessInfo for the process if it could be found; otherwise, null.</returns> public static ProcessInfo GetProcessInfo(int processId, string machineName) { if (IsRemoteMachine(machineName)) { // remote case: we take the hit of looping through all results ProcessInfo[] processInfos = NtProcessManager.GetProcessInfos(machineName, isRemoteMachine: true); foreach (ProcessInfo processInfo in processInfos) { if (processInfo.ProcessId == processId) { return processInfo; } } } else { // local case: do not use performance counter and also attempt to get the matching (by pid) process only ProcessInfo[] processInfos = NtProcessInfoHelper.GetProcessInfos(pid => pid == processId); if (processInfos.Length == 1) { return processInfos[0]; } } return null; } /// <summary>Gets the IDs of all processes on the specified machine.</summary> /// <param name="machineName">The machine to examine.</param> /// <returns>An array of process IDs from the specified machine.</returns> public static int[] GetProcessIds(string machineName) { // Due to the lack of support for EnumModules() on coresysserver, we rely // on PerformanceCounters to get the ProcessIds for both remote desktop // and the local machine, unlike Desktop on which we rely on PCs only for // remote machines. return IsRemoteMachine(machineName) ? NtProcessManager.GetProcessIds(machineName, true) : GetProcessIds(); } /// <summary>Gets the IDs of all processes on the current machine.</summary> public static int[] GetProcessIds() { return NtProcessManager.GetProcessIds(); } /// <summary>Gets the ID of a process from a handle to the process.</summary> /// <param name="processHandle">The handle.</param> /// <returns>The process ID.</returns> public static int GetProcessIdFromHandle(SafeProcessHandle processHandle) { return NtProcessManager.GetProcessIdFromHandle(processHandle); } /// <summary>Gets an array of module infos for the specified process.</summary> /// <param name="processId">The ID of the process whose modules should be enumerated.</param> /// <returns>The array of modules.</returns> public static ProcessModuleCollection GetModules(int processId) { return NtProcessManager.GetModules(processId); } private static bool IsRemoteMachineCore(string machineName) { string baseName; if (machineName.StartsWith("\\", StringComparison.Ordinal)) baseName = machineName.Substring(2); else baseName = machineName; if (baseName.Equals(".")) return false; return !string.Equals(Interop.Kernel32.GetComputerName(), baseName, StringComparison.OrdinalIgnoreCase); } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- static ProcessManager() { // In order to query information (OpenProcess) on some protected processes // like csrss, we need SeDebugPrivilege privilege. // After removing the dependency on Performance Counter, we don't have a chance // to run the code in CLR performance counter to ask for this privilege. // So we will try to get the privilege here. // We could fail if the user account doesn't have right to do this, but that's fair. Interop.Advapi32.LUID luid = new Interop.Advapi32.LUID(); if (!Interop.Advapi32.LookupPrivilegeValue(null, Interop.Advapi32.SeDebugPrivilege, out luid)) { return; } SafeTokenHandle tokenHandle = null; try { if (!Interop.Advapi32.OpenProcessToken( Interop.Kernel32.GetCurrentProcess(), Interop.Kernel32.HandleOptions.TOKEN_ADJUST_PRIVILEGES, out tokenHandle)) { return; } Interop.Advapi32.TokenPrivileges tp = new Interop.Advapi32.TokenPrivileges(); tp.Luid = luid; tp.Attributes = Interop.Advapi32.SEPrivileges.SE_PRIVILEGE_ENABLED; // AdjustTokenPrivileges can return true even if it didn't succeed (when ERROR_NOT_ALL_ASSIGNED is returned). Interop.Advapi32.AdjustTokenPrivileges(tokenHandle, false, tp, 0, IntPtr.Zero, IntPtr.Zero); } finally { if (tokenHandle != null) { tokenHandle.Dispose(); } } } public static SafeProcessHandle OpenProcess(int processId, int access, bool throwIfExited) { SafeProcessHandle processHandle = Interop.Kernel32.OpenProcess(access, false, processId); int result = Marshal.GetLastWin32Error(); if (!processHandle.IsInvalid) { return processHandle; } if (processId == 0) { throw new Win32Exception(5); } // If the handle is invalid because the process has exited, only throw an exception if throwIfExited is true. if (!IsProcessRunning(processId)) { if (throwIfExited) { throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, processId.ToString(CultureInfo.CurrentCulture))); } else { return SafeProcessHandle.InvalidHandle; } } throw new Win32Exception(result); } public static SafeThreadHandle OpenThread(int threadId, int access) { SafeThreadHandle threadHandle = Interop.Kernel32.OpenThread(access, false, threadId); int result = Marshal.GetLastWin32Error(); if (threadHandle.IsInvalid) { if (result == Interop.Errors.ERROR_INVALID_PARAMETER) throw new InvalidOperationException(SR.Format(SR.ThreadExited, threadId.ToString(CultureInfo.CurrentCulture))); throw new Win32Exception(result); } return threadHandle; } } /// <devdoc> /// This static class provides the process api for the WinNt platform. /// We use the performance counter api to query process and thread /// information. Module information is obtained using PSAPI. /// </devdoc> /// <internalonly/> internal static partial class NtProcessManager { private const int ProcessPerfCounterId = 230; private const int ThreadPerfCounterId = 232; private const string PerfCounterQueryString = "230 232"; internal const int IdleProcessID = 0; private static readonly Dictionary<String, ValueId> s_valueIds = new Dictionary<string, ValueId>(19) { { "Pool Paged Bytes", ValueId.PoolPagedBytes }, { "Pool Nonpaged Bytes", ValueId.PoolNonpagedBytes }, { "Elapsed Time", ValueId.ElapsedTime }, { "Virtual Bytes Peak", ValueId.VirtualBytesPeak }, { "Virtual Bytes", ValueId.VirtualBytes }, { "Private Bytes", ValueId.PrivateBytes }, { "Page File Bytes", ValueId.PageFileBytes }, { "Page File Bytes Peak", ValueId.PageFileBytesPeak }, { "Working Set Peak", ValueId.WorkingSetPeak }, { "Working Set", ValueId.WorkingSet }, { "ID Thread", ValueId.ThreadId }, { "ID Process", ValueId.ProcessId }, { "Priority Base", ValueId.BasePriority }, { "Priority Current", ValueId.CurrentPriority }, { "% User Time", ValueId.UserTime }, { "% Privileged Time", ValueId.PrivilegedTime }, { "Start Address", ValueId.StartAddress }, { "Thread State", ValueId.ThreadState }, { "Thread Wait Reason", ValueId.ThreadWaitReason } }; internal static int SystemProcessID { get { const int systemProcessIDOnXP = 4; return systemProcessIDOnXP; } } public static int[] GetProcessIds(string machineName, bool isRemoteMachine) { ProcessInfo[] infos = GetProcessInfos(machineName, isRemoteMachine); int[] ids = new int[infos.Length]; for (int i = 0; i < infos.Length; i++) ids[i] = infos[i].ProcessId; return ids; } public static int[] GetProcessIds() { int[] processIds = new int[256]; int size; for (; ; ) { if (!Interop.Kernel32.EnumProcesses(processIds, processIds.Length * 4, out size)) throw new Win32Exception(); if (size == processIds.Length * 4) { processIds = new int[processIds.Length * 2]; continue; } break; } int[] ids = new int[size / 4]; Array.Copy(processIds, 0, ids, 0, ids.Length); return ids; } public static ProcessModuleCollection GetModules(int processId) { return GetModules(processId, firstModuleOnly: false); } public static ProcessModule GetFirstModule(int processId) { ProcessModuleCollection modules = GetModules(processId, firstModuleOnly: true); return modules.Count == 0 ? null : modules[0]; } private static void HandleError() { int lastError = Marshal.GetLastWin32Error(); switch (lastError) { case Interop.Errors.ERROR_INVALID_HANDLE: case Interop.Errors.ERROR_PARTIAL_COPY: // It's possible that another thread caused this module to become // unloaded (e.g FreeLibrary was called on the module). Ignore it and // move on. break; default: throw new Win32Exception(lastError); } } public static int GetProcessIdFromHandle(SafeProcessHandle processHandle) { return Interop.Kernel32.GetProcessId(processHandle); } public static ProcessInfo[] GetProcessInfos(string machineName, bool isRemoteMachine) { PerformanceCounterLib library = null; try { library = PerformanceCounterLib.GetPerformanceCounterLib(machineName, new CultureInfo("en")); return GetProcessInfos(library); } catch (Exception e) { if (isRemoteMachine) { throw new InvalidOperationException(SR.CouldntConnectToRemoteMachine, e); } else { throw e; } } // We don't want to call library.Close() here because that would cause us to unload all of the perflibs. // On the next call to GetProcessInfos, we'd have to load them all up again, which is SLOW! } static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library) { ProcessInfo[] processInfos; int retryCount = 5; do { try { byte[] dataPtr = library.GetPerformanceData(PerfCounterQueryString); processInfos = GetProcessInfos(library, ProcessPerfCounterId, ThreadPerfCounterId, dataPtr); } catch (Exception e) { throw new InvalidOperationException(SR.CouldntGetProcessInfos, e); } --retryCount; } while (processInfos.Length == 0 && retryCount != 0); if (processInfos.Length == 0) throw new InvalidOperationException(SR.ProcessDisabled); return processInfos; } static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library, int processIndex, int threadIndex, byte[] data) { #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos()"); #endif Dictionary<int, ProcessInfo> processInfos = new Dictionary<int, ProcessInfo>(); List<ThreadInfo> threadInfos = new List<ThreadInfo>(); GCHandle dataHandle = new GCHandle(); try { dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned); IntPtr dataBlockPtr = dataHandle.AddrOfPinnedObject(); Interop.Advapi32.PERF_DATA_BLOCK dataBlock = new Interop.Advapi32.PERF_DATA_BLOCK(); Marshal.PtrToStructure(dataBlockPtr, dataBlock); IntPtr typePtr = (IntPtr)((long)dataBlockPtr + dataBlock.HeaderLength); Interop.Advapi32.PERF_INSTANCE_DEFINITION instance = new Interop.Advapi32.PERF_INSTANCE_DEFINITION(); Interop.Advapi32.PERF_COUNTER_BLOCK counterBlock = new Interop.Advapi32.PERF_COUNTER_BLOCK(); for (int i = 0; i < dataBlock.NumObjectTypes; i++) { Interop.Advapi32.PERF_OBJECT_TYPE type = new Interop.Advapi32.PERF_OBJECT_TYPE(); Marshal.PtrToStructure(typePtr, type); IntPtr instancePtr = (IntPtr)((long)typePtr + type.DefinitionLength); IntPtr counterPtr = (IntPtr)((long)typePtr + type.HeaderLength); List<Interop.Advapi32.PERF_COUNTER_DEFINITION> counterList = new List<Interop.Advapi32.PERF_COUNTER_DEFINITION>(); for (int j = 0; j < type.NumCounters; j++) { Interop.Advapi32.PERF_COUNTER_DEFINITION counter = new Interop.Advapi32.PERF_COUNTER_DEFINITION(); Marshal.PtrToStructure(counterPtr, counter); string counterName = library.GetCounterName(counter.CounterNameTitleIndex); if (type.ObjectNameTitleIndex == processIndex) counter.CounterNameTitlePtr = (int)GetValueId(counterName); else if (type.ObjectNameTitleIndex == threadIndex) counter.CounterNameTitlePtr = (int)GetValueId(counterName); counterList.Add(counter); counterPtr = (IntPtr)((long)counterPtr + counter.ByteLength); } Interop.Advapi32.PERF_COUNTER_DEFINITION[] counters = counterList.ToArray(); for (int j = 0; j < type.NumInstances; j++) { Marshal.PtrToStructure(instancePtr, instance); IntPtr namePtr = (IntPtr)((long)instancePtr + instance.NameOffset); string instanceName = Marshal.PtrToStringUni(namePtr); if (instanceName.Equals("_Total")) continue; IntPtr counterBlockPtr = (IntPtr)((long)instancePtr + instance.ByteLength); Marshal.PtrToStructure(counterBlockPtr, counterBlock); if (type.ObjectNameTitleIndex == processIndex) { ProcessInfo processInfo = GetProcessInfo(type, (IntPtr)((long)instancePtr + instance.ByteLength), counters); if (processInfo.ProcessId == 0 && string.Compare(instanceName, "Idle", StringComparison.OrdinalIgnoreCase) != 0) { // Sometimes we'll get a process structure that is not completely filled in. // We can catch some of these by looking for non-"idle" processes that have id 0 // and ignoring those. #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - found a non-idle process with id 0; ignoring."); #endif } else { if (processInfos.ContainsKey(processInfo.ProcessId)) { // We've found two entries in the perfcounters that claim to be the // same process. We throw an exception. Is this really going to be // helpful to the user? Should we just ignore? #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - found a duplicate process id"); #endif } else { // the performance counters keep a 15 character prefix of the exe name, and then delete the ".exe", // if it's in the first 15. The problem is that sometimes that will leave us with part of ".exe" // at the end. If instanceName ends in ".", ".e", or ".ex" we remove it. string processName = instanceName; if (processName.Length == 15) { if (instanceName.EndsWith(".", StringComparison.Ordinal)) processName = instanceName.Substring(0, 14); else if (instanceName.EndsWith(".e", StringComparison.Ordinal)) processName = instanceName.Substring(0, 13); else if (instanceName.EndsWith(".ex", StringComparison.Ordinal)) processName = instanceName.Substring(0, 12); } processInfo.ProcessName = processName; processInfos.Add(processInfo.ProcessId, processInfo); } } } else if (type.ObjectNameTitleIndex == threadIndex) { ThreadInfo threadInfo = GetThreadInfo(type, (IntPtr)((long)instancePtr + instance.ByteLength), counters); if (threadInfo._threadId != 0) threadInfos.Add(threadInfo); } instancePtr = (IntPtr)((long)instancePtr + instance.ByteLength + counterBlock.ByteLength); } typePtr = (IntPtr)((long)typePtr + type.TotalByteLength); } } finally { if (dataHandle.IsAllocated) dataHandle.Free(); } for (int i = 0; i < threadInfos.Count; i++) { ThreadInfo threadInfo = (ThreadInfo)threadInfos[i]; ProcessInfo processInfo; if (processInfos.TryGetValue(threadInfo._processId, out processInfo)) { processInfo._threadInfoList.Add(threadInfo); } } ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count]; processInfos.Values.CopyTo(temp, 0); return temp; } static ThreadInfo GetThreadInfo(Interop.Advapi32.PERF_OBJECT_TYPE type, IntPtr instancePtr, Interop.Advapi32.PERF_COUNTER_DEFINITION[] counters) { ThreadInfo threadInfo = new ThreadInfo(); for (int i = 0; i < counters.Length; i++) { Interop.Advapi32.PERF_COUNTER_DEFINITION counter = counters[i]; long value = ReadCounterValue(counter.CounterType, (IntPtr)((long)instancePtr + counter.CounterOffset)); switch ((ValueId)counter.CounterNameTitlePtr) { case ValueId.ProcessId: threadInfo._processId = (int)value; break; case ValueId.ThreadId: threadInfo._threadId = (ulong)value; break; case ValueId.BasePriority: threadInfo._basePriority = (int)value; break; case ValueId.CurrentPriority: threadInfo._currentPriority = (int)value; break; case ValueId.StartAddress: threadInfo._startAddress = (IntPtr)value; break; case ValueId.ThreadState: threadInfo._threadState = (ThreadState)value; break; case ValueId.ThreadWaitReason: threadInfo._threadWaitReason = GetThreadWaitReason((int)value); break; } } return threadInfo; } internal static ThreadWaitReason GetThreadWaitReason(int value) { switch (value) { case 0: case 7: return ThreadWaitReason.Executive; case 1: case 8: return ThreadWaitReason.FreePage; case 2: case 9: return ThreadWaitReason.PageIn; case 3: case 10: return ThreadWaitReason.SystemAllocation; case 4: case 11: return ThreadWaitReason.ExecutionDelay; case 5: case 12: return ThreadWaitReason.Suspended; case 6: case 13: return ThreadWaitReason.UserRequest; case 14: return ThreadWaitReason.EventPairHigh; ; case 15: return ThreadWaitReason.EventPairLow; case 16: return ThreadWaitReason.LpcReceive; case 17: return ThreadWaitReason.LpcReply; case 18: return ThreadWaitReason.VirtualMemory; case 19: return ThreadWaitReason.PageOut; default: return ThreadWaitReason.Unknown; } } static ProcessInfo GetProcessInfo(Interop.Advapi32.PERF_OBJECT_TYPE type, IntPtr instancePtr, Interop.Advapi32.PERF_COUNTER_DEFINITION[] counters) { ProcessInfo processInfo = new ProcessInfo(); for (int i = 0; i < counters.Length; i++) { Interop.Advapi32.PERF_COUNTER_DEFINITION counter = counters[i]; long value = ReadCounterValue(counter.CounterType, (IntPtr)((long)instancePtr + counter.CounterOffset)); switch ((ValueId)counter.CounterNameTitlePtr) { case ValueId.ProcessId: processInfo.ProcessId = (int)value; break; case ValueId.PoolPagedBytes: processInfo.PoolPagedBytes = value; break; case ValueId.PoolNonpagedBytes: processInfo.PoolNonPagedBytes = value; break; case ValueId.VirtualBytes: processInfo.VirtualBytes = value; break; case ValueId.VirtualBytesPeak: processInfo.VirtualBytesPeak = value; break; case ValueId.WorkingSetPeak: processInfo.WorkingSetPeak = value; break; case ValueId.WorkingSet: processInfo.WorkingSet = value; break; case ValueId.PageFileBytesPeak: processInfo.PageFileBytesPeak = value; break; case ValueId.PageFileBytes: processInfo.PageFileBytes = value; break; case ValueId.PrivateBytes: processInfo.PrivateBytes = value; break; case ValueId.BasePriority: processInfo.BasePriority = (int)value; break; case ValueId.HandleCount: processInfo.HandleCount = (int)value; break; } } return processInfo; } static ValueId GetValueId(string counterName) { if (counterName != null) { ValueId id; if (s_valueIds.TryGetValue(counterName, out id)) return id; } return ValueId.Unknown; } static long ReadCounterValue(int counterType, IntPtr dataPtr) { if ((counterType & Interop.Advapi32.PerfCounterOptions.NtPerfCounterSizeLarge) != 0) return Marshal.ReadInt64(dataPtr); else return (long)Marshal.ReadInt32(dataPtr); } enum ValueId { Unknown = -1, HandleCount, PoolPagedBytes, PoolNonpagedBytes, ElapsedTime, VirtualBytesPeak, VirtualBytes, PrivateBytes, PageFileBytes, PageFileBytesPeak, WorkingSetPeak, WorkingSet, ThreadId, ProcessId, BasePriority, CurrentPriority, UserTime, PrivilegedTime, StartAddress, ThreadState, ThreadWaitReason } } internal static partial class NtProcessInfoHelper { private static int GetNewBufferSize(int existingBufferSize, int requiredSize) { if (requiredSize == 0) { // // On some old OS like win2000, requiredSize will not be set if the buffer // passed to NtQuerySystemInformation is not enough. // int newSize = existingBufferSize * 2; if (newSize < existingBufferSize) { // In reality, we should never overflow. // Adding the code here just in case it happens. throw new OutOfMemoryException(); } return newSize; } else { // allocating a few more kilo bytes just in case there are some new process // kicked in since new call to NtQuerySystemInformation int newSize = requiredSize + 1024 * 10; if (newSize < requiredSize) { throw new OutOfMemoryException(); } return newSize; } } // Use a smaller buffer size on debug to ensure we hit the retry path. #if DEBUG private const int DefaultCachedBufferSize = 1024; #else private const int DefaultCachedBufferSize = 128 * 1024; #endif private static unsafe ProcessInfo[] GetProcessInfos(IntPtr dataPtr, Predicate<int> processIdFilter) { // Use a dictionary to avoid duplicate entries if any // 60 is a reasonable number for processes on a normal machine. Dictionary<int, ProcessInfo> processInfos = new Dictionary<int, ProcessInfo>(60); long totalOffset = 0; while (true) { IntPtr currentPtr = (IntPtr)((long)dataPtr + totalOffset); ref SystemProcessInformation pi = ref *(SystemProcessInformation *)(currentPtr); // Process ID shouldn't overflow. OS API GetCurrentProcessID returns DWORD. var processInfoProcessId = pi.UniqueProcessId.ToInt32(); if (processIdFilter == null || processIdFilter(processInfoProcessId)) { // get information for a process ProcessInfo processInfo = new ProcessInfo(); processInfo.ProcessId = processInfoProcessId; processInfo.SessionId = (int)pi.SessionId; processInfo.PoolPagedBytes = (long)pi.QuotaPagedPoolUsage; processInfo.PoolNonPagedBytes = (long)pi.QuotaNonPagedPoolUsage; processInfo.VirtualBytes = (long)pi.VirtualSize; processInfo.VirtualBytesPeak = (long)pi.PeakVirtualSize; processInfo.WorkingSetPeak = (long)pi.PeakWorkingSetSize; processInfo.WorkingSet = (long)pi.WorkingSetSize; processInfo.PageFileBytesPeak = (long)pi.PeakPagefileUsage; processInfo.PageFileBytes = (long)pi.PagefileUsage; processInfo.PrivateBytes = (long)pi.PrivatePageCount; processInfo.BasePriority = pi.BasePriority; processInfo.HandleCount = (int)pi.HandleCount; if (pi.ImageName.Buffer == IntPtr.Zero) { if (processInfo.ProcessId == NtProcessManager.SystemProcessID) { processInfo.ProcessName = "System"; } else if (processInfo.ProcessId == NtProcessManager.IdleProcessID) { processInfo.ProcessName = "Idle"; } else { // for normal process without name, using the process ID. processInfo.ProcessName = processInfo.ProcessId.ToString(CultureInfo.InvariantCulture); } } else { string processName = GetProcessShortName(Marshal.PtrToStringUni(pi.ImageName.Buffer, pi.ImageName.Length / sizeof(char))); processInfo.ProcessName = processName; } // get the threads for current process processInfos[processInfo.ProcessId] = processInfo; currentPtr = (IntPtr)((long)currentPtr + Marshal.SizeOf(pi)); int i = 0; while (i < pi.NumberOfThreads) { ref SystemThreadInformation ti = ref *(SystemThreadInformation *)(currentPtr); ThreadInfo threadInfo = new ThreadInfo(); threadInfo._processId = (int)ti.ClientId.UniqueProcess; threadInfo._threadId = (ulong)ti.ClientId.UniqueThread; threadInfo._basePriority = ti.BasePriority; threadInfo._currentPriority = ti.Priority; threadInfo._startAddress = ti.StartAddress; threadInfo._threadState = (ThreadState)ti.ThreadState; threadInfo._threadWaitReason = NtProcessManager.GetThreadWaitReason((int)ti.WaitReason); processInfo._threadInfoList.Add(threadInfo); currentPtr = (IntPtr)((long)currentPtr + Marshal.SizeOf(ti)); i++; } } if (pi.NextEntryOffset == 0) { break; } totalOffset += pi.NextEntryOffset; } ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count]; processInfos.Values.CopyTo(temp, 0); return temp; } // This function generates the short form of process name. // // This is from GetProcessShortName in NT code base. // Check base\screg\winreg\perfdlls\process\perfsprc.c for details. internal static string GetProcessShortName(String name) { if (String.IsNullOrEmpty(name)) { #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - unexpected blank ProcessName"); #endif return String.Empty; } int slash = -1; int period = -1; for (int i = 0; i < name.Length; i++) { if (name[i] == '\\') slash = i; else if (name[i] == '.') period = i; } if (period == -1) period = name.Length - 1; // set to end of string else { // if a period was found, then see if the extension is // .EXE, if so drop it, if not, then use end of string // (i.e. include extension in name) String extension = name.Substring(period); if (String.Equals(".exe", extension, StringComparison.OrdinalIgnoreCase)) period--; // point to character before period else period = name.Length - 1; // set to end of string } if (slash == -1) slash = 0; // set to start of string else slash++; // point to character next to slash // copy characters between period (or end of string) and // slash (or start of string) to make image name return name.Substring(slash, period - slash + 1); } // native struct defined in ntexapi.h [StructLayout(LayoutKind.Sequential)] internal unsafe struct SystemProcessInformation { internal uint NextEntryOffset; internal uint NumberOfThreads; private fixed byte Reserved1[48]; internal Interop.UNICODE_STRING ImageName; internal int BasePriority; internal IntPtr UniqueProcessId; private UIntPtr Reserved2; internal uint HandleCount; internal uint SessionId; private UIntPtr Reserved3; internal UIntPtr PeakVirtualSize; // SIZE_T internal UIntPtr VirtualSize; private uint Reserved4; internal UIntPtr PeakWorkingSetSize; // SIZE_T internal UIntPtr WorkingSetSize; // SIZE_T private UIntPtr Reserved5; internal UIntPtr QuotaPagedPoolUsage; // SIZE_T private UIntPtr Reserved6; internal UIntPtr QuotaNonPagedPoolUsage; // SIZE_T internal UIntPtr PagefileUsage; // SIZE_T internal UIntPtr PeakPagefileUsage; // SIZE_T internal UIntPtr PrivatePageCount; // SIZE_T private fixed long Reserved7[6]; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct SystemThreadInformation { private fixed long Reserved1[3]; private uint Reserved2; internal IntPtr StartAddress; internal CLIENT_ID ClientId; internal int Priority; internal int BasePriority; private uint Reserved3; internal uint ThreadState; internal uint WaitReason; } [StructLayout(LayoutKind.Sequential)] internal struct CLIENT_ID { internal IntPtr UniqueProcess; internal IntPtr UniqueThread; } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V9.Resources { /// <summary>Resource name for the <c>FeedItem</c> resource.</summary> public sealed partial class FeedItemName : gax::IResourceName, sys::IEquatable<FeedItemName> { /// <summary>The possible contents of <see cref="FeedItemName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/feedItems/{feed_id}~{feed_item_id}</c>. /// </summary> CustomerFeedFeedItem = 1, } private static gax::PathTemplate s_customerFeedFeedItem = new gax::PathTemplate("customers/{customer_id}/feedItems/{feed_id_feed_item_id}"); /// <summary>Creates a <see cref="FeedItemName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="FeedItemName"/> containing the provided <paramref name="unparsedResourceName"/> /// . /// </returns> public static FeedItemName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new FeedItemName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="FeedItemName"/> with the pattern /// <c>customers/{customer_id}/feedItems/{feed_id}~{feed_item_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedItemId">The <c>FeedItem</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="FeedItemName"/> constructed from the provided ids.</returns> public static FeedItemName FromCustomerFeedFeedItem(string customerId, string feedId, string feedItemId) => new FeedItemName(ResourceNameType.CustomerFeedFeedItem, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), feedId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)), feedItemId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemId, nameof(feedItemId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="FeedItemName"/> with pattern /// <c>customers/{customer_id}/feedItems/{feed_id}~{feed_item_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedItemId">The <c>FeedItem</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="FeedItemName"/> with pattern /// <c>customers/{customer_id}/feedItems/{feed_id}~{feed_item_id}</c>. /// </returns> public static string Format(string customerId, string feedId, string feedItemId) => FormatCustomerFeedFeedItem(customerId, feedId, feedItemId); /// <summary> /// Formats the IDs into the string representation of this <see cref="FeedItemName"/> with pattern /// <c>customers/{customer_id}/feedItems/{feed_id}~{feed_item_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedItemId">The <c>FeedItem</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="FeedItemName"/> with pattern /// <c>customers/{customer_id}/feedItems/{feed_id}~{feed_item_id}</c>. /// </returns> public static string FormatCustomerFeedFeedItem(string customerId, string feedId, string feedItemId) => s_customerFeedFeedItem.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemId, nameof(feedItemId)))}"); /// <summary>Parses the given resource name string into a new <see cref="FeedItemName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/feedItems/{feed_id}~{feed_item_id}</c></description></item> /// </list> /// </remarks> /// <param name="feedItemName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="FeedItemName"/> if successful.</returns> public static FeedItemName Parse(string feedItemName) => Parse(feedItemName, false); /// <summary> /// Parses the given resource name string into a new <see cref="FeedItemName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/feedItems/{feed_id}~{feed_item_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="feedItemName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="FeedItemName"/> if successful.</returns> public static FeedItemName Parse(string feedItemName, bool allowUnparsed) => TryParse(feedItemName, allowUnparsed, out FeedItemName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="FeedItemName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/feedItems/{feed_id}~{feed_item_id}</c></description></item> /// </list> /// </remarks> /// <param name="feedItemName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="FeedItemName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string feedItemName, out FeedItemName result) => TryParse(feedItemName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="FeedItemName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/feedItems/{feed_id}~{feed_item_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="feedItemName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="FeedItemName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string feedItemName, bool allowUnparsed, out FeedItemName result) { gax::GaxPreconditions.CheckNotNull(feedItemName, nameof(feedItemName)); gax::TemplatedResourceName resourceName; if (s_customerFeedFeedItem.TryParseName(feedItemName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerFeedFeedItem(resourceName[0], split1[0], split1[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(feedItemName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private FeedItemName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string feedId = null, string feedItemId = null) { Type = type; UnparsedResource = unparsedResourceName; CustomerId = customerId; FeedId = feedId; FeedItemId = feedItemId; } /// <summary> /// Constructs a new instance of a <see cref="FeedItemName"/> class from the component parts of pattern /// <c>customers/{customer_id}/feedItems/{feed_id}~{feed_item_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedItemId">The <c>FeedItem</c> ID. Must not be <c>null</c> or empty.</param> public FeedItemName(string customerId, string feedId, string feedItemId) : this(ResourceNameType.CustomerFeedFeedItem, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), feedId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)), feedItemId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedItemId, nameof(feedItemId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>Feed</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string FeedId { get; } /// <summary> /// The <c>FeedItem</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string FeedItemId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerFeedFeedItem: return s_customerFeedFeedItem.Expand(CustomerId, $"{FeedId}~{FeedItemId}"); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as FeedItemName); /// <inheritdoc/> public bool Equals(FeedItemName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(FeedItemName a, FeedItemName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(FeedItemName a, FeedItemName b) => !(a == b); } public partial class FeedItem { /// <summary> /// <see cref="FeedItemName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal FeedItemName ResourceNameAsFeedItemName { get => string.IsNullOrEmpty(ResourceName) ? null : FeedItemName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary><see cref="FeedName"/>-typed view over the <see cref="Feed"/> resource name property.</summary> internal FeedName FeedAsFeedName { get => string.IsNullOrEmpty(Feed) ? null : FeedName.Parse(Feed, allowUnparsed: true); set => Feed = value?.ToString() ?? ""; } } }
using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using NAudio.Utils; namespace NAudio.Wave.Compression { /// <summary> /// Represents an installed ACM Driver /// </summary> public class AcmDriver : IDisposable { private static List<AcmDriver> drivers; private AcmDriverDetails details; private IntPtr driverId; private IntPtr driverHandle; private List<AcmFormatTag> formatTags; private List<AcmFormat> tempFormatsList; // used by enumerator private IntPtr localDllHandle; /// <summary> /// Helper function to determine whether a particular codec is installed /// </summary> /// <param name="shortName">The short name of the function</param> /// <returns>Whether the codec is installed</returns> public static bool IsCodecInstalled(string shortName) { foreach (AcmDriver driver in AcmDriver.EnumerateAcmDrivers()) { if (driver.ShortName == shortName) { return true; } } return false; } /// <summary> /// Attempts to add a new ACM driver from a file /// </summary> /// <param name="driverFile">Full path of the .acm or dll file containing the driver</param> /// <returns>Handle to the driver</returns> public static AcmDriver AddLocalDriver(string driverFile) { IntPtr handle = NativeMethods.LoadLibrary(driverFile); if (handle == IntPtr.Zero) { throw new ArgumentException("Failed to load driver file"); } var driverProc = NativeMethods.GetProcAddress(handle, "DriverProc"); if (driverProc == IntPtr.Zero) { NativeMethods.FreeLibrary(handle); throw new ArgumentException("Failed to discover DriverProc"); } IntPtr driverHandle; var result = AcmInterop.acmDriverAdd(out driverHandle, handle, driverProc, 0, AcmDriverAddFlags.Function); if (result != MmResult.NoError) { NativeMethods.FreeLibrary(handle); throw new MmException(result, "acmDriverAdd"); } var driver = new AcmDriver(driverHandle); // long name seems to be missing when we use acmDriverAdd if (string.IsNullOrEmpty(driver.details.longName)) { driver.details.longName = "Local driver: " + Path.GetFileName(driverFile); driver.localDllHandle = handle; } return driver; } /// <summary> /// Removes a driver previously added using AddLocalDriver /// </summary> /// <param name="localDriver">Local driver to remove</param> public static void RemoveLocalDriver(AcmDriver localDriver) { if (localDriver.localDllHandle == IntPtr.Zero) { throw new ArgumentException("Please pass in the AcmDriver returned by the AddLocalDriver method"); } var removeResult = AcmInterop.acmDriverRemove(localDriver.driverId, 0); // gets stored as a driver Id NativeMethods.FreeLibrary(localDriver.localDllHandle); MmException.Try(removeResult, "acmDriverRemove"); } /// <summary> /// Show Format Choose Dialog /// </summary> /// <param name="ownerWindowHandle">Owner window handle, can be null</param> /// <param name="windowTitle">Window title</param> /// <param name="enumFlags">Enumeration flags. None to get everything</param> /// <param name="enumFormat">Enumeration format. Only needed with certain enumeration flags</param> /// <param name="selectedFormat">The selected format</param> /// <param name="selectedFormatDescription">Textual description of the selected format</param> /// <param name="selectedFormatTagDescription">Textual description of the selected format tag</param> /// <returns>True if a format was selected</returns> public static bool ShowFormatChooseDialog( IntPtr ownerWindowHandle, string windowTitle, AcmFormatEnumFlags enumFlags, WaveFormat enumFormat, out WaveFormat selectedFormat, out string selectedFormatDescription, out string selectedFormatTagDescription) { AcmFormatChoose formatChoose = new AcmFormatChoose(); formatChoose.structureSize = Marshal.SizeOf(formatChoose); formatChoose.styleFlags = AcmFormatChooseStyleFlags.None; formatChoose.ownerWindowHandle = ownerWindowHandle; int maxFormatSize = 200; // guess formatChoose.selectedWaveFormatPointer = Marshal.AllocHGlobal(maxFormatSize); formatChoose.selectedWaveFormatByteSize = maxFormatSize; formatChoose.title = windowTitle; formatChoose.name = null; formatChoose.formatEnumFlags = enumFlags;//AcmFormatEnumFlags.None; formatChoose.waveFormatEnumPointer = IntPtr.Zero; if (enumFormat != null) { IntPtr enumPointer = Marshal.AllocHGlobal(Marshal.SizeOf(enumFormat)); Marshal.StructureToPtr(enumFormat,enumPointer,false); formatChoose.waveFormatEnumPointer = enumPointer; } formatChoose.instanceHandle = IntPtr.Zero; formatChoose.templateName = null; MmResult result = AcmInterop.acmFormatChoose(ref formatChoose); selectedFormat = null; selectedFormatDescription = null; selectedFormatTagDescription = null; if (result == MmResult.NoError) { selectedFormat = WaveFormat.MarshalFromPtr(formatChoose.selectedWaveFormatPointer); selectedFormatDescription = formatChoose.formatDescription; selectedFormatTagDescription = formatChoose.formatTagDescription; } Marshal.FreeHGlobal(formatChoose.waveFormatEnumPointer); Marshal.FreeHGlobal(formatChoose.selectedWaveFormatPointer); if(result != MmResult.AcmCancelled && result != MmResult.NoError) { throw new MmException(result, "acmFormatChoose"); } return result == MmResult.NoError; } /// <summary> /// Gets the maximum size needed to store a WaveFormat for ACM interop functions /// </summary> public int MaxFormatSize { get { int maxFormatSize = 0; MmException.Try(AcmInterop.acmMetrics(driverHandle, AcmMetrics.MaxSizeFormat, out maxFormatSize), "acmMetrics"); return maxFormatSize; } } /// <summary> /// Finds a Driver by its short name /// </summary> /// <param name="shortName">Short Name</param> /// <returns>The driver, or null if not found</returns> public static AcmDriver FindByShortName(string shortName) { foreach (AcmDriver driver in AcmDriver.EnumerateAcmDrivers()) { if (driver.ShortName == shortName) { return driver; } } return null; } /// <summary> /// Gets a list of the ACM Drivers installed /// </summary> public static IEnumerable<AcmDriver> EnumerateAcmDrivers() { drivers = new List<AcmDriver>(); MmException.Try(AcmInterop.acmDriverEnum(new AcmInterop.AcmDriverEnumCallback(DriverEnumCallback), IntPtr.Zero, 0), "acmDriverEnum"); return drivers; } /// <summary> /// The callback for acmDriverEnum /// </summary> private static bool DriverEnumCallback(IntPtr hAcmDriver, IntPtr dwInstance, AcmDriverDetailsSupportFlags flags) { drivers.Add(new AcmDriver(hAcmDriver)); return true; } /// <summary> /// Creates a new ACM Driver object /// </summary> /// <param name="hAcmDriver">Driver handle</param> private AcmDriver(IntPtr hAcmDriver) { driverId = hAcmDriver; details = new AcmDriverDetails(); details.structureSize = System.Runtime.InteropServices.Marshal.SizeOf(details); MmException.Try(AcmInterop.acmDriverDetails(hAcmDriver, ref details, 0), "acmDriverDetails"); } /// <summary> /// The short name of this driver /// </summary> public string ShortName { get { return details.shortName; } } /// <summary> /// The full name of this driver /// </summary> public string LongName { get { return details.longName; } } /// <summary> /// The driver ID /// </summary> public IntPtr DriverId { get { return driverId; } } /// <summary> /// ToString /// </summary> public override string ToString() { return LongName; } /// <summary> /// The list of FormatTags for this ACM Driver /// </summary> public IEnumerable<AcmFormatTag> FormatTags { get { if (formatTags == null) { if (driverHandle == IntPtr.Zero) { throw new InvalidOperationException("Driver must be opened first"); } formatTags = new List<AcmFormatTag>(); AcmFormatTagDetails formatTagDetails = new AcmFormatTagDetails(); formatTagDetails.structureSize = Marshal.SizeOf(formatTagDetails); MmException.Try(AcmInterop.acmFormatTagEnum(this.driverHandle, ref formatTagDetails, AcmFormatTagEnumCallback, IntPtr.Zero, 0), "acmFormatTagEnum"); } return formatTags; } } /// <summary> /// Gets all the supported formats for a given format tag /// </summary> /// <param name="formatTag">Format tag</param> /// <returns>Supported formats</returns> public IEnumerable<AcmFormat> GetFormats(AcmFormatTag formatTag) { if (driverHandle == IntPtr.Zero) { throw new InvalidOperationException("Driver must be opened first"); } tempFormatsList = new List<AcmFormat>(); AcmFormatDetails formatDetails = new AcmFormatDetails(); formatDetails.structSize = Marshal.SizeOf(formatDetails); formatDetails.waveFormatByteSize = MaxFormatSize; // formatTag.FormatSize doesn't work; formatDetails.waveFormatPointer = Marshal.AllocHGlobal(formatDetails.waveFormatByteSize); formatDetails.formatTag = (int)formatTag.FormatTag; // (int)WaveFormatEncoding.Unknown MmResult result = AcmInterop.acmFormatEnum(driverHandle, ref formatDetails, AcmFormatEnumCallback, IntPtr.Zero, AcmFormatEnumFlags.None); Marshal.FreeHGlobal(formatDetails.waveFormatPointer); MmException.Try(result,"acmFormatEnum"); return tempFormatsList; } /// <summary> /// Opens this driver /// </summary> public void Open() { if (driverHandle == IntPtr.Zero) { MmException.Try(AcmInterop.acmDriverOpen(out driverHandle, DriverId, 0), "acmDriverOpen"); } } /// <summary> /// Closes this driver /// </summary> public void Close() { if(driverHandle != IntPtr.Zero) { MmException.Try(AcmInterop.acmDriverClose(driverHandle, 0),"acmDriverClose"); driverHandle = IntPtr.Zero; } } private bool AcmFormatTagEnumCallback(IntPtr hAcmDriverId, ref AcmFormatTagDetails formatTagDetails, IntPtr dwInstance, AcmDriverDetailsSupportFlags flags) { formatTags.Add(new AcmFormatTag(formatTagDetails)); return true; } private bool AcmFormatEnumCallback(IntPtr hAcmDriverId, ref AcmFormatDetails formatDetails, IntPtr dwInstance, AcmDriverDetailsSupportFlags flags) { tempFormatsList.Add(new AcmFormat(formatDetails)); return true; } #region IDisposable Members /// <summary> /// Dispose /// </summary> public void Dispose() { if (driverHandle != IntPtr.Zero) { Close(); GC.SuppressFinalize(this); } } #endregion } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. // using System; using System.Collections.Generic; using HoloToolkit.Unity; namespace HoloToolkit.Sharing { /// <summary> /// The ServerSessionsTracker manages the list of sessions on the server and the users in these sessions. /// Instance is created by Sharing Stage when a connection is found. /// </summary> public class ServerSessionsTracker : IDisposable { private bool disposed; private SessionManager sessionManager; private SessionManagerAdapter sessionManagerAdapter; public event Action<bool, string> SessionCreated; public event Action<Session> SessionAdded; public event Action<Session> SessionClosed; public event Action<Session, User> UserChanged; public event Action<Session, User> UserJoined; public event Action<Session, User> UserLeft; public event Action<Session> CurrentUserLeft; public event Action<Session> CurrentUserJoined; public event Action ServerConnected; public event Action ServerDisconnected; /// <summary> /// List of sessions on the server. /// </summary> public List<Session> Sessions { get; private set; } /// <summary> /// Indicates whether there is a connection to the server or not. /// </summary> public bool IsServerConnected { get; private set; } public ServerSessionsTracker(SessionManager sessionMgr) { sessionManager = sessionMgr; Sessions = new List<Session>(); if (sessionManager != null) { sessionManagerAdapter = new SessionManagerAdapter(); sessionManagerAdapter.ServerConnectedEvent += OnServerConnected; sessionManagerAdapter.ServerDisconnectedEvent += OnServerDisconnected; sessionManagerAdapter.SessionClosedEvent += OnSessionClosed; sessionManagerAdapter.SessionAddedEvent += OnSessionAdded; sessionManagerAdapter.CreateSucceededEvent += OnSessionCreatedSuccess; sessionManagerAdapter.CreateFailedEvent += OnSessionCreatedFail; sessionManagerAdapter.UserChangedEvent += OnUserChanged; sessionManagerAdapter.UserJoinedSessionEvent += OnUserJoined; sessionManagerAdapter.UserLeftSessionEvent += OnUserLeft; sessionManager.AddListener(sessionManagerAdapter); } } /// <summary> /// Retrieves the current session, if any. /// </summary> /// <returns>Current session the app is in. Null if no session is joined.</returns> public Session GetCurrentSession() { return sessionManager.GetCurrentSession(); } /// <summary> /// Join the specified session. /// </summary> /// <param name="session">Session to join.</param> /// <returns>True if the session is being joined or is already joined.</returns> public bool JoinSession(Session session) { // TODO Should prevent joining multiple sessions at the same time if (session != null) { return session.IsJoined() || session.Join(); } return false; } /// <summary> /// Leave the current session. /// </summary> public void LeaveCurrentSession() { using (Session currentSession = GetCurrentSession()) { if (currentSession != null) { currentSession.Leave(); } } } /// <summary> /// Creates a new session on the server. /// </summary> /// <param name="sessionName">Name of the session.</param> /// <returns>True if a session was created, false if not.</returns> public bool CreateSession(string sessionName) { if (disposed) { return false; } return sessionManager.CreateSession(sessionName); } private void OnSessionCreatedFail(XString reason) { using (reason) { SessionCreated.RaiseEvent(false, reason.GetString()); } } private void OnSessionCreatedSuccess(Session session) { using (session) { SessionCreated.RaiseEvent(true, session.GetName().GetString()); } } private void OnUserChanged(Session session, User user) { UserChanged.RaiseEvent(session, user); } private void OnUserLeft(Session session, User user) { UserLeft.RaiseEvent(session, user); if (IsLocalUser(user)) { CurrentUserLeft.RaiseEvent(session); } } private void OnUserJoined(Session session, User newUser) { UserJoined.RaiseEvent(session, newUser); if (IsLocalUser(newUser)) { CurrentUserJoined.RaiseEvent(session); } } private void OnSessionAdded(Session newSession) { Sessions.Add(newSession); SessionAdded.RaiseEvent(newSession); } private void OnSessionClosed(Session session) { for (int i = 0; i < Sessions.Count; i++) { if (Sessions[i].GetName().ToString().Equals(session.GetName().ToString())) { SessionClosed.RaiseEvent(Sessions[i]); Sessions.Remove(Sessions[i]); } } } private void OnServerDisconnected() { IsServerConnected = false; // Remove all sessions for (int i = 0; i < Sessions.Count; i++) { Sessions[i].Dispose(); } Sessions.Clear(); ServerDisconnected.RaiseEvent(); } private void OnServerConnected() { IsServerConnected = true; ServerConnected.RaiseEvent(); } private bool IsLocalUser(User user) { int changedUserId = user.GetID(); using (User localUser = sessionManager.GetCurrentUser()) { int localUserId = localUser.GetID(); return localUserId == changedUserId; } } #region IDisposable public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { OnServerDisconnected(); if (sessionManagerAdapter != null) { sessionManagerAdapter.ServerConnectedEvent -= OnServerConnected; sessionManagerAdapter.ServerDisconnectedEvent -= OnServerDisconnected; sessionManagerAdapter.SessionClosedEvent -= OnSessionClosed; sessionManagerAdapter.SessionAddedEvent -= OnSessionAdded; sessionManagerAdapter.CreateSucceededEvent -= OnSessionCreatedSuccess; sessionManagerAdapter.CreateFailedEvent -= OnSessionCreatedFail; sessionManagerAdapter.UserChangedEvent -= OnUserChanged; sessionManagerAdapter.UserJoinedSessionEvent -= OnUserJoined; sessionManagerAdapter.UserLeftSessionEvent -= OnUserLeft; sessionManagerAdapter.Dispose(); sessionManagerAdapter = null; } if (sessionManager != null) { sessionManager.Dispose(); sessionManager = null; } } disposed = true; } #endregion } }
// <copyright> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> namespace Microsoft.Activities.Presentation.Xaml { using System; using System.Activities; using System.Activities.Debugger; using System.Activities.Presentation.View; using System.Activities.Presentation.ViewState; using System.Collections.Generic; using System.Reflection; using System.Runtime; using System.Xaml; internal static class ViewStateXamlHelper { static readonly string ViewStateManager = WorkflowViewState.ViewStateManagerProperty.MemberName; static readonly string IdRef = WorkflowViewState.IdRefProperty.MemberName; static readonly MethodInfo GetViewStateManager = typeof(WorkflowViewState).GetMethod("GetViewStateManager"); static readonly MethodInfo SetViewStateManager = typeof(WorkflowViewState).GetMethod("SetViewStateManager"); static readonly MethodInfo GetIdRef = typeof(WorkflowViewState).GetMethod("GetIdRef"); static readonly MethodInfo SetIdRef = typeof(WorkflowViewState).GetMethod("SetIdRef"); static readonly List<string> SourceLocationNames = new List<string> { XamlDebuggerXmlReader.StartLineName.MemberName, XamlDebuggerXmlReader.StartColumnName.MemberName, XamlDebuggerXmlReader.EndLineName.MemberName, XamlDebuggerXmlReader.EndColumnName.MemberName }; // This method collects view state attached properties and generates a Xaml node stream // with all view state information appearing within the ViewStateManager node. // It is called when workflow definition is being serialized to string. // inputReader - Nodestream with view state information as attached properties on the activity nodes. // The reader is positioned at the begining of the workflow definition. // idManager - This component issues running sequence numbers for IdRef. // Result - Node stream positioned at the begining of the workflow definition with a // ViewStateManager node containing all view state information. // Implementation logic: // 1. Scan the input nodestream Objects for attached properties that need to be converted (VirtualizedContainerService.HintSize and WorkflowViewStateService.ViewState). // 2. If the Object had a IdRef value then use it otherwise generate a new value. // 3. Store idRef value and corresponding viewstate related attached property nodes (from step 1) // in the viewStateInfo dictionary. // 4. Use the viewStateInfo dictionary to generate ViewStateManager node which is then inserted // into the end of output nodestream. public static XamlReader ConvertAttachedPropertiesToViewState(XamlObjectReader inputReader, ViewStateIdManager idManager) { // Stack to track StartObject/GetObject and EndObject nodes. Stack<Frame> stack = new Stack<Frame>(); XamlMember viewStateManager = new XamlMember(ViewStateManager, GetViewStateManager, SetViewStateManager, inputReader.SchemaContext); XamlMember idRefMember = new XamlMember(IdRef, GetIdRef, SetIdRef, inputReader.SchemaContext); // Xaml member corresponding to x:Class property of the workflow definition. Used to find x:Class value in the node stream. XamlMember activityBuilderName = new XamlMember(typeof(ActivityBuilder).GetProperty("Name"), inputReader.SchemaContext); string activityBuilderTypeName = typeof(ActivityBuilder).Name; // Dictionary to keep track of IdRefs and corresponding viewstate related // attached property nodes. Dictionary<string, XamlNodeList> viewStateInfo = new Dictionary<string, XamlNodeList>(); // Output node list XamlNodeList workflowDefinition = new XamlNodeList(inputReader.SchemaContext); using (XamlWriter workflowDefinitionWriter = workflowDefinition.Writer) { bool design2010NamespaceFound = false; bool inIdRefMember = false; bool inxClassMember = false; bool skipWritingWorkflowDefinition = false; bool skipReadingWorkflowDefinition = false; string xClassName = null; while (skipReadingWorkflowDefinition || inputReader.Read()) { skipWritingWorkflowDefinition = false; skipReadingWorkflowDefinition = false; switch (inputReader.NodeType) { case XamlNodeType.NamespaceDeclaration: if (inputReader.Namespace.Namespace.Equals(NameSpaces.Design2010, StringComparison.Ordinal)) { design2010NamespaceFound = true; } break; case XamlNodeType.StartObject: // Save the Xaml type and clr object on the stack frame. These are used later to generate // IdRef values and attaching the same to the clr object. stack.Push(new Frame() { Type = inputReader.Type, InstanceObject = inputReader.Instance }); // If the design2010 namespace was not found add the namespace node // before the start object is written out. if (!design2010NamespaceFound) { workflowDefinitionWriter.WriteNamespace(new NamespaceDeclaration(NameSpaces.Design2010, NameSpaces.Design2010Prefix)); design2010NamespaceFound = true; } break; case XamlNodeType.GetObject: // Push an empty frame to balance the Pop operation when the EndObject node // is encountered. stack.Push(new Frame() { Type = null }); break; case XamlNodeType.StartMember: // Track when we enter IdRef member so that we can save its value. if (inputReader.Member.Equals(idRefMember)) { inIdRefMember = true; } // Track when we enter x:Class member so that we can save its value. else if (inputReader.Member.Equals(activityBuilderName)) { inxClassMember = true; } // Start of VirtualizedContainerService.HintSize or WorkflowViewStateService.ViewState property. else if (IsAttachablePropertyForConvert(inputReader)) { // The top of stack here corresponds to the activity on which // the above properties are attached. if (stack.Peek().AttachedPropertyNodes == null) { stack.Peek().AttachedPropertyNodes = new XamlNodeList(inputReader.SchemaContext); } // Write the attached property's xaml nodes into the stack. XamlReader subTreeReader = inputReader.ReadSubtree(); XamlWriter attachedPropertyWriter = stack.Peek().AttachedPropertyNodes.Writer; while (subTreeReader.Read()) { attachedPropertyWriter.WriteNode(subTreeReader); } // The subtree reader loop put us at the begining of the next node in the input stream. // So skip reading/writing it out just yet. skipReadingWorkflowDefinition = true; skipWritingWorkflowDefinition = true; } break; case XamlNodeType.Value: // Read and save IdRef/x:Class member values. // Also update idManager to keep track of prefixes and ids seen. if (inIdRefMember) { string idRef = inputReader.Value as string; stack.Peek().IdRef = idRef; idManager.UpdateMap(idRef); } else if (inxClassMember) { xClassName = inputReader.Value as string; idManager.UpdateMap(xClassName); } break; case XamlNodeType.EndMember: // Exit IdRef/x:Class member state. if (inIdRefMember) { inIdRefMember = false; } else if (inxClassMember) { inxClassMember = false; } break; case XamlNodeType.EndObject: // Remove an item from the stack because we encountered the end of an object definition. Frame frameObject = stack.Pop(); // If the object had (viewstate related) attached properties we need to save them // into the viewStateInfo dictionary. if (frameObject.AttachedPropertyNodes != null) { frameObject.AttachedPropertyNodes.Writer.Close(); // If the object didn't have IdRef, generate a new one. if (string.IsNullOrWhiteSpace(frameObject.IdRef)) { // Use the object type name (or x:Class value) to generate a new id. if (frameObject.Type != null) { string prefix = frameObject.Type.Name; if (frameObject.Type.UnderlyingType != null) { prefix = frameObject.Type.UnderlyingType.Name; } if (string.CompareOrdinal(prefix, activityBuilderTypeName) == 0 && !string.IsNullOrWhiteSpace(xClassName)) { frameObject.IdRef = idManager.GetNewId(xClassName); } else { frameObject.IdRef = idManager.GetNewId(prefix); } } else //Fallback to generating a guid value. { frameObject.IdRef = Guid.NewGuid().ToString(); } // Since we didn't see a IdRef on this object, insert the generated // viewstate id into the output Xaml node-stream. workflowDefinitionWriter.WriteStartMember(idRefMember); workflowDefinitionWriter.WriteValue(frameObject.IdRef); workflowDefinitionWriter.WriteEndMember(); // Save the generated idRef on the corresponding clr object as well. if (frameObject.InstanceObject != null) { WorkflowViewState.SetIdRef(frameObject.InstanceObject, frameObject.IdRef); } } viewStateInfo[frameObject.IdRef] = frameObject.AttachedPropertyNodes; } // We're at the end of input nodestream and have collected data in viewStateInfo // so we need to create and insert the ViewStateManager nodes into the output nodestream. if (stack.Count == 0 && viewStateInfo.Count > 0) { XamlNodeList viewStateManagerNodeList = CreateViewStateManagerNodeList(viewStateInfo, inputReader.SchemaContext); XamlReader viewStateManagerNodeReader = viewStateManagerNodeList.GetReader(); // Insert the ViewStateManager nodes into the output node stream. workflowDefinitionWriter.WriteStartMember(viewStateManager); while (viewStateManagerNodeReader.Read()) { workflowDefinitionWriter.WriteNode(viewStateManagerNodeReader); } workflowDefinitionWriter.WriteEndMember(); // viewStateManager } break; } if (!skipWritingWorkflowDefinition) { workflowDefinitionWriter.WriteNode(inputReader); } } } return workflowDefinition.GetReader(); } // This method converts view state information stored within the ViewStateManager node back as // attached properties on corresponding activity nodes. // It is called when workflow definition is being deserialized from a string. // inputReader - Nodestream that may have all view state information in the ViewStateManager node at the end of workflow definition. // The reader is positioned at the begining of the workflow definition. // idManager - This component issues running sequence numbers for IdRef. // viewStateManager - (output) ViewStateManager object instance deserialized from the workflow definition. // Result - Node stream positioned at the begining of the workflow definition with view state related information // appearing as attached properties on activities. The ViewStateManager nodes are removed from the stream. // Implementation logic: // 1. Scan the input nodestream for ViewStateManager node. // 2. If ViewStateManager node is found, store Id and corresponding attached property nodes // in viewStateInfo dictionary. Otherwise return early. // 3. Walk activity nodes in the workflow definition and apply viewstate related attached properties (from // viewStateInfo dictionary) to each node. // 4. If multiple activities have same IdRef values then corresponding viewstate related attached properties // (from viewStateInfo dictionary) are applied to the first of those activities. The other activities with duplicate // IdRef values do not get view state information. public static XamlReader ConvertViewStateToAttachedProperties(XamlReader inputReader, ViewStateIdManager idManager, out Dictionary<string, SourceLocation> viewStateSourceLocationMap) { int idRefLineNumber = 0; int idRefLinePosition = 0; bool shouldWriteIdRefEndMember = false; XamlReader retVal = null; // Xaml member definition for IdRef. Used to identify existing IdRef properties in the input nodestream. XamlMember idRefMember = new XamlMember(IdRef, GetIdRef, SetIdRef, inputReader.SchemaContext); // Dictionary containing Ids and corresponding viewstate related // attached property nodes. Populated by StripViewStateElement method. Dictionary<string, XamlNodeList> viewStateInfo = null; XamlReader workflowDefinition = StripViewStateElement(inputReader, out viewStateInfo, out viewStateSourceLocationMap); // This is used to keep track of duplicate IdRefs in the workflow definition. HashSet<string> idRefsSeen = new HashSet<string>(); // If the inputReader did not have a ViewStateManager node (4.0 format) // return early. if (viewStateInfo == null) { retVal = workflowDefinition; } else { // Stack to track StartObject/GetObject and EndObject nodes. Stack<Frame> stack = new Stack<Frame>(); // Output node list. XamlNodeList mergedNodeList = new XamlNodeList(workflowDefinition.SchemaContext); bool inIdRefMember = false; using (XamlWriter mergedNodeWriter = mergedNodeList.Writer) { IXamlLineInfo lineInfo = workflowDefinition as IXamlLineInfo; IXamlLineInfoConsumer lineInfoComsumer = mergedNodeWriter as IXamlLineInfoConsumer; bool shouldPassLineInfo = lineInfo != null && lineInfo.HasLineInfo && lineInfoComsumer != null && lineInfoComsumer.ShouldProvideLineInfo; while (workflowDefinition.Read()) { bool skipWritingWorkflowDefinition = false; switch (workflowDefinition.NodeType) { case XamlNodeType.StartObject: stack.Push(new Frame { Type = workflowDefinition.Type }); break; case XamlNodeType.GetObject: stack.Push(new Frame { Type = null }); break; case XamlNodeType.StartMember: // Track when the reader enters IdRef. Skip writing the start // node to the output nodelist until we check for duplicates. if (workflowDefinition.Member.Equals(idRefMember)) { inIdRefMember = true; skipWritingWorkflowDefinition = true; if (shouldPassLineInfo) { idRefLineNumber = lineInfo.LineNumber; idRefLinePosition = lineInfo.LinePosition; } } break; case XamlNodeType.Value: if (inIdRefMember) { string idRef = workflowDefinition.Value as string; if (!string.IsNullOrWhiteSpace(idRef)) { // If IdRef value is a duplicate then do not associate it with // the stack frame (top of stack == activity node with IdRef member on it). if (idRefsSeen.Contains(idRef)) { stack.Peek().IdRef = null; } // If the IdRef value is unique then associate it with the // stack frame and also write its value into the output nodestream. else { stack.Peek().IdRef = idRef; idManager.UpdateMap(idRef); idRefsSeen.Add(idRef); if (shouldPassLineInfo) { lineInfoComsumer.SetLineInfo(idRefLineNumber, idRefLinePosition); } mergedNodeWriter.WriteStartMember(idRefMember); if (shouldPassLineInfo) { lineInfoComsumer.SetLineInfo(lineInfo.LineNumber, lineInfo.LinePosition); } mergedNodeWriter.WriteValue(idRef); shouldWriteIdRefEndMember = true; } } // Don't need to write IdRef value into the output // nodestream. If the value was valid, it would have been written above. skipWritingWorkflowDefinition = true; } break; case XamlNodeType.EndMember: // Exit IdRef node. Skip writing the EndMember node, we would have done // it as part of reading the IdRef value. if (inIdRefMember) { inIdRefMember = false; skipWritingWorkflowDefinition = true; if (shouldWriteIdRefEndMember) { shouldWriteIdRefEndMember = false; if (shouldPassLineInfo) { lineInfoComsumer.SetLineInfo(lineInfo.LineNumber, lineInfo.LinePosition); } mergedNodeWriter.WriteEndMember(); } } break; case XamlNodeType.EndObject: Frame frameObject = stack.Pop(); // Before we exit the end of an object, check if it had IdRef // associated with it. If it did, look-up viewStateInfo for viewstate // related attached property nodes and add them to the output nodelist. if (!string.IsNullOrWhiteSpace(frameObject.IdRef)) { XamlNodeList viewStateNodeList; if (viewStateInfo.TryGetValue(frameObject.IdRef, out viewStateNodeList)) { XamlReader viewStateReader = viewStateNodeList.GetReader(); IXamlLineInfo viewStateLineInfo = viewStateReader as IXamlLineInfo; bool viewStateShouldPassLineInfo = viewStateLineInfo != null && viewStateLineInfo.HasLineInfo && lineInfoComsumer != null && lineInfoComsumer.ShouldProvideLineInfo; while (viewStateReader.Read()) { if (viewStateShouldPassLineInfo) { lineInfoComsumer.SetLineInfo(viewStateLineInfo.LineNumber, viewStateLineInfo.LinePosition); } mergedNodeWriter.WriteNode(viewStateReader); } } } break; } if (!skipWritingWorkflowDefinition) { if (shouldPassLineInfo) { lineInfoComsumer.SetLineInfo(lineInfo.LineNumber, lineInfo.LinePosition); } mergedNodeWriter.WriteNode(workflowDefinition); } } } retVal = mergedNodeList.GetReader(); } return retVal; } // This method removes IdRef nodes from the nodestream. This method would be called // when a 4.5 workflow definition is retargeted to 4.0. public static XamlReader RemoveIdRefs(XamlObjectReader inputReader) { XamlMember idRefMember = new XamlMember(IdRef, GetIdRef, SetIdRef, inputReader.SchemaContext); XamlNodeList outputNodeList = new XamlNodeList(inputReader.SchemaContext); using (XamlWriter outputWriter = outputNodeList.Writer) { while (inputReader.Read()) { if (inputReader.NodeType == XamlNodeType.StartMember && inputReader.Member.Equals(idRefMember)) { // Exhaust the idRefMember sub-tree. XamlReader idRefReader = inputReader.ReadSubtree(); while (idRefReader.Read()); } outputWriter.WriteNode(inputReader); } } return outputNodeList.GetReader(); } // This is a helper method to output the nodestream sequence for debugging/diagnostic purposes. public static void NodeLoopTest(XamlReader xamlReader) { #if DEBUG string tabs = ""; int depth = 1; while (xamlReader.Read()) { switch (xamlReader.NodeType) { case XamlNodeType.NamespaceDeclaration: System.Diagnostics.Debug.WriteLine(tabs + "Namespace declaration: {0}:{1}", xamlReader.Namespace.Prefix, xamlReader.Namespace.Namespace); break; case XamlNodeType.StartObject: tabs = new String(' ', depth++); System.Diagnostics.Debug.WriteLine(tabs + "Start object: {0}", xamlReader.Type.Name); break; case XamlNodeType.GetObject: tabs = new String(' ', depth++); System.Diagnostics.Debug.WriteLine(tabs + "Get object"); break; case XamlNodeType.StartMember: tabs = new String(' ', depth++); System.Diagnostics.Debug.WriteLine(tabs + "Start member: {0}, Attachable: {1}", xamlReader.Member.Name, xamlReader.Member.IsAttachable); break; case XamlNodeType.Value: tabs = new String(' ', depth++); System.Diagnostics.Debug.WriteLine(tabs + "Value: {0}", xamlReader.Value); --depth; break; case XamlNodeType.EndMember: tabs = new String(' ', --depth); System.Diagnostics.Debug.WriteLine(tabs + "End member"); break; case XamlNodeType.EndObject: tabs = new String(' ', --depth); System.Diagnostics.Debug.WriteLine(tabs + "End object"); break; } } #endif } // Given the viewStateInfo dictionary, this method returns a xaml node list matching a ViewStateManager // object. static XamlNodeList CreateViewStateManagerNodeList(Dictionary<string, XamlNodeList> viewStateInfo, XamlSchemaContext schemaContext) { XamlNodeList viewStateManagerNodeList = new XamlNodeList(schemaContext); XamlMember viewStateDataMember = new XamlMember(typeof(ViewStateManager).GetProperty("ViewStateData"), schemaContext); XamlType viewStateManagerType = new XamlType(typeof(ViewStateManager), schemaContext); XamlType viewStateDataType = new XamlType(typeof(ViewStateData), schemaContext); XamlMember idMember = new XamlMember(typeof(ViewStateData).GetProperty("Id"), schemaContext); using (XamlWriter viewStateManagerNodeWriter = viewStateManagerNodeList.Writer) { viewStateManagerNodeWriter.WriteStartObject(viewStateManagerType); viewStateManagerNodeWriter.WriteStartMember(viewStateDataMember); viewStateManagerNodeWriter.WriteGetObject(); viewStateManagerNodeWriter.WriteStartMember(XamlLanguage.Items); foreach (KeyValuePair<string, XamlNodeList> entry in viewStateInfo) { viewStateManagerNodeWriter.WriteStartObject(viewStateDataType); viewStateManagerNodeWriter.WriteStartMember(idMember); viewStateManagerNodeWriter.WriteValue(entry.Key); viewStateManagerNodeWriter.WriteEndMember(); // idMember XamlReader viewStateValueReader = entry.Value.GetReader(); while (viewStateValueReader.Read()) { viewStateManagerNodeWriter.WriteNode(viewStateValueReader); } viewStateManagerNodeWriter.WriteEndObject(); // viewStateDataType } viewStateManagerNodeWriter.WriteEndMember(); // XamlLanguage.Items viewStateManagerNodeWriter.WriteEndObject(); // GetObject viewStateManagerNodeWriter.WriteEndMember(); // viewStateDataMember viewStateManagerNodeWriter.WriteEndObject(); // viewStateManagerType viewStateManagerNodeWriter.Close(); } return viewStateManagerNodeList; } // Checks if the Xaml reader is on one of WorkflowViewStateService.ViewState or // VirtualizedContainerService.HintSize members in the nodestream. These // members need to be moved into the ViewStateManager node during the conversion. static bool IsAttachablePropertyForConvert(XamlReader reader) { if (reader.NodeType == XamlNodeType.StartMember) { XamlMember member = reader.Member; if (member.IsAttachable) { if (member.DeclaringType.UnderlyingType == typeof(WorkflowViewStateService) && member.Name.Equals("ViewState", StringComparison.Ordinal)) { return true; } else if (member.DeclaringType.UnderlyingType == typeof(VirtualizedContainerService) && member.Name.Equals("HintSize", StringComparison.Ordinal)) { return true; } } } return false; } // This method reads ViewStateManager nodes from the xaml nodestream and outputs that in the // viewStateInfo dictionary. The input reader is positioned at the begining of the workflow definition. // The method returns a reader positioned at the begining of the workflow definition with the ViewStateManager // nodes removed. static XamlReader StripViewStateElement(XamlReader inputReader, out Dictionary<string, XamlNodeList> viewStateInfo, out Dictionary<string, SourceLocation> viewStateSourceLocationMap) { viewStateSourceLocationMap = null; XamlNodeList strippedNodeList = new XamlNodeList(inputReader.SchemaContext); XamlMember viewStateManager = new XamlMember(ViewStateManager, GetViewStateManager, SetViewStateManager, inputReader.SchemaContext); using (XamlWriter strippedWriter = strippedNodeList.Writer) { IXamlLineInfo lineInfo = inputReader as IXamlLineInfo; IXamlLineInfoConsumer lineInfoComsumer = strippedWriter as IXamlLineInfoConsumer; bool shouldPassLineInfo = lineInfo != null && lineInfo.HasLineInfo && lineInfoComsumer != null && lineInfoComsumer.ShouldProvideLineInfo; viewStateInfo = null; while (inputReader.Read()) { if (inputReader.NodeType == XamlNodeType.StartMember && inputReader.Member.Equals(viewStateManager)) { ReadViewStateInfo(inputReader.ReadSubtree(), out viewStateInfo, out viewStateSourceLocationMap); } if (shouldPassLineInfo) { lineInfoComsumer.SetLineInfo(lineInfo.LineNumber, lineInfo.LinePosition); } strippedWriter.WriteNode(inputReader); } } return strippedNodeList.GetReader(); } // This method reads ViewStateManager nodes from the xaml nodestream and outputs that in the // viewStateInfo dictionary. The input reader is positioned on the ViewStateManagerNode in the nodestream. static void ReadViewStateInfo(XamlReader inputReader, out Dictionary<string, XamlNodeList> viewStateInfo, out Dictionary<string, SourceLocation> viewStateSourceLocationMap) { XamlType viewStateType = new XamlType(typeof(ViewStateData), inputReader.SchemaContext); viewStateInfo = new Dictionary<string, XamlNodeList>(); viewStateSourceLocationMap = new Dictionary<string, SourceLocation>(); bool skipReading = false; while (skipReading || inputReader.Read()) { skipReading = false; if (inputReader.NodeType == XamlNodeType.StartObject && inputReader.Type.Equals(viewStateType)) { string id; XamlNodeList viewStateNodeList; SourceLocation viewStateSourceLocation = null; ReadViewState(viewStateType, inputReader.ReadSubtree(), out id, out viewStateNodeList, out viewStateSourceLocation); if (id != null) { viewStateInfo[id] = viewStateNodeList; viewStateSourceLocationMap[id] = viewStateSourceLocation; } //inputReader will be positioned on the next node so no need to advance it. skipReading = true; } } } // This method reads a ViewStateData node from the xaml nodestream. It outputs the Id property into viewStateId // and the attached viewstate related properties in viewStateNodes. The input reader is positioned on a // ViewStateData node within ViewStateManager. static void ReadViewState(XamlType viewStateType, XamlReader xamlReader, out string viewStateId, out XamlNodeList viewStateNodes, out SourceLocation sourceLocation) { int globalMemberLevel = 0; bool skippingUnexpectedAttachedProperty = false; int skippingUnexpectedAttachedPropertyLevel = 0; viewStateId = null; viewStateNodes = new XamlNodeList(viewStateType.SchemaContext); sourceLocation = null; Stack<Frame> objectNodes = new Stack<Frame>(); XamlMember idMember = new XamlMember(typeof(ViewStateData).GetProperty("Id"), xamlReader.SchemaContext); int[] viewStateDataSourceLocation = new int[4]; int sourceLocationIndex = -1; IXamlLineInfo lineInfo = xamlReader as IXamlLineInfo; IXamlLineInfoConsumer lineInfoComsumer = viewStateNodes.Writer as IXamlLineInfoConsumer; bool shouldPassLineInfo = lineInfo != null && lineInfo.HasLineInfo && lineInfoComsumer != null && lineInfoComsumer.ShouldProvideLineInfo; while (xamlReader.Read()) { bool skipWritingToNodeList = false; switch (xamlReader.NodeType) { case XamlNodeType.StartObject: if (xamlReader.Type.Equals(viewStateType)) { skipWritingToNodeList = true; } objectNodes.Push(new Frame { Type = xamlReader.Type }); break; case XamlNodeType.GetObject: objectNodes.Push(new Frame { Type = null }); break; case XamlNodeType.StartMember: globalMemberLevel++; if (xamlReader.Member.Equals(idMember)) { XamlReader idNode = xamlReader.ReadSubtree(); while (idNode.Read()) { if (idNode.NodeType == XamlNodeType.Value) { viewStateId = idNode.Value as string; } } } else if (globalMemberLevel == 1 && !IsAttachablePropertyForConvert(xamlReader)) { skippingUnexpectedAttachedProperty = true; } if (skippingUnexpectedAttachedProperty) { skippingUnexpectedAttachedPropertyLevel++; } sourceLocationIndex = GetViewStateDataSourceLocationIndexFromCurrentReader(xamlReader); break; case XamlNodeType.EndMember: globalMemberLevel--; if (skippingUnexpectedAttachedProperty) { skippingUnexpectedAttachedPropertyLevel--; } break; case XamlNodeType.Value: if (xamlReader.Value is int && sourceLocationIndex >= 0 && sourceLocationIndex < viewStateDataSourceLocation.Length) { viewStateDataSourceLocation[sourceLocationIndex] = (int)xamlReader.Value; } break; case XamlNodeType.EndObject: Frame objectNode = objectNodes.Pop(); if (objectNode.Type != null && objectNode.Type.Equals(viewStateType)) { skipWritingToNodeList = true; // The ViewStateData's source location should be valid, because // before each EndObject, its SourceLocation is injected. // If not, an exception will be thrown from constructor // of SourceLocation. sourceLocation = new SourceLocation(null, viewStateDataSourceLocation[0], viewStateDataSourceLocation[1], viewStateDataSourceLocation[2], viewStateDataSourceLocation[3] ); } Array.Clear(viewStateDataSourceLocation, 0, viewStateDataSourceLocation.Length); break; }; if (!skipWritingToNodeList && !skippingUnexpectedAttachedProperty) { if (shouldPassLineInfo) { lineInfoComsumer.SetLineInfo(lineInfo.LineNumber, lineInfo.LinePosition); } viewStateNodes.Writer.WriteNode(xamlReader); } if (skippingUnexpectedAttachedPropertyLevel == 0) { skippingUnexpectedAttachedProperty = false; } } viewStateNodes.Writer.Close(); } private static int GetViewStateDataSourceLocationIndexFromCurrentReader(XamlReader xamlReader) { if (xamlReader.NodeType != XamlNodeType.StartMember || xamlReader.Member == null || xamlReader.Member.UnderlyingMember == null || xamlReader.Member.UnderlyingMember.DeclaringType != typeof(XamlDebuggerXmlReader)) { return -1; } // if UnderlineType is XamlDebuggerXmlReader, see if it // is one of {StartLine, StartColumn, EndLine, EndColumn} return SourceLocationNames.IndexOf(xamlReader.Member.Name); } // This class is used for tracking Xaml nodestream data. class Frame { // IdRef value if any associated with the node. public string IdRef { get; set; } // XamlType of the node. Helps generating IdRef values. public XamlType Type { get; set; } // XamlNodes corresponding to viewstate related attached property nodes. public XamlNodeList AttachedPropertyNodes { get; set; } // Underlying CLR object. Used to attach generated IdRef values // when serializing workflow definition. public object InstanceObject { get; set; } } } }
using System.IO; using System.Threading.Tasks; using System.Linq; using OmniSharp.Models.TypeLookup; using OmniSharp.Options; using OmniSharp.Roslyn.CSharp.Services.Types; using TestUtility; using Xunit; using Xunit.Abstractions; namespace OmniSharp.Roslyn.CSharp.Tests { public class TypeLookupFacts : AbstractSingleRequestHandlerTestFixture<TypeLookupService> { public TypeLookupFacts(ITestOutputHelper output, SharedOmniSharpHostFixture sharedOmniSharpHostFixture) : base(output, sharedOmniSharpHostFixture) { } protected override string EndpointName => OmniSharpEndpoints.TypeLookup; [Fact] public async Task OmitsNamespaceForNonRegularCSharpSyntax() { var source = @"class Foo {}"; var testFile = new TestFile("dummy.csx", source); var workspace = TestHelpers.CreateCsxWorkspace(testFile); var controller = new TypeLookupService(workspace, new FormattingOptions()); var response = await controller.Handle(new TypeLookupRequest { FileName = testFile.FileName, Line = 0, Column = 7 }); Assert.Equal("Foo", response.Type); } [Fact] public async Task TypesFromInlineAssemlbyReferenceContainDocumentation() { var testAssemblyPath = Path.Combine(TestAssets.Instance.TestBinariesFolder, "ClassLibraryWithDocumentation.dll"); var source = $@"#r ""{testAssemblyPath}"" using ClassLibraryWithDocumentation; Documented$$Class c; "; var testFile = new TestFile("dummy.csx", source); var position = testFile.Content.GetPointFromPosition(); var workspace = TestHelpers.CreateCsxWorkspace(testFile); var controller = new TypeLookupService(workspace, new FormattingOptions()); var response = await controller.Handle(new TypeLookupRequest { FileName = testFile.FileName, Line = position.Line, Column = position.Offset, IncludeDocumentation = true }); Assert.Equal("This class performs an important function.", response.Documentation?.Trim()); } [Fact] public async Task OmitsNamespaceForTypesInGlobalNamespace() { const string source = @"namespace Bar { class Foo {} } class Baz {}"; var testFile = new TestFile("dummy.cs", source); SharedOmniSharpTestHost.AddFilesToWorkspace(testFile); var requestHandler = GetRequestHandler(SharedOmniSharpTestHost); var requestInNormalNamespace = new TypeLookupRequest { FileName = testFile.FileName, Line = 1, Column = 19 }; var responseInNormalNamespace = await requestHandler.Handle(requestInNormalNamespace); var requestInGlobalNamespace = new TypeLookupRequest { FileName = testFile.FileName, Line = 3, Column = 19 }; var responseInGlobalNamespace = await requestHandler.Handle(requestInGlobalNamespace); Assert.Equal("Bar.Foo", responseInNormalNamespace.Type); Assert.Equal("Baz", responseInGlobalNamespace.Type); } [Fact] public async Task IncludesNamespaceForRegularCSharpSyntax() { const string source = @"namespace Bar { class Foo {} }"; var testFile = new TestFile("dummy.cs", source); SharedOmniSharpTestHost.AddFilesToWorkspace(testFile); var requestHandler = GetRequestHandler(SharedOmniSharpTestHost); var request = new TypeLookupRequest { FileName = testFile.FileName, Line = 1, Column = 19 }; var response = await requestHandler.Handle(request); Assert.Equal("Bar.Foo", response.Type); } [Fact] public async Task IncludesContainingTypeFoNestedTypesForRegularCSharpSyntax() { var source = @"namespace Bar { class Foo { class Xyz {} } }"; var testFile = new TestFile("dummy.cs", source); SharedOmniSharpTestHost.AddFilesToWorkspace(testFile); var requestHandler = GetRequestHandler(SharedOmniSharpTestHost); var request = new TypeLookupRequest { FileName = testFile.FileName, Line = 2, Column = 27 }; var response = await requestHandler.Handle(request); Assert.Equal("Bar.Foo.Xyz", response.Type); } [Fact] public async Task IncludesContainingTypeFoNestedTypesForNonRegularCSharpSyntax() { var source = @"class Foo { class Bar {} }"; var testFile = new TestFile("dummy.csx", source); var workspace = TestHelpers.CreateCsxWorkspace(testFile); var controller = new TypeLookupService(workspace, new FormattingOptions()); var request = new TypeLookupRequest { FileName = testFile.FileName, Line = 1, Column = 23 }; var response = await controller.Handle(request); Assert.Equal("Foo.Bar", response.Type); } private static TestFile s_testFile = new TestFile("dummy.cs", @"using System; using Bar2; using System.Collections.Generic; namespace Bar { class Foo { public Foo() { Console.WriteLine(""abc""); } public void MyMethod(string name, Foo foo, Foo2 foo2) { }; private Foo2 _someField = new Foo2(); public Foo2 SomeProperty { get; } public IDictionary<string, IEnumerable<int>> SomeDict { get; } public void Compute(int index = 2) { } private const int foo = 1; } } namespace Bar2 { class Foo2 { } } namespace Bar3 { enum Foo3 { Val1 = 1, Val2 } } "); [Fact] public async Task DisplayFormatForMethodSymbol_Invocation() { var response = await GetTypeLookUpResponse(line: 6, column: 35); #if NETCOREAPP Assert.Equal("void Console.WriteLine(string? value)", response.Type); #else Assert.Equal("void Console.WriteLine(string value)", response.Type); #endif } [Fact] public async Task DisplayFormatForMethodSymbol_Declaration() { var response = await GetTypeLookUpResponse(line: 9, column: 35); Assert.Equal("void Foo.MyMethod(string name, Foo foo, Foo2 foo2)", response.Type); } [Fact] public async Task DisplayFormatFor_TypeSymbol_Primitive() { var response = await GetTypeLookUpResponse(line: 9, column: 46); Assert.Equal("System.String", response.Type); } [Fact] public async Task DisplayFormatFor_TypeSymbol_ComplexType_SameNamespace() { var response = await GetTypeLookUpResponse(line: 9, column: 56); Assert.Equal("Bar.Foo", response.Type); } [Fact] public async Task DisplayFormatFor_TypeSymbol_ComplexType_DifferentNamespace() { var response = await GetTypeLookUpResponse(line: 9, column: 67); Assert.Equal("Bar2.Foo2", response.Type); } [Fact] public async Task DisplayFormatFor_TypeSymbol_WithGenerics() { var response = await GetTypeLookUpResponse(line: 15, column: 36); Assert.Equal("System.Collections.Generic.IDictionary<System.String, System.Collections.Generic.IEnumerable<System.Int32>>", response.Type); } [Fact] public async Task DisplayFormatForParameterSymbol_Name_Primitive() { var response = await GetTypeLookUpResponse(line: 9, column: 51); Assert.Equal("string name", response.Type); } [Fact] public async Task DisplayFormatFor_ParameterSymbol_ComplexType_SameNamespace() { var response = await GetTypeLookUpResponse(line: 9, column: 60); Assert.Equal("Foo foo", response.Type); } [Fact] public async Task DisplayFormatFor_ParameterSymbol_Name_ComplexType_DifferentNamespace() { var response = await GetTypeLookUpResponse(line: 9, column: 71); Assert.Equal("Foo2 foo2", response.Type); } [Fact] public async Task DisplayFormatFor_ParameterSymbol_Name_WithDefaultValue() { var response = await GetTypeLookUpResponse(line: 17, column: 48); Assert.Equal("int index = 2", response.Type); } [Fact] public async Task DisplayFormatFor_FieldSymbol() { var response = await GetTypeLookUpResponse(line: 11, column: 38); Assert.Equal("Foo2 Foo._someField", response.Type); } [Fact] public async Task DisplayFormatFor_FieldSymbol_WithConstantValue() { var response = await GetTypeLookUpResponse(line: 19, column: 41); Assert.Equal("int Foo.foo = 1", response.Type); } [Fact] public async Task DisplayFormatFor_EnumValue() { var response = await GetTypeLookUpResponse(line: 31, column: 23); Assert.Equal("Foo3.Val2 = 2", response.Type); } [Fact] public async Task DisplayFormatFor_PropertySymbol() { var response = await GetTypeLookUpResponse(line: 13, column: 38); Assert.Equal("Foo2 Foo.SomeProperty", response.Type); } [Fact] public async Task DisplayFormatFor_PropertySymbol_WithGenerics() { var response = await GetTypeLookUpResponse(line: 15, column: 70); Assert.Equal("IDictionary<string, IEnumerable<int>> Foo.SomeDict", response.Type); } [Fact] public async Task StructuredDocumentationRemarksText() { string content = @" class testissue { ///<remarks>You may have some additional information about this class here.</remarks> public static bool C$$ompare(int gameObject, string tagName) { return gameObject.TagifyCompareTag(tagName); } }"; var response = await GetTypeLookUpResponse(content); var expected = @"You may have some additional information about this class here."; Assert.Equal(expected, response.StructuredDocumentation.RemarksText); } [Fact] public async Task StructuredDocumentationSummaryText() { string content = @" class testissue { ///<summary>Checks if object is tagged with the tag.</summary> public static bool C$$ompare(int gameObject, string tagName) { } }"; var response = await GetTypeLookUpResponse(content); var expected = @"Checks if object is tagged with the tag."; Assert.Equal(expected, response.StructuredDocumentation.SummaryText); } [Fact] public async Task StructuredDocumentationReturnsText() { string content = @" class testissue { ///<returns>Returns true if object is tagged with tag.</returns> public static bool C$$ompare(int gameObject, string tagName) { } }"; var response = await GetTypeLookUpResponse(content); var expected = @"Returns true if object is tagged with tag."; Assert.Equal(expected, response.StructuredDocumentation.ReturnsText); } [Fact] public async Task StructuredDocumentationExampleText() { string content = @" class testissue { ///<example>Checks if object is tagged with the tag.</example> public static bool C$$ompare(int gameObject, string tagName) { } }"; var response = await GetTypeLookUpResponse(content); var expected = @"Checks if object is tagged with the tag."; Assert.Equal(expected, response.StructuredDocumentation.ExampleText); } [Fact] public async Task StructuredDocumentationExceptionText() { string content = @" class testissue { ///<exception cref=""A"">A description</exception> ///<exception cref=""B"">B description</exception> public static bool C$$ompare(int gameObject, string tagName) { } }"; var response = await GetTypeLookUpResponse(content); Assert.Equal(2, response.StructuredDocumentation.Exception.Count()); Assert.Equal("A", response.StructuredDocumentation.Exception[0].Name); Assert.Equal("A description", response.StructuredDocumentation.Exception[0].Documentation); Assert.Equal("B", response.StructuredDocumentation.Exception[1].Name); Assert.Equal("B description", response.StructuredDocumentation.Exception[1].Documentation); } [Fact] public async Task StructuredDocumentationParameter() { string content = @" class testissue { /// <param name=""gameObject"">The game object.</param> /// <param name=""tagName"">Name of the tag.</param> public static bool C$$ompare(int gameObject, string tagName) { } }"; var response = await GetTypeLookUpResponse(content); Assert.Equal(2, response.StructuredDocumentation.ParamElements.Length); Assert.Equal("gameObject", response.StructuredDocumentation.ParamElements[0].Name); Assert.Equal("The game object.", response.StructuredDocumentation.ParamElements[0].Documentation); Assert.Equal("tagName", response.StructuredDocumentation.ParamElements[1].Name); Assert.Equal("Name of the tag.", response.StructuredDocumentation.ParamElements[1].Documentation); } [Fact] public async Task StructuredDocumentationTypeParameter() { string content = @" public class TestClass { /// <summary> /// Creates a new array of arbitrary type <typeparamref name=""T""/> and adds the elements of incoming list to it if possible /// </summary> /// <typeparam name=""T"">The element type of the array</typeparam> /// <typeparam name=""X"">The element type of the list</typeparam> public static T[] m$$kArray<T>(int n, List<X> list) { return new T[n]; } }"; var response = await GetTypeLookUpResponse(content); Assert.Equal(2, response.StructuredDocumentation.TypeParamElements.Count()); Assert.Equal("T", response.StructuredDocumentation.TypeParamElements[0].Name); Assert.Equal("The element type of the array", response.StructuredDocumentation.TypeParamElements[0].Documentation); Assert.Equal("X", response.StructuredDocumentation.TypeParamElements[1].Name); Assert.Equal("The element type of the list", response.StructuredDocumentation.TypeParamElements[1].Documentation); } [Fact] public async Task StructuredDocumentationValueText() { string content = @"public class Employee { private string _name; /// <summary>The Name property represents the employee's name.</summary> /// <value>The Name property gets/sets the value of the string field, _name.</value> public string Na$$me { } } "; var response = await GetTypeLookUpResponse(content); var expectedValue = @"The Name property gets/sets the value of the string field, _name."; Assert.Equal(expectedValue, response.StructuredDocumentation.ValueText); var expectedSummary = @"The Name property represents the employee's name."; Assert.Equal(expectedSummary, response.StructuredDocumentation.SummaryText); } [Fact] public async Task StructuredDocumentationNestedTagSee() { string content = @" public class TestClass { /// <summary>DoWork is a method in the TestClass class. <see cref=""System.Console.WriteLine(System.String)""/> for information about output statements.</summary> public static void Do$$Work(int Int1) { } }"; var response = await GetTypeLookUpResponse(content); var expected = @"DoWork is a method in the TestClass class. System.Console.WriteLine(System.String) for information about output statements."; Assert.Equal(expected, response.StructuredDocumentation.SummaryText); } [Fact] public async Task StructuredDocumentationNestedTagParamRef() { string content = @" public class TestClass { /// <summary>Creates a new array of arbitrary type <typeparamref name=""T""/></summary> /// <typeparam name=""T"">The element type of the array</typeparam> public static T[] mk$$Array<T>(int n) { return new T[n]; } }"; var response = await GetTypeLookUpResponse(content); var expected = @"Creates a new array of arbitrary type T "; Assert.Equal(expected, response.StructuredDocumentation.SummaryText); } [Fact] public async Task StructuredDocumentationNestedTagCode() { string content = @" public class TestClass { /// <example>This sample shows how to call the <see cref=""GetZero""/> method. /// <code> /// class TestClass /// { /// static int Main() /// { /// return GetZero(); /// } /// } /// </code> /// </example> public static int $$GetZero() { return 0; } }"; var response = await GetTypeLookUpResponse(content); var expected = @"This sample shows how to call the TestClass.GetZero method. class TestClass { static int Main() { return GetZero(); } } "; Assert.Equal(expected.Replace("\r", ""), response.StructuredDocumentation.ExampleText); } [Fact] public async Task StructuredDocumentationNestedTagPara() { string content = @" public class TestClass { /// <summary>DoWork is a method in the TestClass class. /// <para>Here's how you could make a second paragraph in a description.</para> /// </summary> public static void Do$$Work(int Int1) { } } "; var response = await GetTypeLookUpResponse(content); var expected = @"DoWork is a method in the TestClass class. Here's how you could make a second paragraph in a description."; Assert.Equal(expected.Replace("\r", ""), response.StructuredDocumentation.SummaryText); } [Fact] public async Task StructuredDocumentationNestedTagSeeAlso() { string content = @" public class TestClass { /// <summary>DoWork is a method in the TestClass class. /// <seealso cref=""TestClass.Main""/> /// </summary> public static void Do$$Work(int Int1) { } static void Main() { } }"; var response = await GetTypeLookUpResponse(content); var expected = @"DoWork is a method in the TestClass class. See also: TestClass.Main "; Assert.Equal(expected.Replace("\r", ""), response.StructuredDocumentation.SummaryText); } [Fact] public async Task StructuredDocumentationSummaryAndParam() { string content = @" class testissue { ///<summary>Checks if object is tagged with the tag.</summary> /// <param name=""gameObject"">The game object.</param> /// <param name=""tagName"">Name of the tag.</param> public static bool C$$ompare(int gameObject, string tagName) { } }"; var response = await GetTypeLookUpResponse(content); var expected = @"Checks if object is tagged with the tag."; Assert.Equal(expected, response.StructuredDocumentation.SummaryText); Assert.Equal(2, response.StructuredDocumentation.ParamElements.Length); Assert.Equal("gameObject", response.StructuredDocumentation.ParamElements[0].Name); Assert.Equal("The game object.", response.StructuredDocumentation.ParamElements[0].Documentation); Assert.Equal("tagName", response.StructuredDocumentation.ParamElements[1].Name); Assert.Equal("Name of the tag.", response.StructuredDocumentation.ParamElements[1].Documentation); } [Fact] public async Task StructuredDocumentationManyTags() { string content = @" class testissue { ///<summary>Checks if object is tagged with the tag.</summary> ///<param name=""gameObject"">The game object.</param> ///<example>Invoke using A.Compare(5) where A is an instance of the class testissue.</example> ///<typeparam name=""T"">The element type of the array</typeparam> ///<exception cref=""System.Exception"">Thrown when something goes wrong</exception> ///<remarks>You may have some additional information about this class here.</remarks> ///<returns>Returns an array of type <typeparamref name=""T""/>.</returns> public static T[] C$$ompare(int gameObject) { } }"; var response = await GetTypeLookUpResponse(content); var expectedSummary = @"Checks if object is tagged with the tag."; Assert.Equal(expectedSummary, response.StructuredDocumentation.SummaryText); Assert.Single(response.StructuredDocumentation.ParamElements); Assert.Equal("gameObject", response.StructuredDocumentation.ParamElements[0].Name); Assert.Equal("The game object.", response.StructuredDocumentation.ParamElements[0].Documentation); var expectedExample = @"Invoke using A.Compare(5) where A is an instance of the class testissue."; Assert.Equal(expectedExample, response.StructuredDocumentation.ExampleText); Assert.Single(response.StructuredDocumentation.TypeParamElements); Assert.Equal("T", response.StructuredDocumentation.TypeParamElements[0].Name); Assert.Equal("The element type of the array", response.StructuredDocumentation.TypeParamElements[0].Documentation); Assert.Single(response.StructuredDocumentation.Exception); Assert.Equal("System.Exception", response.StructuredDocumentation.Exception[0].Name); Assert.Equal("Thrown when something goes wrong", response.StructuredDocumentation.Exception[0].Documentation); var expectedRemarks = @"You may have some additional information about this class here."; Assert.Equal(expectedRemarks, response.StructuredDocumentation.RemarksText); var expectedReturns = @"Returns an array of type T ."; Assert.Equal(expectedReturns, response.StructuredDocumentation.ReturnsText); } [Fact] public async Task StructuredDocumentationSpaceBeforeText() { string content = @" public class TestClass { /// <summary><c>DoWork</c> is a method in the <c>TestClass</c> class.</summary> public static void Do$$Work(int Int1) { } }"; var response = await GetTypeLookUpResponse(content); var expected = @"DoWork is a method in the TestClass class."; Assert.Equal(expected, response.StructuredDocumentation.SummaryText); } [Fact] public async Task StructuredDocumentationForParameters1() { string content = @" class testissue { /// <param name=""gameObject"">The game object.</param> /// <param name=""tagName"">Name of the tag.</param> public static bool Compare(int gam$$eObject, string tagName) { } }"; var response = await GetTypeLookUpResponse(content); Assert.Equal("The game object.", response.StructuredDocumentation.SummaryText); } [Fact] public async Task StructuredDocumentationForParameters2() { string content = @" class testissue { /// <param name=""gameObject"">The game object.</param> /// <param name=""tagName"">Name of the tag.</param> public static bool Compare(int gameObject, string tag$$Name) { } }"; var response = await GetTypeLookUpResponse(content); Assert.Equal("Name of the tag.", response.StructuredDocumentation.SummaryText); } private async Task<TypeLookupResponse> GetTypeLookUpResponse(string content) { TestFile testFile = new TestFile("dummy.cs", content); SharedOmniSharpTestHost.AddFilesToWorkspace(testFile); var requestHandler = GetRequestHandler(SharedOmniSharpTestHost); var point = testFile.Content.GetPointFromPosition(); var request = new TypeLookupRequest { FileName = testFile.FileName, Line = point.Line, Column = point.Offset }; request.IncludeDocumentation = true; return await requestHandler.Handle(request); } private async Task<TypeLookupResponse> GetTypeLookUpResponse(int line, int column) { SharedOmniSharpTestHost.AddFilesToWorkspace(s_testFile); var requestHandler = GetRequestHandler(SharedOmniSharpTestHost); var request = new TypeLookupRequest { FileName = s_testFile.FileName, Line = line, Column = column }; return await requestHandler.Handle(request); } } }
using System; using System.Drawing; using MonoMac.Foundation; using MonoMac.AppKit; using MonoMac.ObjCRuntime; namespace NBTExplorer { public partial class AppDelegate : NSApplicationDelegate { MainWindowController mainWindowController; public AppDelegate () { } public override void FinishedLaunching (NSObject notification) { mainWindowController = new MainWindowController (); mainWindowController.Window.MakeKeyAndOrderFront (this); mainWindowController.Window.AppDelegate = this; } public override bool ApplicationShouldTerminateAfterLastWindowClosed (NSApplication sender) { return true; } public NSMenuItem MenuAbout { get { return _menuAbout; } } public NSMenuItem MenuQuit { get { return _menuQuit; } } public NSMenuItem MenuOpen { get { return _menuOpen; } } public NSMenuItem MenuOpenFolder { get { return _menuOpenFolder; } } public NSMenuItem MenuOpenMinecraft { get { return _menuOpenMinecraft; } } public NSMenuItem MenuSave { get { return _menuSave; } } public NSMenuItem MenuCut { get { return _menuCut; } } public NSMenuItem MenuCopy { get { return _menuCopy; } } public NSMenuItem MenuPaste { get { return _menuPaste; } } public NSMenuItem MenuRename { get { return _menuRename; } } public NSMenuItem MenuEditValue { get { return _menuEditValue; } } public NSMenuItem MenuDelete { get { return _menuDelete; } } public NSMenuItem MenuMoveUp { get { return _menuMoveUp; } } public NSMenuItem MenuMoveDown { get { return _menuMoveDown; } } public NSMenuItem MenuFind { get { return _menuFind; } } public NSMenuItem MenuFindNext { get { return _menuFindNext; } } public NSMenuItem MenuInsertByte { get { return _menuInsertByte; } } public NSMenuItem MenuInsertShort { get { return _menuInsertShort; } } public NSMenuItem MenuInsertInt { get { return _menuInsertInt; } } public NSMenuItem MenuInsertLong { get { return _menuInsertLong; } } public NSMenuItem MenuInsertFloat { get { return _menuInsertFloat; } } public NSMenuItem MenuInsertDouble { get { return _menuInsertDouble; } } public NSMenuItem MenuInsertByteArray { get { return _menuInsertByteArray; } } public NSMenuItem MenuInsertIntArray { get { return _menuInsertIntArray; } } public NSMenuItem MenuInsertString { get { return _menuInsertString; } } public NSMenuItem MenuInsertList { get { return _menuInsertList; } } public NSMenuItem MenuInsertCompound { get { return _menuInsertCompound; } } partial void ActionOpen (NSObject sender) { mainWindowController.Window.ActionOpen(); } partial void ActionOpenFolder (NSObject sender) { mainWindowController.Window.ActionOpenFolder(); } partial void ActionOpenMinecraft (NSObject sender) { mainWindowController.Window.ActionOpenMinecraft(); } partial void ActionSave (NSObject sender) { mainWindowController.Window.ActionSave(); } partial void ActionCut (NSObject sender) { mainWindowController.Window.ActionCut(); } partial void ActionCopy (NSObject sender) { mainWindowController.Window.ActionCopy(); } partial void ActionPaste (NSObject sender) { mainWindowController.Window.ActionPaste(); } partial void ActionRename (NSObject sender) { mainWindowController.Window.ActionRenameValue(); } partial void ActionEditValue (NSObject sender) { mainWindowController.Window.ActionEditValue(); } partial void ActionDelete (NSObject sender) { mainWindowController.Window.ActionDeleteValue(); } partial void ActionMoveUp (NSObject sender) { mainWindowController.Window.ActionMoveNodeUp(); } partial void ActionMoveDown (NSObject sender) { mainWindowController.Window.ActionMoveNodeDown(); } partial void ActionFind (NSObject sender) { mainWindowController.Window.ActionFind(); } partial void ActionFindNext (NSObject sender) { mainWindowController.Window.ActionFindNext(); } partial void ActionInsertByte (NSObject sender) { mainWindowController.Window.ActionInsertByteTag(); } partial void ActionInsertShort (NSObject sender) { mainWindowController.Window.ActionInsertShortTag(); } partial void ActionInsertInt (NSObject sender) { mainWindowController.Window.ActionInsertIntTag(); } partial void ActionInsertLong (NSObject sender) { mainWindowController.Window.ActionInsertLongTag(); } partial void ActionInsertFloat (NSObject sender) { mainWindowController.Window.ActionInsertFloatTag(); } partial void ActionInsertDouble (NSObject sender) { mainWindowController.Window.ActionInsertDoubleTag(); } partial void ActionInsertByteArray (NSObject sender) { mainWindowController.Window.ActionInsertByteArrayTag(); } partial void ActionInsertIntArray (NSObject sender) { mainWindowController.Window.ActionInsertIntArrayTag(); } partial void ActionInsertString (NSObject sender) { mainWindowController.Window.ActionInsertStringTag(); } partial void ActionInsertList (NSObject sender) { mainWindowController.Window.ActionInsertListTag(); } partial void ActionInsertCompound (NSObject sender) { mainWindowController.Window.ActionInsertCompoundTag(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Runtime.CompilerServices; namespace System.Text { internal static class InvariantUtf16IntegerFormatter { private const char Minus = '-'; private const char Period = '.'; private const char Seperator = ','; // Invariant formatting uses groups of 3 for each number group seperated by commas. // ex. 1,234,567,890 private const int GroupSize = 3; public static bool TryFormatDecimalInt64(long value, byte precision, Span<byte> buffer, out int bytesWritten) { int digitCount = FormattingHelpers.CountDigits(value); int charsNeeded = digitCount + (int)((value >> 63) & 1); Span<char> span = buffer.NonPortableCast<byte, char>(); if (span.Length < charsNeeded) { bytesWritten = 0; return false; } ref char utf16Bytes = ref span.DangerousGetPinnableReference(); int idx = 0; if (value < 0) { Unsafe.Add(ref utf16Bytes, idx++) = Minus; // Abs(long.MinValue) == long.MaxValue + 1, so we need to re-route to unsigned to handle value if (value == long.MinValue) { if (!TryFormatDecimalUInt64((ulong)long.MaxValue + 1, precision, buffer.Slice(2), out bytesWritten)) return false; bytesWritten += sizeof(char); // Add the minus sign return true; } value = -value; } if (precision != ParsedFormat.NoPrecision) { int leadingZeros = (int)precision - digitCount; while (leadingZeros-- > 0) Unsafe.Add(ref utf16Bytes, idx++) = '0'; } idx += FormattingHelpers.WriteDigits(value, digitCount, ref utf16Bytes, idx); bytesWritten = idx * sizeof(char); return true; } public static bool TryFormatDecimalUInt64(ulong value, byte precision, Span<byte> buffer, out int bytesWritten) { if (value <= long.MaxValue) return TryFormatDecimalInt64((long)value, precision, buffer, out bytesWritten); // Remove a single digit from the number. This will get it below long.MaxValue // Then we call the faster long version and follow-up with writing the last // digit. This ends up being faster by a factor of 2 than to just do the entire // operation using the unsigned versions. value = FormattingHelpers.DivMod(value, 10, out ulong lastDigit); if (precision != ParsedFormat.NoPrecision && precision > 0) precision -= 1; if (!TryFormatDecimalInt64((long)value, precision, buffer, out bytesWritten)) return false; Span<char> span = buffer.Slice(bytesWritten).NonPortableCast<byte, char>(); if (span.Length < sizeof(char)) { bytesWritten = 0; return false; } ref char utf16Bytes = ref span.DangerousGetPinnableReference(); FormattingHelpers.WriteDigits(lastDigit, 1, ref utf16Bytes, 0); bytesWritten += sizeof(char); return true; } public static bool TryFormatNumericInt64(long value, byte precision, Span<byte> buffer, out int bytesWritten) { int digitCount = FormattingHelpers.CountDigits(value); int groupSeperators = (int)FormattingHelpers.DivMod(digitCount, GroupSize, out long firstGroup); if (firstGroup == 0) { firstGroup = 3; groupSeperators--; } int trailingZeros = (precision == ParsedFormat.NoPrecision) ? 2 : precision; int charsNeeded = (int)((value >> 63) & 1) + digitCount + groupSeperators; int idx = charsNeeded; if (trailingZeros > 0) charsNeeded += trailingZeros + 1; // +1 for period. Span<char> span = buffer.NonPortableCast<byte, char>(); if (span.Length < charsNeeded) { bytesWritten = 0; return false; } ref char utf16Bytes = ref span.DangerousGetPinnableReference(); long v = value; if (v < 0) { Unsafe.Add(ref utf16Bytes, 0) = Minus; // Abs(long.MinValue) == long.MaxValue + 1, so we need to re-route to unsigned to handle value if (v == long.MinValue) { if (!TryFormatNumericUInt64((ulong)long.MaxValue + 1, precision, buffer.Slice(2), out bytesWritten)) return false; bytesWritten += sizeof(char); // Add the minus sign return true; } v = -v; } // Write out the trailing zeros if (trailingZeros > 0) { Unsafe.Add(ref utf16Bytes, idx) = Period; FormattingHelpers.WriteDigits(0, trailingZeros, ref utf16Bytes, idx + 1); } // Starting from the back, write each group of digits except the first group while (digitCount > 3) { idx -= 3; v = FormattingHelpers.DivMod(v, 1000, out long groupValue); FormattingHelpers.WriteDigits(groupValue, 3, ref utf16Bytes, idx); Unsafe.Add(ref utf16Bytes, --idx) = Seperator; digitCount -= 3; } // Write the first group of digits. FormattingHelpers.WriteDigits(v, (int)firstGroup, ref utf16Bytes, idx - (int)firstGroup); bytesWritten = charsNeeded * sizeof(char); return true; } public static bool TryFormatNumericUInt64(ulong value, byte precision, Span<byte> buffer, out int bytesWritten) { if (value <= long.MaxValue) return TryFormatNumericInt64((long)value, precision, buffer, out bytesWritten); // The ulong path is much slower than the long path here, so we are doing the last group // inside this method plus the zero padding but routing to the long version for the rest. value = FormattingHelpers.DivMod(value, 1000, out ulong lastGroup); if (!TryFormatNumericInt64((long)value, 0, buffer, out bytesWritten)) return false; if (precision == ParsedFormat.NoPrecision) precision = 2; // Since this method routes entirely to the long version if the number is smaller than // long.MaxValue, we are guaranteed to need to write 3 more digits here before the set // of trailing zeros. int extraChars = 4; // 3 digits + group seperator if (precision > 0) extraChars += precision + 1; // +1 for period. Span<char> span = buffer.Slice(bytesWritten).NonPortableCast<byte, char>(); if (span.Length < extraChars) { bytesWritten = 0; return false; } ref char utf16Bytes = ref span.DangerousGetPinnableReference(); var idx = 0; // Write the last group Unsafe.Add(ref utf16Bytes, idx++) = Seperator; idx += FormattingHelpers.WriteDigits(lastGroup, 3, ref utf16Bytes, idx); // Write out the trailing zeros if (precision > 0) { Unsafe.Add(ref utf16Bytes, idx++) = Period; idx += FormattingHelpers.WriteDigits(0, precision, ref utf16Bytes, idx); } bytesWritten += extraChars * sizeof(char); return true; } public static bool TryFormatHexUInt64(ulong value, byte precision, bool useLower, Span<byte> buffer, out int bytesWritten) { const string HexTableLower = "0123456789abcdef"; const string HexTableUpper = "0123456789ABCDEF"; var digits = 1; var v = value; if (v > 0xFFFFFFFF) { digits += 8; v >>= 0x20; } if (v > 0xFFFF) { digits += 4; v >>= 0x10; } if (v > 0xFF) { digits += 2; v >>= 0x8; } if (v > 0xF) digits++; int paddingCount = (precision == ParsedFormat.NoPrecision) ? 0 : precision - digits; if (paddingCount < 0) paddingCount = 0; int charsNeeded = digits + paddingCount; Span<char> span = buffer.NonPortableCast<byte, char>(); if (span.Length < charsNeeded) { bytesWritten = 0; return false; } string hexTable = useLower ? HexTableLower : HexTableUpper; ref char utf16Bytes = ref span.DangerousGetPinnableReference(); int idx = charsNeeded; for (v = value; digits-- > 0; v >>= 4) Unsafe.Add(ref utf16Bytes, --idx) = hexTable[(int)(v & 0xF)]; while (paddingCount-- > 0) Unsafe.Add(ref utf16Bytes, --idx) = '0'; bytesWritten = charsNeeded * sizeof(char); return true; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ApplicationInsights.Management { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.ApplicationInsights; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// ComponentsOperations operations. /// </summary> public partial interface IComponentsOperations { /// <summary> /// Gets a list of all Application Insights components within a /// subscription. /// </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<ApplicationInsightsComponent>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a list of Application Insights components within a resource /// group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </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<ApplicationInsightsComponent>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes an Application Insights component. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='resourceName'> /// The name of the Application Insights component 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.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string resourceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns an Application Insights component. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='resourceName'> /// The name of the Application Insights component 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<ApplicationInsightsComponent>> GetWithHttpMessagesAsync(string resourceGroupName, string resourceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates (or updates) an Application Insights component. Note: You /// cannot specify a different value for InstrumentationKey nor AppId /// in the Put operation. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='resourceName'> /// The name of the Application Insights component resource. /// </param> /// <param name='insightProperties'> /// Properties that need to be specified to create an Application /// Insights component. /// </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<ApplicationInsightsComponent>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string resourceName, ApplicationInsightsComponent insightProperties, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates an existing component's tags. To update other fields use /// the CreateOrUpdate method. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='resourceName'> /// The name of the Application Insights component resource. /// </param> /// <param name='tags'> /// Resource tags /// </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<ApplicationInsightsComponent>> UpdateTagsWithHttpMessagesAsync(string resourceGroupName, string resourceName, IDictionary<string, string> tags = default(IDictionary<string, string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a list of all Application Insights components within a /// subscription. /// </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<ApplicationInsightsComponent>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a list of Application Insights components 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<ApplicationInsightsComponent>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
using Signum.Engine.Basics; using Signum.Entities.DynamicQuery; using System.Collections.ObjectModel; using System.Text.Json; using System.Text.Json.Serialization; namespace Signum.Engine.Json; #pragma warning disable CS8618 // Non-nullable field is uninitialized. public class FilterJsonConverter : JsonConverter<FilterTS> { public override bool CanConvert(Type objectType) { return typeof(FilterTS).IsAssignableFrom(objectType); } public override void Write(Utf8JsonWriter writer, FilterTS value, JsonSerializerOptions options) { if (value is FilterConditionTS fc) JsonSerializer.Serialize(writer, fc, options); else if (value is FilterGroupTS fg) JsonSerializer.Serialize(writer, fg, options); else throw new UnexpectedValueException(value); } public override FilterTS? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { using (var doc = JsonDocument.ParseValue(ref reader)) { var elem = doc.RootElement; if (elem.TryGetProperty("operation", out var oper)) { return new FilterConditionTS { token = elem.GetProperty("token").GetString()!, operation = oper.GetString()!.ToEnum<FilterOperation>(), value = elem.TryGetProperty("value", out var val) ? val.ToObject<object>(options) : null, }; } if (elem.TryGetProperty("groupOperation", out var groupOper)) return new FilterGroupTS { groupOperation = groupOper.GetString()!.ToEnum<FilterGroupOperation>(), token = elem.TryGetProperty("token", out var token)? token.GetString() : null, filters = elem.GetProperty("filters").EnumerateArray().Select(a => a.ToObject<FilterTS>()!).ToList() }; throw new InvalidOperationException("Impossible to determine type of filter"); } } } [JsonConverter(typeof(FilterJsonConverter))] public abstract class FilterTS { public abstract Filter ToFilter(QueryDescription qd, bool canAggregate, JsonSerializerOptions jsonSerializerOptions); public static FilterTS FromFilter(Filter filter) { if (filter is FilterCondition fc) return new FilterConditionTS { token = fc.Token.FullKey(), operation = fc.Operation, value = fc.Value }; if (filter is FilterGroup fg) return new FilterGroupTS { token = fg.Token?.FullKey(), groupOperation = fg.GroupOperation, filters = fg.Filters.Select(f => FromFilter(f)).ToList(), }; throw new UnexpectedValueException(filter); } } public class FilterConditionTS : FilterTS { public string token; public FilterOperation operation; public object? value; public override Filter ToFilter(QueryDescription qd, bool canAggregate, JsonSerializerOptions jsonSerializerOptions) { var options = SubTokensOptions.CanElement | SubTokensOptions.CanAnyAll | (canAggregate ? SubTokensOptions.CanAggregate : 0); var parsedToken = QueryUtils.Parse(token, qd, options); var expectedValueType = operation.IsList() ? typeof(List<>).MakeGenericType(parsedToken.Type.Nullify()) : parsedToken.Type; var val = value is JsonElement jtok ? jtok.ToObject(expectedValueType, jsonSerializerOptions) : value; if (val is DateTime dt) val = dt.FromUserInterface(); else if (val is ObservableCollection<DateTime?> col) val = col.Select(dt => dt?.FromUserInterface()).ToObservableCollection(); return new FilterCondition(parsedToken, operation, val); } public override string ToString() => $"{token} {operation} {value}"; } public class FilterGroupTS : FilterTS { public FilterGroupOperation groupOperation; public string? token; public List<FilterTS> filters; public override Filter ToFilter(QueryDescription qd, bool canAggregate, JsonSerializerOptions jsonSerializerOptions) { var options = SubTokensOptions.CanElement | SubTokensOptions.CanAnyAll | (canAggregate ? SubTokensOptions.CanAggregate : 0); var parsedToken = token == null ? null : QueryUtils.Parse(token, qd, options); var parsedFilters = filters.Select(f => f.ToFilter(qd, canAggregate, jsonSerializerOptions)).ToList(); return new FilterGroup(groupOperation, parsedToken, parsedFilters); } } public class ColumnTS { public string token; public string? displayName; public Column ToColumn(QueryDescription qd, bool canAggregate) { var queryToken = QueryUtils.Parse(token, qd, SubTokensOptions.CanElement | (canAggregate ? SubTokensOptions.CanAggregate : 0)); return new Column(queryToken, displayName ?? queryToken.NiceName()); } public override string ToString() => $"{token} '{displayName}'"; } public class PaginationTS { public PaginationMode mode; public int? elementsPerPage; public int? currentPage; public PaginationTS() { } public PaginationTS(Pagination pagination) { this.mode = pagination.GetMode(); this.elementsPerPage = pagination.GetElementsPerPage(); this.currentPage = (pagination as Pagination.Paginate)?.CurrentPage; } public override string ToString() => $"{mode} {elementsPerPage} {currentPage}"; public Pagination ToPagination() { return mode switch { PaginationMode.All => new Pagination.All(), PaginationMode.Firsts => new Pagination.Firsts(this.elementsPerPage!.Value), PaginationMode.Paginate => new Pagination.Paginate(this.elementsPerPage!.Value, this.currentPage!.Value), _ => throw new InvalidOperationException($"Unexpected {mode}"), }; } } public class SystemTimeTS { public SystemTimeMode mode; public SystemTimeJoinMode? joinMode; public DateTimeOffset? startDate; public DateTimeOffset? endDate; public SystemTimeTS() { } public SystemTimeTS(SystemTime systemTime) { if (systemTime is SystemTime.AsOf asOf) { mode = SystemTimeMode.AsOf; startDate = asOf.DateTime; } else if (systemTime is SystemTime.Between between) { mode = SystemTimeMode.Between; joinMode = ToSystemTimeJoinMode(between.JoinBehaviour); startDate = between.StartDateTime; endDate = between.EndtDateTime; } else if (systemTime is SystemTime.ContainedIn containedIn) { mode = SystemTimeMode.ContainedIn; joinMode = ToSystemTimeJoinMode(containedIn.JoinBehaviour); startDate = containedIn.StartDateTime; endDate = containedIn.EndtDateTime; } else if (systemTime is SystemTime.All all) { mode = SystemTimeMode.All; joinMode = ToSystemTimeJoinMode(all.JoinBehaviour); startDate = null; endDate = null; } else throw new InvalidOperationException("Unexpected System Time"); } public override string ToString() => $"{mode} {startDate} {endDate}"; public SystemTime ToSystemTime() { return mode switch { SystemTimeMode.AsOf => new SystemTime.AsOf(startDate!.Value), SystemTimeMode.Between => new SystemTime.Between(startDate!.Value, endDate!.Value, ToJoinBehaviour(joinMode!.Value)), SystemTimeMode.ContainedIn => new SystemTime.ContainedIn(startDate!.Value, endDate!.Value, ToJoinBehaviour(joinMode!.Value)), SystemTimeMode.All => new SystemTime.All(ToJoinBehaviour(joinMode!.Value)), _ => throw new InvalidOperationException($"Unexpected {mode}"), }; } public static JoinBehaviour ToJoinBehaviour(SystemTimeJoinMode joinMode) { return joinMode switch { SystemTimeJoinMode.Current => JoinBehaviour.Current, SystemTimeJoinMode.FirstCompatible => JoinBehaviour.FirstCompatible, SystemTimeJoinMode.AllCompatible => JoinBehaviour.AllCompatible, _ => throw new UnexpectedValueException(joinMode), }; } public static SystemTimeJoinMode ToSystemTimeJoinMode(JoinBehaviour joinBehaviour) { return joinBehaviour switch { JoinBehaviour.Current => SystemTimeJoinMode.Current, JoinBehaviour.FirstCompatible => SystemTimeJoinMode.FirstCompatible, JoinBehaviour.AllCompatible => SystemTimeJoinMode.AllCompatible, _ => throw new UnexpectedValueException(joinBehaviour), }; } } public class QueryValueRequestTS { public string querykey; public List<FilterTS> filters; public string valueToken; public bool? multipleValues; public SystemTimeTS/*?*/ systemTime; public QueryValueRequest ToQueryValueRequest(JsonSerializerOptions jsonSerializerOptions) { var qn = QueryLogic.ToQueryName(this.querykey); var qd = QueryLogic.Queries.QueryDescription(qn); var value = valueToken.HasText() ? QueryUtils.Parse(valueToken, qd, SubTokensOptions.CanAggregate | SubTokensOptions.CanElement) : null; return new QueryValueRequest { QueryName = qn, MultipleValues = multipleValues ?? false, Filters = this.filters.EmptyIfNull().Select(f => f.ToFilter(qd, canAggregate: false, jsonSerializerOptions)).ToList(), ValueToken = value, SystemTime = this.systemTime?.ToSystemTime(), }; } public override string ToString() => querykey; } public class QueryRequestTS { public string? queryUrl; public string queryKey; public bool groupResults; public List<FilterTS> filters; public List<OrderTS> orders; public List<ColumnTS> columns; public PaginationTS pagination; public SystemTimeTS? systemTime; public static QueryRequestTS FromQueryRequest(QueryRequest qr) { return new QueryRequestTS { queryKey = QueryUtils.GetKey(qr.QueryName), queryUrl = qr.QueryUrl, groupResults = qr.GroupResults, columns = qr.Columns.Select(c => new ColumnTS { token = c.Token.FullKey(), displayName = c.DisplayName }).ToList(), filters = qr.Filters.Select(f => FilterTS.FromFilter(f)).ToList(), orders = qr.Orders.Select(o => new OrderTS { orderType = o.OrderType, token = o.Token.FullKey() }).ToList(), pagination = new PaginationTS(qr.Pagination), systemTime = qr.SystemTime == null ? null : new SystemTimeTS(qr.SystemTime), }; } public QueryRequest ToQueryRequest(JsonSerializerOptions jsonSerializerOptions) { var qn = QueryLogic.ToQueryName(this.queryKey); var qd = QueryLogic.Queries.QueryDescription(qn); return new QueryRequest { QueryUrl = queryUrl, QueryName = qn, GroupResults = groupResults, Filters = this.filters.EmptyIfNull().Select(f => f.ToFilter(qd, canAggregate: groupResults, jsonSerializerOptions)).ToList(), Orders = this.orders.EmptyIfNull().Select(f => f.ToOrder(qd, canAggregate: groupResults)).ToList(), Columns = this.columns.EmptyIfNull().Select(f => f.ToColumn(qd, canAggregate: groupResults)).ToList(), Pagination = this.pagination.ToPagination(), SystemTime = this.systemTime?.ToSystemTime(), }; } public override string ToString() => queryKey; } public class QueryEntitiesRequestTS { public string queryKey; public List<FilterTS> filters; public List<OrderTS> orders; public int? count; public override string ToString() => queryKey; public QueryEntitiesRequest ToQueryEntitiesRequest(JsonSerializerOptions jsonSerializerOptions) { var qn = QueryLogic.ToQueryName(queryKey); var qd = QueryLogic.Queries.QueryDescription(qn); return new QueryEntitiesRequest { QueryName = qn, Count = count, Filters = filters.EmptyIfNull().Select(f => f.ToFilter(qd, canAggregate: false, jsonSerializerOptions)).ToList(), Orders = orders.EmptyIfNull().Select(f => f.ToOrder(qd, canAggregate: false)).ToList(), }; } } public class OrderTS { public string token; public OrderType orderType; public Order ToOrder(QueryDescription qd, bool canAggregate) { return new Order(QueryUtils.Parse(this.token, qd, SubTokensOptions.CanElement | (canAggregate ? SubTokensOptions.CanAggregate : 0)), orderType); } public override string ToString() => $"{token} {orderType}"; }
// Copyright (c) 2012, Event Store LLP // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the Event Store LLP nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; using EventStore.BufferManagement; using EventStore.Common.Log; using EventStore.Common.Utils; namespace EventStore.Transport.Tcp { public class TcpConnectionLockless : TcpConnectionBase, ITcpConnection { internal const int MaxSendPacketSize = 64 * 1024; internal static readonly BufferManager BufferManager = new BufferManager(TcpConfiguration.BufferChunksCount, TcpConfiguration.SocketBufferSize); private static readonly ILogger Log = LogManager.GetLoggerFor<TcpConnectionLockless>(); private static readonly SocketArgsPool SocketArgsPool = new SocketArgsPool("TcpConnection.SocketArgsPool", TcpConfiguration.SendReceivePoolSize, () => new SocketAsyncEventArgs()); public static ITcpConnection CreateConnectingTcpConnection(Guid connectionId, IPEndPoint remoteEndPoint, TcpClientConnector connector, TimeSpan connectionTimeout, Action<ITcpConnection> onConnectionEstablished, Action<ITcpConnection, SocketError> onConnectionFailed, bool verbose) { var connection = new TcpConnectionLockless(connectionId, remoteEndPoint, verbose); // ReSharper disable ImplicitlyCapturedClosure connector.InitConnect(remoteEndPoint, (_, socket) => { if (connection.InitSocket(socket)) { if (onConnectionEstablished != null) onConnectionEstablished(connection); connection.StartReceive(); connection.TrySend(); } }, (_, socketError) => { if (onConnectionFailed != null) onConnectionFailed(connection, socketError); }, connection, connectionTimeout); // ReSharper restore ImplicitlyCapturedClosure return connection; } public static ITcpConnection CreateAcceptedTcpConnection(Guid connectionId, IPEndPoint remoteEndPoint, Socket socket, bool verbose) { var connection = new TcpConnectionLockless(connectionId, remoteEndPoint, verbose); if (connection.InitSocket(socket)) { connection.StartReceive(); connection.TrySend(); } return connection; } public event Action<ITcpConnection, SocketError> ConnectionClosed; public Guid ConnectionId { get { return _connectionId; } } public int SendQueueSize { get { return _sendQueue.Count; } } private readonly Guid _connectionId; private readonly bool _verbose; private Socket _socket; private SocketAsyncEventArgs _receiveSocketArgs; private SocketAsyncEventArgs _sendSocketArgs; private readonly Common.Concurrent.ConcurrentQueue<ArraySegment<byte>> _sendQueue = new Common.Concurrent.ConcurrentQueue<ArraySegment<byte>>(); private readonly Common.Concurrent.ConcurrentQueue<ReceivedData> _receiveQueue = new Common.Concurrent.ConcurrentQueue<ReceivedData>(); private readonly MemoryStream _memoryStream = new MemoryStream(); private int _sending; private int _receiving; private int _closed; private Action<ITcpConnection, IEnumerable<ArraySegment<byte>>> _receiveCallback; private TcpConnectionLockless(Guid connectionId, IPEndPoint remoteEndPoint, bool verbose): base(remoteEndPoint) { Ensure.NotEmptyGuid(connectionId, "connectionId"); _connectionId = connectionId; _verbose = verbose; } private bool InitSocket(Socket socket) { InitConnectionBase(socket); try { socket.NoDelay = true; } catch (ObjectDisposedException) { CloseInternal(SocketError.Shutdown, "Socket disposed."); return false; } var receiveSocketArgs = SocketArgsPool.Get(); receiveSocketArgs.AcceptSocket = socket; receiveSocketArgs.Completed += OnReceiveAsyncCompleted; var sendSocketArgs = SocketArgsPool.Get(); sendSocketArgs.AcceptSocket = socket; sendSocketArgs.Completed += OnSendAsyncCompleted; Interlocked.Exchange(ref _socket, socket); Interlocked.Exchange(ref _receiveSocketArgs, receiveSocketArgs); Interlocked.Exchange(ref _sendSocketArgs, sendSocketArgs); if (Interlocked.CompareExchange(ref _closed, 0, 0) != 0) { CloseSocket(); ReturnReceivingSocketArgs(); if (Interlocked.CompareExchange(ref _sending, 1, 0) == 0) ReturnSendingSocketArgs(); return false; } return true; } public void EnqueueSend(IEnumerable<ArraySegment<byte>> data) { using (var memStream = new MemoryStream()) { int bytes = 0; foreach (var segment in data) { memStream.Write(segment.Array, segment.Offset, segment.Count); bytes += segment.Count; } _sendQueue.Enqueue(new ArraySegment<byte>(memStream.GetBuffer(), 0, (int)memStream.Length)); NotifySendScheduled(bytes); } TrySend(); } private void TrySend() { while (_sendQueue.Count > 0 && Interlocked.CompareExchange(ref _sending, 1, 0) == 0) { if (_sendQueue.Count > 0 && _sendSocketArgs != null) { //if (TcpConnectionMonitor.Default.IsSendBlocked()) return; _memoryStream.SetLength(0); ArraySegment<byte> sendPiece; while (_sendQueue.TryDequeue(out sendPiece)) { _memoryStream.Write(sendPiece.Array, sendPiece.Offset, sendPiece.Count); if (_memoryStream.Length >= MaxSendPacketSize) break; } _sendSocketArgs.SetBuffer(_memoryStream.GetBuffer(), 0, (int)_memoryStream.Length); try { NotifySendStarting(_sendSocketArgs.Count); var firedAsync = _sendSocketArgs.AcceptSocket.SendAsync(_sendSocketArgs); if (!firedAsync) ProcessSend(_sendSocketArgs); } catch (ObjectDisposedException) { ReturnSendingSocketArgs(); } return; } Interlocked.Exchange(ref _sending, 0); if (Interlocked.CompareExchange(ref _closed, 0, 0) != 0) { if (Interlocked.CompareExchange(ref _sending, 1, 0) == 0) ReturnSendingSocketArgs(); return; } } } private void OnSendAsyncCompleted(object sender, SocketAsyncEventArgs e) { // No other code should go here. All handling is the same for sync/async completion. ProcessSend(e); } private void ProcessSend(SocketAsyncEventArgs socketArgs) { if (socketArgs.SocketError != SocketError.Success) { NotifySendCompleted(0); ReturnSendingSocketArgs(); CloseInternal(socketArgs.SocketError, "Socket send error."); } else { NotifySendCompleted(socketArgs.Count); Interlocked.Exchange(ref _sending, 0); if (Interlocked.CompareExchange(ref _closed, 0, 0) != 0) { if (Interlocked.CompareExchange(ref _sending, 1, 0) == 0) ReturnSendingSocketArgs(); return; } TrySend(); } } public void ReceiveAsync(Action<ITcpConnection, IEnumerable<ArraySegment<byte>>> callback) { if (callback == null) throw new ArgumentNullException("callback"); if (Interlocked.Exchange(ref _receiveCallback, callback) != null) throw new InvalidOperationException("ReceiveAsync called again while previous call wasn't fulfilled"); TryDequeueReceivedData(); } private void StartReceive() { var buffer = BufferManager.CheckOut(); if (buffer.Array == null || buffer.Count == 0 || buffer.Array.Length < buffer.Offset + buffer.Count) throw new Exception("Invalid buffer allocated"); try { NotifyReceiveStarting(); _receiveSocketArgs.SetBuffer(buffer.Array, buffer.Offset, buffer.Count); var firedAsync = _receiveSocketArgs.AcceptSocket.ReceiveAsync(_receiveSocketArgs); if (!firedAsync) ProcessReceive(_receiveSocketArgs); } catch (ObjectDisposedException) { ReturnReceivingSocketArgs(); } } private void OnReceiveAsyncCompleted(object sender, SocketAsyncEventArgs e) { // No other code should go here. All handling is the same on async and sync completion. ProcessReceive(e); } private void ProcessReceive(SocketAsyncEventArgs socketArgs) { // socket closed normally or some error occurred if (socketArgs.BytesTransferred == 0 || socketArgs.SocketError != SocketError.Success) { NotifyReceiveCompleted(0); ReturnReceivingSocketArgs(); CloseInternal(socketArgs.SocketError, socketArgs.SocketError != SocketError.Success ? "Socket receive error" : "Socket closed"); return; } NotifyReceiveCompleted(socketArgs.BytesTransferred); var buf = new ArraySegment<byte>(socketArgs.Buffer, socketArgs.Offset, socketArgs.Count); _receiveQueue.Enqueue(new ReceivedData(buf, socketArgs.BytesTransferred)); socketArgs.SetBuffer(null, 0, 0); StartReceive(); TryDequeueReceivedData(); } private void TryDequeueReceivedData() { while (_receiveQueue.Count > 0 && Interlocked.CompareExchange(ref _receiving, 1, 0) == 0) { if (_receiveQueue.Count > 0 && _receiveCallback != null) { var callback = Interlocked.Exchange(ref _receiveCallback, null); if (callback == null) { Log.Fatal("Some threading issue in TryDequeueReceivedData! Callback is null!"); throw new Exception("Some threading issue in TryDequeueReceivedData! Callback is null!"); } var res = new List<ReceivedData>(_receiveQueue.Count); ReceivedData piece; while (_receiveQueue.TryDequeue(out piece)) { res.Add(piece); } var data = new ArraySegment<byte>[res.Count]; int bytes = 0; for (int i = 0; i < data.Length; ++i) { var d = res[i]; bytes += d.DataLen; data[i] = new ArraySegment<byte>(d.Buf.Array, d.Buf.Offset, d.DataLen); } callback(this, data); for (int i = 0, n = res.Count; i < n; ++i) { TcpConnection.BufferManager.CheckIn(res[i].Buf); // dispose buffers } NotifyReceiveDispatched(bytes); } Interlocked.Exchange(ref _receiving, 0); } } public void Close(string reason) { CloseInternal(SocketError.Success, reason ?? "Normal socket close."); // normal socket closing } private void CloseInternal(SocketError socketError, string reason) { if (Interlocked.CompareExchange(ref _closed, 1, 0) != 0) return; NotifyClosed(); if (_verbose) { Log.Info("ES {12} closed [{0:HH:mm:ss.fff}: N{1}, L{2}, {3:B}]:\nReceived bytes: {4}, Sent bytes: {5}\n" + "Send calls: {6}, callbacks: {7}\nReceive calls: {8}, callbacks: {9}\nClose reason: [{10}] {11}\n", DateTime.UtcNow, RemoteEndPoint, LocalEndPoint, _connectionId, TotalBytesReceived, TotalBytesSent, SendCalls, SendCallbacks, ReceiveCalls, ReceiveCallbacks, socketError, reason, GetType().Name); } CloseSocket(); if (Interlocked.CompareExchange(ref _sending, 1, 0) == 0) ReturnSendingSocketArgs(); var handler = ConnectionClosed; if (handler != null) handler(this, socketError); } private void CloseSocket() { var socket = Interlocked.Exchange(ref _socket, null); if (socket != null) { Helper.EatException(() => socket.Shutdown(SocketShutdown.Both)); Helper.EatException(() => socket.Close(TcpConfiguration.SocketCloseTimeoutMs)); } } private void ReturnSendingSocketArgs() { var socketArgs = Interlocked.Exchange(ref _sendSocketArgs, null); if (socketArgs != null) { socketArgs.Completed -= OnSendAsyncCompleted; socketArgs.AcceptSocket = null; if (socketArgs.Buffer != null) socketArgs.SetBuffer(null, 0, 0); SocketArgsPool.Return(socketArgs); } } private void ReturnReceivingSocketArgs() { var socketArgs = Interlocked.Exchange(ref _receiveSocketArgs, null); if (socketArgs != null) { socketArgs.Completed -= OnReceiveAsyncCompleted; socketArgs.AcceptSocket = null; if (socketArgs.Buffer != null) { BufferManager.CheckIn(new ArraySegment<byte>(socketArgs.Buffer, socketArgs.Offset, socketArgs.Count)); socketArgs.SetBuffer(null, 0, 0); } SocketArgsPool.Return(socketArgs); } } public override string ToString() { return RemoteEndPoint.ToString(); } private struct ReceivedData { public readonly ArraySegment<byte> Buf; public readonly int DataLen; public ReceivedData(ArraySegment<byte> buf, int dataLen) { Buf = buf; DataLen = dataLen; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace SimpleDispatcher.Present.API.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); } } } }
#region File Description //----------------------------------------------------------------------------- // Ionixx Games 3/9/2009 // Copyright (C) Bryan Phelps. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; #endregion namespace SkinnedModelInstancing { /// <summary> /// This is again a wrapper around a ModelMesh. This is the Instanced equivalent of a ModelMesh /// Encapsulates the drawing behavior of instanced model /// This is where the instancing magic happens /// This is set up for vfetch instancing, but nothing is stopping you from doing shader instancing or hardware instancing /// As I mentioned in the doc, the only reason I didn't do this was because I don't have a graphics card that supports vertex texture fetch :-( /// </summary> public class InstancedSkinnedModelMesh { // Max number of instances allowed based on the number of shader parameters // If you change the shader, make sure to change this value! const int MaxInstances = 47; #region Fields private ModelMesh mesh; private int vertexCount; private int indexCount; private int maxInstances; private GraphicsDevice graphicsDevice; private Texture2D animationTexture; private IndexBuffer indexBuffer; // Temporary arrays used during rendering private Matrix[] tempTransforms; private int[] tempAnimations; #endregion /// <summary> /// Constructor /// </summary> /// <param name="modelMesh"></param> /// <param name="animationTexture"></param> /// <param name="device"></param> public InstancedSkinnedModelMesh(ModelMesh modelMesh, Texture2D animationTexture, GraphicsDevice device) { this.graphicsDevice = device; this.mesh = modelMesh; // We are assuming all the mesh parts have the same vertex stride this.vertexCount = this.mesh.VertexBuffer.SizeInBytes / mesh.MeshParts[0].VertexStride; // Calculate the actual number of instances // We're using ushort for our instances, so we can only reference up to ushort.MaxValue this.maxInstances = Math.Min(ushort.MaxValue / this.vertexCount, MaxInstances); // Hold on to a handle to the animation texture this.animationTexture = animationTexture; // Create our temporary arrays based on the actual number of instances we can handle this.tempTransforms = new Matrix[this.maxInstances]; this.tempAnimations = new int[this.maxInstances]; // Replicate index data, as required for vfetch instancing this.ReplicateIndexData(this.mesh); } /// <summary> /// Draws the model mesh based on the specified input transforms and animations /// Any number of transforms and animations can be entered, but the arrays must be the same size /// </summary> /// <param name="transforms"></param> /// <param name="animations"></param> /// <param name="view"></param> /// <param name="projection"></param> public void Draw(Matrix [] transforms, int [] animations, Matrix view, Matrix projection) { if (transforms.Length != animations.Length) throw new ArgumentException("Transforms array and animation frames array must have same length."); // Set the graphics device to use our vertex data this.graphicsDevice.Indices = this.indexBuffer ; // Draw each meshPart for(int i = 0; i < this.mesh.MeshParts.Count; i++) { ModelMeshPart part = this.mesh.MeshParts[i]; this.graphicsDevice.VertexDeclaration = part.VertexDeclaration; this.graphicsDevice.Vertices[0].SetSource(this.mesh.VertexBuffer, part.StreamOffset, part.VertexStride); Effect effect = part.Effect; // Pass camera matrices through to the effect. effect.Parameters["View"].SetValue(view); effect.Parameters["Projection"].SetValue(projection); // Set the vertex count (used by the VFetch instancing technique). // And also set all the parameters the shader needs to get the animation data effect.Parameters["VertexCount"].SetValue(this.vertexCount); effect.Parameters["AnimationTexture"].SetValue(this.animationTexture); // Bone delta and row delta are basically pixel width and pixel height, respectively effect.Parameters["BoneDelta"].SetValue(1f / this.animationTexture.Width); effect.Parameters["RowDelta"].SetValue(1f / this.animationTexture.Height); // Do the actual drawing effect.Begin(); foreach (EffectPass pass in effect.CurrentTechnique.Passes) { pass.Begin(); this.DrawPart(transforms, animations, effect, part); pass.End(); } effect.End(); } } /// <summary> /// DrawPart draws the actual ModelMeshPart /// </summary> /// <param name="transforms"></param> /// <param name="animations"></param> /// <param name="effect"></param> /// <param name="part"></param> private void DrawPart(Matrix [] transforms, int [] animations, Effect effect, ModelMeshPart part) { for (int i = 0; i < transforms.Length; i += maxInstances) { // How many instances can we fit into this batch? int instanceCount = transforms.Length- i; if (instanceCount > maxInstances) instanceCount = maxInstances; // Copy transform and animation data Array.Copy(transforms, i, tempTransforms, 0, instanceCount); Array.Copy(animations, i, tempAnimations, 0, instanceCount); // Send the transform and animation data to the shader effect.Parameters["InstanceTransforms"].SetValue(tempTransforms); effect.Parameters["InstanceAnimations"].SetValue(tempAnimations); effect.CommitChanges(); // Draw maxInstances copies of our geometry in a single batch. this.graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, part.BaseVertex, 0, part.NumVertices * instanceCount, part.StartIndex, part.PrimitiveCount * instanceCount); } } /// <summary> /// Replicate the index data - we need to have indices for each of our instances, based on vfetch instancing /// This is sort of similar to what happens in the InstancingSample, but modified to account for ModelMeshParts /// </summary> /// <param name="mesh"></param> private void ReplicateIndexData(ModelMesh mesh) { List<ushort> indices = new List<ushort>(); int size = mesh.IndexBuffer.IndexElementSize == IndexElementSize.SixteenBits ? 2 : 4; this.indexCount = mesh.IndexBuffer.SizeInBytes / size; ushort[] oldIndices = new ushort[indexCount]; mesh.IndexBuffer.GetData(oldIndices); mesh.IndexBuffer.Dispose(); // We have to replicate index data for each part // Unfortunately, since we have different meshParts we have to do this // If you look at the InstancingSample, they defined their own Model class. // This wasn't a possibility this time because I wanted to leverage the capabilities of the ModelProcessor // Therefore, we have to add this extra logic to deal with ModelMeshParts // Note that if you just replicate the whole index buffer in a pass, the instancing won't work, because // you have to render the instances as contiguous indices // So if your buffer looks like: <indices for meshPart1> <indices for meshPart2> etc.., we need to replicate it like: // <repeat indices for meshPart1 N times> <repeat indices for meshPart2 N times> where N is the number of instances foreach (ModelMeshPart part in mesh.MeshParts) { this.ReplicateIndexData(part, indices, oldIndices); } // Create a new index buffer, and set the replicated data into it. this.indexBuffer = new IndexBuffer(this.graphicsDevice, sizeof(ushort) * indices.Count, BufferUsage.None, IndexElementSize.SixteenBits); this.indexBuffer.SetData(indices.ToArray()); } /// <summary> /// Do the actual replication of the indices, for each ModelMeshPart /// </summary> /// <param name="part"></param> /// <param name="indices"></param> /// <param name="oldIndices"></param> private void ReplicateIndexData(ModelMeshPart part, List<ushort> indices, ushort [] oldIndices) { // Replicate one copy of the original index buffer for each instance. for (int instanceIndex = 0; instanceIndex < maxInstances; instanceIndex++) { int instanceOffset = instanceIndex * vertexCount; // Basically, keep adding the indices. We have to replicate this ModelMeshPart index for each instance we can have // Note that each time we are incrementing by instanceOffset. This is so in the vertex shader, when we divide // by the vertex count, we know exactly which index we are at. for (int i = part.StartIndex; i < part.PrimitiveCount * 3; i++) { indices.Add((ushort)(oldIndices[i] + instanceOffset)); } } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; using osu.Framework.Bindables; using osu.Framework.Configuration; using osu.Framework.Extensions; using osu.Framework.Input.StateChanges; using osuTK; using osuTK.Input; using osuTK.Platform; namespace osu.Framework.Platform { /// <summary> /// Implementation of <see cref="IWindow"/> that provides bindables and /// delegates responsibility to window and graphics backends. /// </summary> public class Window : IWindow { private readonly IWindowBackend windowBackend; private readonly IGraphicsBackend graphicsBackend; #region Properties /// <summary> /// Gets and sets the window title. /// </summary> public string Title { get => windowBackend.Title; set => windowBackend.Title = value; } /// <summary> /// Enables or disables vertical sync. /// </summary> public bool VerticalSync { get => graphicsBackend.VerticalSync; set => graphicsBackend.VerticalSync = value; } /// <summary> /// Returns true if window has been created. /// Returns false if the window has not yet been created, or has been closed. /// </summary> public bool Exists => windowBackend.Exists; /// <summary> /// Returns the scale of window's drawable area. /// In high-dpi environments this will be greater than one. /// </summary> public float Scale => windowBackend.Scale; public Display PrimaryDisplay => windowBackend.PrimaryDisplay; public DisplayMode CurrentDisplayMode => windowBackend.CurrentDisplayMode; public IEnumerable<Display> Displays => windowBackend.Displays; public WindowMode DefaultWindowMode => WindowMode.Windowed; #endregion #region Mutable Bindables /// <summary> /// Provides a bindable that controls the window's position. /// </summary> public Bindable<Point> Position { get; } = new Bindable<Point>(); /// <summary> /// Provides a bindable that controls the window's unscaled internal size. /// </summary> public Bindable<Size> Size { get; } = new BindableSize(); /// <summary> /// Provides a bindable that controls the window's <see cref="WindowState"/>. /// </summary> public Bindable<WindowState> WindowState { get; } = new Bindable<WindowState>(); /// <summary> /// Provides a bindable that controls the window's <see cref="CursorState"/>. /// </summary> public Bindable<CursorState> CursorState { get; } = new Bindable<CursorState>(); /// <summary> /// Provides a bindable that controls the window's visibility. /// </summary> public Bindable<bool> Visible { get; } = new BindableBool(); public Bindable<Display> CurrentDisplay { get; } = new Bindable<Display>(); #endregion #region Immutable Bindables private readonly BindableBool isActive = new BindableBool(true); public IBindable<bool> IsActive => isActive; private readonly BindableBool focused = new BindableBool(); /// <summary> /// Provides a read-only bindable that monitors the window's focused state. /// </summary> public IBindable<bool> Focused => focused; private readonly BindableBool cursorInWindow = new BindableBool(); /// <summary> /// Provides a read-only bindable that monitors the whether the cursor is in the window. /// </summary> public IBindable<bool> CursorInWindow => cursorInWindow; public IBindableList<WindowMode> SupportedWindowModes { get; } = new BindableList<WindowMode>(Enum.GetValues(typeof(WindowMode)).OfType<WindowMode>()); public BindableSafeArea SafeAreaPadding { get; } = new BindableSafeArea(); #endregion #region Events /// <summary> /// Invoked once every window event loop. /// </summary> public event Action Update; /// <summary> /// Invoked after the window has resized. /// </summary> public event Action Resized; /// <summary> /// Invoked when the user attempts to close the window. /// </summary> public event Func<bool> ExitRequested; /// <summary> /// Invoked when the window is about to close. /// </summary> public event Action Exited; /// <summary> /// Invoked when the window loses focus. /// </summary> public event Action FocusLost; /// <summary> /// Invoked when the window gains focus. /// </summary> public event Action FocusGained; /// <summary> /// Invoked when the window becomes visible. /// </summary> public event Action Shown; /// <summary> /// Invoked when the window becomes invisible. /// </summary> public event Action Hidden; /// <summary> /// Invoked when the mouse cursor enters the window. /// </summary> public event Action MouseEntered; /// <summary> /// Invoked when the mouse cursor leaves the window. /// </summary> public event Action MouseLeft; /// <summary> /// Invoked when the window moves. /// </summary> public event Action<Point> Moved; /// <summary> /// Invoked when the user scrolls the mouse wheel over the window. /// </summary> public event Action<MouseScrollRelativeInput> MouseWheel; /// <summary> /// Invoked when the user moves the mouse cursor within the window. /// </summary> public event Action<MousePositionAbsoluteInput> MouseMove; /// <summary> /// Invoked when the user presses a mouse button. /// </summary> public event Action<MouseButtonInput> MouseDown; /// <summary> /// Invoked when the user releases a mouse button. /// </summary> public event Action<MouseButtonInput> MouseUp; /// <summary> /// Invoked when the user presses a key. /// </summary> public event Action<KeyboardKeyInput> KeyDown; /// <summary> /// Invoked when the user releases a key. /// </summary> public event Action<KeyboardKeyInput> KeyUp; /// <summary> /// Invoked when the user types a character. /// </summary> public event Action<char> KeyTyped; /// <summary> /// Invoked when the user drops a file into the window. /// </summary> public event Action<string> DragDrop; #endregion #region Event Invocation protected virtual void OnUpdate() => Update?.Invoke(); protected virtual void OnResized() => Resized?.Invoke(); protected virtual bool OnExitRequested() => ExitRequested?.Invoke() ?? false; protected virtual void OnExited() => Exited?.Invoke(); protected virtual void OnFocusLost() => FocusLost?.Invoke(); protected virtual void OnFocusGained() => FocusGained?.Invoke(); protected virtual void OnShown() => Shown?.Invoke(); protected virtual void OnHidden() => Hidden?.Invoke(); protected virtual void OnMouseEntered() => MouseEntered?.Invoke(); protected virtual void OnMouseLeft() => MouseLeft?.Invoke(); protected virtual void OnMoved(Point point) => Moved?.Invoke(point); protected virtual void OnMouseWheel(MouseScrollRelativeInput evt) => MouseWheel?.Invoke(evt); protected virtual void OnMouseMove(MousePositionAbsoluteInput evt) => MouseMove?.Invoke(evt); protected virtual void OnMouseDown(MouseButtonInput evt) => MouseDown?.Invoke(evt); protected virtual void OnMouseUp(MouseButtonInput evt) => MouseUp?.Invoke(evt); protected virtual void OnKeyDown(KeyboardKeyInput evt) => KeyDown?.Invoke(evt); protected virtual void OnKeyUp(KeyboardKeyInput evt) => KeyUp?.Invoke(evt); protected virtual void OnKeyTyped(char c) => KeyTyped?.Invoke(c); protected virtual void OnDragDrop(string file) => DragDrop?.Invoke(file); #endregion #region Constructors /// <summary> /// Creates a new <see cref="Window"/> using the specified window and graphics backends. /// </summary> /// <param name="windowBackend">The <see cref="IWindowBackend"/> to use.</param> /// <param name="graphicsBackend">The <see cref="IGraphicsBackend"/> to use.</param> public Window(IWindowBackend windowBackend, IGraphicsBackend graphicsBackend) { this.windowBackend = windowBackend; this.graphicsBackend = graphicsBackend; Position.ValueChanged += position_ValueChanged; Size.ValueChanged += size_ValueChanged; CursorState.ValueChanged += evt => { this.windowBackend.CursorVisible = !evt.NewValue.HasFlag(Platform.CursorState.Hidden); this.windowBackend.CursorConfined = evt.NewValue.HasFlag(Platform.CursorState.Confined); }; WindowState.ValueChanged += evt => this.windowBackend.WindowState = evt.NewValue; Visible.ValueChanged += visible_ValueChanged; focused.ValueChanged += evt => { if (evt.NewValue) OnFocusGained(); else OnFocusLost(); }; cursorInWindow.ValueChanged += evt => { if (evt.NewValue) OnMouseEntered(); else OnMouseLeft(); }; windowBackend.Create(); windowBackend.Resized += windowBackend_Resized; windowBackend.WindowStateChanged += () => WindowState.Value = windowBackend.WindowState; windowBackend.Moved += windowBackend_Moved; windowBackend.Hidden += () => Visible.Value = false; windowBackend.Shown += () => Visible.Value = true; windowBackend.FocusGained += () => focused.Value = true; windowBackend.FocusLost += () => focused.Value = false; windowBackend.MouseEntered += () => cursorInWindow.Value = true; windowBackend.MouseLeft += () => cursorInWindow.Value = false; windowBackend.Closed += OnExited; windowBackend.CloseRequested += OnExitRequested; windowBackend.Update += OnUpdate; windowBackend.KeyDown += OnKeyDown; windowBackend.KeyUp += OnKeyUp; windowBackend.KeyTyped += OnKeyTyped; windowBackend.MouseDown += OnMouseDown; windowBackend.MouseUp += OnMouseUp; windowBackend.MouseMove += OnMouseMove; windowBackend.MouseWheel += OnMouseWheel; windowBackend.DragDrop += OnDragDrop; windowBackend.DisplayChanged += d => CurrentDisplay.Value = d; graphicsBackend.Initialise(windowBackend); CurrentDisplay.Value = windowBackend.CurrentDisplay; CurrentDisplay.ValueChanged += evt => windowBackend.CurrentDisplay = evt.NewValue; } #endregion #region Methods /// <summary> /// Starts the window's run loop. /// </summary> public void Run() => windowBackend.Run(); /// <summary> /// Attempts to close the window. /// </summary> public void Close() => windowBackend.Close(); /// <summary> /// Requests that the graphics backend perform a buffer swap. /// </summary> public void SwapBuffers() => graphicsBackend.SwapBuffers(); /// <summary> /// Requests that the graphics backend become the current context. /// May be unrequired for some backends. /// </summary> public void MakeCurrent() => graphicsBackend.MakeCurrent(); public void CycleMode() { // TODO: CycleMode } public void SetupWindow(FrameworkConfigManager config) { // TODO: SetupWindow } #endregion #region Bindable Handling private void visible_ValueChanged(ValueChangedEvent<bool> evt) { windowBackend.Visible = evt.NewValue; if (evt.NewValue) OnShown(); else OnHidden(); } private bool boundsChanging; private void windowBackend_Resized() { if (!boundsChanging) { boundsChanging = true; Position.Value = windowBackend.Position; Size.Value = windowBackend.Size; boundsChanging = false; } OnResized(); } private void windowBackend_Moved(Point point) { if (!boundsChanging) { boundsChanging = true; Position.Value = point; boundsChanging = false; } OnMoved(point); } private void position_ValueChanged(ValueChangedEvent<Point> evt) { if (boundsChanging) return; boundsChanging = true; windowBackend.Position = evt.NewValue; boundsChanging = false; } private void size_ValueChanged(ValueChangedEvent<Size> evt) { if (boundsChanging) return; boundsChanging = true; windowBackend.Size = evt.NewValue; boundsChanging = false; } #endregion #region Deprecated IGameWindow public IWindowInfo WindowInfo => throw new NotImplementedException(); osuTK.WindowState INativeWindow.WindowState { get => WindowState.Value.ToOsuTK(); set => WindowState.Value = value.ToFramework(); } public WindowBorder WindowBorder { get; set; } public Rectangle Bounds { get => new Rectangle(X, Y, Width, Height); set { Position.Value = value.Location; Size.Value = value.Size; } } public Point Location { get => Position.Value; set => Position.Value = value; } Size INativeWindow.Size { get => Size.Value; set => Size.Value = value; } public int X { get => Position.Value.X; set => Position.Value = new Point(value, Position.Value.Y); } public int Y { get => Position.Value.Y; set => Position.Value = new Point(Position.Value.X, value); } public int Width { get => Size.Value.Width; set => Size.Value = new Size(value, Size.Value.Height); } public int Height { get => Size.Value.Height; set => Size.Value = new Size(Size.Value.Width, value); } public Rectangle ClientRectangle { get => new Rectangle(Position.Value.X, Position.Value.Y, (int)(Size.Value.Width * Scale), (int)(Size.Value.Height * Scale)); set { Position.Value = value.Location; Size.Value = new Size((int)(value.Width / Scale), (int)(value.Height / Scale)); } } Size INativeWindow.ClientSize { get => new Size((int)(Size.Value.Width * Scale), (int)(Size.Value.Height * Scale)); set => Size.Value = new Size((int)(value.Width / Scale), (int)(value.Height / Scale)); } public MouseCursor Cursor { get; set; } public bool CursorVisible { get => windowBackend.CursorVisible; set => windowBackend.CursorVisible = value; } public bool CursorGrabbed { get => windowBackend.CursorConfined; set => windowBackend.CursorConfined = value; } #pragma warning disable 0067 public event EventHandler<EventArgs> Move; public event EventHandler<EventArgs> Resize; public event EventHandler<CancelEventArgs> Closing; event EventHandler<EventArgs> INativeWindow.Closed { add => throw new NotImplementedException(); remove => throw new NotImplementedException(); } public event EventHandler<EventArgs> Disposed; public event EventHandler<EventArgs> IconChanged; public event EventHandler<EventArgs> TitleChanged; public event EventHandler<EventArgs> VisibleChanged; public event EventHandler<EventArgs> FocusedChanged; public event EventHandler<EventArgs> WindowBorderChanged; public event EventHandler<EventArgs> WindowStateChanged; event EventHandler<KeyboardKeyEventArgs> INativeWindow.KeyDown { add => throw new NotImplementedException(); remove => throw new NotImplementedException(); } public event EventHandler<KeyPressEventArgs> KeyPress; event EventHandler<KeyboardKeyEventArgs> INativeWindow.KeyUp { add => throw new NotImplementedException(); remove => throw new NotImplementedException(); } public event EventHandler<EventArgs> MouseLeave; public event EventHandler<EventArgs> MouseEnter; event EventHandler<MouseButtonEventArgs> INativeWindow.MouseDown { add => throw new NotImplementedException(); remove => throw new NotImplementedException(); } event EventHandler<MouseButtonEventArgs> INativeWindow.MouseUp { add => throw new NotImplementedException(); remove => throw new NotImplementedException(); } event EventHandler<MouseMoveEventArgs> INativeWindow.MouseMove { add => throw new NotImplementedException(); remove => throw new NotImplementedException(); } event EventHandler<MouseWheelEventArgs> INativeWindow.MouseWheel { add => throw new NotImplementedException(); remove => throw new NotImplementedException(); } public event EventHandler<FileDropEventArgs> FileDrop; public event EventHandler<EventArgs> Load; public event EventHandler<EventArgs> Unload; public event EventHandler<FrameEventArgs> UpdateFrame; public event EventHandler<FrameEventArgs> RenderFrame; #pragma warning restore 0067 bool IWindow.CursorInWindow => CursorInWindow.Value; CursorState IWindow.CursorState { get => CursorState.Value; set => CursorState.Value = value; } bool INativeWindow.Focused => Focused.Value; bool INativeWindow.Visible { get => Visible.Value; set => Visible.Value = value; } bool INativeWindow.Exists => Exists; public void Run(double updateRate) => Run(); public void ProcessEvents() { } public Point PointToClient(Point point) => point; public Point PointToScreen(Point point) => point; public Icon Icon { get; set; } public void Dispose() { } #endregion } }