context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// This code was written for the OpenTK library and has been released // to the Public Domain. // It is provided "as is" without express or implied warranty of any kind. using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Drawing; using System.Threading; using OpenTK; using OpenTK.Graphics.OpenGL; using OpenTK.Input; namespace Examples.Tests { [Example("GameWindow States", ExampleCategory.OpenTK, "GameWindow", 4, Documentation = "GameWindowStates")] public class GameWindowStates : GameWindow { static readonly Font TextFont = new Font(FontFamily.GenericSansSerif, 11); Bitmap TextBitmap = new Bitmap(512, 512); int texture; bool mouse_in_window = false; bool viewport_changed = true; bool refresh_text = true; MouseState mouse, mouse_old; KeyboardState keyboard, keyboard_old; public GameWindowStates() : base(800, 600) { VSync = VSyncMode.On; Keyboard.KeyRepeat = true; Keyboard.KeyDown += KeyDownHandler; MouseEnter += delegate { mouse_in_window = true; }; MouseLeave += delegate { mouse_in_window = false; }; Move += delegate { refresh_text = true; }; Resize += delegate { refresh_text = true; }; WindowBorderChanged += delegate { refresh_text = true; }; WindowStateChanged += delegate { refresh_text = true; }; FocusedChanged += delegate { refresh_text = true; }; Mouse.Move += MouseMoveHandler; Mouse.ButtonDown += MouseButtonHandler; Mouse.ButtonUp += MouseButtonHandler; } void KeyDownHandler(object sender, KeyboardKeyEventArgs e) { switch (e.Key) { case OpenTK.Input.Key.Escape: if (!CursorVisible) CursorVisible = true; else Exit(); break; case Key.Number1: WindowState = WindowState.Normal; break; case Key.Number2: WindowState = WindowState.Maximized; break; case Key.Number3: WindowState = WindowState.Fullscreen; break; case Key.Number4: WindowState = WindowState.Minimized; break; case Key.Number5: WindowBorder = WindowBorder.Resizable; break; case Key.Number6: WindowBorder = WindowBorder.Fixed; break; case Key.Number7: WindowBorder = WindowBorder.Hidden; break; case Key.Left: X = X - 16; break; case Key.Right: X = X + 16; break; case Key.Up: Y = Y - 16; break; case Key.Down: Y = Y + 16; break; case Key.KeypadPlus: case Key.Plus: Size += new Size(16, 16); break; case Key.KeypadMinus: case Key.Minus: Size -= new Size(16, 16); break; } } void MouseMoveHandler(object sender, MouseMoveEventArgs e) { refresh_text = true; } void MouseButtonHandler(object sender, MouseButtonEventArgs e) { refresh_text = true; if (e.Button == MouseButton.Left && e.IsPressed) { CursorVisible = false; } } static int Clamp(int val, int min, int max) { return val > max ? max : val < min ? min : val; } static void DrawString(Graphics gfx, string str, int line) { gfx.DrawString(str, TextFont, Brushes.White, new PointF(0, line * TextFont.Height)); } static void DrawString(Graphics gfx, string str, int line, float offset) { gfx.DrawString(str, TextFont, Brushes.White, new PointF(offset, line * TextFont.Height)); } static void DrawKeyboard(Graphics gfx, KeyboardState keyboard, int line) { const string str = "Keys pressed:"; float space = gfx.MeasureString(" ", TextFont).Width; float offset = gfx.MeasureString(str, TextFont).Width + space; DrawString(gfx, str, line); for (int i = 0; i < (int)Key.LastKey; i++) { Key k = (Key)i; if (keyboard[k]) { string key = k.ToString(); DrawString(gfx, key, line, offset); offset += gfx.MeasureString(key, TextFont).Width + space; } } } static void DrawMouse(Graphics gfx, MouseState mouse, int line) { const string str = "Buttons pressed:"; float space = gfx.MeasureString(" ", TextFont).Width; float offset = gfx.MeasureString(str, TextFont).Width + space; DrawString(gfx, str, line); for (int i = 0; i < (int)MouseButton.LastButton; i++) { MouseButton b = (MouseButton)i; if (mouse[b]) { string button = b.ToString(); DrawString(gfx, button, line, offset); offset += gfx.MeasureString(button, TextFont).Width + space; } } } protected override void OnUpdateFrame(FrameEventArgs e) { mouse = OpenTK.Input.Mouse.GetState(); if (mouse != mouse_old) refresh_text = true; mouse_old = mouse; keyboard = OpenTK.Input.Keyboard.GetState(); if (keyboard != keyboard_old) refresh_text = true; keyboard_old = keyboard; if (refresh_text) { refresh_text = false; using (Graphics gfx = Graphics.FromImage(TextBitmap)) { int line = 0; gfx.Clear(Color.Black); gfx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; DrawString(gfx, String.Format("[1 - 4]: change WindowState (current: {0}).", this.WindowState), line++); DrawString(gfx, String.Format("[5 - 7]: change WindowBorder (current: {0}).", this.WindowBorder), line++); DrawString(gfx, String.Format("Focused: {0}.", this.Focused), line++); DrawString(gfx, String.Format("Mouse {0} window.", mouse_in_window ? "inside" : "outside of"), line++); DrawString(gfx, String.Format("Mouse visible: {0}", CursorVisible), line++); DrawString(gfx, String.Format("Mouse position (absolute): {0}", new Vector3(Mouse.X, Mouse.Y, Mouse.Wheel)), line++); DrawString(gfx, String.Format("Mouse position (relative): {0}", new Vector3(mouse.X, mouse.Y, mouse.WheelPrecise)), line++); DrawString(gfx, String.Format("Window.Bounds: {0}", Bounds), line++); DrawString(gfx, String.Format("Window.Location: {0}, Size: {1}", Location, Size), line++); DrawString(gfx, String.Format("Window.{{X={0}, Y={1}, Width={2}, Height={3}}}", X, Y, Width, Height), line++); DrawString(gfx, String.Format("Window.ClientRectangle: {0}", ClientRectangle), line++); DrawKeyboard(gfx, keyboard, line++); DrawMouse(gfx, mouse, line++); } } System.Drawing.Imaging.BitmapData data = TextBitmap.LockBits( new System.Drawing.Rectangle(0, 0, TextBitmap.Width, TextBitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); GL.TexSubImage2D(TextureTarget.Texture2D, 0, 0, 0, TextBitmap.Width, TextBitmap.Height, PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0); TextBitmap.UnlockBits(data); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); GL.ClearColor(Color.MidnightBlue); GL.Enable(EnableCap.Texture2D); GL.Enable(EnableCap.Blend); GL.BlendFunc(BlendingFactorSrc.One, BlendingFactorDest.OneMinusSrcColor); texture = GL.GenTexture(); GL.BindTexture(TextureTarget.Texture2D, texture); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, TextBitmap.Width, TextBitmap.Height, 0, PixelFormat.Bgra, PixelType.UnsignedByte, IntPtr.Zero); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Nearest); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Nearest); } protected override void OnResize(EventArgs e) { base.OnResize(e); viewport_changed = true; } protected override void OnRenderFrame(FrameEventArgs e) { base.OnRenderFrame(e); if (viewport_changed) { viewport_changed = false; GL.Viewport(0, 0, Width, Height); Matrix4 ortho_projection = Matrix4.CreateOrthographicOffCenter(0, Width, Height, 0, -1, 1); GL.MatrixMode(MatrixMode.Projection); GL.LoadMatrix(ref ortho_projection); } GL.Clear(ClearBufferMask.ColorBufferBit); GL.Begin(BeginMode.Quads); GL.TexCoord2(0, 0); GL.Vertex2(0, 0); GL.TexCoord2(1, 0); GL.Vertex2(TextBitmap.Width, 0); GL.TexCoord2(1, 1); GL.Vertex2(TextBitmap.Width, TextBitmap.Height); GL.TexCoord2(0, 1); GL.Vertex2(0, TextBitmap.Height); GL.End(); SwapBuffers(); } public static void Main() { using (GameWindowStates ex = new GameWindowStates()) { Utilities.SetWindowTitle(ex); ex.Run(30.0); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Linq.Expressions.Tests { public static class BinaryGreaterThanOrEqualTests { public static IEnumerable<object[]> TestData() { foreach (bool useInterpreter in new bool[] { true, false }) { yield return new object[] { new byte[] { 0, 1, byte.MaxValue }, useInterpreter }; yield return new object[] { new char[] { '\0', '\b', 'A', '\uffff' }, useInterpreter }; yield return new object[] { new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }, useInterpreter }; yield return new object[] { new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }, useInterpreter }; yield return new object[] { new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }, useInterpreter }; yield return new object[] { new int[] { 0, 1, -1, int.MinValue, int.MaxValue }, useInterpreter }; yield return new object[] { new long[] { 0, 1, -1, long.MinValue, long.MaxValue }, useInterpreter }; yield return new object[] { new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }, useInterpreter }; yield return new object[] { new short[] { 0, 1, -1, short.MinValue, short.MaxValue }, useInterpreter }; yield return new object[] { new uint[] { 0, 1, uint.MaxValue }, useInterpreter }; yield return new object[] { new ulong[] { 0, 1, ulong.MaxValue }, useInterpreter }; yield return new object[] { new ushort[] { 0, 1, ushort.MaxValue }, useInterpreter }; yield return new object[] { new byte?[] { null, 0, 1, byte.MaxValue }, useInterpreter }; yield return new object[] { new char?[] { null, '\0', '\b', 'A', '\uffff' }, useInterpreter }; yield return new object[] { new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }, useInterpreter }; yield return new object[] { new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }, useInterpreter }; yield return new object[] { new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }, useInterpreter }; yield return new object[] { new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }, useInterpreter }; yield return new object[] { new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }, useInterpreter }; yield return new object[] { new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }, useInterpreter }; yield return new object[] { new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }, useInterpreter }; yield return new object[] { new uint?[] { null, 0, 1, uint.MaxValue }, useInterpreter }; yield return new object[] { new ulong?[] { null, 0, 1, ulong.MaxValue }, useInterpreter }; yield return new object[] { new ushort?[] { null, 0, 1, ushort.MaxValue }, useInterpreter }; } } [Theory] [MemberData(nameof(TestData))] public static void GreaterThanOrEqual(Array array, bool useInterpreter) { Type type = array.GetType().GetElementType(); for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { object a = array.GetValue(i); object b = array.GetValue(j); BinaryExpression equal = Expression.GreaterThanOrEqual(Expression.Constant(a, type), Expression.Constant(b, type)); GeneralBinaryTests.CompileBinaryExpression(equal, useInterpreter, GeneralBinaryTests.CustomGreaterThanOrEqual(a, b)); } } } [Theory] [MemberData(nameof(TestData))] public static void GreaterThan(Array array, bool useInterpreter) { Type type = array.GetType().GetElementType(); for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { object a = array.GetValue(i); object b = array.GetValue(j); BinaryExpression equal = Expression.GreaterThan(Expression.Constant(a, type), Expression.Constant(b, type)); GeneralBinaryTests.CompileBinaryExpression(equal, useInterpreter, GeneralBinaryTests.CustomGreaterThan(a, b)); } } } [Theory] [MemberData(nameof(TestData))] public static void LessThanOrEqual(Array array, bool useInterpreter) { Type type = array.GetType().GetElementType(); for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { object a = array.GetValue(i); object b = array.GetValue(j); BinaryExpression equal = Expression.LessThanOrEqual(Expression.Constant(a, type), Expression.Constant(b, type)); GeneralBinaryTests.CompileBinaryExpression(equal, useInterpreter, GeneralBinaryTests.CustomLessThanOrEqual(a, b)); } } } [Theory] [MemberData(nameof(TestData))] public static void LessThan(Array array, bool useInterpreter) { Type type = array.GetType().GetElementType(); for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { object a = array.GetValue(i); object b = array.GetValue(j); BinaryExpression equal = Expression.LessThan(Expression.Constant(a, type), Expression.Constant(b, type)); GeneralBinaryTests.CompileBinaryExpression(equal, useInterpreter, GeneralBinaryTests.CustomLessThan(a, b)); } } } [Fact] public static void GreaterThanOrEqual_CannotReduce() { Expression exp = Expression.GreaterThanOrEqual(Expression.Constant(0), Expression.Constant(0)); Assert.False(exp.CanReduce); Assert.Same(exp, exp.Reduce()); Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } [Fact] public static void GreaterThan_CannotReduce() { Expression exp = Expression.GreaterThan(Expression.Constant(0), Expression.Constant(0)); Assert.False(exp.CanReduce); Assert.Same(exp, exp.Reduce()); Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } [Fact] public static void LessThanOrEqual_CannotReduce() { Expression exp = Expression.LessThanOrEqual(Expression.Constant(0), Expression.Constant(0)); Assert.False(exp.CanReduce); Assert.Same(exp, exp.Reduce()); Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } [Fact] public static void LessThan_CannotReduce() { Expression exp = Expression.LessThan(Expression.Constant(0), Expression.Constant(0)); Assert.False(exp.CanReduce); Assert.Same(exp, exp.Reduce()); Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } [Fact] public static void ThrowsOnLeftNull() { Assert.Throws<ArgumentNullException>("left", () => Expression.GreaterThanOrEqual(null, Expression.Constant(0))); Assert.Throws<ArgumentNullException>("left", () => Expression.GreaterThan(null, Expression.Constant(0))); Assert.Throws<ArgumentNullException>("left", () => Expression.LessThanOrEqual(null, Expression.Constant(0))); Assert.Throws<ArgumentNullException>("left", () => Expression.LessThanOrEqual(null, Expression.Constant(0))); } [Fact] public static void ThrowsOnRightNull() { Assert.Throws<ArgumentNullException>("right", () => Expression.GreaterThanOrEqual(Expression.Constant(0), null)); Assert.Throws<ArgumentNullException>("right", () => Expression.GreaterThan(Expression.Constant(0), null)); Assert.Throws<ArgumentNullException>("right", () => Expression.LessThanOrEqual(Expression.Constant(0), null)); Assert.Throws<ArgumentNullException>("right", () => Expression.LessThan(Expression.Constant(0), null)); } private static class Unreadable<T> { public static T WriteOnly { set { } } } [Fact] public static void ThrowsOnLeftUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); Assert.Throws<ArgumentException>("left", () => Expression.GreaterThanOrEqual(value, Expression.Constant(1))); Assert.Throws<ArgumentException>("left", () => Expression.GreaterThan(value, Expression.Constant(1))); Assert.Throws<ArgumentException>("left", () => Expression.LessThanOrEqual(value, Expression.Constant(1))); Assert.Throws<ArgumentException>("left", () => Expression.LessThan(value, Expression.Constant(1))); } [Fact] public static void ThrowsOnRightUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); Assert.Throws<ArgumentException>("right", () => Expression.GreaterThanOrEqual(Expression.Constant(1), value)); Assert.Throws<ArgumentException>("right", () => Expression.GreaterThan(Expression.Constant(1), value)); Assert.Throws<ArgumentException>("right", () => Expression.LessThanOrEqual(Expression.Constant(1), value)); Assert.Throws<ArgumentException>("right", () => Expression.LessThan(Expression.Constant(1), value)); } [Fact] public static void GreaterThanOrEqual_ToString() { var e = Expression.GreaterThanOrEqual(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b")); Assert.Equal("(a >= b)", e.ToString()); } [Fact] public static void GreaterThan_ToString() { var e = Expression.GreaterThan(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b")); Assert.Equal("(a > b)", e.ToString()); } [Fact] public static void LessThanOrEqual_ToString() { var e = Expression.LessThanOrEqual(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b")); Assert.Equal("(a <= b)", e.ToString()); } [Fact] public static void LessThan_ToString() { var e = Expression.LessThan(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b")); Assert.Equal("(a < b)", e.ToString()); } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace Microsoft.PythonTools.Analysis { /// <summary> /// A simple dictionary like object which has efficient storage when there's only a single item in the dictionary. /// </summary> [DebuggerDisplay("Count = {Count}")] struct SingleDict<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>> where TKey : class where TValue : class { [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] private object _data; // AnalysisDictionary<TKey, TValue>, SingleEntry<TKey, TValue> or IEqualityComparer<TKey> public SingleDict(IEqualityComparer<TKey> comparer) { _data = comparer; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] private KeyValuePair<TKey, TValue>[] AllItems { get { var single = _data as SingleDependency; if (single != null) { return new[] { new KeyValuePair<TKey, TValue>(single.Key, single.Value) }; } var dict = _data as AnalysisDictionary<TKey, TValue>; if (dict != null) { return dict.ToArray(); } return new KeyValuePair<TKey, TValue>[0]; } } public IEqualityComparer<TKey> Comparer { get { var single = _data as SingleDependency; if (single != null) { return single.Comparer; } var dict = _data as AnalysisDictionary<TKey, TValue>; if (dict != null) { return dict.Comparer; } return (_data as IEqualityComparer<TKey>) ?? EqualityComparer<TKey>.Default; } } sealed class SingleDependency { public readonly TKey Key; public TValue Value; public readonly IEqualityComparer<TKey> Comparer; public SingleDependency(TKey key, TValue value, IEqualityComparer<TKey> comparer) { Key = key; Value = value; Comparer = comparer; } } public bool ContainsKey(TKey key) { var single = _data as SingleDependency; if (single != null) { return single.Comparer.Equals(single.Key, key); } var dict = _data as AnalysisDictionary<TKey, TValue>; if (dict != null) { return dict.ContainsKey(key); } return false; } public bool TryGetValue(TKey key, out TValue value) { SingleDependency single = _data as SingleDependency; if (single != null) { if (single.Comparer.Equals(single.Key, key)) { value = single.Value; return true; } value = default(TValue); return false; } var dict = _data as AnalysisDictionary<TKey, TValue>; if (dict != null) { return dict.TryGetValue(key, out value); } value = default(TValue); return false; } public TValue this[TKey key] { get { TValue res; if (TryGetValue(key, out res)) { return res; } throw new KeyNotFoundException(); } set { IEqualityComparer<TKey> comparer = null; if (_data == null || (comparer = _data as IEqualityComparer<TKey>) != null) { _data = new SingleDependency(key, value, comparer ?? EqualityComparer<TKey>.Default); return; } var single = _data as SingleDependency; if (single != null) { if (single.Comparer.Equals(single.Key, key)) { single.Value = value; return; } var data = new AnalysisDictionary<TKey, TValue>(single.Comparer); data[single.Key] = single.Value; data[key] = value; _data = data; return; } var dict = _data as AnalysisDictionary<TKey, TValue>; if (dict == null) { _data = dict = new AnalysisDictionary<TKey, TValue>(comparer ?? EqualityComparer<TKey>.Default); } dict[key] = value; } } internal void Remove(TKey fromModule) { var single = _data as SingleDependency; if (single != null) { if (single.Comparer.Equals(single.Key, fromModule)) { _data = single.Comparer; } return; } var dict = _data as AnalysisDictionary<TKey, TValue>; if (dict != null) { dict.Remove(fromModule); } } public bool TryGetSingleValue(out TValue value) { var single = _data as SingleDependency; if (single != null) { value = single.Value; return true; } value = default(TValue); return false; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public ICollection<TValue> DictValues { get { Debug.Assert(_data is AnalysisDictionary<TKey, TValue>); return ((AnalysisDictionary<TKey, TValue>)_data).Values; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal AnalysisDictionary<TKey, TValue> InternalDict { get { return _data as AnalysisDictionary<TKey, TValue>; } set { if (value.Count == 1) { using (var e = value.GetEnumerator()) { e.MoveNext(); _data = new SingleDependency(e.Current.Key, e.Current.Value, value.Comparer); } } else { _data = value; } } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public IEnumerable<TValue> Values { get { SingleDependency single; var dict = _data as AnalysisDictionary<TKey, TValue>; if (dict != null) { return dict.Values; } else if ((single = _data as SingleDependency) != null) { return new[] { single.Value }; } return new TValue[0]; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public IEnumerable<TKey> Keys { get { var single = _data as SingleDependency; if (single != null) { yield return single.Key; } var dict = _data as AnalysisDictionary<TKey, TValue>; if (dict != null) { foreach (var value in dict.Keys) { yield return value; } } } } public int Count { get { var single = _data as SingleDependency; if (single != null) { return 1; } var dict = _data as AnalysisDictionary<TKey, TValue>; if (dict != null) { return dict.Count; } return 0; } } public void Clear() { _data = Comparer; } #region IEnumerable<KeyValuePair<TKey,TValue>> Members public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { var single = _data as SingleDependency; if (single != null) { yield return new KeyValuePair<TKey, TValue>(single.Key, single.Value); } var dict = _data as AnalysisDictionary<TKey, TValue>; if (dict != null) { foreach (var keyValue in dict) { yield return keyValue; } } } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } }
// Copyright (c) 2013, Adel Qodmani, Sarah Homsi // All rights reserved. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using System.Diagnostics; using System.IO; namespace IR { /// <summary> /// <para> /// Allows the user to get the distance from a query to a set of documents using the vector-distance model. /// </para> /// <para> /// Bear in mind that this class is meant to be immutable in terms of what documents it queries; if you want your query to work over a different /// set of documents, create a new instance. /// </para> /// </summary> class VectorModeler { // This thing here is VERY dangerous, it's the paths of the documents we're building the system upon; their order in this array is the order used to fill // the frequency matrix and is the order used to report the distances to the user; if any inconsistency happens here, we're basically .. well .. you know private string[] documentsPaths; private Hashtable[] frequencyIndices; // Each array member is a document, each key is a term(string) and each value is its freq(int) private Hashtable uniqueTerms; // keys are unique terms of the documents and value is where the term is index in the frequencyMatrix private double[,] frequencyMatrix; private double[] maxFreqPerDoc; private double[] docCountPerTerm; private double[] IDF; private readonly int DocCount; private readonly int TotalTermsCount; // over all documents private DocumentDistance[] distances; /// <summary> /// Class used to get the closest matching document/s to a given query /// </summary> /// <param name="directoryPath"> The path of the directory where the documents to be queried are. </param> /// <exception cref="System.ArgumentNullException"> Thrown if you pass null to the constructor</exception> /// <exception cref="System.ArgumentException"> Thrown if the path passed is an empty string </exception> /// <exception cref="System.IO.DirectoryNotFoundException"> Thrown if the path passed is corrupted or the directory doesn't exist </exception> /// <exception cref="System.Exception"> Thrown if the directory path passed contains no .txt files in it </exception> public VectorModeler(string directoryPath) { if (directoryPath == null) throw new ArgumentNullException("Parameter cannot be null!", "directoryPath"); if (directoryPath.Length == 0) throw new ArgumentException("Parameter cannot be of length 0", "directoryPath"); if(!Directory.Exists(directoryPath)) throw new DirectoryNotFoundException(String.Format("Cannot find Directory: {0}", directoryPath)); documentsPaths = Directory.GetFiles(directoryPath, "*.txt"); if (documentsPaths.Length == 0) throw new Exception("The directory path you enetered contains no .txt files!"); Debug.WriteLine("Documents' names"); foreach (var item in documentsPaths) { Debug.WriteLine(Path.GetFileName(item)); } Debug.WriteLine(""); this.InitFrequencyIndices(directoryPath); this.InitUniqueTerms(); this.DocCount = this.frequencyIndices.Length; Debug.Assert(DocCount == documentsPaths.Length); this.TotalTermsCount = this.uniqueTerms.Count; this.InitFrequencyMatrix(); distances = new DocumentDistance[DocCount]; for (int i = 0; i < DocCount; i++) { distances[i] = new DocumentDistance(documentsPaths[i]); } // These are some heavy processing, consider using lazy initlization to speed the creation. this.InitMaxFrequencyPerDocument(); this.NormalizeFrequencyMatrix(); this.InitDocCountPerTerm(); this.CalculateInverseDocumentFrequency(); this.CalculateTfIdf(); } /// <summary> /// Fills in the frequencyIndices with the term frequencies for each term in the documents /// </summary> /// <param name="directoryPath"> The directory path in which the documents are to be found </param> private void InitFrequencyIndices(string directoryPath) { frequencyIndices = new Hashtable[documentsPaths.Length]; //filling frquencyIndices for (int i = 0; i < documentsPaths.Length; i++) { frequencyIndices[i] = DocumentsReader.BuildDocumentFrequencyIndex(documentsPaths[i]); } Debug.WriteLine("Frequency Indecies"); for (int i = 0; i < DocCount; i++) // For each document { Debug.WriteLine("Document-{0}", i + 1); foreach (DictionaryEntry pair in frequencyIndices[i]) { Debug.WriteLine("Term: {0} => freq: {1}", pair.Key, pair.Value); } } Debug.WriteLine(""); } /// <summary> /// Fills in the uniqueTerms hashtable where keys are unique terms and values are /// </summary> private void InitUniqueTerms() { int index = 0; uniqueTerms = new Hashtable(); //filling uniqueTerms table foreach (Hashtable doc in frequencyIndices) { foreach (DictionaryEntry item in doc) { if (!uniqueTerms.ContainsKey(item.Key)) uniqueTerms.Add(item.Key, index++); } } Debug.WriteLine("uniqueTerms count: {0} ", uniqueTerms.Count); foreach (DictionaryEntry pair in uniqueTerms) { Debug.WriteLine("Term: {0} => index: {1}", pair.Key, pair.Value); } Debug.WriteLine(""); } /// <summary> /// Fills in the frequencyMatrix with frequencies of each word in the set of documents /// </summary> private void InitFrequencyMatrix() { frequencyMatrix = new double[TotalTermsCount, DocCount]; //filling frequencyMatrix int index = 0; foreach (Hashtable doc in frequencyIndices) { foreach (DictionaryEntry item in uniqueTerms) { if (doc.ContainsKey(item.Key)) frequencyMatrix[(int)item.Value, index] = Convert.ToDouble(doc[item.Key]); else frequencyMatrix[(int)item.Value, index] = 0; } index++; } Debug.WriteLine("Non-Normalized FreqMatrix"); for (int i = 0; i < TotalTermsCount; i++) { for (int j = 0; j < DocCount; j++) { Debug.Write(String.Format("{0:0.0##}", frequencyMatrix[i, j])); Debug.Write("\t"); } Debug.WriteLine(""); } Debug.WriteLine(""); #if false int index = 0; Hashtable uniqueTerms = new Hashtable(); //filling word_index_lookup table foreach (Hashtable doc in frequencyIndices) { foreach (DictionaryEntry item in doc) { if (!uniqueTerms.ContainsKey(item.Key)) uniqueTerms.Add(item.Key, index++); } } frequencyMatrix = new double[uniqueTerms.Count, frequencyIndices.Length];// [terms as rows; documents as cols] index = -1; foreach (Hashtable doc in frequencyIndices) { index++; foreach (DictionaryEntry item in uniqueTerms) { if (doc.ContainsKey(item.Key)) frequencyMatrix[(int)item.Value, index] = Convert.ToDouble(doc[item.Key]); else frequencyMatrix[(int)item.Value, index] = 0; } } #endif } /// <summary> /// Calculates the max frequency per document and stores it in the maxFreqPerDoc /// </summary> private void InitMaxFrequencyPerDocument() { maxFreqPerDoc = new double[DocCount]; double tmpMax; // Get the max freq per doc for (int i = 0; i < DocCount; i++)// For each document i { tmpMax = frequencyMatrix[0, i]; for (int j = 1; j < TotalTermsCount; j++)// For each word that can be in the document { if (frequencyMatrix[j, i] > tmpMax) tmpMax = frequencyMatrix[j, i]; } maxFreqPerDoc[i] = tmpMax; } } /// <summary> /// <para>Normalizes the frequency matrix so that values in it are in it are between 0 and 1 (inclusive).</para> /// <para>It uses the maximum term frequency per document to do so</para> /// </summary> private void NormalizeFrequencyMatrix() { for (int i = 0; i < DocCount; i++)// For each document i { for (int j = 0; j < TotalTermsCount; j++)//For each word that can be in the document frequencyMatrix[j, i] /= maxFreqPerDoc[i]; } Debug.WriteLine("NormalizeFreqMatrix"); for (int i = 0; i < TotalTermsCount; i++) { for (int j = 0; j < DocCount; j++) { Debug.Write(String.Format("{0:0.0##}", frequencyMatrix[i, j])); Debug.Write("\t"); } Debug.WriteLine(""); } Debug.WriteLine(""); } /// <summary> /// Fills the docCountPerTerm array with the count of how many documents contained a given term i /// </summary> private void InitDocCountPerTerm() { docCountPerTerm = new double[TotalTermsCount]; for (int i = 0; i < TotalTermsCount; i++) // For each term i { for (int j = 0; j < DocCount; j++) // For each document { if (frequencyMatrix[i, j] != 0) docCountPerTerm[i]++; } } } /// <summary> /// Builds the IDF array which contains the Log10(docCount/docCountPerTerm) for each term /// It's used in building the TF-IDF table /// </summary> private void CalculateInverseDocumentFrequency() { IDF = new double[TotalTermsCount]; for (int i = 0; i < TotalTermsCount; i++) IDF[i] = Math.Log10(DocCount / docCountPerTerm[i]); Debug.WriteLine("Printing the IDF"); foreach (var item in IDF) { Debug.WriteLine(String.Format("{0:0.0##}", item)); } Debug.WriteLine(""); } /// <summary> /// Builds the tf-idf table using the IDF table and writes it over the frequency matrix /// </summary> private void CalculateTfIdf() { for (int i = 0; i < TotalTermsCount; i++) for (int j = 0; j < DocCount; j++) frequencyMatrix[i, j] *= IDF[i]; Debug.WriteLine("TF-IDF Matrix"); for (int i = 0; i < TotalTermsCount; i++) { for (int j = 0; j < DocCount; j++) { Debug.Write(String.Format("{0:0.0##}", frequencyMatrix[i, j])); Debug.Write("\t"); } Debug.WriteLine(""); } Debug.WriteLine(""); } /// <summary> /// /// </summary> /// <param name="query"> A pre-processed query </param> /// <returns> The frequency vectory of the query or null if no term matches the query in the whole system </returns> private double[] TextToQueryVector(string query) { double[] queryVector = new double[TotalTermsCount]; string[] query_text = query.Split(null); // Discard any terms in the query that are not avaiable in our indices then do whatever you wanna do foreach (string word in query_text) { if (uniqueTerms.ContainsKey(word)) queryVector[(int)uniqueTerms[word]] += 1; } foreach (var item in queryVector) { if (item != 0) return queryVector; } return null; } /// <summary> /// Normalizes the query to be properly used with the documents in this system. /// </summary> /// <param name="queryVector"> The user query to be normalized </param> private void NormalizeQuery(double[] queryVector) { Debug.Assert(queryVector.Length == TotalTermsCount); // queury is normalized by dividing each frequency in it by the max frequency in the query double max = queryVector[0]; foreach (var item in queryVector) { if (item > max) max = item; } for (int i = 0; i < queryVector.Length; i++) queryVector[i] /= max; } /// <summary> /// Uses the IDF in the class to build the TF-IDF of the given query /// </summary> /// <param name="normalizedQueryVector">The normalized user query to be TF-IDFed</param> private void CalculateQueuryTfId(double[] normalizedQueryVector) { Debug.Assert(normalizedQueryVector.Length == TotalTermsCount); for (int i = 0; i < normalizedQueryVector.Length; i++) normalizedQueryVector[i] *= IDF[i]; } /// <summary> /// Uses the TF-IDF table to know the distance between the query and each document in the system. /// </summary> /// <param name="queryVector"> The frequency of each word in the query </param> private void CalculateDistances(double[] queryVector) { // To calc distance for a query; (1) nomralize it (2)get its tf-idf and (3) calc the distance Debug.WriteLine("Query we have now"); foreach (var item in queryVector) Debug.WriteLine(item); Debug.WriteLine(""); this.NormalizeQuery(queryVector); Debug.WriteLine("Query we have after normalization"); foreach (var item in queryVector) Debug.WriteLine(item); Debug.WriteLine(""); this.CalculateQueuryTfId(queryVector); Debug.WriteLine("Query we have after TF-IDF"); foreach (var item in queryVector) Debug.WriteLine(item); Debug.WriteLine(""); double[] sums = new double[DocCount]; for (int i = 0; i < DocCount; i++) // For each document i { for (int j = 0; j < TotalTermsCount; j++) // For each term j { sums[i] += Math.Pow(queryVector[j] - frequencyMatrix[j, i], 2); } } for (int i = 0; i < DocCount; i++) { distances[i].distance = Math.Sqrt(sums[i]); } } /// <summary> /// Uses the TF-IDF table to calculate the consinal similarity between the query and each document in the system. /// </summary> /// <remarks> /// Basically applying the formula for calculating the cosine between two vectors over each document and the query - look it up :P /// Generally considered better than knowing the E-distance (according to a research done at Stanford .. not cited here) /// </remarks> /// <param name="queryVector"> The frequency of each word in the query </param> private void CalculateConsinalSimilarity(double[] queryVector) { this.NormalizeQuery(queryVector); this.CalculateQueuryTfId(queryVector); Debug.WriteLine("Query we have after TF-IDF"); foreach (var item in queryVector) Debug.WriteLine(item); Debug.WriteLine(""); double[] nominator = new double[DocCount]; Debug.WriteLine("Printing the nominator for d1 and the query"); for (int i = 0; i < nominator.Length; i++) // For each document { for (int j = 0; j < TotalTermsCount; j++) // For each term { if (i == 0) { Debug.WriteLine("{0} * {1}", frequencyMatrix[j, i], queryVector[j]); } nominator[i] += queryVector[j] * frequencyMatrix[j, i]; } } Debug.WriteLine(""); double denominatorPartTwo = 0; foreach (var item in queryVector) { denominatorPartTwo += Math.Pow(item, 2); } denominatorPartTwo = Math.Sqrt(denominatorPartTwo); Debug.WriteLine("denominatorPartTwo = {0}", denominatorPartTwo); Debug.WriteLine(""); double[] denominatorPartOne = new double[DocCount]; for (int i = 0; i < denominatorPartOne.Length; i++) // For each document { for (int j = 0; j < TotalTermsCount; j++) // For each term { denominatorPartOne[i] += Math.Pow(frequencyMatrix[j, i], 2); } denominatorPartOne[i] = Math.Sqrt(denominatorPartOne[i]); } for (int i = 0; i < DocCount; i++) { this.distances[i].distance = (nominator[i]) / ((denominatorPartOne[i]) * (denominatorPartTwo)); } } /// <summary> /// Queries the documents to see what documents are most relevant to the user query /// </summary> /// <param name="query"> The users pre-processed query </param> /// <param name="threshold"> The amount of the relevant documents to return; by default it's 0 which means return all documents </param> /// <param name="useVectorDistance"> Set to true if you want to use VectorDistance, otherwise the system will use Cosine similarity </param> /// <returns> Array of DocumentDistances sorted where the first element is the most relevant and the last is the least relevant. /// It returns null if no document has any of the terms in the query </returns> /// <exception cref="System.ArgumentNullException"> Thrown if query is null</exception> /// <exception cref="System.ArgumentException"> Thrown if the query is an empty string </exception> public DocumentDistance[] GetRelevantDocuments(string query, int threshold = 0, bool useVectorDistance = false) { if (query == null) throw new ArgumentNullException("Parameter cannot be null!", "query"); if (query.Length == 0) throw new ArgumentException("Parameter cannot be of length 0", "query"); double[] queryVector = this.TextToQueryVector(query); if (queryVector == null) return null; if (useVectorDistance) { this.CalculateDistances(queryVector); Array.Sort(this.distances); } else { this.CalculateConsinalSimilarity(queryVector); Array.Sort(this.distances); // In CalculateConsinalSimilarity, the documents that are most relevant have a higher number and our sort is an ascending sort // so we reverse the array after sorting to have the most relevant first Array.Reverse(this.distances); } return (threshold <= 0) ? this.distances : this.distances.Take(threshold).ToArray(); } } }
#region Using directives using SimpleFramework.Xml.Core; using SimpleFramework.Xml; using System.Collections.Generic; using System; #endregion namespace SimpleFramework.Xml.Core { public class CollectionTest : ValidationTestCase { private const String LIST = "<?xml version=\"1.0\"?>\n"+ "<test name='example'>\n"+ " <list>\n"+ " <entry id='1'>\n"+ " <text>one</text> \n\r"+ " </entry>\n\r"+ " <entry id='2'>\n"+ " <text>two</text> \n\r"+ " </entry>\n"+ " <entry id='3'>\n"+ " <text>three</text> \n\r"+ " </entry>\n"+ " </list>\n"+ "</test>"; private const String ARRAY_LIST = "<?xml version=\"1.0\"?>\n"+ "<test name='example'>\n"+ " <list class='java.util.ArrayList'>\n"+ " <entry id='1'>\n"+ " <text>one</text> \n\r"+ " </entry>\n\r"+ " <entry id='2'>\n"+ " <text>two</text> \n\r"+ " </entry>\n"+ " <entry id='3'>\n"+ " <text>three</text> \n\r"+ " </entry>\n"+ " </list>\n"+ "</test>"; private const String HASH_SET = "<?xml version=\"1.0\"?>\n"+ "<test name='example'>\n"+ " <list class='java.util.HashSet'>\n"+ " <entry id='1'>\n"+ " <text>one</text> \n\r"+ " </entry>\n\r"+ " <entry id='2'>\n"+ " <text>two</text> \n\r"+ " </entry>\n"+ " <entry id='3'>\n"+ " <text>three</text> \n\r"+ " </entry>\n"+ " </list>\n"+ "</test>"; private const String TREE_SET = "<?xml version=\"1.0\"?>\n"+ "<test name='example'>\n"+ " <list class='java.util.TreeSet'>\n"+ " <entry id='1'>\n"+ " <text>one</text> \n\r"+ " </entry>\n\r"+ " <entry id='2'>\n"+ " <text>two</text> \n\r"+ " </entry>\n"+ " <entry id='3'>\n"+ " <text>three</text> \n\r"+ " </entry>\n"+ " </list>\n"+ "</test>"; private const String ABSTRACT_LIST = "<?xml version=\"1.0\"?>\n"+ "<test name='example'>\n"+ " <list class='SimpleFramework.Xml.Core.CollectionTest$AbstractList'>\n"+ " <entry id='1'>\n"+ " <text>one</text> \n\r"+ " </entry>\n\r"+ " <entry id='2'>\n"+ " <text>two</text> \n\r"+ " </entry>\n"+ " <entry id='3'>\n"+ " <text>three</text> \n\r"+ " </entry>\n"+ " </list>\n"+ "</test>"; private const String NOT_A_COLLECTION = "<?xml version=\"1.0\"?>\n"+ "<test name='example'>\n"+ " <list class='java.util.Hashtable'>\n"+ " <entry id='1'>\n"+ " <text>one</text> \n\r"+ " </entry>\n\r"+ " <entry id='2'>\n"+ " <text>two</text> \n\r"+ " </entry>\n"+ " <entry id='3'>\n"+ " <text>three</text> \n\r"+ " </entry>\n"+ " </list>\n"+ "</test>"; private const String MISSING_COLLECTION = "<?xml version=\"1.0\"?>\n"+ "<test name='example'>\n"+ " <list class='example.MyCollection'>\n"+ " <entry id='1'>\n"+ " <text>one</text> \n\r"+ " </entry>\n\r"+ " <entry id='2'>\n"+ " <text>two</text> \n\r"+ " </entry>\n"+ " <entry id='3'>\n"+ " <text>three</text> \n\r"+ " </entry>\n"+ " </list>\n"+ "</test>"; private const String EXTENDED_ENTRY_LIST = "<?xml version=\"1.0\"?>\n"+ "<test name='example'>\n"+ " <list>\n"+ " <extended-entry id='1' class='SimpleFramework.Xml.Core.CollectionTest$ExtendedEntry'>\n"+ " <text>one</text> \n\r"+ " <description>this is an extended entry</description>\n\r"+ " </extended-entry>\n\r"+ " <extended-entry id='2' class='SimpleFramework.Xml.Core.CollectionTest$ExtendedEntry'>\n"+ " <text>two</text> \n\r"+ " <description>this is the second one</description>\n"+ " </extended-entry>\n"+ " <entry id='3'>\n"+ " <text>three</text> \n\r"+ " </entry>\n"+ " </list>\n"+ "</test>"; private const String TYPE_FROM_FIELD_LIST = "<?xml version=\"1.0\"?>\n"+ "<typeFromFieldList name='example'>\n"+ " <list>\n"+ " <entry id='1'>\n"+ " <text>one</text> \n\r"+ " </entry>\n\r"+ " <entry id='2'>\n"+ " <text>two</text> \n\r"+ " </entry>\n"+ " <entry id='3'>\n"+ " <text>three</text> \n\r"+ " </entry>\n"+ " </list>\n"+ "</typeFromFieldList>"; private const String TYPE_FROM_METHOD_LIST = "<?xml version=\"1.0\"?>\n"+ "<typeFromMethodList name='example'>\n"+ " <list>\n"+ " <entry id='1'>\n"+ " <text>one</text> \n\r"+ " </entry>\n\r"+ " <entry id='2'>\n"+ " <text>two</text> \n\r"+ " </entry>\n"+ " <entry id='3'>\n"+ " <text>three</text> \n\r"+ " </entry>\n"+ " </list>\n"+ "</typeFromMethodList>"; private const String PRIMITIVE_LIST = "<?xml version=\"1.0\"?>\n"+ "<primitiveCollection name='example'>\n"+ " <list>\n"+ " <text>one</text> \n\r"+ " <text>two</text> \n\r"+ " <text>three</text> \n\r"+ " </list>\n"+ "</primitiveCollection>"; private const String COMPOSITE_LIST = "<?xml version=\"1.0\"?>\n"+ "<compositeCollection name='example'>\n"+ " <list>\n"+ " <entry id='1'>\n"+ " <text>one</text> \n\r"+ " </entry>\n\r"+ " <entry id='2'>\n"+ " <text>two</text> \n\r"+ " </entry>\n\r"+ " <entry id='3'>\n"+ " <text>three</text> \n\r"+ " </entry>\n\r"+ " </list>\n"+ "</compositeCollection>"; private const String PRIMITIVE_DEFAULT_LIST = "<?xml version=\"1.0\"?>\n"+ "<primitiveDefaultCollection name='example'>\n"+ " <list>\n"+ " <string>one</string> \n\r"+ " <string>two</string> \n\r"+ " <string>three</string> \n\r"+ " </list>\n"+ "</primitiveDefaultCollection>"; [Root(Name="entry")] private static class Entry : Comparable { [Attribute(Name="id")] private int id; [Element(Name="text")] private String text; public int CompareTo(Object entry) { return id - ((Entry)entry).id; } } [Root(Name="extended-entry")] private static class ExtendedEntry : Entry { [Element(Name="description")] private String description; } [Root(Name="test")] private static class EntrySet : Iterable<Entry> { [ElementList(Name="list", Type=Entry.class)] private Set<Entry> list; [Attribute(Name="name")] private String name; public Iterator<Entry> Iterator() { return list.Iterator(); } } [Root(Name="test")] private static class EntrySortedSet : Iterable<Entry> { [ElementList(Name="list", Type=Entry.class)] private SortedSet<Entry> list; [Attribute(Name="name")] private String name; public Iterator<Entry> Iterator() { return list.Iterator(); } } [Root(Name="test")] private static class EntryList : Iterable<Entry> { [ElementList(Name="list", Type=Entry.class)] private List<Entry> list; [Attribute(Name="name")] private String name; public Iterator<Entry> Iterator() { return list.Iterator(); } } [Root(Name="test")] public static class InvalidList { [ElementList(Name="list", Type=Entry.class)] private String list; [Attribute(Name="name")] private String name; } [Root(Name="test")] public static class UnknownCollectionList : Iterable<Entry> { [ElementList(Name="list", Type=Entry.class)] private UnknownCollection<Entry> list; [Attribute(Name="name")] private String name; public Iterator<Entry> Iterator() { return list.Iterator(); } } [Root] private static class TypeFromFieldList : Iterable<Entry> { [ElementList] private List<Entry> list; [Attribute] private String name; public Iterator<Entry> Iterator() { return list.Iterator(); } } [Root] private static class TypeFromMethodList : Iterable<Entry> { private List<Entry> list; [Attribute] private String name; [ElementList] public List<Entry> List { get { return list; } set { this.list = value; } } //public List<Entry> GetList() { // return list; //} //public void SetList(List<Entry> list) { // this.list = list; //} return list.Iterator(); } } [Root] private static class PrimitiveCollection : Iterable<String> { [ElementList(Name="list", Type=String.class, Entry="text")] private List<String> list; [Attribute(Name="name")] private String name; public Iterator<String> Iterator() { return list.Iterator(); } } [Root] private static class CompositeCollection : Iterable<Entry> { [ElementList(Name="list", Entry="text")] private List<Entry> list; [Attribute(Name="name")] private String name; public Iterator<Entry> Iterator() { return list.Iterator(); } } [Root] private static class PrimitiveDefaultCollection : Iterable<String> { [ElementList] private List<String> list; [Attribute] private String name; public Iterator<String> Iterator() { return list.Iterator(); } } private abstract class AbstractList<T> : ArrayList<T> { public AbstractList() { super(); } } private abstract class UnknownCollection<T> : Collection<T> { public UnknownCollection() { super(); } } private Persister serializer; public void SetUp() { serializer = new Persister(); } public void TestSet() { EntrySet set = serializer.Read(EntrySet.class, LIST); int one = 0; int two = 0; int three = 0; for(Entry entry : set) { if(entry.id == 1 && entry.text.equals("one")) { one++; } if(entry.id == 2 && entry.text.equals("two")) { two++; } if(entry.id == 3 && entry.text.equals("three")) { three++; } } AssertEquals(one, 1); AssertEquals(two, 1); AssertEquals(three, 1); } public void TestSortedSet() { EntrySortedSet set = serializer.Read(EntrySortedSet.class, LIST); int one = 0; int two = 0; int three = 0; for(Entry entry : set) { if(entry.id == 1 && entry.text.equals("one")) { one++; } if(entry.id == 2 && entry.text.equals("two")) { two++; } if(entry.id == 3 && entry.text.equals("three")) { three++; } } AssertEquals(one, 1); AssertEquals(two, 1); AssertEquals(three, 1); Validate(set, serializer); } public void TestList() { EntryList set = serializer.Read(EntryList.class, LIST); int one = 0; int two = 0; int three = 0; for(Entry entry : set) { if(entry.id == 1 && entry.text.equals("one")) { one++; } if(entry.id == 2 && entry.text.equals("two")) { two++; } if(entry.id == 3 && entry.text.equals("three")) { three++; } } AssertEquals(one, 1); AssertEquals(two, 1); AssertEquals(three, 1); Validate(set, serializer); } public void TestHashSet() { EntrySet set = serializer.Read(EntrySet.class, HASH_SET); int one = 0; int two = 0; int three = 0; for(Entry entry : set) { if(entry.id == 1 && entry.text.equals("one")) { one++; } if(entry.id == 2 && entry.text.equals("two")) { two++; } if(entry.id == 3 && entry.text.equals("three")) { three++; } } AssertEquals(one, 1); AssertEquals(two, 1); AssertEquals(three, 1); Validate(set, serializer); } public void TestTreeSet() { EntrySortedSet set = serializer.Read(EntrySortedSet.class, TREE_SET); int one = 0; int two = 0; int three = 0; for(Entry entry : set) { if(entry.id == 1 && entry.text.equals("one")) { one++; } if(entry.id == 2 && entry.text.equals("two")) { two++; } if(entry.id == 3 && entry.text.equals("three")) { three++; } } AssertEquals(one, 1); AssertEquals(two, 1); AssertEquals(three, 1); Validate(set, serializer); } public void TestArrayList() { EntryList list = serializer.Read(EntryList.class, ARRAY_LIST); int one = 0; int two = 0; int three = 0; for(Entry entry : list) { if(entry.id == 1 && entry.text.equals("one")) { one++; } if(entry.id == 2 && entry.text.equals("two")) { two++; } if(entry.id == 3 && entry.text.equals("three")) { three++; } } AssertEquals(one, 1); AssertEquals(two, 1); AssertEquals(three, 1); Validate(list, serializer); } public void TestSortedSetToSet() { EntrySet set = serializer.Read(EntrySet.class, TREE_SET); int one = 0; int two = 0; int three = 0; for(Entry entry : set) { if(entry.id == 1 && entry.text.equals("one")) { one++; } if(entry.id == 2 && entry.text.equals("two")) { two++; } if(entry.id == 3 && entry.text.equals("three")) { three++; } } AssertEquals(one, 1); AssertEquals(two, 1); AssertEquals(three, 1); } public void TestExtendedEntry() { EntrySet set = serializer.Read(EntrySet.class, EXTENDED_ENTRY_LIST); int one = 0; int two = 0; int three = 0; for(Entry entry : set) { if(entry.id == 1 && entry.text.equals("one")) { one++; } if(entry.id == 2 && entry.text.equals("two")) { two++; } if(entry.id == 3 && entry.text.equals("three")) { three++; } } AssertEquals(one, 1); AssertEquals(two, 1); AssertEquals(three, 1); StringWriter out = new StringWriter(); serializer.Write(set, out); serializer.Write(set, System.err); EntrySet other = serializer.Read(EntrySet.class, out.toString()); for(Entry entry : set) { if(entry.id == 1 && entry.text.equals("one")) { one++; } if(entry.id == 2 && entry.text.equals("two")) { two++; } if(entry.id == 3 && entry.text.equals("three")) { three++; } } AssertEquals(one, 2); AssertEquals(two, 2); AssertEquals(three, 2); serializer.Write(other, System.err); } public void TestTypeFromFieldList() { TypeFromFieldList list = serializer.Read(TypeFromFieldList.class, TYPE_FROM_FIELD_LIST); int one = 0; int two = 0; int three = 0; for(Entry entry : list) { if(entry.id == 1 && entry.text.equals("one")) { one++; } if(entry.id == 2 && entry.text.equals("two")) { two++; } if(entry.id == 3 && entry.text.equals("three")) { three++; } } AssertEquals(one, 1); AssertEquals(two, 1); AssertEquals(three, 1); Validate(list, serializer); } public void TestTypeFromMethodList() { TypeFromMethodList list = serializer.Read(TypeFromMethodList.class, TYPE_FROM_METHOD_LIST); int one = 0; int two = 0; int three = 0; for(Entry entry : list) { if(entry.id == 1 && entry.text.equals("one")) { one++; } if(entry.id == 2 && entry.text.equals("two")) { two++; } if(entry.id == 3 && entry.text.equals("three")) { three++; } } AssertEquals(one, 1); AssertEquals(two, 1); AssertEquals(three, 1); Validate(list, serializer); } public void TestPrimitiveCollection() { PrimitiveCollection list = serializer.Read(PrimitiveCollection.class, PRIMITIVE_LIST); int one = 0; int two = 0; int three = 0; for(String entry : list) { if(entry.equals("one")) { one++; } if(entry.equals("two")) { two++; } if(entry.equals("three")) { three++; } } AssertEquals(one, 1); AssertEquals(two, 1); AssertEquals(three, 1); Validate(list, serializer); } // XXX This test needs to inline the entry= attribute so that // XXX we can use it to name the inserted entries public void TestCompositeCollection() { CompositeCollection list = serializer.Read(CompositeCollection.class, COMPOSITE_LIST); int one = 0; int two = 0; int three = 0; for(Entry entry : list) { if(entry.id == 1 && entry.text.equals("one")) { one++; } if(entry.id == 2 && entry.text.equals("two")) { two++; } if(entry.id == 3 && entry.text.equals("three")) { three++; } } AssertEquals(one, 1); AssertEquals(two, 1); AssertEquals(three, 1); Validate(list, serializer); } public void TestPrimitiveDefaultCollection() { PrimitiveDefaultCollection list = serializer.Read(PrimitiveDefaultCollection.class, PRIMITIVE_DEFAULT_LIST); int one = 0; int two = 0; int three = 0; for(String entry : list) { if(entry.equals("one")) { one++; } if(entry.equals("two")) { two++; } if(entry.equals("three")) { three++; } } AssertEquals(one, 1); AssertEquals(two, 1); AssertEquals(three, 1); Validate(list, serializer); } public void TestSetToSortedSet() { bool success = false; try { EntrySortedSet set = serializer.Read(EntrySortedSet.class, HASH_SET); } catch(InstantiationException e) { e.printStackTrace(); success = true; } assertTrue(success); } public void TestListToSet() { bool success = false; try { EntrySet set = serializer.Read(EntrySet.class, ARRAY_LIST); } catch(InstantiationException e) { e.printStackTrace(); success = true; } assertTrue(success); } public void TestInvalidList() { bool success = false; try { InvalidList set = serializer.Read(InvalidList.class, LIST); } catch(InstantiationException e) { e.printStackTrace(); success = true; } assertTrue(success); } public void TestUnknownCollectionList() { bool success = false; try { UnknownCollectionList set = serializer.Read(UnknownCollectionList.class, LIST); } catch(InstantiationException e) { e.printStackTrace(); success = true; } assertTrue(success); } public void TestAbstractList() { bool success = false; try { EntryList set = serializer.Read(EntryList.class, ABSTRACT_LIST); } catch(InstantiationException e) { e.printStackTrace(); success = true; } assertTrue(success); } public void TestNotACollection() { bool success = false; try { EntryList set = serializer.Read(EntryList.class, NOT_A_COLLECTION); } catch(InstantiationException e) { e.printStackTrace(); success = true; } assertTrue(success); } public void TestMissingCollection() { bool success = false; try { EntrySet set = serializer.Read(EntrySet.class, MISSING_COLLECTION); } catch(ClassNotFoundException e) { e.printStackTrace(); success = true; } assertTrue(success); } } }
using System; using NUnit.Framework; using Shielded; using Shielded.ProxyGen; using System.Threading; using System.Threading.Tasks; using System.Linq; using ShieldedTests.ProxyTestEntities; using System.Reflection; using ShieldedTests.ProxyTestEntities2; namespace ShieldedTests { public class TestEntity { public virtual Guid Id { get; set; } public virtual int Counter { get; set; } protected virtual int FullyProtected { get; set; } public void SetFullyProtected(int x) { // this is transactional as well. FullyProtected = x; } public virtual string Name { get { return null; } set { if (Name == "conflicting") // see test below. Assert.AreEqual("testing conflict...", value); // this should be avoided! see ProxyCommuteTest. basically, we could be // running within a commute, and Shielded throws if a commute touches anything // except its field. but changing other properties of this object is always safe. NameChanges.Commute((ref int i) => i++); } } public readonly Shielded<int> NameChanges = new Shielded<int>(); public virtual int AnyPropertyChanges { get; set; } // by convention, if this exists, it gets overriden. public virtual void Commute(Action a) { a(); } // likewise, by convention, this gets called after a property changes. called // from commutes too, in which case it may not access any other shielded field. protected void OnChanged(string name) { if (name != "AnyPropertyChanges") AnyPropertyChanges += 1; } } public class BadEntity { // CodeDOM does not support overriding a property with different accessors on get and set, // so trying to make a proxy of this class will cause an exception. public virtual int X { get; protected set; } } [TestFixture] public class ProxyTests { [Test] public void BasicTest() { var test = Factory.NewShielded<TestEntity>(); Assert.IsTrue(Factory.IsProxy(test.GetType())); Assert.Throws<InvalidOperationException>(() => test.Id = Guid.NewGuid()); var id = Guid.NewGuid(); // the proxy object will, when changed, appear in the list of changed // fields in the Shield.WhenCommitting events... bool committingFired = false; using (Shield.WhenCommitting<TestEntity>(ents => committingFired = true)) { Shield.InTransaction(() => test.Id = id); } Assert.IsTrue(committingFired); Assert.AreEqual(id, test.Id); Shield.InTransaction(() => { test.Id = Guid.Empty; var t = new Thread(() => { Assert.AreEqual(id, test.Id); }); t.Start(); t.Join(); Assert.AreEqual(Guid.Empty, test.Id); }); Assert.AreEqual(Guid.Empty, test.Id); var t2 = new Thread(() => { Assert.AreEqual(Guid.Empty, test.Id); }); t2.Start(); t2.Join(); int transactionCount = 0; Thread tConflict = null; var newTest = Factory.NewShielded<TestEntity>(); Shield.InTransaction(() => { newTest.Id = Guid.NewGuid(); newTest.Name = "testing conflict..."; transactionCount++; if (tConflict == null) { tConflict = new Thread(() => // property setters are not commutable, and cause conflicts Shield.InTransaction(() => newTest.Name = "conflicting")); tConflict.Start(); tConflict.Join(); } }); Assert.AreEqual(2, transactionCount); Assert.AreEqual("testing conflict...", newTest.Name); // it was first "conflicting", then "testing conflict..." Assert.AreEqual(2, newTest.NameChanges); Assert.AreEqual(3, newTest.AnyPropertyChanges); } [Test] public void ProxyCommuteTest() { var test = Factory.NewShielded<TestEntity>(); int transactionCount = 0, commuteCount = 0; Task.WaitAll(Enumerable.Range(1, 100).Select(i => Task.Factory.StartNew(() => { Shield.InTransaction(() => { Interlocked.Increment(ref transactionCount); test.Commute(() => { Interlocked.Increment(ref commuteCount); test.Counter = test.Counter + i; Thread.Sleep(1); }); }); }, TaskCreationOptions.LongRunning)).ToArray()); Assert.AreEqual(5050, test.Counter); // commutes never conflict (!) Assert.AreEqual(100, transactionCount); Assert.Greater(commuteCount, 100); Assert.Throws<InvalidOperationException>(() => Shield.InTransaction(() => { test.Commute(() => { // this will throw, because it tries to run a commute on NameChanges, which // is a separate shielded obj from the backing storage of the proxy. // test.Commute can only touch the virtual fields, or non-shielded objects. // a setter that commutes over another shielded field should be avoided! test.Name = "something"; Assert.Fail(); }); })); } [Test] public void ProtectedSetterTest() { Assert.Throws<InvalidOperationException>(() => Factory.NewShielded<BadEntity>()); var test = Factory.NewShielded<TestEntity>(); Assert.Throws<InvalidOperationException>(() => test.SetFullyProtected(5)); Shield.InTransaction(() => test.SetFullyProtected(5)); } private void AssertTransactional<T>(IIdentifiable<T> item) { Assert.IsTrue(Factory.IsProxy(item.GetType())); Assert.Throws<InvalidOperationException>(() => item.Id = default(T)); bool detectable = false; using (Shield.WhenCommitting<IIdentifiable<T>>(ts => detectable = true)) Shield.InTransaction(() => item.Id = default(T)); Assert.IsTrue(detectable); } [Test] public void PreparationTest() { // first, let's get one before the preparation var e1 = Factory.NewShielded<Entity1>(); AssertTransactional(e1); Factory.PrepareTypes( Assembly.GetExecutingAssembly().GetTypes() .Where(t => t.Namespace != null && t.Namespace.StartsWith("ShieldedTests.ProxyTestEntities", StringComparison.Ordinal) && t.IsClass) .ToArray()); var e2 = Factory.NewShielded<Entity2>(); AssertTransactional(e2); var e3 = Factory.NewShielded<Entity3>(); AssertTransactional(e3); var e4 = Factory.NewShielded<Entity4>(); AssertTransactional(e4); } [Test] public void ProxyWithImmutableCollTest() { var e = Factory.NewShielded<EntityWithExternalProperty>(); AssertTransactional(e); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.Contracts; using System.Globalization; using System.Collections.Generic; namespace System { [Immutable] public class String { [System.Runtime.CompilerServices.IndexerName("Chars")] public char this[int index] { get { Contract.Requires(0 <= index); Contract.Requires(index < this.Length); return default(char); } } public int Length { [Pure] [Reads(ReadsAttribute.Reads.Nothing)] get { Contract.Ensures(Contract.Result<int>() >= 0); return default(int); } } #if !SILVERLIGHT [Pure] [GlobalAccess(false)] [Escapes(true, false)] public CharEnumerator GetEnumerator() { // Contract.Ensures(Contract.Result<string>().IsNew); Contract.Ensures(Contract.Result<CharEnumerator>() != null); return default(CharEnumerator); } #endif [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String IsInterned(String str) { Contract.Requires(str != null); Contract.Ensures(Contract.Result<string>() == null || Contract.Result<string>().Length == str.Length); Contract.Ensures(Contract.Result<string>() == null || str.Equals(Contract.Result<string>())); return default(String); } public static String Intern(String str) { Contract.Requires(str != null); Contract.Ensures(Contract.Result<string>().Length == str.Length); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat(String[] values) { Contract.Requires(values != null); //Contract.Ensures(Contract.Result<string>().Length == Sum({ String s in values); s.Length })); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat(String str0, String str1, String str2, String str3) { Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<string>().Length == (str0 == null ? 0 : str0.Length) + (str1 == null ? 0 : str1.Length) + (str2 == null ? 0 : str2.Length) + (str3 == null ? 0 : str3.Length)); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat(String str0, String str1, String str2) { Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<string>().Length == (str0 == null ? 0 : str0.Length) + (str1 == null ? 0 : str1.Length) + (str2 == null ? 0 : str2.Length)); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat(String str0, String str1) { Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<string>().Length == (str0 == null ? 0 : str0.Length) + (str1 == null ? 0 : str1.Length)); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat(object[] args) { Contract.Requires(args != null); Contract.Ensures(Contract.Result<String>() != null); return default(String); } #if !SILVERLIGHT [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat(object arg0, object arg1, object arg2, object arg3) { Contract.Ensures(Contract.Result<String>() != null); return default(String); } #endif [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat(object arg0, object arg1, object arg2) { Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat(object arg0, object arg1) { Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat(object arg0) { Contract.Ensures(Contract.Result<String>() != null); return default(String); } #if NETFRAMEWORK_4_0 || NETFRAMEWORK_4_5 [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat(IEnumerable<string> args) { Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat<T>(IEnumerable<T> args) { Contract.Ensures(Contract.Result<String>() != null); return default(String); } #endif [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Copy(String str) { Contract.Requires(str != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Format(IFormatProvider provider, String format, object[] args) { Contract.Requires(format != null); Contract.Requires(args != null); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Format(String format, object[] args) { Contract.Requires(format != null); Contract.Requires(args != null); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Format(String format, object arg0, object arg1, object arg2) { Contract.Requires(format != null); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Format(String format, object arg0, object arg1) { Contract.Requires(format != null); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Format(String format, object arg0) { Contract.Requires(format != null); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] public String Remove(int startIndex) { Contract.Requires(startIndex >= 0); Contract.Requires(startIndex < this.Length); Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<String>().Length == startIndex); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String Remove(int index, int count) { Contract.Requires(index >= 0); Contract.Requires(count >= 0); Contract.Requires(index + count <= Length); Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<string>().Length == this.Length - count); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String Replace(String oldValue, String newValue) { Contract.Requires(oldValue != null); Contract.Requires(oldValue.Length > 0); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String Replace(char oldChar, char newChar) { Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String Insert(int startIndex, String value) { Contract.Requires(value != null); Contract.Requires(0 <= startIndex); Contract.Requires(startIndex <= this.Length); // When startIndex == this.Length, then it is added at the end of the instance Contract.Ensures(Contract.Result<string>().Length == this.Length + value.Length); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String Trim() { Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String ToUpper(System.Globalization.CultureInfo culture) { Contract.Requires(culture != null); Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<string>().Length == this.Length, "Are there languages for which this isn't true?!?"); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String ToUpper() { Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<string>().Length == this.Length); return default(String); } #if !SILVERLIGHT [Pure] public string ToUpperInvariant() { Contract.Ensures(Contract.Result<string>() != null); Contract.Ensures(Contract.Result<string>().Length == this.Length); return default(string); } #endif [Pure] public String ToLower(System.Globalization.CultureInfo culture) { Contract.Requires(culture != null); Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<string>().Length == this.Length); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String ToLower() { Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<string>().Length == this.Length); return default(String); } #if !SILVERLIGHT [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String ToLowerInvariant() { Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<String>().Length == this.Length); return default(String); } #endif [Pure] [Reads(ReadsAttribute.Reads.Owned)] public bool StartsWith(String value) { Contract.Requires(value != null); Contract.Ensures(!Contract.Result<bool>() || value.Length <= this.Length); return default(bool); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public bool StartsWith(String value, StringComparison comparisonType) { Contract.Requires(value != null); Contract.Requires(Enum.IsDefined(typeof(StringComparison), comparisonType)); Contract.Ensures(!Contract.Result<bool>() || value.Length <= this.Length); return default(bool); } #if !SILVERLIGHT [Pure] [Reads(ReadsAttribute.Reads.Owned)] public bool StartsWith(String value, bool ignoreCase, CultureInfo culture) { Contract.Requires(value != null); Contract.Ensures(!Contract.Result<bool>() || value.Length <= this.Length); return default(bool); } #endif [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String PadRight(int totalWidth) { Contract.Requires(totalWidth >= 0); Contract.Ensures(Contract.Result<string>().Length == totalWidth); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String PadRight(int totalWidth, char paddingChar) { Contract.Requires(totalWidth >= 0); Contract.Ensures(Contract.Result<string>().Length == totalWidth); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String PadLeft(int totalWidth, char paddingChar) { Contract.Requires(totalWidth >= 0); Contract.Ensures(Contract.Result<string>().Length == totalWidth); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String PadLeft(int totalWidth) { Contract.Requires(totalWidth >= 0); Contract.Ensures(Contract.Result<string>().Length == totalWidth); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOf(char value) { Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOf(String value) { Contract.Requires(value != null); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOf(char value, int startIndex) { Contract.Requires(this == Empty || startIndex >= 0); Contract.Requires(this == Empty || startIndex < this.Length); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOf(String value, int startIndex) { Contract.Requires(value != null); Contract.Requires(this == Empty || startIndex >= 0); Contract.Requires(this == Empty || startIndex < this.Length); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOf(String value, StringComparison comparisonType) { Contract.Requires(value != null); Contract.Requires(Enum.IsDefined(typeof(StringComparison), comparisonType)); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOf(char value, int startIndex, int count) { Contract.Requires(this == String.Empty || startIndex >= 0); Contract.Requires(this == String.Empty || count >= 0); Contract.Requires(this == String.Empty || startIndex + 1 - count >= 0); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() <= startIndex - count); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOf(String value, int startIndex, int count) { Contract.Requires(value != null); Contract.Requires(this == String.Empty || startIndex >= 0); Contract.Requires(this == String.Empty || count >= 0); Contract.Requires(this == String.Empty || startIndex < this.Length); Contract.Requires(this == String.Empty || startIndex + 1 - count >= 0); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOf(String value, int startIndex, StringComparison comparisonType) { Contract.Requires(value != null); Contract.Requires(this == String.Empty || startIndex >= 0); Contract.Requires(this == String.Empty || startIndex < this.Length); Contract.Requires(Enum.IsDefined(typeof(StringComparison), comparisonType)); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOf(String value, int startIndex, int count, StringComparison comparisonType) { Contract.Requires(value != null); Contract.Requires(this == String.Empty || startIndex >= 0); Contract.Requires(this == String.Empty || count >= 0); Contract.Requires(this == String.Empty || startIndex < this.Length); Contract.Requires(this == String.Empty || startIndex + 1 - count >= 0); Contract.Requires(Enum.IsDefined(typeof(StringComparison), comparisonType)); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOfAny(char[] anyOf) { Contract.Requires(anyOf != null); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOfAny(char[] anyOf, int startIndex) { Contract.Requires(anyOf != null); Contract.Requires(this == String.Empty || startIndex >= 0); Contract.Requires(this == String.Empty || startIndex < Length); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() <= Length); Contract.Ensures(Contract.Result<int>() == -1 || Contract.Result<int>() >= startIndex); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOfAny(char[] anyOf, int startIndex, int count) { Contract.Requires(anyOf != null); Contract.Requires(this == String.Empty || startIndex >= 0); Contract.Requires(this == String.Empty || startIndex < this.Length); Contract.Requires(this == String.Empty || count >= 0); Contract.Requires(this == String.Empty || startIndex - count >= 0); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() <= startIndex); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int IndexOf(char value) { Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int IndexOf(String value) { Contract.Requires(value != null); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() == -1 || Contract.Result<int>() <= Length - value.Length); return default(int); } // F: Funny enough the IndexOf* family do not have the special case for the empty string... [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int IndexOf(char value, int startIndex) { Contract.Requires(startIndex >= 0); Contract.Requires(startIndex <= Length); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() == -1 || Contract.Result<int>() >= startIndex); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int IndexOf(String value, int startIndex) { Contract.Requires(value != null); Contract.Requires(startIndex >= 0); Contract.Requires(startIndex <= Length); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(value == String.Empty || Contract.Result<int>() < Length); Contract.Ensures(Contract.Result<int>() == -1 || Contract.Result<int>() >= startIndex); Contract.Ensures(value != String.Empty || Contract.Result<int>() == startIndex); return default(int); } [Pure] public int IndexOf(String value, StringComparison comparisonType) { Contract.Requires(value != null); Contract.Requires(Enum.IsDefined(typeof(StringComparison), comparisonType)); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() == -1 || Contract.Result<int>() <= Length - value.Length); Contract.Ensures(value != String.Empty || Contract.Result<int>() == 0); return default(int); } [Pure] public int IndexOf(char value, int startIndex, int count) { Contract.Requires(startIndex >= 0); Contract.Requires(count >= 0); Contract.Requires(startIndex + count <= Length); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < startIndex + count); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int IndexOf(String value, int startIndex, int count) { Contract.Requires(value != null); Contract.Requires(startIndex >= 0); Contract.Requires(count >= 0); Contract.Requires(startIndex + count <= Length); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(value == String.Empty || Contract.Result<int>() < startIndex + count); Contract.Ensures(Contract.Result<int>() == -1 || Contract.Result<int>() >= startIndex); Contract.Ensures(value != String.Empty || Contract.Result<int>() == startIndex); return default(int); } [Pure] public int IndexOf(String value, int startIndex, StringComparison comparisonType) { Contract.Requires(value != null); Contract.Requires(startIndex >= 0); Contract.Requires(startIndex <= Length); Contract.Requires(Enum.IsDefined(typeof(StringComparison), comparisonType)); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(value == String.Empty || Contract.Result<int>() < Length); Contract.Ensures(Contract.Result<int>() == -1 || Contract.Result<int>() >= startIndex); Contract.Ensures(value != String.Empty || Contract.Result<int>() == startIndex); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int IndexOf(String value, int startIndex, int count, StringComparison comparisonType) { Contract.Requires(value != null); Contract.Requires(startIndex >= 0); Contract.Requires(count >= 0); Contract.Requires(startIndex + count <= Length); Contract.Requires(Enum.IsDefined(typeof(StringComparison), comparisonType)); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(value == String.Empty || Contract.Result<int>() < startIndex + count); Contract.Ensures(Contract.Result<int>() == -1 || Contract.Result<int>() >= startIndex); Contract.Ensures(value != String.Empty || Contract.Result<int>() == startIndex); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int IndexOfAny(char[] anyOf) { Contract.Requires(anyOf != null); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int IndexOfAny(char[] anyOf, int startIndex) { Contract.Requires(anyOf != null); Contract.Requires(startIndex >= 0); Contract.Requires(startIndex <= Length); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int IndexOfAny(char[] anyOf, int startIndex, int count) { Contract.Requires(anyOf != null); Contract.Requires(startIndex >= 0); Contract.Requires(count >= 0); Contract.Requires(startIndex + count <= Length); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } public static readonly string/*!*/ Empty; [Pure] [Reads(ReadsAttribute.Reads.Owned)] public bool EndsWith(String value) { Contract.Requires(value != null); Contract.Ensures(!Contract.Result<bool>() || value.Length <= this.Length); return default(bool); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public bool EndsWith(String value, StringComparison comparisonType) { Contract.Requires(value != null); Contract.Requires(Enum.IsDefined(typeof(StringComparison), comparisonType)); Contract.Ensures(!Contract.Result<bool>() || this.Length >= value.Length); return default(bool); } #if !SILVERLIGHT [Pure] [Reads(ReadsAttribute.Reads.Owned)] public bool EndsWith(String value, bool ignoreCase, CultureInfo culture) { Contract.Requires(value != null); Contract.Ensures(!Contract.Result<bool>() || this.Length >= value.Length); return default(bool); } #endif [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static int CompareOrdinal(String strA, String strB) { return default(int); } [Pure] public static int CompareOrdinal(String strA, int indexA, String strB, int indexB, int length) { Contract.Requires(indexA >= 0); Contract.Requires(indexB >= 0); Contract.Requires(length >= 0); // From the documentation (and a quick test) one can derive that == is admissible Contract.Requires(indexA <= strA.Length); Contract.Requires(indexB <= strB.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static int Compare(String strA, String strB) { return default(int); } #if !SILVERLIGHT [Pure] public static int Compare(String strA, int indexA, String strB, int indexB, int length, bool ignoreCase, System.Globalization.CultureInfo culture) { Contract.Requires(culture != null); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static int Compare(String strA, int indexA, String strB, int indexB, int length, bool ignoreCase) { Contract.Requires(indexA >= 0); Contract.Requires(indexB >= 0); Contract.Requires(length >= 0); Contract.Requires(indexA <= strA.Length); Contract.Requires(indexB <= strB.Length); Contract.Requires((strA != null && strB != null) || length == 0); return default(int); } #endif [Pure] public static int Compare(String strA, int indexA, String strB, int indexB, int length, CultureInfo culture, CompareOptions options) { Contract.Requires(culture != null); return default(int); } [Pure] public static int Compare(string strA, string strB, StringComparison comparisonType) { return default(int); } [Pure] public static int Compare(string strA, int indexA, string strB, int indexB, int length, StringComparison comparisonType) { Contract.Requires(indexA >= 0); Contract.Requires(indexB >= 0); Contract.Requires(length >= 0); Contract.Requires(indexA <= strA.Length); Contract.Requires(indexB <= strB.Length); Contract.Requires((strA != null && strB != null) || length == 0); Contract.Requires(Enum.IsDefined(typeof(StringComparison), comparisonType)); return default(int); } [Pure] public static int Compare(String strA, String strB, CultureInfo culture, CompareOptions options) { Contract.Requires(culture != null); return default(int); } [Pure] public static int Compare(String strA, int indexA, String strB, int indexB, int length) { Contract.Requires(indexA >= 0); Contract.Requires(indexB >= 0); Contract.Requires(length >= 0); Contract.Requires(indexA <= strA.Length); Contract.Requires(indexB <= strB.Length); Contract.Requires((strA != null && strB != null) || length == 0); return default(int); } #if !SILVERLIGHT [Pure] public static int Compare(String strA, String strB, bool ignoreCase, System.Globalization.CultureInfo culture) { Contract.Requires(culture != null); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static int Compare(String strA, String strB, bool ignoreCase) { return default(int); } #endif [Pure] public bool Contains(string value) { Contract.Requires(value != null); Contract.Ensures(!Contract.Result<bool>() || this.Length >= value.Length); return default(bool); } public String(char c, int count) { Contract.Ensures(this.Length == count); } public String(char[] array) { Contract.Ensures(array != null || this.Length == 0); Contract.Ensures(array == null || this.Length == array.Length); } public String(char[] value, int startIndex, int length) { Contract.Requires(value != null); Contract.Requires(startIndex >= 0); Contract.Requires(length >= 0); Contract.Requires(startIndex + length <= value.Length); Contract.Ensures(this.Length == length); } /* These should all be pointer arguments return default(String); } public String (ref SByte arg0, int arg1, int arg2, System.Text.Encoding arg3) { return default(String); } public String (ref SByte arg0, int arg1, int arg2) { return default(String); } public String (ref SByte arg0) { return default(String); } public String (ref char arg0, int arg1, int arg2) { return default(String); } public String (ref char arg0) { return default(String); } */ [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String TrimEnd(params char[] trimChars) { Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String TrimStart(params char[] trimChars) { Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String Trim(params char[] trimChars) { Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String Substring(int startIndex, int length) { Contract.Requires(0 <= startIndex); Contract.Requires(0 <= length); Contract.Requires(startIndex <= this.Length ); Contract.Requires(startIndex <= this.Length - length); Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<string>().Length == length); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String Substring(int startIndex) { Contract.Requires(0 <= startIndex); Contract.Requires(startIndex <= this.Length); Contract.Ensures(Contract.Result<string>().Length == this.Length - startIndex); Contract.Ensures(Contract.Result<String>() != null); return default(String); } #if !SILVERLIGHT [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String[] Split(char[] arg0, int arg1) { Contract.Ensures(Contract.Result<String[]>() != null); Contract.Ensures(Contract.Result<String[]>().Length >= 1); Contract.Ensures(Contract.Result<String[]>()[0].Length <= this.Length); Contract.Ensures(Contract.ForAll(0, Contract.Result<string[]>().Length, i => Contract.Result<string[]>()[i] != null)); return default(String[]); } #endif [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String[] Split(char[] separator) { Contract.Ensures(Contract.Result<String[]>() != null); Contract.Ensures(Contract.Result<String[]>().Length >= 1); Contract.Ensures(Contract.Result<String[]>()[0].Length <= this.Length); Contract.Ensures(Contract.ForAll(0, Contract.Result<string[]>().Length, i => Contract.Result<string[]>()[i] != null)); return default(String[]); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public string[] Split(char[] separator, StringSplitOptions options) { Contract.Ensures(Contract.Result<string[]>() != null); Contract.Ensures(Contract.ForAll(0, Contract.Result<string[]>().Length, i => Contract.Result<string[]>()[i] != null)); return default(string[]); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public string[] Split(string[] separator, StringSplitOptions options) { Contract.Ensures(Contract.Result<string[]>() != null); Contract.Ensures(Contract.ForAll(0, Contract.Result<string[]>().Length, i => Contract.Result<string[]>()[i] != null)); return default(string[]); } #if !SILVERLIGHT [Pure] [Reads(ReadsAttribute.Reads.Owned)] public string[] Split(char[] separator, int count, StringSplitOptions options) { Contract.Ensures(Contract.Result<string[]>() != null); Contract.Ensures(Contract.ForAll(0, Contract.Result<string[]>().Length, i => Contract.Result<string[]>()[i] != null)); return default(string[]); } #endif #if !SILVERLIGHT_4_0_WP [Pure] [Reads(ReadsAttribute.Reads.Owned)] #if !SILVERLIGHT public #else internal #endif string[] Split(string[] separator, int count, StringSplitOptions options) { Contract.Ensures(Contract.Result<string[]>() != null); Contract.Ensures(Contract.ForAll(0, Contract.Result<string[]>().Length, i => Contract.Result<string[]>()[i] != null)); return default(string[]); } #endif #if !SILVERLIGHT [Pure] [Reads(ReadsAttribute.Reads.Owned)] public char[] ToCharArray(int startIndex, int length) { Contract.Requires(startIndex >= 0); Contract.Requires(startIndex <= this.Length); Contract.Requires(startIndex + length <= this.Length); Contract.Requires(length >= 0); Contract.Ensures(Contract.Result<char[]>() != null); return default(char[]); } #endif [Pure] [Reads(ReadsAttribute.Reads.Owned)] public char[] ToCharArray() { Contract.Ensures(Contract.Result<char[]>() != null); return default(char[]); } public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { Contract.Requires(destination != null); Contract.Requires(count >= 0); Contract.Requires(sourceIndex >= 0); Contract.Requires(count <= (this.Length - sourceIndex)); Contract.Requires(destinationIndex <= (destination.Length - count)); Contract.Requires(destinationIndex >= 0); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static bool operator !=(String a, String b) { return default(bool); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static bool operator ==(String a, String b) { return default(bool); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static bool Equals(String a, String b) { Contract.Ensures((object)a != (object)b || Contract.Result<bool>()); return default(bool); } [Pure] public virtual bool Equals(String arg0) { Contract.Ensures((object)this != (object)arg0 || Contract.Result<bool>()); return default(bool); } [Pure] public bool Equals(String value, StringComparison comparisonType) { return default(bool); } [Pure] public static bool Equals(String a, String b, StringComparison comparisonType) { return default(bool); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Join(String separator, String[] value, int startIndex, int count) { Contract.Requires(value != null); Contract.Requires(startIndex >= 0); Contract.Requires(count >= 0); Contract.Requires(startIndex + count <= value.Length); Contract.Ensures(Contract.Result<string>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Join(String separator, String[] value) { Contract.Requires(value != null); Contract.Ensures(Contract.Result<string>() != null); return default(String); } #if NETFRAMEWORK_4_0 || NETFRAMEWORK_4_5 [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Join(String separator, Object[] value) { Contract.Requires(value != null); Contract.Ensures(Contract.Result<string>() != null); return default(String); } [Pure] public static string Join(string separator, IEnumerable<string> values) { Contract.Requires(values != null); Contract.Ensures(Contract.Result<string>() != null); return default(String); } [Pure] public static string Join<T>(string separator, IEnumerable<T> values) { Contract.Requires(values != null); Contract.Ensures(Contract.Result<string>() != null); return default(String); } #endif [Pure] public static bool IsNullOrEmpty(string str) { Contract.Ensures( Contract.Result<bool>() && (str == null || str.Length == 0) || !Contract.Result<bool>() && str != null && str.Length > 0); #if NETFRAMEWORK_4_5 || NETFRAMEWORK_4_0 || SILVERLIGHT_4_0 || SILVERLIGHT_5_0 Contract.Ensures(!Contract.Result<bool>() || IsNullOrWhiteSpace(str)); #endif return default(bool); } #if NETFRAMEWORK_4_5 || NETFRAMEWORK_4_0 || SILVERLIGHT_4_0 || SILVERLIGHT_5_0 [Pure] public static bool IsNullOrWhiteSpace(string str) { Contract.Ensures(Contract.Result<bool>() && (str == null || str.Length == 0) || !Contract.Result<bool>() && str != null && str.Length > 0); return default(bool); } #endif } }
// 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.Http.Headers; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using CURLAUTH = Interop.Http.CURLAUTH; using CURLcode = Interop.Http.CURLcode; using CURLoption = Interop.Http.CURLoption; using CurlProtocols = Interop.Http.CurlProtocols; using CURLProxyType = Interop.Http.curl_proxytype; using SafeCurlHandle = Interop.Http.SafeCurlHandle; using SafeCurlSListHandle = Interop.Http.SafeCurlSListHandle; using SafeCallbackHandle = Interop.Http.SafeCallbackHandle; using SeekCallback = Interop.Http.SeekCallback; using ReadWriteCallback = Interop.Http.ReadWriteCallback; using ReadWriteFunction = Interop.Http.ReadWriteFunction; using SslCtxCallback = Interop.Http.SslCtxCallback; using DebugCallback = Interop.Http.DebugCallback; namespace System.Net.Http { internal partial class CurlHandler : HttpMessageHandler { private sealed class EasyRequest : TaskCompletionSource<HttpResponseMessage> { internal readonly CurlHandler _handler; internal readonly HttpRequestMessage _requestMessage; internal readonly CurlResponseMessage _responseMessage; internal readonly CancellationToken _cancellationToken; internal readonly HttpContentAsyncStream _requestContentStream; internal SafeCurlHandle _easyHandle; private SafeCurlSListHandle _requestHeaders; internal MultiAgent _associatedMultiAgent; internal SendTransferState _sendTransferState; internal bool _isRedirect = false; internal Uri _targetUri; private SafeCallbackHandle _callbackHandle; public EasyRequest(CurlHandler handler, HttpRequestMessage requestMessage, CancellationToken cancellationToken) : base(TaskCreationOptions.RunContinuationsAsynchronously) { _handler = handler; _requestMessage = requestMessage; _cancellationToken = cancellationToken; if (requestMessage.Content != null) { _requestContentStream = new HttpContentAsyncStream(requestMessage.Content); } _responseMessage = new CurlResponseMessage(this); _targetUri = requestMessage.RequestUri; } /// <summary> /// Initialize the underlying libcurl support for this EasyRequest. /// This is separated out of the constructor so that we can take into account /// any additional configuration needed based on the request message /// after the EasyRequest is configured and so that error handling /// can be better handled in the caller. /// </summary> internal void InitializeCurl() { // Create the underlying easy handle SafeCurlHandle easyHandle = Interop.Http.EasyCreate(); if (easyHandle.IsInvalid) { throw new OutOfMemoryException(); } _easyHandle = easyHandle; // Configure the handle SetUrl(); SetMultithreading(); SetRedirection(); SetVerb(); SetVersion(); SetDecompressionOptions(); SetProxyOptions(_requestMessage.RequestUri); SetCredentialsOptions(_handler.GetCredentials(_requestMessage.RequestUri)); SetCookieOption(_requestMessage.RequestUri); SetRequestHeaders(); SetSslOptions(); } public void EnsureResponseMessagePublished() { // If the response message hasn't been published yet, do any final processing of it before it is. if (!Task.IsCompleted) { // On Windows, if the response was automatically decompressed, Content-Encoding and Content-Length // headers are removed from the response. Do the same thing here. DecompressionMethods dm = _handler.AutomaticDecompression; if (dm != DecompressionMethods.None) { HttpContentHeaders contentHeaders = _responseMessage.Content.Headers; IEnumerable<string> encodings; if (contentHeaders.TryGetValues(HttpKnownHeaderNames.ContentEncoding, out encodings)) { foreach (string encoding in encodings) { if (((dm & DecompressionMethods.GZip) != 0 && string.Equals(encoding, EncodingNameGzip, StringComparison.OrdinalIgnoreCase)) || ((dm & DecompressionMethods.Deflate) != 0 && string.Equals(encoding, EncodingNameDeflate, StringComparison.OrdinalIgnoreCase))) { contentHeaders.Remove(HttpKnownHeaderNames.ContentEncoding); contentHeaders.Remove(HttpKnownHeaderNames.ContentLength); break; } } } } } // Now ensure it's published. bool result = TrySetResult(_responseMessage); Debug.Assert(result || Task.Status == TaskStatus.RanToCompletion, "If the task was already completed, it should have been completed successfully; " + "we shouldn't be completing as successful after already completing as failed."); } public void FailRequest(Exception error) { Debug.Assert(error != null, "Expected non-null exception"); var oce = error as OperationCanceledException; if (oce != null) { TrySetCanceled(oce.CancellationToken); } else { if (error is IOException || error is CurlException || error == null) { error = CreateHttpRequestException(error); } TrySetException(error); } // There's not much we can reasonably assert here about the result of TrySet*. // It's possible that the task wasn't yet completed (e.g. a failure while initiating the request), // it's possible that the task was already completed as success (e.g. a failure sending back the response), // and it's possible that the task was already completed as failure (e.g. we handled the exception and // faulted the task, but then tried to fault it again while finishing processing in the main loop). // Make sure the exception is available on the response stream so that it's propagated // from any attempts to read from the stream. _responseMessage.ResponseStream.SignalComplete(error); } public void Cleanup() // not called Dispose because the request may still be in use after it's cleaned up { _responseMessage.ResponseStream.SignalComplete(); // No more callbacks so no more data // Don't dispose of the ResponseMessage.ResponseStream as it may still be in use // by code reading data stored in the stream. // Dispose of the input content stream if there was one. Nothing should be using it any more. if (_requestContentStream != null) _requestContentStream.Dispose(); // Dispose of the underlying easy handle. We're no longer processing it. if (_easyHandle != null) _easyHandle.Dispose(); // Dispose of the request headers if we had any. We had to keep this handle // alive as long as the easy handle was using it. We didn't need to do any // ref counting on the safe handle, though, as the only processing happens // in Process, which ensures the handle will be rooted while libcurl is // doing any processing that assumes it's valid. if (_requestHeaders != null) _requestHeaders.Dispose(); if (_callbackHandle != null) _callbackHandle.Dispose(); } private void SetUrl() { EventSourceTrace("Url: {0}", _requestMessage.RequestUri); SetCurlOption(CURLoption.CURLOPT_URL, _requestMessage.RequestUri.AbsoluteUri); SetCurlOption(CURLoption.CURLOPT_PROTOCOLS, (long)(CurlProtocols.CURLPROTO_HTTP | CurlProtocols.CURLPROTO_HTTPS)); } private void SetMultithreading() { SetCurlOption(CURLoption.CURLOPT_NOSIGNAL, 1L); } private void SetRedirection() { if (!_handler._automaticRedirection) { return; } SetCurlOption(CURLoption.CURLOPT_FOLLOWLOCATION, 1L); CurlProtocols redirectProtocols = string.Equals(_requestMessage.RequestUri.Scheme, UriSchemeHttps, StringComparison.OrdinalIgnoreCase) ? CurlProtocols.CURLPROTO_HTTPS : // redirect only to another https CurlProtocols.CURLPROTO_HTTP | CurlProtocols.CURLPROTO_HTTPS; // redirect to http or to https SetCurlOption(CURLoption.CURLOPT_REDIR_PROTOCOLS, (long)redirectProtocols); SetCurlOption(CURLoption.CURLOPT_MAXREDIRS, _handler._maxAutomaticRedirections); EventSourceTrace("Max automatic redirections: {0}", _handler._maxAutomaticRedirections); } private void SetVerb() { EventSourceTrace<string>("Verb: {0}", _requestMessage.Method.Method); if (_requestMessage.Method == HttpMethod.Put) { SetCurlOption(CURLoption.CURLOPT_UPLOAD, 1L); if (_requestMessage.Content == null) { SetCurlOption(CURLoption.CURLOPT_INFILESIZE, 0L); } } else if (_requestMessage.Method == HttpMethod.Head) { SetCurlOption(CURLoption.CURLOPT_NOBODY, 1L); } else if (_requestMessage.Method == HttpMethod.Post) { SetCurlOption(CURLoption.CURLOPT_POST, 1L); if (_requestMessage.Content == null) { SetCurlOption(CURLoption.CURLOPT_POSTFIELDSIZE, 0L); SetCurlOption(CURLoption.CURLOPT_COPYPOSTFIELDS, string.Empty); } } else if (_requestMessage.Method == HttpMethod.Trace) { SetCurlOption(CURLoption.CURLOPT_CUSTOMREQUEST, _requestMessage.Method.Method); SetCurlOption(CURLoption.CURLOPT_NOBODY, 1L); } else { SetCurlOption(CURLoption.CURLOPT_CUSTOMREQUEST, _requestMessage.Method.Method); if (_requestMessage.Content != null) { SetCurlOption(CURLoption.CURLOPT_UPLOAD, 1L); } } } private void SetVersion() { Version v = _requestMessage.Version; if (v != null) { // Try to use the requested version, if a known version was explicitly requested. // If an unknown version was requested, we simply use libcurl's default. var curlVersion = (v.Major == 1 && v.Minor == 1) ? Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_1_1 : (v.Major == 1 && v.Minor == 0) ? Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_1_0 : (v.Major == 2 && v.Minor == 0) ? Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_2_0 : Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_NONE; if (curlVersion != Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_NONE) { // Ask libcurl to use the specified version if possible. CURLcode c = Interop.Http.EasySetOptionLong(_easyHandle, CURLoption.CURLOPT_HTTP_VERSION, (long)curlVersion); if (c == CURLcode.CURLE_OK) { // Success. The requested version will be used. EventSourceTrace("HTTP version: {0}", v); } else if (c == CURLcode.CURLE_UNSUPPORTED_PROTOCOL) { // The requested version is unsupported. Fall back to using the default version chosen by libcurl. EventSourceTrace("Unsupported protocol: {0}", v); } else { // Some other error. Fail. ThrowIfCURLEError(c); } } } } private void SetDecompressionOptions() { if (!_handler.SupportsAutomaticDecompression) { return; } DecompressionMethods autoDecompression = _handler.AutomaticDecompression; bool gzip = (autoDecompression & DecompressionMethods.GZip) != 0; bool deflate = (autoDecompression & DecompressionMethods.Deflate) != 0; if (gzip || deflate) { string encoding = (gzip && deflate) ? EncodingNameGzip + "," + EncodingNameDeflate : gzip ? EncodingNameGzip : EncodingNameDeflate; SetCurlOption(CURLoption.CURLOPT_ACCEPT_ENCODING, encoding); EventSourceTrace<string>("Encoding: {0}", encoding); } } internal void SetProxyOptions(Uri requestUri) { if (!_handler._useProxy) { // Explicitly disable the use of a proxy. This will prevent libcurl from using // any proxy, including ones set via environment variable. SetCurlOption(CURLoption.CURLOPT_PROXY, string.Empty); EventSourceTrace("UseProxy false, disabling proxy"); return; } if (_handler.Proxy == null) { // UseProxy was true, but Proxy was null. Let libcurl do its default handling, // which includes checking the http_proxy environment variable. EventSourceTrace("UseProxy true, Proxy null, using default proxy"); return; } // Custom proxy specified. Uri proxyUri; try { // Should we bypass a proxy for this URI? if (_handler.Proxy.IsBypassed(requestUri)) { SetCurlOption(CURLoption.CURLOPT_PROXY, string.Empty); EventSourceTrace("Proxy's IsBypassed returned true, bypassing proxy"); return; } // Get the proxy Uri for this request. proxyUri = _handler.Proxy.GetProxy(requestUri); if (proxyUri == null) { EventSourceTrace("GetProxy returned null, using default."); return; } } catch (PlatformNotSupportedException) { // WebRequest.DefaultWebProxy throws PlatformNotSupportedException, // in which case we should use the default rather than the custom proxy. EventSourceTrace("PlatformNotSupportedException from proxy, using default"); return; } // Configure libcurl with the gathered proxy information SetCurlOption(CURLoption.CURLOPT_PROXYTYPE, (long)CURLProxyType.CURLPROXY_HTTP); SetCurlOption(CURLoption.CURLOPT_PROXY, proxyUri.AbsoluteUri); SetCurlOption(CURLoption.CURLOPT_PROXYPORT, proxyUri.Port); EventSourceTrace("Proxy: {0}", proxyUri); KeyValuePair<NetworkCredential, CURLAUTH> credentialScheme = GetCredentials(proxyUri, _handler.Proxy.Credentials, AuthTypesPermittedByCredentialKind(_handler.Proxy.Credentials)); NetworkCredential credentials = credentialScheme.Key; if (credentials == CredentialCache.DefaultCredentials) { // No "default credentials" on Unix; nop just like UseDefaultCredentials. EventSourceTrace("Default proxy credentials. Skipping."); } else if (credentials != null) { if (string.IsNullOrEmpty(credentials.UserName)) { throw new ArgumentException(SR.net_http_argument_empty_string, "UserName"); } string credentialText = string.IsNullOrEmpty(credentials.Domain) ? string.Format("{0}:{1}", credentials.UserName, credentials.Password) : string.Format("{2}\\{0}:{1}", credentials.UserName, credentials.Password, credentials.Domain); EventSourceTrace("Proxy credentials set."); SetCurlOption(CURLoption.CURLOPT_PROXYUSERPWD, credentialText); } } internal void SetCredentialsOptions(KeyValuePair<NetworkCredential, CURLAUTH> credentialSchemePair) { if (credentialSchemePair.Key == null) { return; } NetworkCredential credentials = credentialSchemePair.Key; CURLAUTH authScheme = credentialSchemePair.Value; string userName = string.IsNullOrEmpty(credentials.Domain) ? credentials.UserName : string.Format("{0}\\{1}", credentials.Domain, credentials.UserName); SetCurlOption(CURLoption.CURLOPT_USERNAME, userName); SetCurlOption(CURLoption.CURLOPT_HTTPAUTH, (long)authScheme); if (credentials.Password != null) { SetCurlOption(CURLoption.CURLOPT_PASSWORD, credentials.Password); } EventSourceTrace("Credentials set."); } internal void SetCookieOption(Uri uri) { if (!_handler._useCookie) { return; } string cookieValues = _handler.CookieContainer.GetCookieHeader(uri); if (!string.IsNullOrEmpty(cookieValues)) { SetCurlOption(CURLoption.CURLOPT_COOKIE, cookieValues); EventSourceTrace<string>("Cookies: {0}", cookieValues); } } internal void SetRequestHeaders() { HttpContentHeaders contentHeaders = null; if (_requestMessage.Content != null) { SetChunkedModeForSend(_requestMessage); // TODO: Content-Length header isn't getting correctly placed using ToString() // This is a bug in HttpContentHeaders that needs to be fixed. if (_requestMessage.Content.Headers.ContentLength.HasValue) { long contentLength = _requestMessage.Content.Headers.ContentLength.Value; _requestMessage.Content.Headers.ContentLength = null; _requestMessage.Content.Headers.ContentLength = contentLength; } contentHeaders = _requestMessage.Content.Headers; } var slist = new SafeCurlSListHandle(); // Add request and content request headers if (_requestMessage.Headers != null) { AddRequestHeaders(_requestMessage.Headers, slist); } if (contentHeaders != null) { AddRequestHeaders(contentHeaders, slist); if (contentHeaders.ContentType == null) { if (!Interop.Http.SListAppend(slist, NoContentType)) { throw CreateHttpRequestException(new CurlException((int)CURLcode.CURLE_OUT_OF_MEMORY, isMulti: false)); } } } // Since libcurl always adds a Transfer-Encoding header, we need to explicitly block // it if caller specifically does not want to set the header if (_requestMessage.Headers.TransferEncodingChunked.HasValue && !_requestMessage.Headers.TransferEncodingChunked.Value) { if (!Interop.Http.SListAppend(slist, NoTransferEncoding)) { throw CreateHttpRequestException(new CurlException((int)CURLcode.CURLE_OUT_OF_MEMORY, isMulti: false)); } } if (!slist.IsInvalid) { _requestHeaders = slist; SetCurlOption(CURLoption.CURLOPT_HTTPHEADER, slist); } else { slist.Dispose(); } } private void SetSslOptions() { // SSL Options should be set regardless of the type of the original request, // in case an http->https redirection occurs. // // While this does slow down the theoretical best path of the request the code // to decide that we need to register the callback is more complicated than, and // potentially more expensive than, just always setting the callback. SslProvider.SetSslOptions(this, _handler.ClientCertificateOptions); } internal void SetCurlCallbacks( IntPtr easyGCHandle, ReadWriteCallback receiveHeadersCallback, ReadWriteCallback sendCallback, SeekCallback seekCallback, ReadWriteCallback receiveBodyCallback, DebugCallback debugCallback) { if (_callbackHandle == null) { _callbackHandle = new SafeCallbackHandle(); } // Add callback for processing headers Interop.Http.RegisterReadWriteCallback( _easyHandle, ReadWriteFunction.Header, receiveHeadersCallback, easyGCHandle, ref _callbackHandle); // If we're sending data as part of the request, add callbacks for sending request data if (_requestMessage.Content != null) { Interop.Http.RegisterReadWriteCallback( _easyHandle, ReadWriteFunction.Read, sendCallback, easyGCHandle, ref _callbackHandle); Interop.Http.RegisterSeekCallback( _easyHandle, seekCallback, easyGCHandle, ref _callbackHandle); } // If we're expecting any data in response, add a callback for receiving body data if (_requestMessage.Method != HttpMethod.Head) { Interop.Http.RegisterReadWriteCallback( _easyHandle, ReadWriteFunction.Write, receiveBodyCallback, easyGCHandle, ref _callbackHandle); } if (EventSourceTracingEnabled) { SetCurlOption(CURLoption.CURLOPT_VERBOSE, 1L); CURLcode curlResult = Interop.Http.RegisterDebugCallback( _easyHandle, debugCallback, easyGCHandle, ref _callbackHandle); if (curlResult != CURLcode.CURLE_OK) { EventSourceTrace("Failed to register debug callback."); } } } internal CURLcode SetSslCtxCallback(SslCtxCallback callback, IntPtr userPointer) { if (_callbackHandle == null) { _callbackHandle = new SafeCallbackHandle(); } CURLcode result = Interop.Http.RegisterSslCtxCallback(_easyHandle, callback, userPointer, ref _callbackHandle); return result; } private static void AddRequestHeaders(HttpHeaders headers, SafeCurlSListHandle handle) { foreach (KeyValuePair<string, IEnumerable<string>> header in headers) { string headerValue = headers.GetHeaderString(header.Key); string headerKeyAndValue = string.IsNullOrEmpty(headerValue) ? header.Key + ";" : // semicolon used by libcurl to denote empty value that should be sent header.Key + ": " + headerValue; if (!Interop.Http.SListAppend(handle, headerKeyAndValue)) { throw CreateHttpRequestException(new CurlException((int)CURLcode.CURLE_OUT_OF_MEMORY, isMulti: false)); } } } internal void SetCurlOption(CURLoption option, string value) { ThrowIfCURLEError(Interop.Http.EasySetOptionString(_easyHandle, option, value)); } internal void SetCurlOption(CURLoption option, long value) { ThrowIfCURLEError(Interop.Http.EasySetOptionLong(_easyHandle, option, value)); } internal void SetCurlOption(CURLoption option, IntPtr value) { ThrowIfCURLEError(Interop.Http.EasySetOptionPointer(_easyHandle, option, value)); } internal void SetCurlOption(CURLoption option, SafeHandle value) { ThrowIfCURLEError(Interop.Http.EasySetOptionPointer(_easyHandle, option, value)); } internal sealed class SendTransferState { internal readonly byte[] _buffer = new byte[RequestBufferSize]; // PERF TODO: Determine if this should be optimized to start smaller and grow internal int _offset; internal int _count; internal Task<int> _task; internal void SetTaskOffsetCount(Task<int> task, int offset, int count) { Debug.Assert(offset >= 0, "Offset should never be negative"); Debug.Assert(count >= 0, "Count should never be negative"); Debug.Assert(offset <= count, "Offset should never be greater than count"); _task = task; _offset = offset; _count = count; } } internal void SetRedirectUri(Uri redirectUri) { _targetUri = _requestMessage.RequestUri; _requestMessage.RequestUri = redirectUri; } private void EventSourceTrace<TArg0>(string formatMessage, TArg0 arg0, [CallerMemberName] string memberName = null) { CurlHandler.EventSourceTrace(formatMessage, arg0, easy: this, memberName: memberName); } private void EventSourceTrace(string message, [CallerMemberName] string memberName = null) { CurlHandler.EventSourceTrace(message, easy: this, memberName: memberName); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Text.Tests { public class EncodingGetString { #region Positive Test Cases [Fact] public void PosTest1() { PositiveTestString(Encoding.UTF8, "TestString", new byte[] { 84, 101, 115, 116, 83, 116, 114, 105, 110, 103 }, "00A"); } [Fact] public void PosTest2() { PositiveTestString(Encoding.UTF8, "", new byte[] { }, "00B"); } [Fact] public void PosTest3() { PositiveTestString(Encoding.UTF8, "FooBA\u0400R", new byte[] { 70, 111, 111, 66, 65, 208, 128, 82 }, "00C"); } [Fact] public void PosTest4() { PositiveTestString(Encoding.UTF8, "\u00C0nima\u0300l", new byte[] { 195, 128, 110, 105, 109, 97, 204, 128, 108 }, "00D"); } [Fact] public void PosTest5() { PositiveTestString(Encoding.UTF8, "Test\uD803\uDD75Test", new byte[] { 84, 101, 115, 116, 240, 144, 181, 181, 84, 101, 115, 116 }, "00E"); } [Fact] public void PosTest6() { PositiveTestString(Encoding.UTF8, "\0Te\nst\0\t\0T\u000Fest\0", new byte[] { 0, 84, 101, 10, 115, 116, 0, 9, 0, 84, 15, 101, 115, 116, 0 }, "00F"); } [Fact] public void PosTest7() { PositiveTestString(Encoding.UTF8, "\uFFFDTest\uFFFD\uFFFD\u0130\uFFFDTest\uFFFD", new byte[] { 196, 84, 101, 115, 116, 196, 196, 196, 176, 176, 84, 101, 115, 116, 176 }, "00G"); } [Fact] public void PosTest8() { PositiveTestString(Encoding.UTF8, "TestTest", new byte[] { 84, 101, 115, 116, 84, 101, 115, 116 }, "00H"); } [Fact] public void PosTest9() { PositiveTestString(Encoding.UTF8, "\uFFFD", new byte[] { 176 }, "00I"); } [Fact] public void PosTest10() { PositiveTestString(Encoding.UTF8, "\uFFFD", new byte[] { 196 }, "00J"); } [Fact] public void PosTest11() { PositiveTestString(Encoding.UTF8, "\uD803\uDD75\uD803\uDD75\uD803\uDD75", new byte[] { 240, 144, 181, 181, 240, 144, 181, 181, 240, 144, 181, 181 }, "00K"); } [Fact] public void PosTest12() { PositiveTestString(Encoding.UTF8, "\u0130", new byte[] { 196, 176 }, "00L"); } [Fact] public void PosTest13() { PositiveTestString(Encoding.UTF8, "\uFFFD\uD803\uDD75\uD803\uDD75\uFFFD\uFFFD", new byte[] { 240, 240, 144, 181, 181, 240, 144, 181, 181, 240, 144, 240 }, "0A2"); } [Fact] public void PosTest14() { PositiveTestString(Encoding.Unicode, "TestString\uFFFD", new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 83, 0, 116, 0, 114, 0, 105, 0, 110, 0, 103, 0, 45 }, "00A3"); } [Fact] public void PosTest15() { PositiveTestString(Encoding.Unicode, "", new byte[] { }, "00B3"); } [Fact] public void PosTest16() { PositiveTestString(Encoding.Unicode, "FooBA\u0400R", new byte[] { 70, 0, 111, 0, 111, 0, 66, 0, 65, 0, 0, 4, 82, 0 }, "00C3"); } [Fact] public void PosTest17() { PositiveTestString(Encoding.Unicode, "\u00C0nima\u0300l", new byte[] { 192, 0, 110, 0, 105, 0, 109, 0, 97, 0, 0, 3, 108, 0 }, "00D3"); } [Fact] public void PosTest18() { PositiveTestString(Encoding.Unicode, "Test\uD803\uDD75Test", new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 3, 216, 117, 221, 84, 0, 101, 0, 115, 0, 116, 0 }, "00E3"); } [Fact] public void PosTest19() { PositiveTestString(Encoding.Unicode, "\0Te\nst\0\t\0T\u000Fest\0", new byte[] { 0, 0, 84, 0, 101, 0, 10, 0, 115, 0, 116, 0, 0, 0, 9, 0, 0, 0, 84, 0, 15, 0, 101, 0, 115, 0, 116, 0, 0, 0 }, "00F3"); } [Fact] public void PosTest20() { PositiveTestString(Encoding.Unicode, "TestTest", new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 84, 0, 101, 0, 115, 0, 116, 0 }, "00G3"); } [Fact] public void PosTest21() { PositiveTestString(Encoding.Unicode, "TestTest\uFFFD", new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 84, 0, 101, 0, 115, 0, 116, 0, 117, 221 }, "00H3"); } [Fact] public void PosTest22() { PositiveTestString(Encoding.Unicode, "TestTest\uFFFD", new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 84, 0, 101, 0, 115, 0, 116, 0, 3, 216 }, "00I3"); } [Fact] public void PosTest23() { PositiveTestString(Encoding.Unicode, "\uFFFD\uFFFD", new byte[] { 3, 216, 84 }, "00J3"); } [Fact] public void PosTest24() { PositiveTestString(Encoding.Unicode, "\uD803\uDD75\uD803\uDD75\uD803\uDD75", new byte[] { 3, 216, 117, 221, 3, 216, 117, 221, 3, 216, 117, 221 }, "00K3"); } [Fact] public void PosTest25() { PositiveTestString(Encoding.Unicode, "\u0130", new byte[] { 48, 1 }, "00L3"); } [Fact] public void PosTest26() { PositiveTestString(Encoding.Unicode, "\uD803\uDD75\uD803\uDD75", new byte[] { 3, 216, 117, 221, 3, 216, 117, 221 }, "0A23"); } [Fact] public void PosTest27() { PositiveTestString(Encoding.BigEndianUnicode, "TestString\uFFFD", new byte[] { 0, 84, 0, 101, 0, 115, 0, 116, 0, 83, 0, 116, 0, 114, 0, 105, 0, 110, 0, 103, 0 }, "00A4"); } [Fact] public void PosTest28() { PositiveTestString(Encoding.BigEndianUnicode, "", new byte[] { }, "00B4"); } [Fact] public void PosTest29() { PositiveTestString(Encoding.BigEndianUnicode, "FooBA\u0400R\uFFFD", new byte[] { 0, 70, 0, 111, 0, 111, 0, 66, 0, 65, 4, 0, 0, 82, 70 }, "00C4"); } [Fact] public void PosTest30() { PositiveTestString(Encoding.BigEndianUnicode, "\u00C0nima\u0300l", new byte[] { 0, 192, 0, 110, 0, 105, 0, 109, 0, 97, 3, 0, 0, 108 }, "00D4"); } [Fact] public void PosTest31() { PositiveTestString(Encoding.BigEndianUnicode, "Test\uD803\uDD75Test", new byte[] { 0, 84, 0, 101, 0, 115, 0, 116, 216, 3, 221, 117, 0, 84, 0, 101, 0, 115, 0, 116 }, "00E4"); } [Fact] public void PosTest32() { PositiveTestString(Encoding.BigEndianUnicode, "\0Te\nst\0\t\0T\u000Fest\0\uFFFD", new byte[] { 0, 0, 0, 84, 0, 101, 0, 10, 0, 115, 0, 116, 0, 0, 0, 9, 0, 0, 0, 84, 0, 15, 0, 101, 0, 115, 0, 116, 0, 0, 0 }, "00F4"); } [Fact] public void PosTest33() { PositiveTestString(Encoding.BigEndianUnicode, "TestTest", new byte[] { 0, 84, 0, 101, 0, 115, 0, 116, 0, 84, 0, 101, 0, 115, 0, 116 }, "00G4"); } [Fact] public void PosTest34() { PositiveTestString(Encoding.BigEndianUnicode, "TestTest\uFFFD", new byte[] { 0, 84, 0, 101, 0, 115, 0, 116, 0, 84, 0, 101, 0, 115, 0, 116, 221, 117 }, "00H4"); } [Fact] public void PosTest35() { PositiveTestString(Encoding.BigEndianUnicode, "TestTest\uFFFD", new byte[] { 0, 84, 0, 101, 0, 115, 0, 116, 0, 84, 0, 101, 0, 115, 0, 116, 216, 3 }, "00I4"); } [Fact] public void PosTest36() { PositiveTestString(Encoding.BigEndianUnicode, "\uFFFD\uFFFD", new byte[] { 216, 3, 48 }, "00J4"); } [Fact] public void PosTest37() { PositiveTestString(Encoding.BigEndianUnicode, "\uD803\uDD75\uD803\uDD75\uD803\uDD75", new byte[] { 216, 3, 221, 117, 216, 3, 221, 117, 216, 3, 221, 117 }, "00K4"); } [Fact] public void PosTest38() { PositiveTestString(Encoding.BigEndianUnicode, "\u0130", new byte[] { 1, 48 }, "00L4"); } [Fact] public void PosTest39() { PositiveTestString(Encoding.BigEndianUnicode, "\uD803\uDD75\uD803\uDD75", new byte[] { 216, 3, 221, 117, 216, 3, 221, 117 }, "0A24"); } #endregion #region Negative Test Cases [Fact] public void NegTest1() { NegativeTestChars2<ArgumentNullException>(new UTF8Encoding(), null, 0, 0, "00P"); } [Fact] public void NegTest2() { NegativeTestChars2<ArgumentOutOfRangeException>(new UTF8Encoding(), new byte[] { 0, 0 }, -1, 1, "00P"); } [Fact] public void NegTest3() { NegativeTestChars2<ArgumentOutOfRangeException>(new UTF8Encoding(), new byte[] { 0, 0 }, 1, -1, "00Q"); } [Fact] public void NegTest4() { NegativeTestChars2<ArgumentOutOfRangeException>(new UTF8Encoding(), new byte[] { 0, 0 }, 0, 10, "00R"); } [Fact] public void NegTest5() { NegativeTestChars2<ArgumentOutOfRangeException>(new UTF8Encoding(), new byte[] { 0, 0 }, 3, 0, "00S"); } [Fact] public void NegTest6() { NegativeTestChars2<ArgumentNullException>(new UnicodeEncoding(), null, 0, 0, "00P3"); } [Fact] public void NegTest7() { NegativeTestChars2<ArgumentOutOfRangeException>(new UnicodeEncoding(), new byte[] { 0, 0 }, -1, 1, "00P3"); } [Fact] public void NegTest8() { NegativeTestChars2<ArgumentOutOfRangeException>(new UnicodeEncoding(), new byte[] { 0, 0 }, 1, -1, "00Q3"); } [Fact] public void NegTest9() { NegativeTestChars2<ArgumentOutOfRangeException>(new UnicodeEncoding(), new byte[] { 0, 0 }, 0, 10, "00R3"); } [Fact] public void NegTest10() { NegativeTestChars2<ArgumentOutOfRangeException>(new UnicodeEncoding(), new byte[] { 0, 0 }, 3, 0, "00S3"); } [Fact] public void NegTest11() { NegativeTestChars2<ArgumentNullException>(new UnicodeEncoding(true, false), null, 0, 0, "00P4"); } [Fact] public void NegTest12() { NegativeTestChars2<ArgumentOutOfRangeException>(new UnicodeEncoding(true, false), new byte[] { 0, 0 }, -1, 1, "00P4"); } [Fact] public void NegTest13() { NegativeTestChars2<ArgumentOutOfRangeException>(new UnicodeEncoding(true, false), new byte[] { 0, 0 }, 1, -1, "00Q4"); } [Fact] public void NegTest14() { NegativeTestChars2<ArgumentOutOfRangeException>(new UnicodeEncoding(true, false), new byte[] { 0, 0 }, 0, 10, "00R4"); } [Fact] public void NegTest15() { NegativeTestChars2<ArgumentOutOfRangeException>(new UnicodeEncoding(true, false), new byte[] { 0, 0 }, 3, 0, "00S4"); } #endregion public void PositiveTestString(Encoding enc, string expected, byte[] bytes, string id) { string str = enc.GetString(bytes, 0, bytes.Length); Assert.Equal(expected, str); } private string GetStrBytes(string input) { StringBuilder sb = new StringBuilder(); foreach (char c in input) { sb.Append(((int)c).ToString("X")); sb.Append(" "); } return sb.ToString(); } public void NegativeTestChars2<T>(Encoding enc, byte[] bytes, int index, int count, string id) where T : Exception { Assert.Throws<T>(() => { string str = enc.GetString(bytes, index, count); }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Linq; using System.Text; using System.Xml; using System.Xml.Linq; using CoreXml.Test.XLinq; using Microsoft.Test.ModuleCore; using XmlCoreTest.Common; namespace XLinqTests { public class LoadFromStream : XLinqTestCase { // Type is CoreXml.Test.XLinq.FunctionalTests+TreeManipulationTests+LoadFromStream // Test Case #region Constants private const string purchaseOrderXml = @"<PurchaseOrder><Item price='100'>Motor<![CDATA[cdata]]><elem>inner text</elem>text<?pi pi pi?></Item></PurchaseOrder>"; #endregion #region Fields private readonly XDocument _purchaseOrder = new XDocument(new XElement("PurchaseOrder", new XElement("Item", "Motor", new XAttribute("price", "100"), new XCData("cdata"), new XElement("elem", "inner text"), new XText("text"), new XProcessingInstruction("pi", "pi pi")))); #endregion #region Public Methods and Operators public override void AddChildren() { AddChild(new TestVariation(StreamStateAfterLoading) { Attribute = new VariationAttribute("Stream state after loading") { Priority = 0 } }); AddChild(new TestVariation(XDEncodings) { Attribute = new VariationAttribute("XDocument.Load() Encodings: UTF8, UTF16, UTF16BE") { Priority = 0 } }); AddChild(new TestVariation(XEEncodings) { Attribute = new VariationAttribute("XElement.Load() Encodings: UTF8, UTF16, UTF16BE") { Priority = 0 } }); AddChild(new TestVariation(LoadOptionsPWS) { Attribute = new VariationAttribute("XDocument.Load(), Load options, preserveWhitespace, Stream") { Param = "Stream", Priority = 0 } }); AddChild(new TestVariation(LoadOptionsPWS) { Attribute = new VariationAttribute("XDocument.Load(), Load options, preserveWhitespace, Uri") { Param = "Uri", Priority = 0 } }); AddChild(new TestVariation(LoadOptionsBU) { Attribute = new VariationAttribute("XDocument.Load(), Load options, BaseUri, Uri") { Param = "Uri", Priority = 0 } }); AddChild(new TestVariation(LoadOptionsLI) { Attribute = new VariationAttribute("XDocument.Load(), Load options, LineInfo, Uri") { Param = "Uri", Priority = 0 } }); AddChild(new TestVariation(LoadOptionsLI) { Attribute = new VariationAttribute("XDocument.Load(), Load options, LineInfo, Stream") { Param = "Stream", Priority = 0 } }); AddChild(new TestVariation(XE_LoadOptionsPWS) { Attribute = new VariationAttribute("XElement.Load(), Load options, preserveWhitespace, Uri") { Param = "Uri", Priority = 0 } }); AddChild(new TestVariation(XE_LoadOptionsPWS) { Attribute = new VariationAttribute("XElement.Load(), Load options, preserveWhitespace, Stream") { Param = "Stream", Priority = 0 } }); AddChild(new TestVariation(XE_LoadOptionsBU) { Attribute = new VariationAttribute("XElement.Load(), Load options, BaseUri, Uri") { Param = "Uri", Priority = 0 } }); AddChild(new TestVariation(XE_LoadOptionsLI) { Attribute = new VariationAttribute("XElement.Load(), Load options, LineInfo, Stream") { Param = "Stream", Priority = 0 } }); AddChild(new TestVariation(XE_LoadOptionsLI) { Attribute = new VariationAttribute("XElement.Load(), Load options, LineInfo, Uri") { Param = "Uri", Priority = 0 } }); AddChild(new TestVariation(SaveOptionsTests) { Attribute = new VariationAttribute("XDocument.Save(), SaveOptions.DisableFormatting | SaveOptions.OmitDuplicateNamespaces") { Param = 3, Priority = 1 } }); AddChild(new TestVariation(SaveOptionsTests) { Attribute = new VariationAttribute("XDocument.Save(), SaveOptions.OmitDuplicateNamespaces") { Param = 2, Priority = 1 } }); AddChild(new TestVariation(SaveOptionsTests) { Attribute = new VariationAttribute("XDocument.Save(), SaveOptions.None") { Param = 0, Priority = 1 } }); AddChild(new TestVariation(SaveOptionsTests) { Attribute = new VariationAttribute("XDocument.Save(), SaveOptions.DisableFormatting ") { Param = 1, Priority = 1 } }); AddChild(new TestVariation(ElementSaveOptionsTests) { Attribute = new VariationAttribute("XElement.Save(), SaveOptions.OmitDuplicateNamespaces") { Param = 2, Priority = 1 } }); AddChild(new TestVariation(ElementSaveOptionsTests) { Attribute = new VariationAttribute("XElement.Save(), SaveOptions.None") { Param = 0, Priority = 1 } }); AddChild(new TestVariation(ElementSaveOptionsTests) { Attribute = new VariationAttribute("XElement.Save(), SaveOptions.DisableFormatting ") { Param = 1, Priority = 1 } }); AddChild(new TestVariation(ElementSaveOptionsTests) { Attribute = new VariationAttribute("XElement.Save(), SaveOptions.DisableFormatting | SaveOptions.OmitDuplicateNamespaces") { Param = 3, Priority = 1 } }); AddChild(new TestVariation(SaveOptionsDefaultTests) { Attribute = new VariationAttribute("XDocument.Save(), SaveOptions - default") { Priority = 1 } }); AddChild(new TestVariation(ElementSaveOptionsDefaultTests) { Attribute = new VariationAttribute("XElement.Save(), SaveOptions - default") { Priority = 1 } }); AddChild(new TestVariation(EncodingHints) { Attribute = new VariationAttribute("XDocument.Save(), Encoding hints UTF-8") { Param = "UTF-8", Priority = 1 } }); AddChild(new TestVariation(EncodingHintsDefault) { Attribute = new VariationAttribute("XDocument.Save(), Encoding hints - No hint, Fallback to UTF8") { Priority = 1 } }); } public void ElementSaveOptionsDefaultTests() { byte[] expected, actual; var doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), new XElement("root", new XProcessingInstruction("PI", ""), new XAttribute("id", "root"), new XAttribute(XNamespace.Xmlns + "p", "ns1"), new XElement("{ns1}A", new XAttribute(XNamespace.Xmlns + "p", "ns1")))); using (var ms = new MemoryStream()) { using (var sw = new StreamWriter(ms, Encoding.UTF8)) { doc.Root.Save(sw); sw.Flush(); expected = ms.ToArray(); } } // write via Stream using (var ms = new MemoryStream()) { doc.Root.Save(ms); actual = ms.ToArray(); } TestLog.Compare(actual.Length, expected.Length, "Length not the same"); for (int index = 0; index < actual.Length; index++) { TestLog.Equals(actual[index], expected[index], "Error on position " + index); } } public void ElementSaveOptionsTests() { var so = (SaveOptions)CurrentChild.Param; byte[] expected, actual; var doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), new XElement("root", new XProcessingInstruction("PI", ""), new XAttribute("id", "root"), new XAttribute(XNamespace.Xmlns + "p", "ns1"), new XElement("{ns1}A", new XAttribute(XNamespace.Xmlns + "p", "ns1")))); // write via writer using (var ms = new MemoryStream()) { using (var sw = new StreamWriter(ms, Encoding.UTF8)) { doc.Root.Save(sw, so); sw.Flush(); expected = ms.ToArray(); } } // write via Stream using (var ms = new MemoryStream()) { doc.Root.Save(ms, so); actual = ms.ToArray(); } TestLog.Compare(actual.Length, expected.Length, "Length not the same"); for (int index = 0; index < actual.Length; index++) { TestLog.Equals(actual[index], expected[index], "Error on position " + index); } } public void EncodingHints() { Encoding enc = Encoding.GetEncoding(CurrentChild.Param as string); var doc = new XDocument(new XDeclaration("1.0", enc.WebName, "yes"), new XElement("root", new XProcessingInstruction("PI", ""), new XAttribute("id", "root"), new XAttribute(XNamespace.Xmlns + "p", "ns1"), new XElement("{ns1}A", new XAttribute(XNamespace.Xmlns + "p", "ns1")))); using (var ms = new MemoryStream()) { doc.Save(ms); ms.Position = 0; using (var sr = new StreamReader(ms)) { XDocument d1 = XDocument.Load(sr); TestLog.Compare(sr.CurrentEncoding.Equals(enc), "Encoding does not match"); TestLog.Compare(d1.Declaration.Encoding, enc.WebName, "declaration does not match"); } } } //[Variation(Priority = 1, Desc = "XDocument.Save(), Encoding hints - No hint, Fallback to UTF8")] public void EncodingHintsDefault() { var doc = new XDocument(new XElement("root", new XProcessingInstruction("PI", ""), new XAttribute("id", "root"), new XAttribute(XNamespace.Xmlns + "p", "ns1"), new XElement("{ns1}A", new XAttribute(XNamespace.Xmlns + "p", "ns1")))); using (var ms = new MemoryStream()) { doc.Save(ms); ms.Position = 0; using (var sr = new StreamReader(ms)) { XDocument d1 = XDocument.Load(sr); TestLog.Compare(sr.CurrentEncoding.Equals(Encoding.UTF8), "Encoding does not match"); TestLog.Compare(d1.Declaration.Encoding, Encoding.UTF8.WebName, "declaration does not match"); } } } public void LoadOptionsBU() { string fileName = @"NoExternals.xml"; var how = CurrentChild.Param as string; XDocument doc = GetXDocument(fileName, LoadOptions.SetBaseUri, how); foreach (XObject node in doc.DescendantNodes().OfType<object>().Concat2(doc.Descendants().Attributes().OfType<object>())) { string baseUri = node.BaseUri; // fail when use stream replace file if (!String.IsNullOrWhiteSpace(baseUri)) { TestLog.Compare(new Uri(baseUri), new Uri(GetFullTestPath(fileName)), "base uri failed"); } } doc = GetXDocument(fileName, LoadOptions.None, how); foreach (XObject node in doc.DescendantNodes().OfType<object>().Concat2(doc.Descendants().Attributes().OfType<object>())) { string baseUri = node.BaseUri; TestLog.Compare(baseUri, "", "base uri failed"); } } //[Variation(Priority = 0, Desc = "XDocument.Load(), Load options, LineInfo, Uri", Param = "Uri")] //[Variation(Priority = 0, Desc = "XDocument.Load(), Load options, LineInfo, Stream", Param = "Stream")] public void LoadOptionsLI() { string fileName = @"NoExternals.xml"; var how = CurrentChild.Param as string; XDocument doc = GetXDocument(fileName, LoadOptions.SetLineInfo, how); foreach (object node in doc.DescendantNodes().OfType<object>().Concat2(doc.Descendants().Attributes().OfType<object>())) { TestLog.Compare((node as IXmlLineInfo).LineNumber != 0, "LineNumber failed"); TestLog.Compare((node as IXmlLineInfo).LinePosition != 0, "LinePosition failed"); } doc = GetXDocument(fileName, LoadOptions.None, how); foreach (object node in doc.DescendantNodes().OfType<object>().Concat2(doc.Descendants().Attributes().OfType<object>())) { TestLog.Compare((node as IXmlLineInfo).LineNumber == 0, "LineNumber failed"); TestLog.Compare((node as IXmlLineInfo).LinePosition == 0, "LinePosition failed"); } } public void LoadOptionsPWS() { string fileName = @"NoExternals.xml"; var how = CurrentChild.Param as string; // PreserveWhitespace = true XDocument doc = GetXDocument(fileName, LoadOptions.PreserveWhitespace, how); TestLog.Compare(doc.Root.FirstNode.NodeType == XmlNodeType.Text, "First node in root should be whitespace"); // PreserveWhitespace = false ... default doc = GetXDocument(fileName, LoadOptions.None, how); TestLog.Compare(doc.Root.FirstNode.NodeType == XmlNodeType.Element, "First node in root should be element(no ws)"); } public void SaveOptionsDefaultTests() { byte[] expected, actual; var doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), new XElement("root", new XProcessingInstruction("PI", ""), new XAttribute("id", "root"), new XAttribute(XNamespace.Xmlns + "p", "ns1"), new XElement("{ns1}A", new XAttribute(XNamespace.Xmlns + "p", "ns1")))); using (var ms = new MemoryStream()) { using (var sw = new StreamWriter(ms, Encoding.UTF8)) { doc.Save(sw); sw.Flush(); expected = ms.ToArray(); } } // write via Stream using (var ms = new MemoryStream()) { doc.Save(ms); actual = ms.ToArray(); } TestLog.Compare(actual.Length, expected.Length, "Length not the same"); for (int index = 0; index < actual.Length; index++) { TestLog.Equals(actual[index], expected[index], "Error on position " + index); } } public void SaveOptionsTests() { var so = (SaveOptions)CurrentChild.Param; byte[] expected, actual; var doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), new XElement("root", new XProcessingInstruction("PI", ""), new XAttribute("id", "root"), new XAttribute(XNamespace.Xmlns + "p", "ns1"), new XElement("{ns1}A", new XAttribute(XNamespace.Xmlns + "p", "ns1")))); // write via writer using (var ms = new MemoryStream()) { using (var sw = new StreamWriter(ms, Encoding.UTF8)) { doc.Save(sw, so); sw.Flush(); expected = ms.ToArray(); } } // write via Stream using (var ms = new MemoryStream()) { doc.Save(ms, so); actual = ms.ToArray(); } TestLog.Compare(actual.Length, expected.Length, "Length not the same"); for (int index = 0; index < actual.Length; index++) { TestLog.Equals(actual[index], expected[index], "Error on position " + index); } } //[Variation(Priority = 0, Desc = "Stream state after loading")] public void StreamStateAfterLoading() { MemoryStream ms = CreateStream(purchaseOrderXml, Encoding.UTF8); XDocument.Load(ms); // if stream is not closed we should be able to reset it's position and read it again ms.Position = 0; XDocument.Load(ms); } //[Variation(Priority = 0, Desc = "XDocument.Load() Encodings: UTF8, UTF16, UTF16BE")] public void XDEncodings() { foreach (Encoding enc in new[] { Encoding.UTF8, Encoding.GetEncoding("UTF-16"), Encoding.GetEncoding("UTF-16BE") }) { MemoryStream ms = CreateStream(purchaseOrderXml, enc); XDocument d = XDocument.Load(ms); TestLog.Compare(XNode.DeepEquals(d, _purchaseOrder), "Not the same"); } } //[Variation(Priority = 0, Desc = "XElement.Load() Encodings: UTF8, UTF16, UTF16BE")] public void XEEncodings() { foreach (Encoding enc in new[] { Encoding.UTF8, Encoding.GetEncoding("UTF-16"), Encoding.GetEncoding("UTF-16BE") }) { MemoryStream ms = CreateStream(purchaseOrderXml, enc); XElement e = XElement.Load(ms); TestLog.Compare(XNode.DeepEquals(e, _purchaseOrder.Root), "Not the same"); } } //[Variation(Priority = 0, Desc = "XDocument.Load(), Load options, preserveWhitespace, Uri", Param = "Uri")] //[Variation(Priority = 0, Desc = "XDocument.Load(), Load options, preserveWhitespace, Stream", Param = "Stream")] //[Variation(Priority = 0, Desc = "XElement.Load(), Load options, BaseUri, Uri", Param = "Uri")] //[Variation(Priority = 0, Desc = "XElement.Load(), Load options, BaseUri, Stream", Param = "Stream")] public void XE_LoadOptionsBU() { string fileName = @"NoExternals.xml"; var how = CurrentChild.Param as string; XElement e = GetXElement(fileName, LoadOptions.SetBaseUri, how); foreach (XObject node in e.DescendantNodesAndSelf().OfType<object>().Concat2(e.DescendantsAndSelf().Attributes().OfType<object>())) { string baseUri = node.BaseUri; if (!String.IsNullOrWhiteSpace(baseUri)) { TestLog.Compare(new Uri(baseUri), new Uri(GetFullTestPath(fileName)), "base uri failed"); } } e = GetXElement(fileName, LoadOptions.None, how); foreach (XObject node in e.DescendantNodesAndSelf().OfType<object>().Concat2(e.DescendantsAndSelf().Attributes().OfType<object>())) { string baseUri = node.BaseUri; TestLog.Compare(baseUri, "", "base uri failed"); } } //[Variation(Priority = 0, Desc = "XElement.Load(), Load options, LineInfo, Uri", Param = "Uri")] //[Variation(Priority = 0, Desc = "XElement.Load(), Load options, LineInfo, Stream", Param = "Stream")] public void XE_LoadOptionsLI() { string fileName = @"NoExternals.xml"; var how = CurrentChild.Param as string; XElement e = GetXElement(fileName, LoadOptions.SetLineInfo, how); foreach (object node in e.DescendantNodesAndSelf().OfType<object>().Concat2(e.DescendantsAndSelf().Attributes().OfType<object>())) { TestLog.Compare((node as IXmlLineInfo).LineNumber != 0, "LineNumber failed"); TestLog.Compare((node as IXmlLineInfo).LinePosition != 0, "LinePosition failed"); } e = GetXElement(fileName, LoadOptions.None, how); foreach (object node in e.DescendantNodesAndSelf().OfType<object>().Concat2(e.DescendantsAndSelf().Attributes().OfType<object>())) { TestLog.Compare((node as IXmlLineInfo).LineNumber == 0, "LineNumber failed"); TestLog.Compare((node as IXmlLineInfo).LinePosition == 0, "LinePosition failed"); } } public void XE_LoadOptionsPWS() { string fileName = @"NoExternals.xml"; var how = CurrentChild.Param as string; XElement e = GetXElement(fileName, LoadOptions.PreserveWhitespace, how); TestLog.Compare(e.FirstNode.NodeType == XmlNodeType.Text, "First node in root should be whitespace"); // PreserveWhitespace = false ... default e = GetXElement(fileName, LoadOptions.None, how); TestLog.Compare(e.FirstNode.NodeType == XmlNodeType.Element, "First node in root should be element(no ws)"); } #endregion #region Methods private static MemoryStream CreateStream(string data, Encoding enc) { var ms = new MemoryStream(); // StreamWriter is closing the memorystream when used with using ... so we keep it this way var sw = new StreamWriter(ms, enc); sw.Write(data); sw.Flush(); ms.Position = 0; return ms; } private static string GetFullTestPath(string fileName) { return Path.Combine(FilePathUtil.GetTestDataPath() + @"/XLinq", fileName); } // Save options: //[Variation(Priority = 1, Desc = "XDocument.Save(), SaveOptions.DisableFormatting | SaveOptions.OmitDuplicateNamespaces", Param = SaveOptions.DisableFormatting | SaveOptions.OmitDuplicateNamespaces)] //[Variation(Priority = 1, Desc = "XDocument.Save(), SaveOptions.DisableFormatting ", Param = SaveOptions.DisableFormatting)] //[Variation(Priority = 1, Desc = "XDocument.Save(), SaveOptions.OmitDuplicateNamespaces", Param = SaveOptions.OmitDuplicateNamespaces)] //[Variation(Priority = 1, Desc = "XDocument.Save(), SaveOptions.None", Param = SaveOptions.None)] private static XDocument GetXDocument(string fileName, LoadOptions lo, string how) { switch (how) { case "Uri": return XDocument.Load(FilePathUtil.getStream(GetFullTestPath(fileName)), lo); case "Stream": using (Stream s = FilePathUtil.getStream(GetFullTestPath(fileName))) { return XDocument.Load(s, lo); } default: throw new TestFailedException("TEST FAILED: don't know how to create XDocument"); } } private static XElement GetXElement(string fileName, LoadOptions lo, string how) { switch (how) { case "Uri": return XElement.Load(FilePathUtil.getStream(GetFullTestPath(fileName)), lo); case "Stream": using (Stream s = FilePathUtil.getStream(GetFullTestPath(fileName))) { return XElement.Load(s, lo); } default: throw new TestFailedException("TEST FAILED: don't know how to create XDocument"); } } #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace NVelocity.Runtime.Directive { using App.Event; using Context; using Exception; using Parser.Node; /// <summary> Pluggable directive that handles the <code>#parse()</code> /// statement in VTL. /// /// <pre> /// Notes: /// ----- /// 1) The parsed source material can only come from somewhere in /// the TemplateRoot tree for security reasons. There is no way /// around this. If you want to include content from elsewhere on /// your disk, use a link from somwhere under Template Root to that /// content. /// /// 2) There is a limited parse depth. It is set as a property /// "directive.parse.max.depth = 10" by default. This 10 deep /// limit is a safety feature to prevent infinite loops. /// </pre> /// /// </summary> /// <author> <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a> /// </author> /// <author> <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a> /// </author> /// <author> <a href="mailto:Christoph.Reck@dlr.de">Christoph Reck</a> /// </author> /// <version> $Id: Parse.java 724825 2008-12-09 18:56:06Z nbubna $ /// </version> public class Parse : InputBase { /// <summary> Return type of this directive.</summary> /// <returns> The type of this directive. /// </returns> override public int Type { get { return NVelocity.Runtime.Directive.DirectiveType.LINE; } } private int maxDepth; /// <summary> Return name of this directive.</summary> /// <returns> The name of this directive. /// </returns> public override string Name { get { return "parse"; } } /// <summary> Init's the #parse directive.</summary> /// <param name="rs"> /// </param> /// <param name="context"> /// </param> /// <param name="node"> /// </param> /// <throws> TemplateInitException </throws> public override void Init(IRuntimeServices rs, IInternalContextAdapter context, INode node) { base.Init(rs, context, node); this.maxDepth = rsvc.GetInt(NVelocity.Runtime.RuntimeConstants.PARSE_DIRECTIVE_MAXDEPTH, 10); } /// <summary> iterates through the argument list and renders every /// argument that is appropriate. Any non appropriate /// arguments are logged, but render() continues. /// </summary> /// <param name="context"> /// </param> /// <param name="writer"> /// </param> /// <param name="node"> /// </param> /// <returns> True if the directive rendered successfully. /// </returns> /// <throws> IOException </throws> /// <throws> ResourceNotFoundException </throws> /// <throws> ParseErrorException </throws> /// <throws> MethodInvocationException </throws> public override bool Render(IInternalContextAdapter context, System.IO.TextWriter writer, INode node) { /* * if rendering is no longer allowed (after a stop), we can safely * skip execution of all the parse directives. */ if (!context.AllowRendering) { return true; } /* * did we Get an argument? */ if (node.GetChild(0) == null) { rsvc.Log.Error("#parse() null argument"); return false; } /* * does it have a value? If you have a null reference, then no. */ object value = node.GetChild(0).Value(context); if (value == null) { rsvc.Log.Error("#parse() null argument"); return false; } /* * Get the path */ string sourcearg = value.ToString(); /* * check to see if the argument will be changed by the event cartridge */ string arg = EventHandlerUtil.IncludeEvent(rsvc, context, sourcearg, context.CurrentTemplateName, Name); /* * a null return value from the event cartridge indicates we should not * input a resource. */ bool blockinput = false; if (arg == null) blockinput = true; if (maxDepth > 0) { /* * see if we have exceeded the configured depth. */ object[] templateStack = context.TemplateNameStack; if (templateStack.Length >= maxDepth) { System.Text.StringBuilder path = new System.Text.StringBuilder(); for (int i = 0; i < templateStack.Length; ++i) { path.Append(" > " + templateStack[i]); } rsvc.Log.Error("Max recursion depth reached (" + templateStack.Length + ')' + " File stack:" + path); return false; } } /* * now use the Runtime resource loader to Get the template */ Template t = null; try { if (!blockinput) t = rsvc.GetTemplate(arg, GetInputEncoding(context)); } catch (ResourceNotFoundException rnfe) { /* * the arg wasn't found. Note it and throw */ rsvc.Log.Error("#parse(): cannot find template '" + arg + "', called at " + Log.Log.FormatFileString(this)); throw rnfe; } catch (ParseErrorException pee) { /* * the arg was found, but didn't parse - syntax Error * note it and throw */ rsvc.Log.Error("#parse(): syntax error in #parse()-ed template '" + arg + "', called at " + Log.Log.FormatFileString(this)); throw pee; } /** * pass through application level runtime exceptions */ catch (System.SystemException e) { rsvc.Log.Error("Exception rendering #parse(" + arg + ") at " + Log.Log.FormatFileString(this)); throw e; } catch (System.Exception e) { string msg = "Exception rendering #parse(" + arg + ") at " + Log.Log.FormatFileString(this); rsvc.Log.Error(msg, e); throw new VelocityException(msg, e); } /** * Add the template name to the macro libraries list */ System.Collections.IList macroLibraries = context.MacroLibraries; /** * if macroLibraries are not set create a new one */ if (macroLibraries == null) { macroLibraries = new System.Collections.ArrayList(); } context.MacroLibraries = macroLibraries; macroLibraries.Add(arg); /* * and render it */ try { if (!blockinput) { context.PushCurrentTemplateName(arg); ((SimpleNode)t.Data).Render(context, writer); } } /** * pass through application level runtime exceptions */ catch (System.SystemException e) { /** * LogMessage #parse errors so the user can track which file called which. */ rsvc.Log.Error("Exception rendering #parse(" + arg + ") at " + Log.Log.FormatFileString(this)); throw e; } catch (System.Exception e) { string msg = "Exception rendering #parse(" + arg + ") at " + Log.Log.FormatFileString(this); rsvc.Log.Error(msg, e); throw new VelocityException(msg, e); } finally { if (!blockinput) context.PopCurrentTemplateName(); } /* * note - a blocked input is still a successful operation as this is * expected behavior. */ return true; } } }
using UnityEngine; using System.Collections; #if UNITY_EDITOR using UnityEditor; #endif public enum HorizontalAlignments { Left, Right, Center } public enum VerticalAlignments { Top, Bottom, Center } public class PlatformSpecifics : MonoBehaviour { #if UNITY_5 public new Renderer renderer { get { return GetComponent<Renderer> ();} } #endif public Platform[] restrictPlatform; [System.Serializable] public class MaterialPerPlatform { public Platform platform; public Material mat; public MaterialPerPlatform (Platform _platform, Material _mat) { platform = _platform; mat = _mat; } } public MaterialPerPlatform[] materialPerPlatform; [System.Serializable] public class LocalScalePerPlatform { public Platform platform; public Vector3 localScale; public LocalScalePerPlatform (Platform _platform, Vector3 _localScale) { platform = _platform; localScale = _localScale; } } public LocalScalePerPlatform[] localScalePerPlatform; [System.Serializable] public class LocalScalePerAspectRatio { public AspectRatio aspectRatio; public Vector3 localScale; public LocalScalePerAspectRatio (AspectRatio _aspectRatio, Vector3 _localScale) { aspectRatio = _aspectRatio; localScale = _localScale; } } public LocalScalePerAspectRatio[] localScalePerAspectRatio; [System.Serializable] public class LocalPositionPerPlatform { public Platform platform; public Vector3 localPosition; public LocalPositionPerPlatform (Platform _platform, Vector3 _localPosition) { platform = _platform; localPosition = _localPosition; } } public LocalPositionPerPlatform[] localPositionPerPlatform; [System.Serializable] public class LocalPositionPerAspectRatio { public AspectRatio aspectRatio; public Vector3 localPosition; public LocalPositionPerAspectRatio (AspectRatio _aspectRatio, Vector3 _localPosition) { aspectRatio = _aspectRatio; localPosition = _localPosition; } } public LocalPositionPerAspectRatio[] localPositionPerAspectRatio; [System.Serializable] public class AnchorPosition { public Camera alignmentCamera; public HorizontalAlignments horizontalAlignment; public VerticalAlignments verticalAlignment; public bool positionXAsPercent, positionYAsPercent, centerX = true, centerY = true; public Vector2 screenPosition; public AnchorPosition (HorizontalAlignments _horizontalAlignment, VerticalAlignments _verticalAlignment, bool _positionXAsPercent, bool _positionYAsPercent, bool _centerX, bool _centerY, Vector2 _screenPosition) { horizontalAlignment = _horizontalAlignment; verticalAlignment = _verticalAlignment; positionXAsPercent = _positionXAsPercent; positionYAsPercent = _positionYAsPercent; centerX = _centerX; centerY = _centerY; screenPosition = _screenPosition; } } public AnchorPosition[] anchorPositions; [System.Serializable] public class FontPerPlatform { public Platform platform; public Font font; public Material mat; public FontPerPlatform (Platform _platform, Font _font, Material _mat) { platform = _platform; font = _font; mat = _mat; } } public FontPerPlatform[] fontPerPlatform; [System.Serializable] public class TextMeshTextPerPlatform { public Platform platform; public string text; public TextMeshTextPerPlatform (Platform _platform, string _text) { platform = _platform; text = _text; } } public TextMeshTextPerPlatform[] textMeshTextPerPlatform; #if UNITY_EDITOR public static bool UseEditorApplyMode; #endif void Awake () { Init(); ApplySpecifics(Platforms.platform); } public void Init() { if(restrictPlatform == null) restrictPlatform = new Platform[0]; if(materialPerPlatform == null) materialPerPlatform = new MaterialPerPlatform[0]; if(localScalePerPlatform == null) localScalePerPlatform = new LocalScalePerPlatform[0]; if(localScalePerAspectRatio == null) localScalePerAspectRatio = new LocalScalePerAspectRatio[0]; if(localPositionPerPlatform == null) localPositionPerPlatform = new LocalPositionPerPlatform[0]; if(localPositionPerAspectRatio == null) localPositionPerAspectRatio = new LocalPositionPerAspectRatio[0]; if(anchorPositions == null) anchorPositions = new AnchorPosition[0]; if(fontPerPlatform == null) fontPerPlatform = new FontPerPlatform[0]; if(textMeshTextPerPlatform == null) textMeshTextPerPlatform = new TextMeshTextPerPlatform[0]; } private bool isCompatiblePlatform(Platform platform1, Platform platform2) { if (Platforms.IsiOSPlatform(platform1) && platform2 == Platform.iOS) return true; else return (platform1 == platform2); } public void ApplySpecifics(Platform platform) { ApplySpecifics(platform, true); } public void ApplySpecifics(Platform platform, bool applyPlatformRestriction) { if(applyPlatformRestriction) { bool currentPlatformActive = ApplyRestrictPlatform(platform); if(!currentPlatformActive) return; } ApplyMaterial(platform); ApplyLocalScale(platform); ApplyLocalPosition(platform); ApplyFont(platform); ApplyTextMeshText(platform); } public bool ApplyRestrictPlatform(Platform platform) { if(restrictPlatform != null && restrictPlatform.Length > 0) { bool foundPlatform = false; for(int i=0; i<restrictPlatform.Length; i++) { if (isCompatiblePlatform(platform, restrictPlatform[i])) { foundPlatform = true; break; } } if(!foundPlatform) { #if UNITY_EDITOR if (!UseEditorApplyMode) { if(Application.isEditor) DestroyImmediate(gameObject, true); else Destroy(gameObject); } #else if(Application.isEditor) DestroyImmediate(gameObject, true); else Destroy(gameObject); #endif return false; } else { return true; } } return true; } public void ApplyMaterial(Platform platform) { if(materialPerPlatform != null) { foreach(MaterialPerPlatform pair in materialPerPlatform) { if (isCompatiblePlatform(platform, pair.platform)) { GetComponent<Renderer>().sharedMaterial = pair.mat; break; } } } } public void ApplyLocalScale(Platform platform) { #if UNITY_4_6 var rectTransform = GetComponent<RectTransform>(); #endif if(localScalePerPlatform != null) { foreach(LocalScalePerPlatform pair in localScalePerPlatform) { if (isCompatiblePlatform(platform, pair.platform)) { #if UNITY_4_6 if (rectTransform != null) rectTransform.localScale = pair.localScale; else transform.localScale = pair.localScale; #else transform.localScale = pair.localScale; #endif break; } } } if(Platforms.IsPlatformAspectBased(platform.ToString()) && localScalePerAspectRatio != null) { foreach(LocalScalePerAspectRatio pair in localScalePerAspectRatio) { if(AspectRatios.GetAspectRatio() == pair.aspectRatio) { #if UNITY_4_6 if (rectTransform != null) rectTransform.localScale = pair.localScale; else transform.localScale = pair.localScale; #else transform.localScale = pair.localScale; #endif break; } } } } public void ApplyLocalPosition(Platform platform) { #if UNITY_4_6 var rectTransform = GetComponent<RectTransform>(); #endif if(localPositionPerPlatform != null) { foreach(LocalPositionPerPlatform pair in localPositionPerPlatform) { if (isCompatiblePlatform(platform, pair.platform)) { #if UNITY_4_6 if (rectTransform != null) rectTransform.localPosition = pair.localPosition; else transform.localPosition = pair.localPosition; #else transform.localPosition = pair.localPosition; #endif break; } } } if(Platforms.IsPlatformAspectBased(platform.ToString()) && localPositionPerAspectRatio != null) { foreach(LocalPositionPerAspectRatio pair in localPositionPerAspectRatio) { if(AspectRatios.GetAspectRatio() == pair.aspectRatio) { #if UNITY_4_6 if (rectTransform != null) rectTransform.localPosition = pair.localPosition; else transform.localPosition = pair.localPosition; #else transform.localPosition = pair.localPosition; #endif break; } } } // if an anchor position, it will override others #if UNITY_4_6 if(anchorPositions != null && rectTransform == null) { #else if(anchorPositions != null) { #endif foreach(AnchorPosition pair in anchorPositions) { // make sure we have a camera to align to var cam = pair.alignmentCamera; if (cam == null) { Debug.LogError("No alignment camera is attached to GameObject: " + gameObject.name); continue; } // get screen size float screenWidth = Screen.width, screenHeight = Screen.height; #if UNITY_EDITOR if (UseEditorApplyMode) AspectRatios.getScreenSizeHack(out screenWidth, out screenHeight); #endif // get position var pos = pair.screenPosition; if (pair.positionXAsPercent) pos.x *= screenWidth;// * 0.01f; if (pair.positionYAsPercent) pos.y *= screenHeight;// * 0.01f; // global calculations var ray = cam.ScreenPointToRay(pos); var planePoint = RayInersectPlane(ray, -cam.transform.forward, transform.position); ray = cam.ScreenPointToRay(Vector3.zero); var bottomLeft = RayInersectPlane(ray, -cam.transform.forward, transform.position); ray = cam.ScreenPointToRay(new Vector3(screenWidth, screenHeight, 0)); var topRight = RayInersectPlane(ray, -cam.transform.forward, transform.position); // get object radius float radius = 0; var renderer = GetComponent<Renderer>(); if (renderer != null) radius = (renderer.bounds.max - renderer.bounds.min).magnitude * .5f; // get new projected width and height var screenSize = (topRight - bottomLeft); screenWidth = Vector3.Dot(screenSize, cam.transform.right); screenHeight = Vector3.Dot(screenSize, cam.transform.up); // horizontal alignment types switch (pair.horizontalAlignment) { case HorizontalAlignments.Left: planePoint += cam.transform.right * (!pair.centerX ? radius : 0); break; case HorizontalAlignments.Right: planePoint += cam.transform.right * (screenWidth - (!pair.centerX ? radius : 0)); break; case HorizontalAlignments.Center: planePoint += cam.transform.right * (screenWidth * .5f); break; } // vertical alignment types switch (pair.verticalAlignment) { case VerticalAlignments.Bottom: planePoint += cam.transform.up * (!pair.centerY ? radius : 0); break; case VerticalAlignments.Top: planePoint += cam.transform.up * (screenHeight - (!pair.centerY ? radius : 0)); break; case VerticalAlignments.Center: planePoint += cam.transform.up * (screenHeight * .5f); break; } // set final position transform.position = planePoint; } } } private Vector3 PointInersectPlane(Vector3 vector, Vector3 planeNormal, Vector3 planeLocation) { return vector - (planeNormal * Vector3.Dot(vector-planeLocation, planeNormal)); } private Vector3 RayInersectPlane(Ray ray, Vector3 planeNormal, Vector3 planeLocation) { float dot = (-(planeNormal.x*planeLocation.x) - (planeNormal.y*planeLocation.y) - (planeNormal.z*planeLocation.z)); float dot3 = (planeNormal.x*ray.direction.x) + (planeNormal.y*ray.direction.y) + (planeNormal.z*ray.direction.z); float dot2 = -((dot + (planeNormal.x*ray.origin.x) + (planeNormal.y*ray.origin.y) + (planeNormal.z*ray.origin.z)) / dot3); return (ray.origin + (dot2*ray.direction)); } public void ApplyFont(Platform platform) { if(fontPerPlatform != null) { foreach(FontPerPlatform pair in fontPerPlatform) { if (isCompatiblePlatform(platform, pair.platform)) { this.GetComponent<TextMesh>().font = pair.font; GetComponent<Renderer>().sharedMaterial = pair.mat; break; } } } } public void ApplyTextMeshText(Platform platform) { if(textMeshTextPerPlatform != null) { foreach(TextMeshTextPerPlatform pair in textMeshTextPerPlatform) { if (isCompatiblePlatform(platform, pair.platform)) { this.GetComponent<TextMesh>().text = pair.text; break; } } } } }
// // System.Xml.Serialization.XmlSchemaExporter // // Author: // Tim Coleman (tim@timcoleman.com) // Lluis Sanchez Gual (lluis@ximian.com) // // Copyright (C) Tim Coleman, 2002 // // // 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.Xml; using System.Xml.Schema; using System.Collections; namespace System.Xml.Serialization { #if CONFIG_SERIALIZATION public class XmlSchemaExporter { #region Fields XmlSchemas schemas; Hashtable exportedMaps = new Hashtable(); Hashtable exportedElements = new Hashtable(); bool encodedFormat = false; XmlDocument xmlDoc; #endregion #region Constructors public XmlSchemaExporter (XmlSchemas schemas) { this.schemas = schemas; } internal XmlSchemaExporter (XmlSchemas schemas, bool encodedFormat) { this.encodedFormat = encodedFormat; this.schemas = schemas; } #endregion // Constructors #region Methods [MonoTODO] public string ExportAnyType (string ns) { throw new NotImplementedException (); } public void ExportMembersMapping (XmlMembersMapping xmlMembersMapping) { ExportMembersMapping (xmlMembersMapping, true); } internal void ExportMembersMapping (XmlMembersMapping xmlMembersMapping, bool exportEnclosingType) { ClassMap cmap = (ClassMap) xmlMembersMapping.ObjectMap; if (xmlMembersMapping.HasWrapperElement && exportEnclosingType) { XmlSchema schema = GetSchema (xmlMembersMapping.Namespace); XmlSchemaComplexType stype = new XmlSchemaComplexType (); XmlSchemaSequence particle; XmlSchemaAnyAttribute anyAttribute; ExportMembersMapSchema (schema, cmap, null, stype.Attributes, out particle, out anyAttribute); stype.Particle = particle; stype.AnyAttribute = anyAttribute; if (encodedFormat) { stype.Name = xmlMembersMapping.ElementName; schema.Items.Add (stype); } else { XmlSchemaElement selem = new XmlSchemaElement (); selem.Name = xmlMembersMapping.ElementName; selem.SchemaType = stype; schema.Items.Add (selem); } } else { ICollection members = cmap.ElementMembers; if (members != null) { foreach (XmlTypeMapMemberElement member in members) { if (member is XmlTypeMapMemberAnyElement && member.TypeData.IsListType) { XmlSchema mschema = GetSchema (xmlMembersMapping.Namespace); XmlSchemaParticle par = GetSchemaArrayElement (mschema, member.ElementInfo); if (par is XmlSchemaAny) { XmlSchemaComplexType ct = FindComplexType (mschema.Items, "any"); if (ct != null) continue; ct = new XmlSchemaComplexType (); ct.Name = "any"; ct.IsMixed = true; XmlSchemaSequence seq = new XmlSchemaSequence (); ct.Particle = seq; seq.Items.Add (par); mschema.Items.Add (ct); continue; } } XmlTypeMapElementInfo einfo = (XmlTypeMapElementInfo) member.ElementInfo [0]; XmlSchema schema; if (encodedFormat) { schema = GetSchema (xmlMembersMapping.Namespace); ImportNamespace (schema, XmlSerializer.EncodingNamespace); } else schema = GetSchema (einfo.Namespace); XmlSchemaElement exe = FindElement (schema.Items, einfo.ElementName); XmlSchemaElement elem; Type memType = member.GetType(); if (member is XmlTypeMapMemberFlatList) throw new InvalidOperationException ("Unwrapped arrays not supported as parameters"); else if (memType == typeof(XmlTypeMapMemberElement)) elem = (XmlSchemaElement) GetSchemaElement (schema, einfo, member.DefaultValue, false); else elem = (XmlSchemaElement) GetSchemaElement (schema, einfo, false); // In encoded format, the schema elements are not needed if (!encodedFormat) schema.Items.Add (elem); if (exe != null) { if (exe.SchemaTypeName.Equals (elem.SchemaTypeName)) schema.Items.Remove (elem); else { string s = "The XML element named '" + einfo.ElementName + "' "; s += "from namespace '" + schema.TargetNamespace + "' references distinct types " + elem.SchemaTypeName.Name + " and " + exe.SchemaTypeName.Name + ". "; s += "Use XML attributes to specify another XML name or namespace for the element or types."; throw new InvalidOperationException (s); } } } } } CompileSchemas (); } [MonoTODO] public XmlQualifiedName ExportTypeMapping (XmlMembersMapping xmlMembersMapping) { throw new NotImplementedException (); } public void ExportTypeMapping (XmlTypeMapping xmlTypeMapping) { if (!xmlTypeMapping.IncludeInSchema) return; if (IsElementExported (xmlTypeMapping)) return; if (encodedFormat) { ExportClassSchema (xmlTypeMapping); XmlSchema schema = GetSchema (xmlTypeMapping.XmlTypeNamespace); ImportNamespace (schema, XmlSerializer.EncodingNamespace); } else { XmlSchema schema = GetSchema (xmlTypeMapping.Namespace); XmlTypeMapElementInfo einfo = new XmlTypeMapElementInfo (null, xmlTypeMapping.TypeData); einfo.Namespace = xmlTypeMapping.Namespace; einfo.ElementName = xmlTypeMapping.ElementName; if (xmlTypeMapping.TypeData.IsComplexType) einfo.MappedType = xmlTypeMapping; einfo.IsNullable = false; schema.Items.Add (GetSchemaElement (schema, einfo, false)); SetElementExported (xmlTypeMapping); } CompileSchemas (); } void ExportClassSchema (XmlTypeMapping map) { if (IsMapExported (map)) return; SetMapExported (map); if (map.TypeData.Type == typeof(object)) { foreach (XmlTypeMapping dmap in map.DerivedTypes) if (dmap.TypeData.SchemaType == SchemaTypes.Class) ExportClassSchema (dmap); return; } XmlSchema schema = GetSchema (map.XmlTypeNamespace); XmlSchemaComplexType stype = new XmlSchemaComplexType (); stype.Name = map.XmlType; schema.Items.Add (stype); ClassMap cmap = (ClassMap)map.ObjectMap; if (cmap.HasSimpleContent) { XmlSchemaSimpleContent simple = new XmlSchemaSimpleContent (); stype.ContentModel = simple; XmlSchemaSimpleContentExtension ext = new XmlSchemaSimpleContentExtension (); simple.Content = ext; XmlSchemaSequence particle; XmlSchemaAnyAttribute anyAttribute; ExportMembersMapSchema (schema, cmap, map.BaseMap, ext.Attributes, out particle, out anyAttribute); ext.AnyAttribute = anyAttribute; if (map.BaseMap == null) ext.BaseTypeName = cmap.SimpleContentBaseType; else ext.BaseTypeName = new XmlQualifiedName (map.BaseMap.XmlType, map.BaseMap.XmlTypeNamespace); } else if (map.BaseMap != null && map.BaseMap.IncludeInSchema) { XmlSchemaComplexContent cstype = new XmlSchemaComplexContent (); XmlSchemaComplexContentExtension ext = new XmlSchemaComplexContentExtension (); ext.BaseTypeName = new XmlQualifiedName (map.BaseMap.XmlType, map.BaseMap.XmlTypeNamespace); cstype.Content = ext; stype.ContentModel = cstype; XmlSchemaSequence particle; XmlSchemaAnyAttribute anyAttribute; ExportMembersMapSchema (schema, cmap, map.BaseMap, ext.Attributes, out particle, out anyAttribute); ext.Particle = particle; ext.AnyAttribute = anyAttribute; stype.IsMixed = cmap.XmlTextCollector != null; ImportNamespace (schema, map.BaseMap.XmlTypeNamespace); ExportClassSchema (map.BaseMap); } else { XmlSchemaSequence particle; XmlSchemaAnyAttribute anyAttribute; ExportMembersMapSchema (schema, cmap, map.BaseMap, stype.Attributes, out particle, out anyAttribute); stype.Particle = particle; stype.AnyAttribute = anyAttribute; stype.IsMixed = cmap.XmlTextCollector != null; } foreach (XmlTypeMapping dmap in map.DerivedTypes) if (dmap.TypeData.SchemaType == SchemaTypes.Class) ExportClassSchema (dmap); } void ExportMembersMapSchema (XmlSchema schema, ClassMap map, XmlTypeMapping baseMap, XmlSchemaObjectCollection outAttributes, out XmlSchemaSequence particle, out XmlSchemaAnyAttribute anyAttribute) { particle = null; XmlSchemaSequence seq = new XmlSchemaSequence (); ICollection members = map.ElementMembers; if (members != null && !map.HasSimpleContent) { foreach (XmlTypeMapMemberElement member in members) { if (baseMap != null && DefinedInBaseMap (baseMap, member)) continue; Type memType = member.GetType(); if (memType == typeof(XmlTypeMapMemberFlatList)) { XmlSchemaParticle part = GetSchemaArrayElement (schema, member.ElementInfo); if (part != null) seq.Items.Add (part); } else if (memType == typeof(XmlTypeMapMemberAnyElement)) { seq.Items.Add (GetSchemaArrayElement (schema, member.ElementInfo)); } else if (memType == typeof(XmlTypeMapMemberElement)) { seq.Items.Add (GetSchemaElement (schema, (XmlTypeMapElementInfo) member.ElementInfo [0], member.DefaultValue, true)); } else { seq.Items.Add (GetSchemaElement (schema, (XmlTypeMapElementInfo) member.ElementInfo [0], true)); } } } if (seq.Items.Count > 0) particle = seq; // Write attributes ICollection attributes = map.AttributeMembers; if (attributes != null) { foreach (XmlTypeMapMemberAttribute attr in attributes) { if (baseMap != null && DefinedInBaseMap (baseMap, attr)) continue; outAttributes.Add (GetSchemaAttribute (schema, attr, true)); } } XmlTypeMapMember anyAttrMember = map.DefaultAnyAttributeMember; if (anyAttrMember != null) anyAttribute = new XmlSchemaAnyAttribute (); else anyAttribute = null; } XmlSchemaElement FindElement (XmlSchemaObjectCollection col, string name) { foreach (XmlSchemaObject ob in col) { XmlSchemaElement elem = ob as XmlSchemaElement; if (elem != null && elem.Name == name) return elem; } return null; } XmlSchemaComplexType FindComplexType (XmlSchemaObjectCollection col, string name) { foreach (XmlSchemaObject ob in col) { XmlSchemaComplexType ctype = ob as XmlSchemaComplexType; if (ctype != null && ctype.Name == name) return ctype; } return null; } XmlSchemaAttribute GetSchemaAttribute (XmlSchema currentSchema, XmlTypeMapMemberAttribute attinfo, bool isTypeMember) { XmlSchemaAttribute sat = new XmlSchemaAttribute (); if (attinfo.DefaultValue != System.DBNull.Value) sat.DefaultValue = XmlCustomFormatter.ToXmlString (attinfo.TypeData, attinfo.DefaultValue); ImportNamespace (currentSchema, attinfo.Namespace); XmlSchema memberSchema; if (attinfo.Namespace.Length == 0 && attinfo.Form != XmlSchemaForm.Qualified) memberSchema = currentSchema; else memberSchema = GetSchema (attinfo.Namespace); if (currentSchema == memberSchema || encodedFormat) { sat.Name = attinfo.AttributeName; if (isTypeMember) sat.Form = attinfo.Form; if (attinfo.TypeData.SchemaType == SchemaTypes.Enum) { ImportNamespace (currentSchema, attinfo.DataTypeNamespace); ExportEnumSchema (attinfo.MappedType); sat.SchemaTypeName = new XmlQualifiedName (attinfo.TypeData.XmlType, attinfo.DataTypeNamespace);; } else if (attinfo.TypeData.SchemaType == SchemaTypes.Array && TypeTranslator.IsPrimitive (attinfo.TypeData.ListItemType)) { sat.SchemaType = GetSchemaSimpleListType (attinfo.TypeData); } else sat.SchemaTypeName = new XmlQualifiedName (attinfo.TypeData.XmlType, attinfo.DataTypeNamespace);; } else { sat.RefName = new XmlQualifiedName (attinfo.AttributeName, attinfo.Namespace); foreach (XmlSchemaObject ob in memberSchema.Items) if (ob is XmlSchemaAttribute && ((XmlSchemaAttribute)ob).Name == attinfo.AttributeName) return sat; memberSchema.Items.Add (GetSchemaAttribute (memberSchema, attinfo, false)); } return sat; } XmlSchemaParticle GetSchemaElement (XmlSchema currentSchema, XmlTypeMapElementInfo einfo, bool isTypeMember) { return GetSchemaElement (currentSchema, einfo, System.DBNull.Value, isTypeMember); } XmlSchemaParticle GetSchemaElement (XmlSchema currentSchema, XmlTypeMapElementInfo einfo, object defaultValue, bool isTypeMember) { if (einfo.IsTextElement) return null; if (einfo.IsUnnamedAnyElement) { XmlSchemaAny any = new XmlSchemaAny (); any.MinOccurs = 0; any.MaxOccurs = 1; return any; } XmlSchemaElement selem = new XmlSchemaElement (); if (isTypeMember) { selem.MaxOccurs = 1; selem.MinOccurs = einfo.IsNullable ? 1 : 0; if ((einfo.TypeData.IsValueType && einfo.Member != null && !einfo.Member.IsOptionalValueType) || encodedFormat) selem.MinOccurs = 1; } XmlSchema memberSchema = null; if (!encodedFormat) { memberSchema = GetSchema (einfo.Namespace); ImportNamespace (currentSchema, einfo.Namespace); } if (currentSchema == memberSchema || encodedFormat || !isTypeMember) { if (isTypeMember) selem.IsNillable = einfo.IsNullable; selem.Name = einfo.ElementName; XmlQualifiedName typeName = new XmlQualifiedName (einfo.TypeData.XmlType, einfo.DataTypeNamespace); if (defaultValue != System.DBNull.Value) selem.DefaultValue = XmlCustomFormatter.ToXmlString (einfo.TypeData, defaultValue); if (einfo.Form != XmlSchemaForm.Qualified) selem.Form = einfo.Form; switch (einfo.TypeData.SchemaType) { case SchemaTypes.XmlNode: selem.SchemaType = GetSchemaXmlNodeType (); break; case SchemaTypes.XmlSerializable: selem.SchemaType = GetSchemaXmlSerializableType (); break; case SchemaTypes.Enum: selem.SchemaTypeName = new XmlQualifiedName (einfo.MappedType.XmlType, einfo.MappedType.XmlTypeNamespace); ImportNamespace (currentSchema, einfo.MappedType.XmlTypeNamespace); ExportEnumSchema (einfo.MappedType); break; case SchemaTypes.Array: XmlQualifiedName atypeName = ExportArraySchema (einfo.MappedType, currentSchema.TargetNamespace); selem.SchemaTypeName = atypeName; ImportNamespace (currentSchema, atypeName.Namespace); break; case SchemaTypes.Class: if (einfo.MappedType.TypeData.Type != typeof(object)) { selem.SchemaTypeName = new XmlQualifiedName (einfo.MappedType.XmlType, einfo.MappedType.XmlTypeNamespace); ImportNamespace (currentSchema, einfo.MappedType.XmlTypeNamespace); } else if (encodedFormat) selem.SchemaTypeName = new XmlQualifiedName (einfo.MappedType.XmlType, einfo.MappedType.XmlTypeNamespace); ExportClassSchema (einfo.MappedType); break; case SchemaTypes.Primitive: selem.SchemaTypeName = new XmlQualifiedName (einfo.TypeData.XmlType, einfo.DataTypeNamespace);; break; } } else { selem.RefName = new XmlQualifiedName (einfo.ElementName, einfo.Namespace); foreach (XmlSchemaObject ob in memberSchema.Items) if (ob is XmlSchemaElement && ((XmlSchemaElement)ob).Name == einfo.ElementName) return selem; memberSchema.Items.Add (GetSchemaElement (memberSchema, einfo, defaultValue, false)); } return selem; } void ImportNamespace (XmlSchema schema, string ns) { if (ns == "" || ns == schema.TargetNamespace || ns == XmlSchema.Namespace) return; foreach (XmlSchemaObject sob in schema.Includes) if ((sob is XmlSchemaImport) && ((XmlSchemaImport)sob).Namespace == ns) return; XmlSchemaImport imp = new XmlSchemaImport (); imp.Namespace = ns; schema.Includes.Add (imp); } bool DefinedInBaseMap (XmlTypeMapping map, XmlTypeMapMember member) { if (((ClassMap)map.ObjectMap).FindMember (member.Name) != null) return true; else if (map.BaseMap != null) return DefinedInBaseMap (map.BaseMap, member); else return false; } XmlSchemaType GetSchemaXmlNodeType () { XmlSchemaComplexType stype = new XmlSchemaComplexType (); stype.IsMixed = true; XmlSchemaSequence seq = new XmlSchemaSequence (); seq.Items.Add (new XmlSchemaAny ()); stype.Particle = seq; return stype; } XmlSchemaType GetSchemaXmlSerializableType () { XmlSchemaComplexType stype = new XmlSchemaComplexType (); XmlSchemaSequence seq = new XmlSchemaSequence (); XmlSchemaElement selem = new XmlSchemaElement (); selem.RefName = new XmlQualifiedName ("schema",XmlSchema.Namespace); seq.Items.Add (selem); seq.Items.Add (new XmlSchemaAny ()); stype.Particle = seq; return stype; } XmlSchemaSimpleType GetSchemaSimpleListType (TypeData typeData) { XmlSchemaSimpleType stype = new XmlSchemaSimpleType (); XmlSchemaSimpleTypeList list = new XmlSchemaSimpleTypeList (); TypeData itemTypeData = TypeTranslator.GetTypeData (typeData.ListItemType); list.ItemTypeName = new XmlQualifiedName (itemTypeData.XmlType, XmlSchema.Namespace); stype.Content = list; return stype; } XmlSchemaParticle GetSchemaArrayElement (XmlSchema currentSchema, XmlTypeMapElementInfoList infos) { int numInfos = infos.Count; if (numInfos > 0 && ((XmlTypeMapElementInfo)infos[0]).IsTextElement) numInfos--; if (numInfos == 0) return null; if (numInfos == 1) { XmlSchemaParticle selem = GetSchemaElement (currentSchema, (XmlTypeMapElementInfo) infos[infos.Count-1], true); selem.MinOccursString = "0"; selem.MaxOccursString = "unbounded"; return selem; } else { XmlSchemaChoice schoice = new XmlSchemaChoice (); schoice.MinOccursString = "0"; schoice.MaxOccursString = "unbounded"; foreach (XmlTypeMapElementInfo einfo in infos) { if (einfo.IsTextElement) continue; schoice.Items.Add (GetSchemaElement (currentSchema, einfo, true)); } return schoice; } } void ExportEnumSchema (XmlTypeMapping map) { if (IsMapExported (map)) return; SetMapExported (map); XmlSchema schema = GetSchema (map.XmlTypeNamespace); XmlSchemaSimpleType stype = new XmlSchemaSimpleType (); stype.Name = map.ElementName; schema.Items.Add (stype); XmlSchemaSimpleTypeRestriction rest = new XmlSchemaSimpleTypeRestriction (); rest.BaseTypeName = new XmlQualifiedName ("string",XmlSchema.Namespace); EnumMap emap = (EnumMap) map.ObjectMap; foreach (EnumMap.EnumMapMember emem in emap.Members) { XmlSchemaEnumerationFacet ef = new XmlSchemaEnumerationFacet (); ef.Value = emem.XmlName; rest.Facets.Add (ef); } stype.Content = rest; } XmlQualifiedName ExportArraySchema (XmlTypeMapping map, string defaultNamespace) { ListMap lmap = (ListMap) map.ObjectMap; if (encodedFormat) { string name, ns, schemaNs; lmap.GetArrayType (-1, out name, out ns); if (ns == XmlSchema.Namespace) schemaNs = defaultNamespace; else schemaNs = ns; if (IsMapExported (map)) return new XmlQualifiedName (lmap.GetSchemaArrayName (), schemaNs); SetMapExported (map); XmlSchema schema = GetSchema (schemaNs); XmlSchemaComplexType stype = new XmlSchemaComplexType (); stype.Name = lmap.GetSchemaArrayName (); schema.Items.Add (stype); XmlSchemaComplexContent content = new XmlSchemaComplexContent(); content.IsMixed = false; stype.ContentModel = content; XmlSchemaComplexContentRestriction rest = new XmlSchemaComplexContentRestriction (); content.Content = rest; rest.BaseTypeName = new XmlQualifiedName ("Array", XmlSerializer.EncodingNamespace); XmlSchemaAttribute at = new XmlSchemaAttribute (); rest.Attributes.Add (at); at.RefName = new XmlQualifiedName ("arrayType", XmlSerializer.EncodingNamespace); XmlAttribute arrayType = Document.CreateAttribute ("arrayType", XmlSerializer.WsdlNamespace); arrayType.Value = ns + (ns != "" ? ":" : "") + name; at.UnhandledAttributes = new XmlAttribute [] { arrayType }; ImportNamespace (schema, XmlSerializer.WsdlNamespace); XmlTypeMapElementInfo einfo = (XmlTypeMapElementInfo) lmap.ItemInfo[0]; if (einfo.MappedType != null) { switch (einfo.TypeData.SchemaType) { case SchemaTypes.Enum: ExportEnumSchema (einfo.MappedType); break; case SchemaTypes.Array: ExportArraySchema (einfo.MappedType, schemaNs); break; case SchemaTypes.Class: ExportClassSchema (einfo.MappedType); break; } } return new XmlQualifiedName (lmap.GetSchemaArrayName (), schemaNs); } else { if (IsMapExported (map)) return new XmlQualifiedName (map.XmlType, map.XmlTypeNamespace); SetMapExported (map); XmlSchema schema = GetSchema (map.XmlTypeNamespace); XmlSchemaComplexType stype = new XmlSchemaComplexType (); stype.Name = map.ElementName; schema.Items.Add (stype); XmlSchemaParticle spart = GetSchemaArrayElement (schema, lmap.ItemInfo); if (spart is XmlSchemaChoice) stype.Particle = spart; else { XmlSchemaSequence seq = new XmlSchemaSequence (); seq.Items.Add (spart); stype.Particle = seq; } return new XmlQualifiedName (map.XmlType, map.XmlTypeNamespace); } } XmlDocument Document { get { if (xmlDoc == null) xmlDoc = new XmlDocument (); return xmlDoc; } } bool IsMapExported (XmlTypeMapping map) { if (exportedMaps.ContainsKey (GetMapKey(map))) return true; return false; } void SetMapExported (XmlTypeMapping map) { exportedMaps [GetMapKey(map)] = map; } bool IsElementExported (XmlTypeMapping map) { if (exportedElements.ContainsKey (GetMapKey(map))) return true; if (map.TypeData.Type == typeof(object)) return true; return false; } void SetElementExported (XmlTypeMapping map) { exportedElements [GetMapKey(map)] = map; } string GetMapKey (XmlTypeMapping map) { // Don't use type name for array types, since we can have different // classes that represent the same array type (for example // StringCollection and string[]). if (map.TypeData.IsListType) return GetArrayKeyName (map.TypeData) + " " + map.XmlType + " " + map.XmlTypeNamespace; else return map.TypeData.FullTypeName + " " + map.XmlType + " " + map.XmlTypeNamespace; } string GetArrayKeyName (TypeData td) { TypeData etd = td.ListItemTypeData; return "*arrayof*" + (etd.IsListType ? GetArrayKeyName (etd) : etd.FullTypeName); } void CompileSchemas () { // foreach (XmlSchema sc in schemas) // sc.Compile (null); } XmlSchema GetSchema (string ns) { XmlSchema schema = schemas [ns]; if (schema == null) { schema = new XmlSchema (); schema.TargetNamespace = ns; if (!encodedFormat) schema.ElementFormDefault = XmlSchemaForm.Qualified; schemas.Add (schema); } return schema; } #endregion // Methods } #endif // CONFIG_SERIALIZATION }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.PythonTools.Parsing; using Microsoft.VisualStudio.Debugger; namespace Microsoft.PythonTools.DkmDebugger.Proxies { [DebuggerDisplay("& {Read()}")] internal struct ByteProxy : IWritableDataProxy<Byte> { public DkmProcess Process { get; private set; } public ulong Address { get; private set; } public ByteProxy(DkmProcess process, ulong address) : this() { Debug.Assert(process != null && address != 0); Process = process; Address = address; } public long ObjectSize { get { return sizeof(Byte); } } public unsafe Byte Read() { Byte result; Process.ReadMemory(Address, DkmReadMemoryFlags.None, &result, sizeof(Byte)); return result; } object IValueStore.Read() { return Read(); } public void Write(Byte value) { Process.WriteMemory(Address, new[] { value }); } void IWritableDataProxy.Write(object value) { Write((Byte)value); } } [DebuggerDisplay("& {Read()}")] internal struct SByteProxy : IWritableDataProxy<SByte> { public DkmProcess Process { get; private set; } public ulong Address { get; private set; } public SByteProxy(DkmProcess process, ulong address) : this() { Debug.Assert(process != null && address != 0); Process = process; Address = address; } public long ObjectSize { get { return sizeof(SByte); } } public unsafe SByte Read() { SByte result; Process.ReadMemory(Address, DkmReadMemoryFlags.None, &result, sizeof(SByte)); return result; } object IValueStore.Read() { return Read(); } public void Write(SByte value) { Process.WriteMemory(Address, new[] { (byte)value }); } void IWritableDataProxy.Write(object value) { Write((SByte)value); } } [DebuggerDisplay("& {Read()}")] internal struct Int16Proxy : IWritableDataProxy<Int16> { public DkmProcess Process { get; private set; } public ulong Address { get; private set; } public Int16Proxy(DkmProcess process, ulong address) : this() { Debug.Assert(process != null && address != 0); Process = process; Address = address; } public long ObjectSize { get { return sizeof(Int16); } } public unsafe Int16 Read() { Int16 result; Process.ReadMemory(Address, DkmReadMemoryFlags.None, &result, sizeof(Int16)); return result; } object IValueStore.Read() { return Read(); } public void Write(Int16 value) { byte[] buf = BitConverter.GetBytes(value); Process.WriteMemory(Address, buf); } void IWritableDataProxy.Write(object value) { Write((Int16)value); } } [DebuggerDisplay("& {Read()}")] internal struct UInt16Proxy : IWritableDataProxy<UInt16> { public DkmProcess Process { get; private set; } public ulong Address { get; private set; } public UInt16Proxy(DkmProcess process, ulong address) : this() { Debug.Assert(process != null && address != 0); Process = process; Address = address; } public long ObjectSize { get { return sizeof(UInt16); } } public unsafe UInt16 Read() { UInt16 result; Process.ReadMemory(Address, DkmReadMemoryFlags.None, &result, sizeof(UInt16)); return result; } object IValueStore.Read() { return Read(); } public void Write(UInt16 value) { byte[] buf = BitConverter.GetBytes(value); Process.WriteMemory(Address, buf); } void IWritableDataProxy.Write(object value) { Write((UInt16)value); } } [DebuggerDisplay("& {Read()}")] internal struct Int32Proxy : IWritableDataProxy<Int32> { public DkmProcess Process { get; private set; } public ulong Address { get; private set; } public Int32Proxy(DkmProcess process, ulong address) : this() { Debug.Assert(process != null && address != 0); Process = process; Address = address; } public long ObjectSize { get { return sizeof(Int32); } } public unsafe Int32 Read() { Int32 result; Process.ReadMemory(Address, DkmReadMemoryFlags.None, &result, sizeof(Int32)); return result; } object IValueStore.Read() { return Read(); } public void Write(Int32 value) { byte[] buf = BitConverter.GetBytes(value); Process.WriteMemory(Address, buf); } void IWritableDataProxy.Write(object value) { Write((Int32)value); } } [DebuggerDisplay("& {Read()}")] internal struct UInt32Proxy : IWritableDataProxy<UInt32> { public DkmProcess Process { get; private set; } public ulong Address { get; private set; } public UInt32Proxy(DkmProcess process, ulong address) : this() { Debug.Assert(process != null && address != 0); Process = process; Address = address; } public long ObjectSize { get { return sizeof(UInt32); } } public unsafe UInt32 Read() { UInt32 result; Process.ReadMemory(Address, DkmReadMemoryFlags.None, &result, sizeof(UInt32)); return result; } object IValueStore.Read() { return Read(); } public void Write(UInt32 value) { byte[] buf = BitConverter.GetBytes(value); Process.WriteMemory(Address, buf); } void IWritableDataProxy.Write(object value) { Write((UInt32)value); } } [DebuggerDisplay("& {Read()}")] internal struct Int32EnumProxy<TEnum> : IWritableDataProxy<TEnum> { public Int32Proxy UnderlyingProxy { get; private set; } [SuppressMessage("Microsoft.Usage", "CA2207:InitializeValueTypeStaticFieldsInline", Justification = ".cctor used for debug check, not initialization")] static Int32EnumProxy() { Debug.Assert(typeof(TEnum).IsSubclassOf(typeof(Enum))); } public Int32EnumProxy(DkmProcess process, ulong address) : this() { UnderlyingProxy = new Int32Proxy(process, address); } public DkmProcess Process { get { return UnderlyingProxy.Process; } } public ulong Address { get { return UnderlyingProxy.Address; } } public long ObjectSize { get { return UnderlyingProxy.ObjectSize; } } public unsafe TEnum Read() { return (TEnum)Enum.ToObject(typeof(TEnum), UnderlyingProxy.Read()); } object IValueStore.Read() { return Read(); } public void Write(TEnum value) { UnderlyingProxy.Write(Convert.ToInt32(value)); } void IWritableDataProxy.Write(object value) { Write((TEnum)value); } } [DebuggerDisplay("& {Read()}")] internal struct Int64Proxy : IWritableDataProxy<Int64> { public DkmProcess Process { get; private set; } public ulong Address { get; private set; } public Int64Proxy(DkmProcess process, ulong address) : this() { Debug.Assert(process != null && address != 0); Process = process; Address = address; } public long ObjectSize { get { return sizeof(Int64); } } public unsafe Int64 Read() { Int64 result; Process.ReadMemory(Address, DkmReadMemoryFlags.None, &result, sizeof(Int64)); return result; } object IValueStore.Read() { return Read(); } public void Write(Int64 value) { byte[] buf = BitConverter.GetBytes(value); Process.WriteMemory(Address, buf); } void IWritableDataProxy.Write(object value) { Write((Int64)value); } } [DebuggerDisplay("& {Read()}")] internal struct UInt64Proxy : IWritableDataProxy<UInt64> { public DkmProcess Process { get; private set; } public ulong Address { get; private set; } public UInt64Proxy(DkmProcess process, ulong address) : this() { Debug.Assert(process != null && address != 0); Process = process; Address = address; } public long ObjectSize { get { return sizeof(UInt64); } } public unsafe UInt64 Read() { UInt64 result; Process.ReadMemory(Address, DkmReadMemoryFlags.None, &result, sizeof(UInt64)); return result; } object IValueStore.Read() { return Read(); } public void Write(UInt64 value) { byte[] buf = BitConverter.GetBytes(value); Process.WriteMemory(Address, buf); } void IWritableDataProxy.Write(object value) { Write((UInt64)value); } } [DebuggerDisplay("& {Read()}")] internal struct SingleProxy : IWritableDataProxy<Single> { public DkmProcess Process { get; private set; } public ulong Address { get; private set; } public SingleProxy(DkmProcess process, ulong address) : this() { Debug.Assert(process != null && address != 0); Process = process; Address = address; } public long ObjectSize { get { return sizeof(Single); } } public unsafe Single Read() { Single result; Process.ReadMemory(Address, DkmReadMemoryFlags.None, &result, sizeof(Single)); return result; } object IValueStore.Read() { return Read(); } public void Write(Single value) { byte[] buf = BitConverter.GetBytes(value); Process.WriteMemory(Address, buf); } void IWritableDataProxy.Write(object value) { Write((Single)value); } } [DebuggerDisplay("& {Read()}")] internal struct DoubleProxy : IWritableDataProxy<Double> { public DkmProcess Process { get; private set; } public ulong Address { get; private set; } public DoubleProxy(DkmProcess process, ulong address) : this() { Debug.Assert(process != null && address != 0); Process = process; Address = address; } public long ObjectSize { get { return sizeof(Double); } } public unsafe Double Read() { Double result; Process.ReadMemory(Address, DkmReadMemoryFlags.None, &result, sizeof(Double)); return result; } object IValueStore.Read() { return Read(); } public void Write(Double value) { byte[] buf = BitConverter.GetBytes(value); Process.WriteMemory(Address, buf); } void IWritableDataProxy.Write(object value) { Write((Double)value); } } [DebuggerDisplay("& {Read()}")] internal struct SSizeTProxy : IWritableDataProxy<long> { public DkmProcess Process { get; private set; } public ulong Address { get; private set; } public SSizeTProxy(DkmProcess process, ulong address) : this() { Debug.Assert(process != null && address != 0); Process = process; Address = address; } public long ObjectSize { get { return Process.GetPointerSize(); } } public unsafe long Read() { if (Process.Is64Bit()) { long result; Process.ReadMemory(Address, DkmReadMemoryFlags.None, &result, sizeof(long)); return result; } else { int result; Process.ReadMemory(Address, DkmReadMemoryFlags.None, &result, sizeof(int)); return result; } } object IValueStore.Read() { return Read(); } public void Write(long value) { byte[] buf = Process.Is64Bit() ? BitConverter.GetBytes(value) : BitConverter.GetBytes((int)value); Process.WriteMemory(Address, buf); } void IWritableDataProxy.Write(object value) { Write((long)value); } public void Increment(long amount = 1) { Write(Read() + amount); } public void Decrement(long amount = 1) { Increment(-amount); } } [DebuggerDisplay("& {Read()}")] internal struct BoolProxy : IWritableDataProxy<bool> { public DkmProcess Process { get; private set; } public ulong Address { get; private set; } public BoolProxy(DkmProcess process, ulong address) : this() { Debug.Assert(process != null && address != 0); Process = process; Address = address; } public long ObjectSize { get { return sizeof(byte); } } public unsafe bool Read() { byte b; Process.ReadMemory(Address, DkmReadMemoryFlags.None, &b, sizeof(byte)); return b != 0; } object IValueStore.Read() { return Read(); } public void Write(bool value) { Process.WriteMemory(Address, new[] { value ? (byte)1 : (byte)0 }); } void IWritableDataProxy.Write(object value) { Write((bool)value); } } [DebuggerDisplay("& {Read()}")] internal struct CharProxy : IDataProxy { public DkmProcess Process { get; private set; } public ulong Address { get; private set; } public CharProxy(DkmProcess process, ulong address) : this() { Debug.Assert(process != null && address != 0); Process = process; Address = address; } public long ObjectSize { get { return sizeof(byte); } } unsafe object IValueStore.Read() { byte b; Process.ReadMemory(Address, DkmReadMemoryFlags.None, &b, sizeof(byte)); string s = ((char)b).ToString(); if (Process.GetPythonRuntimeInfo().LanguageVersion <= PythonLanguageVersion.V27) { return new AsciiString(new[] { b }, s); } else { return s; } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Runtime; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Runtime.ConsistentRing; using Orleans.Runtime.Counters; using Orleans.Runtime.GrainDirectory; using Orleans.Runtime.LogConsistency; using Orleans.Runtime.Messaging; using Orleans.Runtime.MultiClusterNetwork; using Orleans.Runtime.Providers; using Orleans.Runtime.ReminderService; using Orleans.Runtime.Scheduler; using Orleans.Services; using Orleans.Streams; using Orleans.Runtime.Versions; using Orleans.Versions; using Orleans.ApplicationParts; using Orleans.Configuration; using Orleans.Serialization; using Orleans.Internal; namespace Orleans.Runtime { /// <summary> /// Orleans silo. /// </summary> public class Silo { /// <summary> Standard name for Primary silo. </summary> public const string PrimarySiloName = "Primary"; private static TimeSpan WaitForMessageToBeQueuedForOutbound = TimeSpan.FromSeconds(2); /// <summary> Silo Types. </summary> public enum SiloType { /// <summary> No silo type specified. </summary> None = 0, /// <summary> Primary silo. </summary> Primary, /// <summary> Secondary silo. </summary> Secondary, } private readonly ILocalSiloDetails siloDetails; private readonly ClusterOptions clusterOptions; private readonly ISiloMessageCenter messageCenter; private readonly OrleansTaskScheduler scheduler; private readonly LocalGrainDirectory localGrainDirectory; private readonly ActivationDirectory activationDirectory; private readonly IncomingMessageAgent incomingAgent; private readonly IncomingMessageAgent incomingSystemAgent; private readonly IncomingMessageAgent incomingPingAgent; private readonly ILogger logger; private TypeManager typeManager; private readonly TaskCompletionSource<int> siloTerminatedTask = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously); private readonly SiloStatisticsManager siloStatistics; private readonly InsideRuntimeClient runtimeClient; private IReminderService reminderService; private SystemTarget fallbackScheduler; private readonly ISiloStatusOracle siloStatusOracle; private readonly IMultiClusterOracle multiClusterOracle; private readonly ExecutorService executorService; private Watchdog platformWatchdog; private readonly TimeSpan initTimeout; private readonly TimeSpan stopTimeout = TimeSpan.FromMinutes(1); private readonly Catalog catalog; private readonly object lockable = new object(); private readonly GrainFactory grainFactory; private readonly ISiloLifecycleSubject siloLifecycle; private readonly IMembershipService membershipService; private List<GrainService> grainServices = new List<GrainService>(); private readonly ILoggerFactory loggerFactory; /// <summary> /// Gets the type of this /// </summary> internal string Name => this.siloDetails.Name; internal OrleansTaskScheduler LocalScheduler { get { return scheduler; } } internal ILocalGrainDirectory LocalGrainDirectory { get { return localGrainDirectory; } } internal IMultiClusterOracle LocalMultiClusterOracle { get { return multiClusterOracle; } } internal IConsistentRingProvider RingProvider { get; private set; } internal ICatalog Catalog => catalog; internal SystemStatus SystemStatus { get; set; } internal IServiceProvider Services { get; } /// <summary> SiloAddress for this silo. </summary> public SiloAddress SiloAddress => this.siloDetails.SiloAddress; /// <summary> /// Silo termination event used to signal shutdown of this silo. /// </summary> public WaitHandle SiloTerminatedEvent // one event for all types of termination (shutdown, stop and fast kill). => ((IAsyncResult)this.siloTerminatedTask.Task).AsyncWaitHandle; public Task SiloTerminated { get { return this.siloTerminatedTask.Task; } } // one event for all types of termination (shutdown, stop and fast kill). private bool isFastKilledNeeded = false; // Set to true if something goes wrong in the shutdown/stop phase private SchedulingContext multiClusterOracleContext; private SchedulingContext reminderServiceContext; private LifecycleSchedulingSystemTarget lifecycleSchedulingSystemTarget; private EventHandler processExitHandler; /// <summary> /// Initializes a new instance of the <see cref="Silo"/> class. /// </summary> /// <param name="siloDetails">The silo initialization parameters</param> /// <param name="services">Dependency Injection container</param> [Obsolete("This constructor is obsolete and may be removed in a future release. Use SiloHostBuilder to create an instance of ISiloHost instead.")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Should not Dispose of messageCenter in this method because it continues to run / exist after this point.")] public Silo(ILocalSiloDetails siloDetails, IServiceProvider services) { string name = siloDetails.Name; // Temporarily still require this. Hopefuly gone when 2.0 is released. this.siloDetails = siloDetails; this.SystemStatus = SystemStatus.Creating; AsynchAgent.IsStarting = true; // todo. use ISiloLifecycle instead? var startTime = DateTime.UtcNow; IOptions<ClusterMembershipOptions> clusterMembershipOptions = services.GetRequiredService<IOptions<ClusterMembershipOptions>>(); initTimeout = clusterMembershipOptions.Value.MaxJoinAttemptTime; if (Debugger.IsAttached) { initTimeout = StandardExtensions.Max(TimeSpan.FromMinutes(10), clusterMembershipOptions.Value.MaxJoinAttemptTime); stopTimeout = initTimeout; } var localEndpoint = this.siloDetails.SiloAddress.Endpoint; services.GetService<SerializationManager>().RegisterSerializers(services.GetService<IApplicationPartManager>()); this.Services = services; this.Services.InitializeSiloUnobservedExceptionsHandler(); //set PropagateActivityId flag from node config IOptions<SiloMessagingOptions> messagingOptions = services.GetRequiredService<IOptions<SiloMessagingOptions>>(); RequestContext.PropagateActivityId = messagingOptions.Value.PropagateActivityId; this.loggerFactory = this.Services.GetRequiredService<ILoggerFactory>(); logger = this.loggerFactory.CreateLogger<Silo>(); logger.Info(ErrorCode.SiloGcSetting, "Silo starting with GC settings: ServerGC={0} GCLatencyMode={1}", GCSettings.IsServerGC, Enum.GetName(typeof(GCLatencyMode), GCSettings.LatencyMode)); if (!GCSettings.IsServerGC) { logger.Warn(ErrorCode.SiloGcWarning, "Note: Silo not running with ServerGC turned on - recommend checking app config : <configuration>-<runtime>-<gcServer enabled=\"true\">"); logger.Warn(ErrorCode.SiloGcWarning, "Note: ServerGC only kicks in on multi-core systems (settings enabling ServerGC have no effect on single-core machines)."); } if (logger.IsEnabled(LogLevel.Debug)) { var highestLogLevel = logger.IsEnabled(LogLevel.Trace) ? nameof(LogLevel.Trace) : nameof(LogLevel.Debug); logger.LogWarning( new EventId((int)ErrorCode.SiloGcWarning), $"A verbose logging level ({highestLogLevel}) is configured. This will impact performance. The recommended log level is {nameof(LogLevel.Information)}."); } logger.Info(ErrorCode.SiloInitializing, "-------------- Initializing silo on host {0} MachineName {1} at {2}, gen {3} --------------", this.siloDetails.DnsHostName, Environment.MachineName, localEndpoint, this.siloDetails.SiloAddress.Generation); logger.Info(ErrorCode.SiloInitConfig, "Starting silo {0}", name); var siloMessagingOptions = this.Services.GetRequiredService<IOptions<SiloMessagingOptions>>(); BufferPool.InitGlobalBufferPool(siloMessagingOptions.Value); try { grainFactory = Services.GetRequiredService<GrainFactory>(); } catch (InvalidOperationException exc) { logger.Error(ErrorCode.SiloStartError, "Exception during Silo.Start, GrainFactory was not registered in Dependency Injection container", exc); throw; } // Performance metrics siloStatistics = Services.GetRequiredService<SiloStatisticsManager>(); // The scheduler scheduler = Services.GetRequiredService<OrleansTaskScheduler>(); runtimeClient = Services.GetRequiredService<InsideRuntimeClient>(); // Initialize the message center messageCenter = Services.GetRequiredService<MessageCenter>(); var dispatcher = this.Services.GetRequiredService<Dispatcher>(); messageCenter.RerouteHandler = dispatcher.RerouteMessage; messageCenter.SniffIncomingMessage = runtimeClient.SniffIncomingMessage; // Now the router/directory service // This has to come after the message center //; note that it then gets injected back into the message center.; localGrainDirectory = Services.GetRequiredService<LocalGrainDirectory>(); // Now the activation directory. activationDirectory = Services.GetRequiredService<ActivationDirectory>(); // Now the consistent ring provider RingProvider = Services.GetRequiredService<IConsistentRingProvider>(); catalog = Services.GetRequiredService<Catalog>(); executorService = Services.GetRequiredService<ExecutorService>(); // Now the incoming message agents var messageFactory = this.Services.GetRequiredService<MessageFactory>(); incomingSystemAgent = new IncomingMessageAgent(Message.Categories.System, messageCenter, activationDirectory, scheduler, catalog.Dispatcher, messageFactory, this.loggerFactory); incomingPingAgent = new IncomingMessageAgent(Message.Categories.Ping, messageCenter, activationDirectory, scheduler, catalog.Dispatcher, messageFactory, this.loggerFactory); incomingAgent = new IncomingMessageAgent(Message.Categories.Application, messageCenter, activationDirectory, scheduler, catalog.Dispatcher, messageFactory, this.loggerFactory); siloStatusOracle = Services.GetRequiredService<ISiloStatusOracle>(); this.membershipService = Services.GetRequiredService<IMembershipService>(); this.clusterOptions = Services.GetRequiredService<IOptions<ClusterOptions>>().Value; var multiClusterOptions = Services.GetRequiredService<IOptions<MultiClusterOptions>>().Value; if (!multiClusterOptions.HasMultiClusterNetwork) { logger.Info("Skip multicluster oracle creation (no multicluster network configured)"); } else { multiClusterOracle = Services.GetRequiredService<IMultiClusterOracle>(); } this.SystemStatus = SystemStatus.Created; AsynchAgent.IsStarting = false; StringValueStatistic.FindOrCreate(StatisticNames.SILO_START_TIME, () => LogFormatter.PrintDate(startTime)); // this will help troubleshoot production deployment when looking at MDS logs. this.siloLifecycle = this.Services.GetRequiredService<ISiloLifecycleSubject>(); // register all lifecycle participants IEnumerable<ILifecycleParticipant<ISiloLifecycle>> lifecycleParticipants = this.Services.GetServices<ILifecycleParticipant<ISiloLifecycle>>(); foreach(ILifecycleParticipant<ISiloLifecycle> participant in lifecycleParticipants) { participant?.Participate(this.siloLifecycle); } // register all named lifecycle participants IKeyedServiceCollection<string, ILifecycleParticipant<ISiloLifecycle>> namedLifecycleParticipantCollection = this.Services.GetService<IKeyedServiceCollection<string,ILifecycleParticipant<ISiloLifecycle>>>(); foreach (ILifecycleParticipant<ISiloLifecycle> participant in namedLifecycleParticipantCollection ?.GetServices(this.Services) ?.Select(s => s.GetService(this.Services))) { participant?.Participate(this.siloLifecycle); } // add self to lifecycle this.Participate(this.siloLifecycle); logger.Info(ErrorCode.SiloInitializingFinished, "-------------- Started silo {0}, ConsistentHashCode {1:X} --------------", SiloAddress.ToLongString(), SiloAddress.GetConsistentHashCode()); } public async Task StartAsync(CancellationToken cancellationToken) { StartTaskWithPerfAnalysis("Start Scheduler", scheduler.Start, new Stopwatch()); // SystemTarget for provider init calls this.lifecycleSchedulingSystemTarget = Services.GetRequiredService<LifecycleSchedulingSystemTarget>(); this.fallbackScheduler = Services.GetRequiredService<FallbackSystemTarget>(); RegisterSystemTarget(lifecycleSchedulingSystemTarget); try { await this.scheduler.QueueTask(() => this.siloLifecycle.OnStart(cancellationToken), this.lifecycleSchedulingSystemTarget.SchedulingContext); } catch (Exception exc) { logger.Error(ErrorCode.SiloStartError, "Exception during Silo.Start", exc); throw; } } private void CreateSystemTargets() { logger.Debug("Creating System Targets for this silo."); logger.Debug("Creating {0} System Target", "SiloControl"); var siloControl = ActivatorUtilities.CreateInstance<SiloControl>(Services); RegisterSystemTarget(siloControl); logger.Debug("Creating {0} System Target", "ProtocolGateway"); RegisterSystemTarget(new ProtocolGateway(this.SiloAddress, this.loggerFactory)); logger.Debug("Creating {0} System Target", "DeploymentLoadPublisher"); RegisterSystemTarget(Services.GetRequiredService<DeploymentLoadPublisher>()); logger.Debug("Creating {0} System Target", "RemoteGrainDirectory + CacheValidator"); RegisterSystemTarget(LocalGrainDirectory.RemoteGrainDirectory); RegisterSystemTarget(LocalGrainDirectory.CacheValidator); logger.Debug("Creating {0} System Target", "RemoteClusterGrainDirectory"); RegisterSystemTarget(LocalGrainDirectory.RemoteClusterGrainDirectory); logger.Debug("Creating {0} System Target", "ClientObserverRegistrar + TypeManager"); this.RegisterSystemTarget(this.Services.GetRequiredService<ClientObserverRegistrar>()); var implicitStreamSubscriberTable = Services.GetRequiredService<ImplicitStreamSubscriberTable>(); var versionDirectorManager = this.Services.GetRequiredService<CachedVersionSelectorManager>(); var grainTypeManager = this.Services.GetRequiredService<GrainTypeManager>(); IOptions<TypeManagementOptions> typeManagementOptions = this.Services.GetRequiredService<IOptions<TypeManagementOptions>>(); typeManager = new TypeManager(SiloAddress, grainTypeManager, siloStatusOracle, LocalScheduler, typeManagementOptions.Value.TypeMapRefreshInterval, implicitStreamSubscriberTable, this.grainFactory, versionDirectorManager, this.loggerFactory); this.RegisterSystemTarget(typeManager); logger.Debug("Creating {0} System Target", "MembershipOracle"); if (this.membershipService is SystemTarget) { RegisterSystemTarget((SystemTarget)this.membershipService); } if (multiClusterOracle != null && multiClusterOracle is SystemTarget) { logger.Debug("Creating {0} System Target", "MultiClusterOracle"); RegisterSystemTarget((SystemTarget)multiClusterOracle); } logger.Debug("Finished creating System Targets for this silo."); } private async Task InjectDependencies() { catalog.SiloStatusOracle = this.siloStatusOracle; this.siloStatusOracle.SubscribeToSiloStatusEvents(localGrainDirectory); // consistentRingProvider is not a system target per say, but it behaves like the localGrainDirectory, so it is here this.siloStatusOracle.SubscribeToSiloStatusEvents((ISiloStatusListener)RingProvider); this.siloStatusOracle.SubscribeToSiloStatusEvents(typeManager); this.siloStatusOracle.SubscribeToSiloStatusEvents(Services.GetRequiredService<DeploymentLoadPublisher>()); this.siloStatusOracle.SubscribeToSiloStatusEvents(Services.GetRequiredService<ClientObserverRegistrar>()); var reminderTable = Services.GetService<IReminderTable>(); if (reminderTable != null) { logger.Info($"Creating reminder grain service for type={reminderTable.GetType()}"); // Start the reminder service system target reminderService = new LocalReminderService(this, reminderTable, this.initTimeout, this.loggerFactory); ; RegisterSystemTarget((SystemTarget)reminderService); } RegisterSystemTarget(catalog); await scheduler.QueueAction(catalog.Start, catalog.SchedulingContext) .WithTimeout(initTimeout, $"Starting Catalog failed due to timeout {initTimeout}"); // SystemTarget for provider init calls this.fallbackScheduler = Services.GetRequiredService<FallbackSystemTarget>(); RegisterSystemTarget(fallbackScheduler); } private Task OnRuntimeInitializeStart(CancellationToken ct) { lock (lockable) { if (!this.SystemStatus.Equals(SystemStatus.Created)) throw new InvalidOperationException(String.Format("Calling Silo.Start() on a silo which is not in the Created state. This silo is in the {0} state.", this.SystemStatus)); this.SystemStatus = SystemStatus.Starting; } logger.Info(ErrorCode.SiloStarting, "Silo Start()"); var processExitHandlingOptions = this.Services.GetRequiredService<IOptions<ProcessExitHandlingOptions>>().Value; if (processExitHandlingOptions.FastKillOnProcessExit) { var weakCapture = new WeakReference<Silo>(this); this.processExitHandler = (sender, args) => { if (weakCapture.TryGetTarget(out var silo)) silo.HandleProcessExit(sender, args); }; AppDomain.CurrentDomain.ProcessExit += this.processExitHandler; } //TODO: setup thead pool directly to lifecycle StartTaskWithPerfAnalysis("ConfigureThreadPoolAndServicePointSettings", this.ConfigureThreadPoolAndServicePointSettings, Stopwatch.StartNew()); return Task.CompletedTask; } private void StartTaskWithPerfAnalysis(string taskName, Action task, Stopwatch stopWatch) { stopWatch.Restart(); task.Invoke(); stopWatch.Stop(); this.logger.Info(ErrorCode.SiloStartPerfMeasure, $"{taskName} took {stopWatch.ElapsedMilliseconds} Milliseconds to finish"); } private async Task StartAsyncTaskWithPerfAnalysis(string taskName, Func<Task> task, Stopwatch stopWatch) { stopWatch.Restart(); await task.Invoke(); stopWatch.Stop(); this.logger.Info(ErrorCode.SiloStartPerfMeasure, $"{taskName} took {stopWatch.ElapsedMilliseconds} Milliseconds to finish"); } private async Task OnRuntimeServicesStart(CancellationToken ct) { //TODO: Setup all (or as many as possible) of the class started in this call to work directly with lifecyce var stopWatch = Stopwatch.StartNew(); // The order of these 4 is pretty much arbitrary. StartTaskWithPerfAnalysis("Start Message center",messageCenter.Start,stopWatch); StartTaskWithPerfAnalysis("Start Incoming message agents", IncomingMessageAgentsStart, stopWatch); void IncomingMessageAgentsStart() { incomingPingAgent.Start(); incomingSystemAgent.Start(); incomingAgent.Start(); } StartTaskWithPerfAnalysis("Start local grain directory", LocalGrainDirectory.Start, stopWatch); StartTaskWithPerfAnalysis("Init implicit stream subscribe table", InitImplicitStreamSubscribeTable, stopWatch); void InitImplicitStreamSubscribeTable() { // Initialize the implicit stream subscribers table. var implicitStreamSubscriberTable = Services.GetRequiredService<ImplicitStreamSubscriberTable>(); var grainTypeManager = Services.GetRequiredService<GrainTypeManager>(); implicitStreamSubscriberTable.InitImplicitStreamSubscribers(grainTypeManager.GrainClassTypeData.Select(t => t.Value.Type).ToArray()); } this.runtimeClient.CurrentStreamProviderRuntime = this.Services.GetRequiredService<SiloProviderRuntime>(); // This has to follow the above steps that start the runtime components await StartAsyncTaskWithPerfAnalysis("Create system targets and inject dependencies", () => { CreateSystemTargets(); return InjectDependencies(); }, stopWatch); // Validate the configuration. // TODO - refactor validation - jbragg //GlobalConfig.Application.ValidateConfiguration(logger); } private async Task OnRuntimeGrainServicesStart(CancellationToken ct) { var stopWatch = Stopwatch.StartNew(); // Load and init grain services before silo becomes active. await StartAsyncTaskWithPerfAnalysis("Init grain services", () => CreateGrainServices(), stopWatch); var versionStore = Services.GetService<IVersionStore>(); await StartAsyncTaskWithPerfAnalysis("Init type manager", () => scheduler .QueueTask(() => this.typeManager.Initialize(versionStore), this.typeManager.SchedulingContext) .WithTimeout(this.initTimeout, $"TypeManager Initializing failed due to timeout {initTimeout}"), stopWatch); //if running in multi cluster scenario, start the MultiClusterNetwork Oracle if (this.multiClusterOracle != null) { await StartAsyncTaskWithPerfAnalysis("Start multicluster oracle", StartMultiClusterOracle, stopWatch); async Task StartMultiClusterOracle() { logger.Info("Starting multicluster oracle with my ServiceId={0} and ClusterId={1}.", this.clusterOptions.ServiceId, this.clusterOptions.ClusterId); this.multiClusterOracleContext = (multiClusterOracle as SystemTarget)?.SchedulingContext ?? this.fallbackScheduler.SchedulingContext; await scheduler.QueueTask(() => multiClusterOracle.Start(), multiClusterOracleContext) .WithTimeout(initTimeout, $"Starting MultiClusterOracle failed due to timeout {initTimeout}"); logger.Debug("multicluster oracle created successfully."); } } try { StatisticsOptions statisticsOptions = Services.GetRequiredService<IOptions<StatisticsOptions>>().Value; StartTaskWithPerfAnalysis("Start silo statistics", () => this.siloStatistics.Start(statisticsOptions), stopWatch); logger.Debug("Silo statistics manager started successfully."); // Finally, initialize the deployment load collector, for grains with load-based placement await StartAsyncTaskWithPerfAnalysis("Start deployment load collector", StartDeploymentLoadCollector, stopWatch); async Task StartDeploymentLoadCollector() { var deploymentLoadPublisher = Services.GetRequiredService<DeploymentLoadPublisher>(); await this.scheduler.QueueTask(deploymentLoadPublisher.Start, deploymentLoadPublisher.SchedulingContext) .WithTimeout(this.initTimeout, $"Starting DeploymentLoadPublisher failed due to timeout {initTimeout}"); logger.Debug("Silo deployment load publisher started successfully."); } // Start background timer tick to watch for platform execution stalls, such as when GC kicks in var healthCheckParticipants = this.Services.GetService<IEnumerable<IHealthCheckParticipant>>().ToList(); this.platformWatchdog = new Watchdog(statisticsOptions.LogWriteInterval, healthCheckParticipants, this.executorService, this.loggerFactory); this.platformWatchdog.Start(); if (this.logger.IsEnabled(LogLevel.Debug)) { logger.Debug("Silo platform watchdog started successfully."); } } catch (Exception exc) { this.SafeExecute(() => this.logger.Error(ErrorCode.Runtime_Error_100330, String.Format("Error starting silo {0}. Going to FastKill().", this.SiloAddress), exc)); throw; } if (logger.IsEnabled(LogLevel.Debug)) { logger.Debug("Silo.Start complete: System status = {0}", this.SystemStatus); } } private Task OnBecomeActiveStart(CancellationToken ct) { var stopWatch = Stopwatch.StartNew(); StartTaskWithPerfAnalysis("Start gateway", StartGateway, stopWatch); void StartGateway() { // Now that we're active, we can start the gateway var mc = this.messageCenter as MessageCenter; mc?.StartGateway(this.Services.GetRequiredService<ClientObserverRegistrar>()); logger.Debug("Message gateway service started successfully."); } this.SystemStatus = SystemStatus.Running; return Task.CompletedTask; } private async Task OnActiveStart(CancellationToken ct) { var stopWatch = Stopwatch.StartNew(); if (this.reminderService != null) { await StartAsyncTaskWithPerfAnalysis("Start reminder service", StartReminderService, stopWatch); async Task StartReminderService() { // so, we have the view of the membership in the consistentRingProvider. We can start the reminder service this.reminderServiceContext = (this.reminderService as SystemTarget)?.SchedulingContext ?? this.fallbackScheduler.SchedulingContext; await this.scheduler.QueueTask(this.reminderService.Start, this.reminderServiceContext) .WithTimeout(this.initTimeout, $"Starting ReminderService failed due to timeout {initTimeout}"); this.logger.Debug("Reminder service started successfully."); } } foreach (var grainService in grainServices) { await StartGrainService(grainService); } } private async Task CreateGrainServices() { var grainServices = this.Services.GetServices<IGrainService>(); foreach (var grainService in grainServices) { await RegisterGrainService(grainService); } } private async Task RegisterGrainService(IGrainService service) { var grainService = (GrainService)service; RegisterSystemTarget(grainService); grainServices.Add(grainService); await this.scheduler.QueueTask(() => grainService.Init(Services), grainService.SchedulingContext).WithTimeout(this.initTimeout, $"GrainService Initializing failed due to timeout {initTimeout}"); logger.Info($"Grain Service {service.GetType().FullName} registered successfully."); } private async Task StartGrainService(IGrainService service) { var grainService = (GrainService)service; await this.scheduler.QueueTask(grainService.Start, grainService.SchedulingContext).WithTimeout(this.initTimeout, $"Starting GrainService failed due to timeout {initTimeout}"); logger.Info($"Grain Service {service.GetType().FullName} started successfully."); } private void ConfigureThreadPoolAndServicePointSettings() { PerformanceTuningOptions performanceTuningOptions = Services.GetRequiredService<IOptions<PerformanceTuningOptions>>().Value; if (performanceTuningOptions.MinDotNetThreadPoolSize > 0 || performanceTuningOptions.MinIOThreadPoolSize > 0) { int workerThreads; int completionPortThreads; ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads); if (performanceTuningOptions.MinDotNetThreadPoolSize > workerThreads || performanceTuningOptions.MinIOThreadPoolSize > completionPortThreads) { // if at least one of the new values is larger, set the new min values to be the larger of the prev. and new config value. int newWorkerThreads = Math.Max(performanceTuningOptions.MinDotNetThreadPoolSize, workerThreads); int newCompletionPortThreads = Math.Max(performanceTuningOptions.MinIOThreadPoolSize, completionPortThreads); bool ok = ThreadPool.SetMinThreads(newWorkerThreads, newCompletionPortThreads); if (ok) { logger.Info(ErrorCode.SiloConfiguredThreadPool, "Configured ThreadPool.SetMinThreads() to values: {0},{1}. Previous values are: {2},{3}.", newWorkerThreads, newCompletionPortThreads, workerThreads, completionPortThreads); } else { logger.Warn(ErrorCode.SiloFailedToConfigureThreadPool, "Failed to configure ThreadPool.SetMinThreads(). Tried to set values to: {0},{1}. Previous values are: {2},{3}.", newWorkerThreads, newCompletionPortThreads, workerThreads, completionPortThreads); } } } // Set .NET ServicePointManager settings to optimize throughput performance when using Azure storage // http://blogs.msdn.com/b/windowsazurestorage/archive/2010/06/25/nagle-s-algorithm-is-not-friendly-towards-small-requests.aspx logger.Info(ErrorCode.SiloConfiguredServicePointManager, "Configured .NET ServicePointManager to Expect100Continue={0}, DefaultConnectionLimit={1}, UseNagleAlgorithm={2} to improve Azure storage performance.", performanceTuningOptions.Expect100Continue, performanceTuningOptions.DefaultConnectionLimit, performanceTuningOptions.UseNagleAlgorithm); ServicePointManager.Expect100Continue = performanceTuningOptions.Expect100Continue; ServicePointManager.DefaultConnectionLimit = performanceTuningOptions.DefaultConnectionLimit; ServicePointManager.UseNagleAlgorithm = performanceTuningOptions.UseNagleAlgorithm; } /// <summary> /// Gracefully stop the run time system only, but not the application. /// Applications requests would be abruptly terminated, while the internal system state gracefully stopped and saved as much as possible. /// Grains are not deactivated. /// </summary> public void Stop() { var cancellationSource = new CancellationTokenSource(); cancellationSource.Cancel(); StopAsync(cancellationSource.Token).GetAwaiter().GetResult(); } /// <summary> /// Gracefully stop the run time system and the application. /// All grains will be properly deactivated. /// All in-flight applications requests would be awaited and finished gracefully. /// </summary> public void Shutdown() { var cancellationSource = new CancellationTokenSource(this.stopTimeout); StopAsync(cancellationSource.Token).GetAwaiter().GetResult(); } /// <summary> /// Gracefully stop the run time system only, but not the application. /// Applications requests would be abruptly terminated, while the internal system state gracefully stopped and saved as much as possible. /// </summary> public async Task StopAsync(CancellationToken cancellationToken) { bool gracefully = !cancellationToken.IsCancellationRequested; string operation = gracefully ? "Shutdown()" : "Stop()"; bool stopAlreadyInProgress = false; lock (lockable) { if (this.SystemStatus.Equals(SystemStatus.Stopping) || this.SystemStatus.Equals(SystemStatus.ShuttingDown) || this.SystemStatus.Equals(SystemStatus.Terminated)) { stopAlreadyInProgress = true; // Drop through to wait below } else if (!this.SystemStatus.Equals(SystemStatus.Running)) { throw new InvalidOperationException(String.Format("Calling Silo.{0} on a silo which is not in the Running state. This silo is in the {1} state.", operation, this.SystemStatus)); } else { if (gracefully) this.SystemStatus = SystemStatus.ShuttingDown; else this.SystemStatus = SystemStatus.Stopping; } } if (stopAlreadyInProgress) { logger.Info(ErrorCode.SiloStopInProgress, "Silo termination is in progress - Will wait for it to finish"); var pause = TimeSpan.FromSeconds(1); while (!this.SystemStatus.Equals(SystemStatus.Terminated)) { logger.Info(ErrorCode.WaitingForSiloStop, "Waiting {0} for termination to complete", pause); await Task.Delay(pause); } await this.SiloTerminated; return; } try { await this.scheduler.QueueTask(() => this.siloLifecycle.OnStop(cancellationToken), this.lifecycleSchedulingSystemTarget.SchedulingContext); } finally { if (this.processExitHandler != null) { AppDomain.CurrentDomain.ProcessExit -= this.processExitHandler; this.processExitHandler = null; } SafeExecute(scheduler.Stop); SafeExecute(scheduler.PrintStatistics); } } private Task OnRuntimeServicesStop(CancellationToken ct) { if (this.isFastKilledNeeded || ct.IsCancellationRequested) // No time for this return Task.CompletedTask; // Start rejecting all silo to silo application messages SafeExecute(messageCenter.BlockApplicationMessages); // Stop scheduling/executing application turns SafeExecute(scheduler.StopApplicationTurns); return Task.CompletedTask; } private Task OnRuntimeInitializeStop(CancellationToken ct) { // 10, 11, 12: Write Dead in the table, Drain scheduler, Stop msg center, ... logger.Info(ErrorCode.SiloStopped, "Silo is Stopped()"); // incoming messages SafeExecute(incomingSystemAgent.Stop); SafeExecute(incomingPingAgent.Stop); SafeExecute(incomingAgent.Stop); // timers if (platformWatchdog != null) SafeExecute(platformWatchdog.Stop); // Silo may be dying before platformWatchdog was set up if (!ct.IsCancellationRequested) SafeExecute(activationDirectory.PrintActivationDirectory); SafeExecute(messageCenter.Stop); SafeExecute(siloStatistics.Stop); SafeExecute(() => this.SystemStatus = SystemStatus.Terminated); // Setting the event should be the last thing we do. // Do nothing after that! this.siloTerminatedTask.SetResult(0); return Task.CompletedTask; } private async Task OnBecomeActiveStop(CancellationToken ct) { if (this.isFastKilledNeeded) return; bool gracefully = !ct.IsCancellationRequested; string operation = gracefully ? "Shutdown()" : "Stop()"; try { if (gracefully) { logger.Info(ErrorCode.SiloShuttingDown, "Silo starting to Shutdown()"); //Stop LocalGrainDirectory await scheduler.QueueTask(()=>localGrainDirectory.Stop(true), localGrainDirectory.CacheValidator.SchedulingContext) .WithCancellation(ct, "localGrainDirectory Stop failed because the task was cancelled"); SafeExecute(() => catalog.DeactivateAllActivations().Wait(ct)); //wait for all queued message sent to OutboundMessageQueue before MessageCenter stop and OutboundMessageQueue stop. await Task.Delay(WaitForMessageToBeQueuedForOutbound); } } catch (Exception exc) { logger.Error(ErrorCode.SiloFailedToStopMembership, $"Failed to {operation}. About to FastKill this silo.", exc); this.isFastKilledNeeded = true; } // Stop the gateway SafeExecute(messageCenter.StopAcceptingClientMessages); } private async Task OnActiveStop(CancellationToken ct) { if (this.isFastKilledNeeded || ct.IsCancellationRequested) return; if (reminderService != null) { await this.scheduler .QueueTask(reminderService.Stop, this.reminderServiceContext) .WithCancellation(ct, "Stopping ReminderService failed because the task was cancelled"); } foreach (var grainService in grainServices) { await this.scheduler .QueueTask(grainService.Stop, grainService.SchedulingContext) .WithCancellation(ct, "Stopping GrainService failed because the task was cancelled"); if (this.logger.IsEnabled(LogLevel.Debug)) { logger.Debug( "{GrainServiceType} Grain Service with Id {GrainServiceId} stopped successfully.", grainService.GetType().FullName, grainService.GetPrimaryKeyLong(out string ignored)); } } } private void SafeExecute(Action action) { Utils.SafeExecute(action, logger, "Silo.Stop"); } private void HandleProcessExit(object sender, EventArgs e) { // NOTE: We need to minimize the amount of processing occurring on this code path -- we only have under approx 2-3 seconds before process exit will occur this.logger.Warn(ErrorCode.Runtime_Error_100220, "Process is exiting"); this.isFastKilledNeeded = true; this.Stop(); } internal void RegisterSystemTarget(SystemTarget target) { var providerRuntime = this.Services.GetRequiredService<SiloProviderRuntime>(); providerRuntime.RegisterSystemTarget(target); } /// <summary> Return dump of diagnostic data from this silo. </summary> /// <param name="all"></param> /// <returns>Debug data for this silo.</returns> public string GetDebugDump(bool all = true) { var sb = new StringBuilder(); foreach (var systemTarget in activationDirectory.AllSystemTargets()) sb.AppendFormat("System target {0}:", ((ISystemTargetBase)systemTarget).GrainId.ToString()).AppendLine(); var enumerator = activationDirectory.GetEnumerator(); while(enumerator.MoveNext()) { Utils.SafeExecute(() => { var activationData = enumerator.Current.Value; var workItemGroup = scheduler.GetWorkItemGroup(activationData.SchedulingContext); if (workItemGroup == null) { sb.AppendFormat("Activation with no work item group!! Grain {0}, activation {1}.", activationData.Grain, activationData.ActivationId); sb.AppendLine(); return; } if (all || activationData.State.Equals(ActivationState.Valid)) { sb.AppendLine(workItemGroup.DumpStatus()); sb.AppendLine(activationData.DumpStatus()); } }); } logger.Info(ErrorCode.SiloDebugDump, sb.ToString()); return sb.ToString(); } /// <summary> Object.ToString override -- summary info for this silo. </summary> public override string ToString() { return localGrainDirectory.ToString(); } private void Participate(ISiloLifecycle lifecycle) { lifecycle.Subscribe<Silo>(ServiceLifecycleStage.RuntimeInitialize, (ct) => Task.Run(() => OnRuntimeInitializeStart(ct)), (ct) => Task.Run(() => OnRuntimeInitializeStop(ct))); lifecycle.Subscribe<Silo>(ServiceLifecycleStage.RuntimeServices, (ct) => Task.Run(() => OnRuntimeServicesStart(ct)), (ct) => Task.Run(() => OnRuntimeServicesStop(ct))); lifecycle.Subscribe<Silo>(ServiceLifecycleStage.RuntimeGrainServices, (ct) => Task.Run(() => OnRuntimeGrainServicesStart(ct))); lifecycle.Subscribe<Silo>(ServiceLifecycleStage.BecomeActive, (ct) => Task.Run(() => OnBecomeActiveStart(ct)), (ct) => Task.Run(() => OnBecomeActiveStop(ct))); lifecycle.Subscribe<Silo>(ServiceLifecycleStage.Active, (ct) => Task.Run(() => OnActiveStart(ct)), (ct) => Task.Run(() => OnActiveStop(ct))); } } // A dummy system target for fallback scheduler internal class FallbackSystemTarget : SystemTarget { public FallbackSystemTarget(ILocalSiloDetails localSiloDetails, ILoggerFactory loggerFactory) : base(Constants.FallbackSystemTargetId, localSiloDetails.SiloAddress, loggerFactory) { } } // A dummy system target for fallback scheduler internal class LifecycleSchedulingSystemTarget : SystemTarget { public LifecycleSchedulingSystemTarget(ILocalSiloDetails localSiloDetails, ILoggerFactory loggerFactory) : base(Constants.LifecycleSchedulingSystemTargetId, localSiloDetails.SiloAddress, loggerFactory) { } } }
//------------------------------------------------------------------------------ // <copyright file="ScriptControlManager.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI { using System; using System.Collections.ObjectModel; using System.Collections.Generic; using System.Globalization; using System.Text; using System.Web.UI; using System.Web.Resources; using System.Web.Util; using Debug = System.Diagnostics.Debug; internal class ScriptControlManager { private OrderedDictionary<IExtenderControl, List<Control>> _extenderControls; private bool _pagePreRenderRaised; private OrderedDictionary<IScriptControl, int> _scriptControls; private ScriptManager _scriptManager; private bool _scriptReferencesRegistered; public ScriptControlManager(ScriptManager scriptManager) { _scriptManager = scriptManager; } private OrderedDictionary<IExtenderControl, List<Control>> ExtenderControls { get { if (_extenderControls == null) { _extenderControls = new OrderedDictionary<IExtenderControl, List<Control>>(); } return _extenderControls; } } private OrderedDictionary<IScriptControl, int> ScriptControls { get { if (_scriptControls == null) { _scriptControls = new OrderedDictionary<IScriptControl, int>(); } return _scriptControls; } } public void AddScriptReferences(List<ScriptReferenceBase> scriptReferences) { #if DEBUG if (_scriptReferencesRegistered) { Debug.Fail("AddScriptReferences should only be called once per request but it was already called during this request."); } #endif AddScriptReferencesForScriptControls(scriptReferences); AddScriptReferencesForExtenderControls(scriptReferences); _scriptReferencesRegistered = true; } private void AddScriptReferencesForScriptControls(List<ScriptReferenceBase> scriptReferences) { // PERF: Use field directly to avoid creating Dictionary if not already created if (_scriptControls != null) { foreach (IScriptControl scriptControl in _scriptControls.Keys) { AddScriptReferenceForScriptControl(scriptReferences, scriptControl); } } } private static void AddScriptReferenceForScriptControl(List<ScriptReferenceBase> scriptReferences, IScriptControl scriptControl) { IEnumerable<ScriptReference> scriptControlReferences = scriptControl.GetScriptReferences(); if (scriptControlReferences != null) { Control scriptControlAsControl = (Control)scriptControl; ClientUrlResolverWrapper urlResolverWrapper = null; foreach (ScriptReference scriptControlReference in scriptControlReferences) { if (scriptControlReference != null) { if (urlResolverWrapper == null) { urlResolverWrapper = new ClientUrlResolverWrapper(scriptControlAsControl); } // set containing control on each script reference for client url resolution scriptControlReference.ClientUrlResolver = urlResolverWrapper; scriptControlReference.IsStaticReference = false; scriptControlReference.ContainingControl = scriptControlAsControl; // add to collection of all references scriptReferences.Add(scriptControlReference); } } } } private void AddScriptReferencesForExtenderControls(List<ScriptReferenceBase> scriptReferences) { // PERF: Use field directly to avoid creating Dictionary if not already created if (_extenderControls != null) { foreach (IExtenderControl extenderControl in _extenderControls.Keys) { AddScriptReferenceForExtenderControl(scriptReferences, extenderControl); } } } private static void AddScriptReferenceForExtenderControl(List<ScriptReferenceBase> scriptReferences, IExtenderControl extenderControl) { IEnumerable<ScriptReference> extenderControlReferences = extenderControl.GetScriptReferences(); if (extenderControlReferences != null) { Control extenderControlAsControl = (Control)extenderControl; ClientUrlResolverWrapper urlResolverWrapper = null; foreach (ScriptReference extenderControlReference in extenderControlReferences) { if (extenderControlReference != null) { if (urlResolverWrapper == null) { urlResolverWrapper = new ClientUrlResolverWrapper(extenderControlAsControl); } // set containing control on each script reference for client url resolution extenderControlReference.ClientUrlResolver = urlResolverWrapper; extenderControlReference.IsStaticReference = false; extenderControlReference.ContainingControl = extenderControlAsControl; // add to collection of all references scriptReferences.Add(extenderControlReference); } } } } private bool InControlTree(Control targetControl) { for (Control parent = targetControl.Parent; parent != null; parent = parent.Parent) { if (parent == _scriptManager.Page) { return true; } } return false; } public void OnPagePreRender(object sender, EventArgs e) { _pagePreRenderRaised = true; } public void RegisterExtenderControl<TExtenderControl>(TExtenderControl extenderControl, Control targetControl) where TExtenderControl : Control, IExtenderControl { if (extenderControl == null) { throw new ArgumentNullException("extenderControl"); } if (targetControl == null) { throw new ArgumentNullException("targetControl"); } VerifyTargetControlType(extenderControl, targetControl); if (!_pagePreRenderRaised) { throw new InvalidOperationException(AtlasWeb.ScriptControlManager_RegisterExtenderControlTooEarly); } if (_scriptReferencesRegistered) { throw new InvalidOperationException(AtlasWeb.ScriptControlManager_RegisterExtenderControlTooLate); } // A single ExtenderControl may theoretically be registered multiple times List<Control> targetControls; if (!ExtenderControls.TryGetValue(extenderControl, out targetControls)) { targetControls = new List<Control>(); ExtenderControls[extenderControl] = targetControls; } targetControls.Add(targetControl); } public void RegisterScriptControl<TScriptControl>(TScriptControl scriptControl) where TScriptControl : Control, IScriptControl { if (scriptControl == null) { throw new ArgumentNullException("scriptControl"); } if (!_pagePreRenderRaised) { throw new InvalidOperationException(AtlasWeb.ScriptControlManager_RegisterScriptControlTooEarly); } if (_scriptReferencesRegistered) { throw new InvalidOperationException(AtlasWeb.ScriptControlManager_RegisterScriptControlTooLate); } // A single ScriptControl may theoretically be registered multiple times int timesRegistered; ScriptControls.TryGetValue(scriptControl, out timesRegistered); timesRegistered++; ScriptControls[scriptControl] = timesRegistered; } public void RegisterScriptDescriptors(IExtenderControl extenderControl) { if (extenderControl == null) { throw new ArgumentNullException("extenderControl"); } Control extenderControlAsControl = extenderControl as Control; if (extenderControlAsControl == null) { throw new ArgumentException( String.Format(CultureInfo.InvariantCulture, AtlasWeb.Common_ArgumentInvalidType, typeof(Control).FullName), "extenderControl"); } List<Control> targetControls; if (!ExtenderControls.TryGetValue(extenderControl, out targetControls)) { throw new ArgumentException( String.Format(CultureInfo.InvariantCulture, AtlasWeb.ScriptControlManager_ExtenderControlNotRegistered, extenderControlAsControl.ID), "extenderControl"); } Debug.Assert(targetControls != null && targetControls.Count > 0); // A single ExtenderControl may theoretically be registered multiple times foreach (Control targetControl in targetControls) { // Only register ExtenderControl scripts if the target control is visible and in the control tree. // Else, we assume the target was not rendered. if (targetControl.Visible && InControlTree(targetControl)) { IEnumerable<ScriptDescriptor> scriptDescriptors = extenderControl.GetScriptDescriptors(targetControl); RegisterScriptsForScriptDescriptors(scriptDescriptors, extenderControlAsControl); } } } public void RegisterScriptDescriptors(IScriptControl scriptControl) { if (scriptControl == null) { throw new ArgumentNullException("scriptControl"); } Control scriptControlAsControl = scriptControl as Control; if (scriptControlAsControl == null) { throw new ArgumentException( String.Format(CultureInfo.InvariantCulture, AtlasWeb.Common_ArgumentInvalidType, typeof(Control).FullName), "scriptControl"); } // Verify that ScriptControl was previously registered int timesRegistered; if (!ScriptControls.TryGetValue(scriptControl, out timesRegistered)) { throw new ArgumentException( String.Format(CultureInfo.InvariantCulture, AtlasWeb.ScriptControlManager_ScriptControlNotRegistered, scriptControlAsControl.ID), "scriptControl"); } // A single ScriptControl may theoretically be registered multiple times for (int i = 0; i < timesRegistered; i++) { IEnumerable<ScriptDescriptor> scriptDescriptors = scriptControl.GetScriptDescriptors(); RegisterScriptsForScriptDescriptors(scriptDescriptors, scriptControlAsControl); } } private void RegisterScriptsForScriptDescriptors(IEnumerable<ScriptDescriptor> scriptDescriptors, Control control) { if (scriptDescriptors != null) { StringBuilder initBuilder = null; foreach (ScriptDescriptor scriptDescriptor in scriptDescriptors) { if (scriptDescriptor != null) { if (initBuilder == null) { initBuilder = new StringBuilder(); initBuilder.AppendLine("Sys.Application.add_init(function() {"); } initBuilder.Append(" "); initBuilder.AppendLine(scriptDescriptor.GetScript()); // Call into the descriptor to possibly register dispose functionality for async posts scriptDescriptor.RegisterDisposeForDescriptor(_scriptManager, control); } } // If scriptDescriptors enumeration is empty, we don't want to register any script. if (initBuilder != null) { initBuilder.AppendLine("});"); string initScript = initBuilder.ToString(); // DevDiv 35243: Do not use the script itself as the key, since different controls could // possibly register the exact same script, or the same control may want to register the // same script more than once. // Generate a unique script key for every registration. string initScriptKey = _scriptManager.CreateUniqueScriptKey(); _scriptManager.RegisterStartupScriptInternal( control, typeof(ScriptManager), initScriptKey, initScript, true); } } } private static void VerifyTargetControlType<TExtenderControl>( TExtenderControl extenderControl, Control targetControl) where TExtenderControl : Control, IExtenderControl { Type extenderControlType = extenderControl.GetType(); // Use TargetControlTypeCache instead of directly calling Type.GetCustomAttributes(). // Increases requests/second by nearly 100% in ScriptControlScenario.aspx test. Type[] types = TargetControlTypeCache.GetTargetControlTypes(extenderControlType); if (types.Length == 0) { throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.ScriptControlManager_NoTargetControlTypes, extenderControlType, typeof(TargetControlTypeAttribute))); } Type targetControlType = targetControl.GetType(); foreach (Type type in types) { if (type.IsAssignableFrom(targetControlType)) { return; } } throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.ScriptControlManager_TargetControlTypeInvalid, extenderControl.ID, targetControl.ID, extenderControlType, targetControlType)); } } }
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt using System; using System.Collections.Generic; using NUnit.Framework.Constraints.Comparers; namespace NUnit.Framework.Constraints { /// <summary> /// NUnitEqualityComparer encapsulates NUnit's handling of /// equality tests between objects. /// </summary> public sealed class NUnitEqualityComparer { #region Static and Instance Fields /// <summary> /// If true, all string comparisons will ignore case /// </summary> private bool caseInsensitive; /// <summary> /// If true, arrays will be treated as collections, allowing /// those of different dimensions to be compared /// </summary> private bool compareAsCollection; /// <summary> /// Comparison objects used in comparisons for some constraints. /// </summary> private readonly List<EqualityAdapter> externalComparers = new List<EqualityAdapter>(); /// <summary> /// List of points at which a failure occurred. /// </summary> private List<FailurePoint> failurePoints; /// <summary> /// List of comparers used to compare pairs of objects. /// </summary> private readonly List<IChainComparer> _comparers; #endregion /// <summary> /// Initializes a new instance of the <see cref="NUnitEqualityComparer"/> class. /// </summary> public NUnitEqualityComparer() { var enumerablesComparer = new EnumerablesComparer(this); _comparers = new List<IChainComparer> { new ArraysComparer(this, enumerablesComparer), new DictionariesComparer(this), new DictionaryEntriesComparer(this), new KeyValuePairsComparer(this), new StringsComparer(this ), new StreamsComparer(this), new CharsComparer(this), new DirectoriesComparer(), new NumericsComparer(), new DateTimeOffsetsComparer(this), new TimeSpanToleranceComparer(), new TupleComparer(this), new ValueTupleComparer(this), new StructuralComparer(this), new EquatablesComparer(this), enumerablesComparer }; } #region Properties /// <summary> /// Gets and sets a flag indicating whether case should /// be ignored in determining equality. /// </summary> public bool IgnoreCase { get { return caseInsensitive; } set { caseInsensitive = value; } } /// <summary> /// Gets and sets a flag indicating that arrays should be /// compared as collections, without regard to their shape. /// </summary> public bool CompareAsCollection { get { return compareAsCollection; } set { compareAsCollection = value; } } /// <summary> /// Gets the list of external comparers to be used to /// test for equality. They are applied to members of /// collections, in place of NUnit's own logic. /// </summary> public IList<EqualityAdapter> ExternalComparers { get { return externalComparers; } } /// <summary> /// Gets the list of failure points for the last Match performed. /// The list consists of objects to be interpreted by the caller. /// This generally means that the caller may only make use of /// objects it has placed on the list at a particular depth. /// </summary> public IList<FailurePoint> FailurePoints { get { return failurePoints; } } /// <summary> /// Flags the comparer to include <see cref="DateTimeOffset.Offset"/> /// property in comparison of two <see cref="DateTimeOffset"/> values. /// </summary> /// <remarks> /// Using this modifier does not allow to use the <see cref="Tolerance"/> /// modifier. /// </remarks> public bool WithSameOffset { get; set; } #endregion #region Public Methods /// <summary> /// Compares two objects for equality within a tolerance. /// </summary> public bool AreEqual(object x, object y, ref Tolerance tolerance) { return AreEqual(x, y, ref tolerance, new ComparisonState(true)); } internal bool AreEqual(object x, object y, ref Tolerance tolerance, ComparisonState state) { this.failurePoints = new List<FailurePoint>(); if (x == null && y == null) return true; if (x == null || y == null) return false; if (object.ReferenceEquals(x, y)) return true; if (state.DidCompare(x, y)) return false; EqualityAdapter externalComparer = GetExternalComparer(x, y); if (externalComparer != null) return externalComparer.AreEqual(x, y); foreach (IChainComparer comparer in _comparers) { bool? result = comparer.Equal(x, y, ref tolerance, state); if (result.HasValue) return result.Value; } return x.Equals(y); } #endregion #region Helper Methods private EqualityAdapter GetExternalComparer(object x, object y) { foreach (EqualityAdapter adapter in externalComparers) if (adapter.CanCompare(x, y)) return adapter; return null; } #endregion #region Nested FailurePoint Class /// <summary> /// FailurePoint class represents one point of failure /// in an equality test. /// </summary> public sealed class FailurePoint { /// <summary> /// The location of the failure /// </summary> public long Position; /// <summary> /// The expected value /// </summary> public object ExpectedValue; /// <summary> /// The actual value /// </summary> public object ActualValue; /// <summary> /// Indicates whether the expected value is valid /// </summary> public bool ExpectedHasData; /// <summary> /// Indicates whether the actual value is valid /// </summary> public bool ActualHasData; } #endregion } }
using System; using LanguageExt; using static LanguageExt.Prelude; using static LanguageExt.TypeClass; using System.Diagnostics.Contracts; using LanguageExt.TypeClasses; using LanguageExt.ClassInstances; namespace LanguageExt { public static partial class Prelude { /// <summary> /// Append an extra item to the tuple /// </summary> [Pure] public static Tuple<A, B, C, D, E, F, G> add<A, B, C, D, E, F, G>(Tuple<A, B, C, D, E, F> self, G seventh) => Tuple(self.Item1, self.Item2, self.Item3, self.Item4, self.Item5, self.Item6, seventh); /// <summary> /// Semigroup append /// </summary> [Pure] public static Tuple<A, B, C, D, E, F> append<SemiA, SemiB, SemiC, SemiD, SemiE, SemiF, A, B, C, D, E, F>(Tuple<A, B, C, D, E, F> a, Tuple<A, B, C, D, E, F> b) where SemiA : struct, Semigroup<A> where SemiB : struct, Semigroup<B> where SemiC : struct, Semigroup<C> where SemiD : struct, Semigroup<D> where SemiE : struct, Semigroup<E> where SemiF : struct, Semigroup<F> => Tuple(default(SemiA).Append(a.Item1, b.Item1), default(SemiB).Append(a.Item2, b.Item2), default(SemiC).Append(a.Item3, b.Item3), default(SemiD).Append(a.Item4, b.Item4), default(SemiE).Append(a.Item5, b.Item5), default(SemiF).Append(a.Item6, b.Item6)); /// <summary> /// Semigroup append /// </summary> [Pure] public static A append<SemiA, A>(Tuple<A, A, A, A, A, A> a) where SemiA : struct, Semigroup<A> => default(SemiA).Append(a.Item1, default(SemiA).Append(a.Item2, default(SemiA).Append(a.Item3, default(SemiA).Append(a.Item4, default(SemiA).Append(a.Item5, a.Item6))))); /// <summary> /// Monoid concat /// </summary> [Pure] public static Tuple<A, B, C, D, E, F> concat<MonoidA, MonoidB, MonoidC, MonoidD, MonoidE, MonoidF, A, B, C, D, E, F>(Tuple<A, B, C, D, E, F> a, Tuple<A, B, C, D, E, F> b) where MonoidA : struct, Monoid<A> where MonoidB : struct, Monoid<B> where MonoidC : struct, Monoid<C> where MonoidD : struct, Monoid<D> where MonoidE : struct, Monoid<E> where MonoidF : struct, Monoid<F> => Tuple(mconcat<MonoidA, A>(a.Item1, b.Item1), mconcat<MonoidB, B>(a.Item2, b.Item2), mconcat<MonoidC, C>(a.Item3, b.Item3), mconcat<MonoidD, D>(a.Item4, b.Item4), mconcat<MonoidE, E>(a.Item5, b.Item5), mconcat<MonoidF, F>(a.Item6, b.Item6)); /// <summary> /// Monoid concat /// </summary> [Pure] public static A concat<MonoidA, A>(Tuple<A, A, A, A, A, A> a) where MonoidA : struct, Monoid<A> => mconcat<MonoidA, A>(a.Item1, a.Item2, a.Item3, a.Item4, a.Item5, a.Item6); /// <summary> /// Take the first item /// </summary> [Pure] public static A head<A, B, C, D, E, F>(Tuple<A, B, C, D, E, F> self) => self.Item1; /// <summary> /// Take the last item /// </summary> [Pure] public static F last<A, B, C, D, E, F>(Tuple<A, B, C, D, E, F> self) => self.Item6; /// <summary> /// Take the second item onwards and build a new tuple /// </summary> [Pure] public static Tuple<B, C, D, E, F> tail<A, B, C, D, E, F>(Tuple<A, B, C, D, E, F> self) => Tuple(self.Item2, self.Item3, self.Item4, self.Item5, self.Item6); /// <summary> /// Sum of the items /// </summary> [Pure] public static A sum<NUM, A>(Tuple<A, A, A, A, A, A> self) where NUM : struct, Num<A> => TypeClass.sum<NUM, FoldTuple<A>, Tuple<A, A, A, A, A, A>, A>(self); /// <summary> /// Product of the items /// </summary> [Pure] public static A product<NUM, A>(Tuple<A, A, A, A, A, A> self) where NUM : struct, Num<A> => TypeClass.product<NUM, FoldTuple<A>, Tuple<A, A, A, A, A, A>, A>(self); /// <summary> /// One of the items matches the value passed /// </summary> [Pure] public static bool contains<EQ, A>(Tuple<A, A, A, A, A, A> self, A value) where EQ : struct, Eq<A> => default(EQ).Equals(self.Item1, value) || default(EQ).Equals(self.Item2, value) || default(EQ).Equals(self.Item3, value) || default(EQ).Equals(self.Item4, value) || default(EQ).Equals(self.Item5, value) || default(EQ).Equals(self.Item6, value); /// <summary> /// Map /// </summary> [Pure] public static R map<A, B, C, D, E, F, R>(Tuple<A, B, C, D, E, F> self, Func<Tuple<A, B, C, D, E, F>, R> map) => map(self); /// <summary> /// Map /// </summary> [Pure] public static R map<A, B, C, D, E, F, R>(Tuple<A, B, C, D, E, F> self, Func<A, B, C, D, E, F, R> map) => map(self.Item1, self.Item2, self.Item3, self.Item4, self.Item5, self.Item6); /// <summary> /// Tri-map to tuple /// </summary> [Pure] public static Tuple<U, V, W, X, Y, Z> map<A, B, C, D, E, F, U, V, W, X, Y, Z>(Tuple<A, B, C, D, E, F> self, Func<A, U> firstMap, Func<B, V> secondMap, Func<C, W> thirdMap, Func<D, X> fourthMap, Func<E, Y> fifthMap, Func<F, Z> sixthMap) => Tuple(firstMap(self.Item1), secondMap(self.Item2), thirdMap(self.Item3), fourthMap(self.Item4), fifthMap(self.Item5), sixthMap(self.Item6)); /// <summary> /// First item-map to tuple /// </summary> [Pure] public static Tuple<R1, B, C, D, E, F> mapFirst<A, B, C, D, E, F, R1>(Tuple<A, B, C, D, E, F> self, Func<A, R1> firstMap) => Tuple(firstMap(self.Item1), self.Item2, self.Item3, self.Item4, self.Item5, self.Item6); /// <summary> /// Second item-map to tuple /// </summary> [Pure] public static Tuple<A, R2, C, D, E, F> mapSecond<A, B, C, D, E, F, R2>(Tuple<A, B, C, D, E, F> self, Func<B, R2> secondMap) => Tuple(self.Item1, secondMap(self.Item2), self.Item3, self.Item4, self.Item5, self.Item6); /// <summary> /// Third item-map to tuple /// </summary> [Pure] public static Tuple<A, B, R3, D, E, F> mapThird<A, B, C, D, E, F, R3>(Tuple<A, B, C, D, E, F> self, Func<C, R3> thirdMap) => Tuple(self.Item1, self.Item2, thirdMap(self.Item3), self.Item4, self.Item5, self.Item6); /// <summary> /// Fourth item-map to tuple /// </summary> [Pure] public static Tuple<A, B, C, R4, E, F> mapFourth<A, B, C, D, E, F, R4>(Tuple<A, B, C, D, E, F> self, Func<D, R4> fourthMap) => Tuple(self.Item1, self.Item2, self.Item3, fourthMap(self.Item4), self.Item5, self.Item6); /// <summary> /// Fifth item-map to tuple /// </summary> [Pure] public static Tuple<A, B, C, D, R5, F> mapFifth<A, B, C, D, E, F, R5>(Tuple<A, B, C, D, E, F> self, Func<E, R5> fifthMap) => Tuple(self.Item1, self.Item2, self.Item3, self.Item4, fifthMap(self.Item5), self.Item6); /// <summary> /// Sixth item-map to tuple /// </summary> [Pure] public static Tuple<A, B, C, D, E, R6> mapSixth<A, B, C, D, E, F, R6>(Tuple<A, B, C, D, E, F> self, Func<F, R6> sixthMap) => Tuple(self.Item1, self.Item2, self.Item3, self.Item4, self.Item5, sixthMap(self.Item6)); /// <summary> /// Iterate /// </summary> public static Unit iter<A, B, C, D, E, F>(Tuple<A, B, C, D, E, F> self, Action<A, B, C, D, E, F> func) { func(self.Item1, self.Item2, self.Item3, self.Item4, self.Item5, self.Item6); return Unit.Default; } /// <summary> /// Iterate /// </summary> public static Unit iter<A, B, C, D, E, F>(Tuple<A, B, C, D, E, F> self, Action<A> first, Action<B> second, Action<C> third, Action<D> fourth, Action<E> fifth, Action<F> sixth) { first(self.Item1); second(self.Item2); third(self.Item3); fourth(self.Item4); fifth(self.Item5); sixth(self.Item6); return Unit.Default; } /// <summary> /// Fold /// </summary> [Pure] public static S fold<A, B, C, D, E, F, S>(Tuple<A, B, C, D, E, F> self, S state, Func<S, A, B, C, D, E, F, S> fold) => fold(state, self.Item1, self.Item2, self.Item3, self.Item4, self.Item5, self.Item6); /// <summary> /// Fold /// </summary> [Pure] public static S sextFold<A, B, C, D, E, F, S>(Tuple<A, B, C, D, E, F> self, S state, Func<S, A, S> firstFold, Func<S, B, S> secondFold, Func<S, C, S> thirdFold, Func<S, D, S> fourthFold, Func<S, E, S> fifthFold, Func<S, F, S> sixthFold) => sixthFold(fifthFold(fourthFold(thirdFold(secondFold(firstFold(state, self.Item1), self.Item2), self.Item3), self.Item4), self.Item5), self.Item6); /// <summary> /// Fold back /// </summary> [Pure] public static S sextFoldBack<A, B, C, D, E, F, S>(Tuple<A, B, C, D, E, F> self, S state, Func<S, F, S> firstFold, Func<S, E, S> secondFold, Func<S, D, S> thirdFold, Func<S, C, S> fourthFold, Func<S, B, S> fifthFold, Func<S, A, S> sixthFold) => sixthFold(fifthFold(fourthFold(thirdFold(secondFold(firstFold(state, self.Item6), self.Item5), self.Item4), self.Item3), self.Item2), self.Item1); } }
#if UNITY_EDITOR || RUNTIME_CSG using System; using System.Collections; using System.Collections.Generic; //using UnityEditor; using UnityEngine; namespace Sabresaurus.SabreCSG { public enum PrimitiveBrushType { Cube, Sphere, Cylinder, Prism, Custom }; /// <summary> /// A simple brush that represents a single convex shape /// </summary> [ExecuteInEditMode] public class PrimitiveBrush : Brush { [SerializeField] Polygon[] polygons; [SerializeField, HideInInspector] int prismSideCount = 6; [SerializeField, HideInInspector] int cylinderSideCount = 20; [SerializeField, HideInInspector] int sphereSideCount = 6; [SerializeField, HideInInspector] PrimitiveBrushType brushType = PrimitiveBrushType.Cube; [SerializeField, HideInInspector] bool tracked = false; int cachedInstanceID = 0; private CSGModelBase parentCsgModel; [SerializeField] WorldTransformData cachedWorldTransform; [SerializeField] int objectVersionSerialized; int objectVersionUnserialized; public PrimitiveBrushType BrushType { get { return brushType; } set { brushType = value; } } /// <summary> /// Provide new polygons for the brush /// </summary> /// <param name="polygons">New polygons.</param> /// <param name="breakTypeRelation">If the brush type has changed set this to <c>true</c>. For example if you change a cuboid into a wedge, the brush type should no longer be Cube. See BreakTypeRelation() for more details</param> public void SetPolygons(Polygon[] polygons, bool breakTypeRelation = true) { this.polygons = polygons; Invalidate(true); if (breakTypeRelation) { BreakTypeRelation(); } } /// <summary> /// Brushes retain knowledge of what they were made from, so it's easy to adjust the side count on a prism for example, while retaining some of its transform information. If you start cutting away at a prism using the clip tool for instance, it should stop tracking it as following the initial form. This method allows you to tell the brush it is no longer tracking a base form. /// </summary> public void BreakTypeRelation() { brushType = PrimitiveBrushType.Custom; } #if UNITY_EDITOR [UnityEditor.Callbacks.DidReloadScripts] static void OnReloadedScripts() { PrimitiveBrush[] brushes = FindObjectsOfType<PrimitiveBrush>(); for (int i = 0; i < brushes.Length; i++) { brushes[i].UpdateVisibility(); } } #endif void Start() { cachedWorldTransform = new WorldTransformData(transform); EnsureWellFormed(); Invalidate(false); if (brushCache == null || brushCache.Polygons == null || brushCache.Polygons.Length == 0) { RecachePolygons(true); } #if UNITY_EDITOR UnityEditor.EditorUtility.SetSelectedRenderState(GetComponent<Renderer>(), UnityEditor.EditorSelectedRenderState.Hidden); /* Deprecated UnityEditor.EditorUtility.SetSelectedWireframeHidden(GetComponent<Renderer>(), true); */ #endif objectVersionUnserialized = objectVersionSerialized; } /// <summary> /// Reset the polygons to those specified in the brush type. For example if the brush type is a cube, the polygons are reset to a cube. /// </summary> public void ResetPolygons() { if (brushType == PrimitiveBrushType.Cube) { polygons = BrushFactory.GenerateCube(); } else if (brushType == PrimitiveBrushType.Cylinder) { if (cylinderSideCount < 3) { cylinderSideCount = 3; } polygons = BrushFactory.GenerateCylinder(cylinderSideCount); } else if (brushType == PrimitiveBrushType.Sphere) { if (sphereSideCount < 3) { sphereSideCount = 3; } // Lateral only goes halfway around the sphere (180 deg), longitudinal goes all the way (360 deg) polygons = BrushFactory.GenerateSphere(sphereSideCount, sphereSideCount * 2); } else if (brushType == PrimitiveBrushType.Prism) { if (prismSideCount < 3) { prismSideCount = 3; } polygons = BrushFactory.GeneratePrism(prismSideCount); } else if (brushType == Sabresaurus.SabreCSG.PrimitiveBrushType.Custom) { // Do nothing Debug.LogError("PrimitiveBrushType.Custom is not a valid type for new brush creation"); } else { throw new NotImplementedException(); } } void DrawPolygons(Color color, params Polygon[] polygons) { GL.Begin(GL.TRIANGLES); color.a = 0.7f; GL.Color(color); for (int j = 0; j < polygons.Length; j++) { Polygon polygon = polygons[j]; Vector3 position1 = polygon.Vertices[0].Position; for (int i = 1; i < polygon.Vertices.Length - 1; i++) { GL.Vertex(transform.TransformPoint(position1)); GL.Vertex(transform.TransformPoint(polygon.Vertices[i].Position)); GL.Vertex(transform.TransformPoint(polygon.Vertices[i + 1].Position)); } } GL.End(); } #if UNITY_EDITOR public void OnRepaint(UnityEditor.SceneView sceneView, Event e) { // Selected brush green outline if (!isBrushConvex) { SabreCSGResources.GetSelectedBrushMaterial().SetPass(0); DrawPolygons(Color.red, polygons); } } #endif public override Polygon[] GenerateTransformedPolygons() { Polygon[] polygonsCopy = polygons.DeepCopy<Polygon>(); Vector3 center = transform.position; Quaternion rotation = transform.rotation; Vector3 scale = transform.localScale; for (int i = 0; i < polygons.Length; i++) { for (int j = 0; j < polygons[i].Vertices.Length; j++) { polygonsCopy[i].Vertices[j].Position = rotation * polygonsCopy[i].Vertices[j].Position.Multiply(scale) + center; polygonsCopy[i].Vertices[j].Normal = rotation * polygonsCopy[i].Vertices[j].Normal; } // Just updated a load of vertex positions, so make sure the cached plane is updated polygonsCopy[i].CalculatePlane(); } return polygonsCopy; } public override void RecalculateBrushCache() { RecachePolygons(true); RecalculateIntersections(); } public override void RecachePolygons(bool markUnbuilt) { if (brushCache == null) { brushCache = new BrushCache(); } Polygon[] cachedTransformedPolygons = GenerateTransformedPolygons(); Bounds cachedTransformedBounds = GetBoundsTransformed(); brushCache.Set(mode, cachedTransformedPolygons, cachedTransformedBounds, markUnbuilt); } public override void RecalculateIntersections() { CSGModelBase csgModel = GetCSGModel(); if (csgModel != null) { List<Brush> brushes = GetCSGModel().GetBrushes(); // Tracked brushes at edit time can be added in any order, so sort them IComparer<Brush> comparer = new BrushOrderComparer(); for (int i = 0; i < brushes.Count; i++) { if (brushes[i] == null) { brushes.RemoveAt(i); i--; } } brushes.Sort(comparer); RecalculateIntersections(brushes, true); } } public override void RecalculateIntersections(List<Brush> brushes, bool isRootChange) { List<Brush> previousVisualIntersections = brushCache.IntersectingVisualBrushes; List<Brush> previousCollisionIntersections = brushCache.IntersectingCollisionBrushes; List<Brush> intersectingVisualBrushes = CalculateIntersectingBrushes(this, brushes, false); List<Brush> intersectingCollisionBrushes = CalculateIntersectingBrushes(this, brushes, true); brushCache.SetIntersection(intersectingVisualBrushes, intersectingCollisionBrushes); if (isRootChange) { // Brushes that are either newly intersecting or no longer intersecting, they need to recalculate their // intersections, but also rebuild List<Brush> brushesToRecalcAndRebuild = new List<Brush>(); // Brushes that are still intersecting, these should recalculate their intersections any way in case // sibling order has changed to make sure their intersection order is still correct List<Brush> brushesToRecalculateOnly = new List<Brush>(); // Brushes that are either new or existing intersections for (int i = 0; i < intersectingVisualBrushes.Count; i++) { if (intersectingVisualBrushes[i] != null) { if (!previousVisualIntersections.Contains(intersectingVisualBrushes[i])) { // It's a newly intersecting brush if (!brushesToRecalcAndRebuild.Contains(intersectingVisualBrushes[i])) { brushesToRecalcAndRebuild.Add(intersectingVisualBrushes[i]); } } else { // Intersection was already present if (!brushesToRecalculateOnly.Contains(intersectingVisualBrushes[i])) { brushesToRecalculateOnly.Add(intersectingVisualBrushes[i]); } } } } // Find any brushes that no longer intersect for (int i = 0; i < previousVisualIntersections.Count; i++) { if (previousVisualIntersections[i] != null && !intersectingVisualBrushes.Contains(previousVisualIntersections[i])) { if (!brushesToRecalcAndRebuild.Contains(previousVisualIntersections[i])) { brushesToRecalcAndRebuild.Add(previousVisualIntersections[i]); } } } // Collision Pass // Brushes that are either new or existing intersections for (int i = 0; i < intersectingCollisionBrushes.Count; i++) { if (intersectingCollisionBrushes[i] != null) { if (!previousCollisionIntersections.Contains(intersectingCollisionBrushes[i])) { // It's a newly intersecting brush if (!brushesToRecalcAndRebuild.Contains(intersectingCollisionBrushes[i])) { brushesToRecalcAndRebuild.Add(intersectingCollisionBrushes[i]); } } else { // Intersection was already present if (!brushesToRecalculateOnly.Contains(intersectingCollisionBrushes[i])) { brushesToRecalculateOnly.Add(intersectingCollisionBrushes[i]); } } } } // Find any brushes that no longer intersect for (int i = 0; i < previousCollisionIntersections.Count; i++) { if (previousCollisionIntersections[i] != null && !intersectingCollisionBrushes.Contains(previousCollisionIntersections[i])) { if (!brushesToRecalcAndRebuild.Contains(previousCollisionIntersections[i])) { brushesToRecalcAndRebuild.Add(previousCollisionIntersections[i]); } } } // Notify brushes that are either newly intersecting or no longer intersecting that they need to recalculate and rebuild for (int i = 0; i < brushesToRecalcAndRebuild.Count; i++) { // Brush intersection has changed brushesToRecalcAndRebuild[i].RecalculateIntersections(brushes, false); // Brush needs to be built brushesToRecalcAndRebuild[i].BrushCache.SetUnbuilt(); } // Brushes that remain intersecting should recalc their intersection lists just in case sibling order has changed for (int i = 0; i < brushesToRecalculateOnly.Count; i++) { // Brush intersection has changed brushesToRecalculateOnly[i].RecalculateIntersections(brushes, false); } } } // Fired by the CSG Model public override void OnUndoRedoPerformed() { if (objectVersionSerialized != objectVersionUnserialized) { Invalidate(true); } } void EnsureWellFormed() { if (polygons == null || polygons.Length == 0) { // Reset custom brushes back to a cube if (brushType == PrimitiveBrushType.Custom) { brushType = PrimitiveBrushType.Cube; } ResetPolygons(); } } // public void OnDrawGizmosSelected() // { // // Ensure Edit Mode is on // GetCSGModel().EditMode = true; // } // // public void OnDrawGizmos() // { // EnsureWellFormed(); // // // Gizmos.color = Color.green; // // for (int i = 0; i < PolygonFactory.hackyDisplay1.Count; i++) // // { // // Gizmos.DrawSphere(PolygonFactory.hackyDisplay1[i], 0.2f); // // } // // // // Gizmos.color = Color.red; // // for (int i = 0; i < PolygonFactory.hackyDisplay2.Count; i++) // // { // // Gizmos.DrawSphere(PolygonFactory.hackyDisplay2[i], 0.2f); // // } // } void OnDisable() { // OnDisable is called on recompilation, so make sure we only process when needed if (this.enabled == false || (gameObject.activeInHierarchy == false && transform.root.gameObject.activeInHierarchy == true)) { GetCSGModel().OnBrushDisabled(this); // Copy the intersections list since the source list will change as we call recalculate on other brushes List<Brush> intersectingVisualBrushes = new List<Brush>(brushCache.IntersectingVisualBrushes); for (int i = 0; i < intersectingVisualBrushes.Count; i++) { if (intersectingVisualBrushes[i] != null) { intersectingVisualBrushes[i].RecalculateIntersections(); intersectingVisualBrushes[i].BrushCache.SetUnbuilt(); } } } } void UpdateTracking() { CSGModelBase parentCSGModel = GetCSGModel(); // Make sure the CSG Model knows about this brush. If they duplicated a brush in the hierarchy then this // allows us to make sure the CSG Model knows about it if (parentCSGModel != null) { bool newBrush = parentCSGModel.TrackBrush(this); if (newBrush) { MeshFilter meshFilter = gameObject.AddOrGetComponent<MeshFilter>(); meshFilter.sharedMesh = new Mesh(); brushCache = new BrushCache(); EnsureWellFormed(); RecalculateBrushCache(); } Invalidate(false); tracked = true; } else { tracked = false; } } void OnEnable() { UpdateTracking(); } void Update() { if (!tracked) { UpdateTracking(); } // If the transform has changed, needs rebuild if (cachedWorldTransform.SetFromTransform(transform)) { Invalidate(true); } } /// <summary> /// Tells the brush it has changed /// </summary> /// <param name="polygonsChanged">If set to <c>true</c> polygons will be recached.</param> public override void Invalidate(bool polygonsChanged) { if (!gameObject.activeInHierarchy) { return; } // Make sure there is a mesh filter on this object MeshFilter meshFilter = gameObject.AddOrGetComponent<MeshFilter>(); MeshRenderer meshRenderer = gameObject.AddOrGetComponent<MeshRenderer>(); // Used to use mesh colliders for ray collision, but not any more so clean them up MeshCollider[] meshColliders = GetComponents<MeshCollider>(); if (meshColliders.Length > 0) { for (int i = 0; i < meshColliders.Length; i++) { DestroyImmediate(meshColliders[i]); } } bool requireRegen = false; // If the cached ID hasn't been set or we mismatch if (cachedInstanceID == 0 || gameObject.GetInstanceID() != cachedInstanceID) { requireRegen = true; cachedInstanceID = gameObject.GetInstanceID(); } Mesh renderMesh = meshFilter.sharedMesh; if (requireRegen) { renderMesh = new Mesh(); } if (polygons != null) { List<int> polygonIndices; BrushFactory.GenerateMeshFromPolygons(polygons, ref renderMesh, out polygonIndices); } if (mode == CSGMode.Subtract) { MeshHelper.Invert(ref renderMesh); } // Displace the triangles for display along the normals very slightly (this is so we can overlay built // geometry with semi-transparent geometry and avoid depth fighting) MeshHelper.Displace(ref renderMesh, 0.001f); meshFilter.sharedMesh = renderMesh; meshRenderer.receiveShadows = false; meshRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; meshFilter.hideFlags = HideFlags.NotEditable;// | HideFlags.HideInInspector; meshRenderer.hideFlags = HideFlags.NotEditable;// | HideFlags.HideInInspector; #if UNITY_EDITOR Material material; if (IsNoCSG) { material = UnityEditor.AssetDatabase.LoadMainAssetAtPath(CSGModel.GetSabreCSGPath() + "Materials/NoCSG.mat") as Material; } else { material = UnityEditor.AssetDatabase.LoadMainAssetAtPath(CSGModel.GetSabreCSGPath() + "Materials/" + this.mode.ToString() + ".mat") as Material; } meshRenderer.sharedMaterial = material; #endif isBrushConvex = GeometryHelper.IsBrushConvex(polygons); if (polygonsChanged) { RecalculateBrushCache(); } UpdateVisibility(); objectVersionSerialized++; objectVersionUnserialized = objectVersionSerialized; } public override void UpdateVisibility() { // Display brush if the CSG Model says to or if the brush isn't under a CSG Model CSGModelBase csgModel = GetCSGModel(); bool isVisible = false; if (csgModel == null || csgModel.AreBrushesVisible) { isVisible = true; } MeshRenderer meshRenderer = GetComponent<MeshRenderer>(); if (meshRenderer != null) { meshRenderer.enabled = isVisible; } } // public Polygon GetPolygonFromTriangle(int triangleIndex) // { // int polygonIndex = polygonIndices[triangleIndex]; // return polygons[polygonIndex]; // } public override Bounds GetBounds() { if (polygons.Length > 0) { Bounds bounds = new Bounds(polygons[0].Vertices[0].Position, Vector3.zero); for (int i = 0; i < polygons.Length; i++) { for (int j = 0; j < polygons[i].Vertices.Length; j++) { bounds.Encapsulate(polygons[i].Vertices[j].Position); } } return bounds; } else { return new Bounds(Vector3.zero, Vector3.zero); } } public override Bounds GetBoundsTransformed() { if (polygons.Length > 0) { Bounds bounds = new Bounds(transform.TransformPoint(polygons[0].Vertices[0].Position), Vector3.zero); for (int i = 0; i < polygons.Length; i++) { for (int j = 0; j < polygons[i].Vertices.Length; j++) { bounds.Encapsulate(transform.TransformPoint(polygons[i].Vertices[j].Position)); } } return bounds; } else { return new Bounds(Vector3.zero, Vector3.zero); } } public float CalculateExtentsInAxis(Vector3 worldAxis) { // Transform the world axis direction to local Vector3 localAxis = transform.InverseTransformDirection(worldAxis); float minDot = Vector3.Dot(polygons[0].Vertices[0].Position, localAxis); float maxDot = minDot; for (int i = 0; i < polygons.Length; i++) { for (int j = 0; j < polygons[i].Vertices.Length; j++) { float dot = Vector3.Dot(polygons[i].Vertices[j].Position, localAxis); minDot = Mathf.Min(dot, minDot); maxDot = Mathf.Max(dot, maxDot); } } return maxDot - minDot; } public Bounds GetBoundsLocalTo(Transform otherTransform) { if (polygons.Length > 0) { Bounds bounds = new Bounds(otherTransform.InverseTransformPoint(transform.TransformPoint(polygons[0].Vertices[0].Position)), Vector3.zero); for (int i = 0; i < polygons.Length; i++) { for (int j = 0; j < polygons[i].Vertices.Length; j++) { bounds.Encapsulate(otherTransform.InverseTransformPoint(transform.TransformPoint(polygons[i].Vertices[j].Position))); } } return bounds; } else { return new Bounds(Vector3.zero, Vector3.zero); } } public override int[] GetPolygonIDs() { int[] ids = new int[polygons.Length]; for (int i = 0; i < polygons.Length; i++) { ids[i] = polygons[i].UniqueIndex; } return ids; } public override Polygon[] GetPolygons() { return polygons; } public override int AssignUniqueIDs(int startingIndex) { for (int i = 0; i < polygons.Length; i++) { int uniqueIndex = startingIndex + i; polygons[i].UniqueIndex = uniqueIndex; } int assignedCount = polygons.Length; return assignedCount; } /// <summary> /// Resets the pivot to the center of the brush. The world position of vertices remains unchanged, but the brush position and local vertex positions are updated so that the pivot is at the center. /// </summary> public void ResetPivot() { Vector3 delta = GetBounds().center; for (int i = 0; i < polygons.Length; i++) { for (int j = 0; j < polygons[i].Vertices.Length; j++) { polygons[i].Vertices[j].Position -= delta; } } // Bounds is aligned with the object transform.Translate(delta); // Counter the delta offset Transform[] childTransforms = transform.GetComponentsInChildren<Transform>(true); for (int i = 0; i < childTransforms.Length; i++) { if (childTransforms[i] != transform) { childTransforms[i].Translate(-delta); } } // Only invalidate if it's actually been realigned if (delta != Vector3.zero) { Invalidate(true); } } /// <summary> /// Duplicates the brush game object and returns the new object. /// </summary> /// <returns>The game object of the new brush.</returns> public GameObject Duplicate() { GameObject newObject = Instantiate(this.gameObject); newObject.name = this.gameObject.name; newObject.transform.parent = this.transform.parent; return newObject; } public override void PrepareToBuild(List<Brush> brushes, bool forceRebuild) { if (forceRebuild) { brushCache.SetUnbuilt(); RecachePolygons(true); RecalculateIntersections(brushes, true); } } /// <summary> /// Get the CSG Model that the brush is under /// </summary> /// <returns>The CSG Model.</returns> public CSGModelBase GetCSGModel() { if (parentCsgModel == null) { CSGModelBase[] models = transform.GetComponentsInParent<CSGModelBase>(true); if (models.Length > 0) { parentCsgModel = models[0]; } } return parentCsgModel; } public override BrushOrder GetBrushOrder() { Transform csgModelTransform = GetCSGModel().transform; List<int> reversePositions = new List<int>(); Transform traversedTransform = transform; reversePositions.Add(traversedTransform.GetSiblingIndex()); while (traversedTransform.parent != null && traversedTransform.parent != csgModelTransform) { traversedTransform = traversedTransform.parent; reversePositions.Add(traversedTransform.GetSiblingIndex()); } BrushOrder brushOrder = new BrushOrder(); int count = reversePositions.Count; brushOrder.Position = new int[count]; for (int i = 0; i < count; i++) { brushOrder.Position[i] = reversePositions[count - 1 - i]; } return brushOrder; } #if (UNITY_5_0 || UNITY_5_1) void OnDrawGizmosSelected() { CSGModel parentCSGModel = GetCSGModel() as CSGModel; if(parentCSGModel != null) { // Ensure Edit Mode is on parentCSGModel.EditMode = true; } } #endif } } #endif
using System; using System.Drawing; using System.Windows.Forms; using System.Runtime.InteropServices; /* * * NOTE : These classes and logic will work only and only if the * following key in the registry is set * HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced\EnableToolTips\ * */ namespace BalloonCS { // public enum TooltipIcon : int // { // None, // Info, // Warning, // Error // } internal class BalloonTool : NativeWindow { } /// <summary> /// A sample class to manipulate ballon tooltips. /// Windows XP balloon-tips if used properly can /// be very helpful. /// This class creates a balloon tooltip. /// This becomes useful for showing important information /// quickly to the user. /// For example in a data-entry form full of /// controls the most important /// and used control is the Order Placement button. /// Guide the user by using this hover balloon on it. /// This helps in a shorter learning cycle of the /// application. /// </summary> public class HoverBalloon : IDisposable { private BalloonTool m_tool = null; private int m_maxWidth = 250; private string m_displayText = "FMS HoverBalloon Tooltip Control Display text"; private string m_title = "FMS HoverBalloon"; private TooltipIcon m_titleIcon = TooltipIcon.None; private const string TOOLTIPS_CLASS = "tooltips_class32"; private const int WS_POPUP = unchecked((int)0x80000000); private const int SWP_NOSIZE = 0x0001; private const int SWP_NOMOVE = 0x0002; private const int SWP_NOACTIVATE = 0x0010; private const int WM_USER = 0x0400; private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1); [StructLayout(LayoutKind.Sequential)] private struct TOOLINFO { public int cbSize; public int uFlags; public IntPtr hwnd; public IntPtr uId; public Rectangle rect; public IntPtr hinst; [MarshalAs(UnmanagedType.LPTStr)] public string lpszText; public uint lParam; } private const int TTS_ALWAYSTIP = 0x01; private const int TTS_NOPREFIX = 0x02; private const int TTS_BALLOON = 0x40; private const int TTF_SUBCLASS = 0x0010; private const int TTF_TRANSPARENT = 0x0100; private const int TTM_ADDTOOL = WM_USER + 50; private const int TTM_SETMAXTIPWIDTH = WM_USER + 24; private const int TTM_SETTITLE = WM_USER + 33; [DllImport("User32", SetLastError=true)] private static extern bool SetWindowPos( IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags); [DllImport("User32", SetLastError=true)] private static extern int GetClientRect( IntPtr hWnd, ref Rectangle lpRect); [DllImport("User32", SetLastError=true)] private static extern int SendMessage( IntPtr hWnd, int Msg, int wParam, IntPtr lParam); public HoverBalloon() { m_tool = new BalloonTool(); } private bool disposed = false; public void Dispose() { Dispose(true); // Take yourself off the Finalization queue // to prevent finalization code for this object // from executing a second time. GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if(!this.disposed) { if(disposing) { // release managed resources if any } // release unmanaged resource m_tool.DestroyHandle(); // Note that this is not thread safe. // Another thread could start disposing the object // after the managed resources are disposed, // but before the disposed flag is set to true. // If thread safety is necessary, it must be // implemented by the client. } disposed = true; } // Finalizer ~HoverBalloon() { Dispose(false); } public void SetToolTip(Control parent, string tipText) { System.Diagnostics.Debug.Assert(parent.Handle!=IntPtr.Zero, "parent hwnd is null", "SetToolTip"); m_displayText = tipText; CreateParams cp = new CreateParams(); cp.ClassName = TOOLTIPS_CLASS; cp.Style = WS_POPUP | TTS_BALLOON | TTS_NOPREFIX | TTS_ALWAYSTIP; cp.Parent = parent.Handle; // create the tool m_tool.CreateHandle(cp); // make sure we make it the top level window SetWindowPos( m_tool.Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE); // create and fill in the tool tip info TOOLINFO ti = new TOOLINFO(); ti.cbSize = Marshal.SizeOf(ti); ti.uFlags = TTF_TRANSPARENT | TTF_SUBCLASS; ti.hwnd = parent.Handle; ti.lpszText = m_displayText; // get the display co-ordinates GetClientRect(parent.Handle, ref ti.rect); // add the tool tip IntPtr ptrStruct = Marshal.AllocHGlobal(Marshal.SizeOf(ti)); Marshal.StructureToPtr(ti, ptrStruct, true); SendMessage( m_tool.Handle, TTM_ADDTOOL, 0, ptrStruct); ti = (TOOLINFO)Marshal.PtrToStructure(ptrStruct, typeof(TOOLINFO)); Marshal.FreeHGlobal(ptrStruct); SendMessage( m_tool.Handle, TTM_SETMAXTIPWIDTH, 0, new IntPtr(m_maxWidth)); if(m_title != null || m_title!=string.Empty) { IntPtr ptrTitle = Marshal.StringToHGlobalAuto(m_title); SendMessage( m_tool.Handle, TTM_SETTITLE, (int)m_titleIcon, ptrTitle); Marshal.FreeHGlobal(ptrTitle); } } /// <summary> /// Sets the maximum text width of the tooltip text. /// At that length the tooltip will start wrapping text /// over to the next line. /// </summary> public int MaximumTextWidth { get { return m_maxWidth; } set { m_maxWidth = value; } } /// <summary> /// Sets up the title of the tooltip. /// </summary> public string Title { get { return m_title; } set { m_title = value; } } /// <summary> /// Sets the icon for the tooltip. /// </summary> public TooltipIcon TitleIcon { get { return m_titleIcon; } set { m_titleIcon = value; } } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // Copyright (C) 2004 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.IO; using System.Globalization; using Xunit; namespace System.Data.Tests { public class DataTableReadXmlSchemaTest : DataSetAssertion, IDisposable { private DataSet CreateTestSet() { var ds = new DataSet(); ds.Tables.Add("Table1"); ds.Tables.Add("Table2"); ds.Tables[0].Columns.Add("Column1_1"); ds.Tables[0].Columns.Add("Column1_2"); ds.Tables[0].Columns.Add("Column1_3"); ds.Tables[1].Columns.Add("Column2_1"); ds.Tables[1].Columns.Add("Column2_2"); ds.Tables[1].Columns.Add("Column2_3"); ds.Tables[0].Rows.Add(new object[] { "ppp", "www", "xxx" }); ds.Relations.Add("Rel1", ds.Tables[0].Columns[2], ds.Tables[1].Columns[0]); return ds; } private CultureInfo _currentCultureBackup; public DataTableReadXmlSchemaTest() { _currentCultureBackup = CultureInfo.CurrentCulture; ; CultureInfo.CurrentCulture = new CultureInfo("fi-FI"); } public void Dispose() { CultureInfo.CurrentCulture = _currentCultureBackup; } [Fact] public void SuspiciousDataSetElement() { string schema = @"<?xml version='1.0'?> <xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'> <xsd:attribute name='foo' type='xsd:string'/> <xsd:attribute name='bar' type='xsd:string'/> <xsd:complexType name='attRef'> <xsd:attribute name='att1' type='xsd:int'/> <xsd:attribute name='att2' type='xsd:string'/> </xsd:complexType> <xsd:element name='doc'> <xsd:complexType> <xsd:choice> <xsd:element name='elem' type='attRef'/> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema>"; var ds = new DataSet(); ds.Tables.Add(new DataTable("elem")); ds.Tables[0].ReadXmlSchema(new StringReader(schema)); AssertDataTable("table", ds.Tables[0], "elem", 2, 0, 0, 0, 0, 0); } [Fact] public void UnusedComplexTypesIgnored() { string xs = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' id='hoge'> <xs:element name='Root'> <xs:complexType> <xs:sequence> <xs:element name='Child' type='xs:string' /> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name='unusedType'> <xs:sequence> <xs:element name='Orphan' type='xs:string' /> </xs:sequence> </xs:complexType> </xs:schema>"; AssertExtensions.Throws<ArgumentException>(null, () => { var ds = new DataSet(); ds.Tables.Add(new DataTable("Root")); ds.Tables.Add(new DataTable("unusedType")); ds.Tables[0].ReadXmlSchema(new StringReader(xs)); AssertDataTable("dt", ds.Tables[0], "Root", 1, 0, 0, 0, 0, 0); // Here "unusedType" table is never imported. ds.Tables[1].ReadXmlSchema(new StringReader(xs)); }); } [Fact] public void IsDataSetAndTypeIgnored() { string xsbase = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'> <xs:element name='Root' type='unusedType' msdata:IsDataSet='{0}'> </xs:element> <xs:complexType name='unusedType'> <xs:sequence> <xs:element name='Child' type='xs:string' /> </xs:sequence> </xs:complexType> </xs:schema>"; AssertExtensions.Throws<ArgumentException>(null, () => { // When explicit msdata:IsDataSet value is "false", then // treat as usual. string xs = string.Format(xsbase, "false"); var ds = new DataSet(); ds.Tables.Add(new DataTable("Root")); ds.Tables[0].ReadXmlSchema(new StringReader(xs)); AssertDataTable("dt", ds.Tables[0], "Root", 1, 0, 0, 0, 0, 0); // Even if a global element uses a complexType, it will be // ignored if the element has msdata:IsDataSet='true' xs = string.Format(xsbase, "true"); ds = new DataSet(); ds.Tables.Add(new DataTable("Root")); ds.Tables[0].ReadXmlSchema(new StringReader(xs)); }); } [Fact] public void NestedReferenceNotAllowed() { string xs = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'> <xs:element name='Root' type='unusedType' msdata:IsDataSet='true'> </xs:element> <xs:complexType name='unusedType'> <xs:sequence> <xs:element name='Child' type='xs:string' /> </xs:sequence> </xs:complexType> <xs:element name='Foo'> <xs:complexType> <xs:sequence> <xs:element ref='Root' /> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>"; AssertExtensions.Throws<ArgumentException>(null, () => { // DataSet element cannot be converted into a DataTable. // (i.e. cannot be referenced in any other elements) var ds = new DataSet(); ds.Tables.Add(new DataTable()); ds.Tables[0].ReadXmlSchema(new StringReader(xs)); }); } [Fact] public void LocaleOnRootWithoutIsDataSet() { string xs = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'> <xs:element name='Root' msdata:Locale='ja-JP'> <xs:complexType> <xs:sequence> <xs:element name='Child' type='xs:string' /> </xs:sequence> <xs:attribute name='Attr' type='xs:integer' /> </xs:complexType> </xs:element> </xs:schema>"; var ds = new DataSet(); ds.Tables.Add("Root"); ds.Tables[0].ReadXmlSchema(new StringReader(xs)); DataTable dt = ds.Tables[0]; AssertDataTable("dt", dt, "Root", 2, 0, 0, 0, 0, 0); Assert.Equal("ja-JP", dt.Locale.Name); // DataTable's Locale comes from msdata:Locale AssertDataColumn("col1", dt.Columns[0], "Attr", true, false, 0, 1, "Attr", MappingType.Attribute, typeof(long), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false); AssertDataColumn("col2", dt.Columns[1], "Child", false, false, 0, 1, "Child", MappingType.Element, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 1, string.Empty, false, false); } [Fact] public void PrefixedTargetNS() { string xs = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata' xmlns:x='urn:foo' targetNamespace='urn:foo' elementFormDefault='qualified'> <xs:element name='DS' msdata:IsDataSet='true'> <xs:complexType> <xs:choice> <xs:element ref='x:R1' /> <xs:element ref='x:R2' /> </xs:choice> </xs:complexType> <xs:key name='key'> <xs:selector xpath='./any/string_is_OK/x:R1'/> <xs:field xpath='x:Child2'/> </xs:key> <xs:keyref name='kref' refer='x:key'> <xs:selector xpath='.//x:R2'/> <xs:field xpath='x:Child2'/> </xs:keyref> </xs:element> <xs:element name='R3' type='x:RootType' /> <xs:complexType name='extracted'> <xs:choice> <xs:element ref='x:R1' /> <xs:element ref='x:R2' /> </xs:choice> </xs:complexType> <xs:element name='R1' type='x:RootType'> <xs:unique name='Rkey'> <xs:selector xpath='.//x:Child1'/> <xs:field xpath='.'/> </xs:unique> <xs:keyref name='Rkref' refer='x:Rkey'> <xs:selector xpath='.//x:Child2'/> <xs:field xpath='.'/> </xs:keyref> </xs:element> <xs:element name='R2' type='x:RootType'> </xs:element> <xs:complexType name='RootType'> <xs:choice> <xs:element name='Child1' type='xs:string'> </xs:element> <xs:element name='Child2' type='xs:string' /> </xs:choice> <xs:attribute name='Attr' type='xs:integer' /> </xs:complexType> </xs:schema>"; // No prefixes on tables and columns var ds = new DataSet(); ds.Tables.Add(new DataTable("R3")); ds.Tables[0].ReadXmlSchema(new StringReader(xs)); DataTable dt = ds.Tables[0]; AssertDataTable("R3", dt, "R3", 3, 0, 0, 0, 0, 0); AssertDataColumn("col1", dt.Columns[0], "Attr", true, false, 0, 1, "Attr", MappingType.Attribute, typeof(long), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false); } private void ReadTest1Check(DataSet ds) { AssertDataSet("dataset", ds, "NewDataSet", 2, 1); AssertDataTable("tbl1", ds.Tables[0], "Table1", 3, 0, 0, 1, 1, 0); AssertDataTable("tbl2", ds.Tables[1], "Table2", 3, 0, 1, 0, 1, 0); DataRelation rel = ds.Relations[0]; AssertDataRelation("rel", rel, "Rel1", false, new string[] { "Column1_3" }, new string[] { "Column2_1" }, true, true); AssertUniqueConstraint("uc", rel.ParentKeyConstraint, "Constraint1", false, new string[] { "Column1_3" }); AssertForeignKeyConstraint("fk", rel.ChildKeyConstraint, "Rel1", AcceptRejectRule.None, Rule.Cascade, Rule.Cascade, new string[] { "Column2_1" }, new string[] { "Column1_3" }); } [Fact] public void TestSampleFileSimpleTables() { var ds = new DataSet(); ds.Tables.Add(new DataTable("foo")); ds.Tables[0].ReadXmlSchema(new StringReader( @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='foo' type='ct' /> <xs:complexType name='ct'> <xs:simpleContent> <xs:extension base='xs:integer'> <xs:attribute name='attr' /> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:schema>")); AssertDataSet("005", ds, "NewDataSet", 1, 0); DataTable dt = ds.Tables[0]; AssertDataTable("tab", dt, "foo", 2, 0, 0, 0, 0, 0); AssertDataColumn("attr", dt.Columns[0], "attr", true, false, 0, 1, "attr", MappingType.Attribute, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false); AssertDataColumn("text", dt.Columns[1], "foo_text", false, false, 0, 1, "foo_text", MappingType.SimpleContent, typeof(long), DBNull.Value, string.Empty, -1, string.Empty, 1, string.Empty, false, false); ds = new DataSet(); ds.Tables.Add(new DataTable("foo")); ds.Tables[0].ReadXmlSchema(new StringReader( @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='foo' type='st' /> <xs:complexType name='st'> <xs:attribute name='att1' /> <xs:attribute name='att2' type='xs:int' default='2' /> </xs:complexType> </xs:schema>")); AssertDataSet("006", ds, "NewDataSet", 1, 0); dt = ds.Tables[0]; AssertDataTable("tab", dt, "foo", 2, 0, 0, 0, 0, 0); AssertDataColumn("att1", dt.Columns["att1"], "att1", true, false, 0, 1, "att1", MappingType.Attribute, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, /*0*/-1, string.Empty, false, false); AssertDataColumn("att2", dt.Columns["att2"], "att2", true, false, 0, 1, "att2", MappingType.Attribute, typeof(int), 2, string.Empty, -1, string.Empty, /*1*/-1, string.Empty, false, false); } [Fact] public void TestSampleFileComplexTables3() { var ds = new DataSet(); ds.Tables.Add(new DataTable("e")); ds.Tables[0].ReadXmlSchema(new StringReader( @"<!-- Modified w3ctests attQ014.xsd --> <xsd:schema xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" targetNamespace=""http://xsdtesting"" xmlns:x=""http://xsdtesting""> <xsd:element name=""root""> <xsd:complexType> <xsd:sequence> <xsd:element name=""e""> <xsd:complexType> <xsd:simpleContent> <xsd:extension base=""xsd:decimal""> <xsd:attribute name=""a"" type=""xsd:string""/> </xsd:extension> </xsd:simpleContent> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:schema>")); DataTable dt = ds.Tables[0]; AssertDataTable("root", dt, "e", 2, 0, 0, 0, 0, 0); AssertDataColumn("attr", dt.Columns[0], "a", true, false, 0, 1, "a", MappingType.Attribute, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false); AssertDataColumn("simple", dt.Columns[1], "e_text", false, false, 0, 1, "e_text", MappingType.SimpleContent, typeof(decimal), DBNull.Value, string.Empty, -1, string.Empty, 1, string.Empty, false, false); } [Fact] public void TestSampleFileXPath() { var ds = new DataSet(); ds.Tables.Add(new DataTable("Track")); ds.Tables[0].ReadXmlSchema(new StringReader( @"<?xml version=""1.0"" encoding=""utf-8"" ?> <xs:schema targetNamespace=""http://neurosaudio.com/Tracks.xsd"" xmlns=""http://neurosaudio.com/Tracks.xsd"" xmlns:mstns=""http://neurosaudio.com/Tracks.xsd"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata"" elementFormDefault=""qualified"" id=""Tracks""> <xs:element name=""Tracks""> <xs:complexType> <xs:sequence> <xs:element name=""Track"" minOccurs=""0"" maxOccurs=""unbounded""> <xs:complexType> <xs:sequence> <xs:element name=""Title"" type=""xs:string"" /> <xs:element name=""Artist"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""Album"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""Performer"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""Sequence"" type=""xs:unsignedInt"" minOccurs=""0"" /> <xs:element name=""Genre"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""Comment"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""Year"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""Duration"" type=""xs:unsignedInt"" minOccurs=""0"" /> <xs:element name=""Path"" type=""xs:string"" /> <xs:element name=""DevicePath"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""FileSize"" type=""xs:unsignedInt"" minOccurs=""0"" /> <xs:element name=""Source"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""FlashStatus"" type=""xs:unsignedInt"" /> <xs:element name=""HDStatus"" type=""xs:unsignedInt"" /> </xs:sequence> <xs:attribute name=""ID"" type=""xs:unsignedInt"" msdata:AutoIncrement=""true"" msdata:AutoIncrementSeed=""1"" /> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> <xs:key name=""TrackPK"" msdata:PrimaryKey=""true""> <xs:selector xpath="".//mstns:Track"" /> <xs:field xpath=""@ID"" /> </xs:key> </xs:element> </xs:schema>")); } [Fact] public void ReadConstraints() { const string Schema = @"<?xml version=""1.0"" encoding=""utf-8""?> <xs:schema id=""NewDataSet"" xmlns="""" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata""> <xs:element name=""NewDataSet"" msdata:IsDataSet=""true"" msdata:Locale=""en-US""> <xs:complexType> <xs:choice maxOccurs=""unbounded""> <xs:element name=""Table1""> <xs:complexType> <xs:sequence> <xs:element name=""col1"" type=""xs:int"" minOccurs=""0"" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name=""Table2""> <xs:complexType> <xs:sequence> <xs:element name=""col1"" type=""xs:int"" minOccurs=""0"" /> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> <xs:unique name=""Constraint1""> <xs:selector xpath="".//Table1"" /> <xs:field xpath=""col1"" /> </xs:unique> <xs:keyref name=""fk1"" refer=""Constraint1"" msdata:ConstraintOnly=""true""> <xs:selector xpath="".//Table2"" /> <xs:field xpath=""col1"" /> </xs:keyref> </xs:element> </xs:schema>"; var ds = new DataSet(); ds.Tables.Add(new DataTable()); ds.Tables.Add(new DataTable()); ds.Tables[0].ReadXmlSchema(new StringReader(Schema)); ds.Tables[1].ReadXmlSchema(new StringReader(Schema)); Assert.Equal(0, ds.Relations.Count); Assert.Equal(1, ds.Tables[0].Constraints.Count); Assert.Equal(0, ds.Tables[1].Constraints.Count); Assert.Equal("Constraint1", ds.Tables[0].Constraints[0].ConstraintName); } } }
/*The MIT License (MIT) Copyright (c) 2014 PMU Staff Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Server.Scripting; using Server.IO; using Server.Players; using System.Xml; using Server; using Server.Network; using Server.Maps; namespace Script { public class PitchBlackAbyss { public enum Difficulty {Easy, Normal}; public enum Room {One, Two, Three, Four, Heal, Maze, Random, Start, End, Error}; public static void ChangeDungeonCoords(Client client, Enums.Direction dir) { int dist = 1; int rand = Server.Math.Rand(1, 10000); if (rand <= 66) { //.66% chance warp exPlayer.Get(client).DungeonX = Server.Math.Rand(0, exPlayer.Get(client).DungeonMaxX-1); exPlayer.Get(client).DungeonY = Server.Math.Rand(0, exPlayer.Get(client).DungeonMaxY-1); return; } else if (rand <= 666) { //6% chance skip dist = 2; } if (dir == Enums.Direction.Up) { exPlayer.Get(client).DungeonY = exPlayer.Get(client).DungeonY - dist; if (exPlayer.Get(client).DungeonY < 0) { exPlayer.Get(client).DungeonY += exPlayer.Get(client).DungeonMaxY; } } else if (dir == Enums.Direction.Down) { exPlayer.Get(client).DungeonY = (exPlayer.Get(client).DungeonY + dist) % exPlayer.Get(client).DungeonMaxY; } else if (dir == Enums.Direction.Left) { exPlayer.Get(client).DungeonX = exPlayer.Get(client).DungeonX - dist; if (exPlayer.Get(client).DungeonX < 0) { exPlayer.Get(client).DungeonX += exPlayer.Get(client).DungeonMaxX; } } else if (dir == Enums.Direction.Right) { exPlayer.Get(client).DungeonX = (exPlayer.Get(client).DungeonX + dist) % exPlayer.Get(client).DungeonMaxX; } } //change to use Enums.Direction public static void GetDungeonRoom(Client client, int dir) { //gets the room type from a table //dir: 1=up,2=down,3=left,4=right Enums.Direction direc; if (dir == 1) { direc = Enums.Direction.Up; } else if (dir == 2) { direc = Enums.Direction.Down; } else if (dir == 3) { direc = Enums.Direction.Left; } else { //dir = 4 direc = Enums.Direction.Right; } ChangeDungeonCoords(client, direc); int x = 0, y = 0; switch (dir) { case 1: { x = client.Player.X; if (x > 19) x = x - 14; //adjust for maze maps y = 12; } break; case 2: { x = client.Player.X; if (x > 19) x = x - 14; y = 2; } break; case 3: { x = 17; y = client.Player.Y; if (y > 14) y = y - 10; } break; case 4: { x = 2; y = client.Player.Y; if (y > 14) y = y - 10; } break; } if (client.Player.IsInParty()) { Server.Players.Parties.Party party = Server.Players.Parties.PartyManager.FindPlayerParty(client); foreach (Client member in party.GetOnlineMemberClients() ) { //check if they're in the same room if (client != member && exPlayer.Get(client).DungeonX == exPlayer.Get(member).DungeonX && exPlayer.Get(client).DungeonY == exPlayer.Get(member).DungeonY) { Messenger.PlayerWarp(client, member.Player.Map, x, y); return; } } } Room rtype = GetRoomType(client); int roomType; if (rtype == Room.One) roomType = 1; else if (rtype == Room.Two) roomType = 2; else if (rtype == Room.Three) roomType = 3; else if (rtype == Room.Four || rtype == Room.Heal) roomType = 4; else if (rtype == Room.Random) roomType = 5; else if (rtype == Room.Maze) roomType = 7; else if (rtype == Room.End) roomType = 6; else // rtype == Room.Error return; int smallType = roomType % 10; //explanation of roomTypes: normally # of openings //5 = random, 0 = preset/special //1, 2, 3, 4, 5 = not against an edge //6 = preset, not randomized //+10 is locked //+20 is against right edge //+40 is against left edge //+80 is against bottom edge //+160 is against top edge //modifiers stack, so +210 = top-right corner, locked int DungeonMaxX = exPlayer.Get(client).DungeonMaxX; int DungeonMaxY = exPlayer.Get(client).DungeonMaxY; int mapNum = 1; int rand; int[] one = new int[4] { 1549, 1547, 1548, 1550 }; int[] two = new int[6] { 1553, 1551, 1552, 1554, 1555, 1556 }; int[] three = new int[4] { 1557, 1560, 1558, 1559 }; int four = 1561; switch (smallType) { case 1: { // mapNum = one[dir - 1]; } break; case 2: { // rand = Server.Math.Rand(1, 4); switch (dir) { case 1: { mapNum = two[rand * 2 - 2]; } break; case 2: { if (rand == 1) { mapNum = two[rand]; } else { mapNum = two[rand + 1]; } } break; case 3: { if (rand == 3) { mapNum = two[rand + 2]; } else { mapNum = two[rand]; } } break; case 4: { if (rand == 1) { mapNum = two[rand - 1]; } else { mapNum = two[rand * 2 - 1]; } } break; } } break; case 3: { rand = Server.Math.Rand(1, 4); mapNum = three[(dir + rand) % 4]; } break; case 4: { // mapNum = four; } break; case 5: { //random rand = Server.Math.Rand(1, 11); switch (rand) { case 1: case 9: case 10: mapNum = one[dir - 1]; break; case 2: case 3: case 4: { rand = rand - 1; switch (dir) { case 1: { mapNum = two[rand * 2 - 2]; } break; case 2: { if (rand == 1) { mapNum = two[rand]; } else { mapNum = two[rand + 1]; } } break; case 3: { if (rand == 3) { mapNum = two[rand + 2]; } else { mapNum = two[rand]; } } break; case 4: { if (rand == 1) { mapNum = two[rand - 1]; } else { mapNum = two[rand * 2 - 1]; } } break; } } break; case 5: case 6: case 7: { rand = rand - 4; mapNum = three[(dir + rand) % 4]; } break; case 8: mapNum = four; break; } } break; case 6: { mapNum = 1562; } break; case 7: { mapNum = 1543; //maze map } break; } InstancedMap imap = new InstancedMap(MapManager.GenerateMapID("i")); if (mapNum == 1543) { GenerateMaze(client, direc); return; } MapCloner.CloneMapTiles(MapManager.RetrieveMap(mapNum), imap); //if (mapNum == 1562 /*&& exPlayer.Get(client).DungeonID == 20*/) { //replace the boss warps //imap.SetAttribute(9, 3, Enums.TileType.Scripted, 41, 0, 0, "Xatu", "", ""); //imap.SetAttribute(10, 3, Enums.TileType.Scripted, 41, 0, 0, "Xatu", "", ""); //} if (smallType != 6) { DecorateMap(client, imap); //SpawnNpcs(client, imap); //SpawnItems(client, imap); } Messenger.PlayerWarp(client, imap, x, y); if (smallType != 6) { SpawnItems(client, imap); SpawnNpcsBad(client, imap); UnlockRoom(client, imap); //will only unlock if no enemies } } public static void DecorateMap(Client client, IMap imap) { int rand, rand2; int x = exPlayer.Get(client).DungeonX; int y = exPlayer.Get(client).DungeonY; int id = exPlayer.Get(client).DungeonID; int randx, randy; if (Server.Math.Rand(0,20) == 0) { //lock if (imap.MaxX == 19) { for (int i = 8; i <= 11; i++) { if (imap.Tile[i,1].Type == Enums.TileType.Walkable) { imap.SetTile(i, 1, 6, 4, 1); imap.SetAttribute(i, 1, Enums.TileType.Key, 559, 1, 0, "", "", ""); } if (imap.Tile[i,13].Type == Enums.TileType.Walkable) { imap.SetTile(i, 13, 6, 4, 1); imap.SetAttribute(i, 13, Enums.TileType.Key, 559, 1, 0, "", "", ""); } } for (int i = 6; i <= 8; i++) { if (imap.Tile[1,i].Type == Enums.TileType.Walkable) { imap.SetTile(1,i, 6, 4, 1); imap.SetAttribute(1,i, Enums.TileType.Key, 559, 1, 0, "", "", ""); } if (imap.Tile[18,i].Type == Enums.TileType.Walkable) { imap.SetTile(18,i, 6, 4, 1); imap.SetAttribute(18,i, Enums.TileType.Key, 559, 1, 0, "", "", ""); } } } else if (imap.MaxX == 46) { for (int i = 22; i <= 24; i++) { if (imap.Tile[i,1].Type == Enums.TileType.Walkable) { imap.SetTile(i, 1, 6, 4, 1); imap.SetAttribute(i, 1, Enums.TileType.Key, 559, 1, 0, "", "", ""); } if (imap.Tile[i,33].Type == Enums.TileType.Walkable) { imap.SetTile(i, 33, 6, 4, 1); imap.SetAttribute(i, 33, Enums.TileType.Key, 559, 1, 0, "", "", ""); } } for (int i = 16; i <= 18; i++) { if (imap.Tile[1,i].Type == Enums.TileType.Walkable) { imap.SetTile(1,i, 6, 4, 1); imap.SetAttribute(1,i, Enums.TileType.Key, 559, 1, 0, "", "", ""); } if (imap.Tile[45,i].Type == Enums.TileType.Walkable) { imap.SetTile(45,i, 6, 4, 1); imap.SetAttribute(45,i, Enums.TileType.Key, 559, 1, 0, "", "", ""); } } } } imap.OriginalDarkness = Server.Math.Rand(0,19); if (imap.MaxX > 20) imap.OriginalDarkness += 6; imap.Indoors = true; imap.Music = "PMD2) Dark Crater.ogg"; //ground decorations if ((x != 1 && y != 1) && (x != 10) && (y != 10)){ rand = Server.Math.Rand(28, 42); for (int i = 1; i <= rand; i++) { randx = Server.Math.Rand(0, imap.MaxX+1); randy = Server.Math.Rand(0, imap.MaxY+1); rand2 = Server.Math.Rand(0, 2); if (rand2==0) rand2 = 404; else rand2 = 417; imap.SetTile(randx, randy, rand2, 9, 0); } } //wall decorations rand = Server.Math.Rand(0, 20); for (int i = 1; i <= rand; i++) { randx = Server.Math.Rand(0, imap.MaxX+1); randy = Server.Math.Rand(0, imap.MaxY+1); rand2 = Server.Math.Rand(0, 2); if (rand2==0) rand2 = 471; else rand2 = 484; if (imap.Tile[randx,randy].Type == Server.Enums.TileType.NPCAvoid) imap.SetTile(randx, randy, rand2, 9, 1); else i--; } AddTraps(client, imap); } public static void AddTraps(Client client, IMap imap) { int[] traps = new int[] {2, 3, 4, 5, 6, 7, 23, 25, 26, 28, 42, 43, 44, 50, 51, 52, 53}; int randx, randy; int rand = Server.Math.Rand(0, 20); if (rand >= 17) { //17, 18, 19; 2 traps for (int i = 0; i < 2; i++) { randx = Server.Math.Rand(0, imap.MaxX+1); randy = Server.Math.Rand(0, imap.MaxY+1); rand = traps[Server.Math.Rand(0, traps.Length)]; if (imap.Tile[randx,randy].Type == Server.Enums.TileType.Walkable) imap.SetAttribute(randx, randy, Enums.TileType.Scripted, rand, 0, 0, "", "", ""); else i--; } } else if (rand >= 10) { //1 trap; 1/2 chance of no trap for (int i = 0; i < 1; i++) { randx = Server.Math.Rand(0, imap.MaxX+1); randy = Server.Math.Rand(0, imap.MaxY+1); rand = traps[Server.Math.Rand(0, traps.Length)]; if (imap.Tile[randx,randy].Type == Server.Enums.TileType.Walkable) imap.SetAttribute(randx, randy, Enums.TileType.Scripted, rand, 0, 0, "", "", ""); else i--; } } } public static void UnlockRoom(Client client, IMap imap) { int remainingEnemies = 0; for (int i = 0; i < Constants.MAX_MAP_NPCS; i++) { if (!imap.IsNpcSlotEmpty(i)) remainingEnemies++; } if (remainingEnemies <= 1) { if (imap.MaxX == 19) { for (int i = 8; i <= 11; i++) { if (imap.Tile[i,1].Type == Enums.TileType.Key) { imap.SetTile(i, 1, 0, 0, 1); imap.SetAttribute(i, 1, Enums.TileType.Walkable, 0, 0, 0, "", "", ""); Messenger.SendTile(i, 1, imap); } if (imap.Tile[i,13].Type == Enums.TileType.Key) { imap.SetTile(i, 13, 0, 0, 1); imap.SetAttribute(i, 13, Enums.TileType.Walkable, 0, 0, 0, "", "", ""); Messenger.SendTile(i, 13, imap); } } for (int i = 6; i <= 8; i++) { if (imap.Tile[1,i].Type == Enums.TileType.Key) { imap.SetTile(1, i, 0, 0, 1); imap.SetAttribute(1, i, Enums.TileType.Walkable, 0, 0, 0, "", "", ""); Messenger.SendTile(1, i, imap); } if (imap.Tile[18,i].Type == Enums.TileType.Key) { imap.SetTile(18,i, 0, 0, 1); imap.SetAttribute(18, i, Enums.TileType.Walkable, 0, 0, 0, "", "", ""); Messenger.SendTile(18, i, imap); } } } else if (imap.MaxX == 46) { for (int i = 22; i <= 24; i++) { if (imap.Tile[i,1].Type == Enums.TileType.Key) { imap.SetTile(i, 1, 0, 0, 1); imap.SetAttribute(i, 1, Enums.TileType.Walkable, 0, 0, 0, "", "", ""); Messenger.SendTile(i, 1, imap); } if (imap.Tile[i,33].Type == Enums.TileType.Key) { imap.SetTile(i, 33, 0, 0, 1); imap.SetAttribute(i, 33, Enums.TileType.Walkable, 0, 0, 0, "", "", ""); Messenger.SendTile(i, 33, imap); } } for (int i = 16; i <= 18; i++) { if (imap.Tile[1,i].Type == Enums.TileType.Key) { imap.SetTile(1, i, 0, 0, 1); imap.SetAttribute(1, i, Enums.TileType.Walkable, 0, 0, 0, "", "", ""); Messenger.SendTile(1, i, imap); } if (imap.Tile[45,i].Type == Enums.TileType.Key) { imap.SetTile(45, i, 0, 0, 1); imap.SetAttribute(45, i, Enums.TileType.Walkable, 0, 0, 0, "", "", ""); Messenger.SendTile(45, i, imap); } } } } } public static void SpawnItems(Client client, IMap imap) { //new item code #region item arrays int[] heal = new int[] { 2, //apple 4, //oran berry 991, //oren berry 487, //pecha berry 493, //chesto berry 496, //persim berry 492, //cheri berry 494, //rawst berry 497, //lum berry 489, //reviver seed //reviser seed 452, //revival herb 557, //dark liquid 203, //elixir 86 //leppa berry }; int[] held = new int[] { 41, //power band 87, //def. scarf 153, //zinc band 46, //special band 483, //pecha scarf 298, //heal ribbon 323, //persim band 421, //no-stick cap 431, //no-slip cap 151, //stamina band 66, //x-ray specs 348 //y-ray specs }; int[] oneuse = new int[] { 559, //pitch-black key 432, //pathfinder orb 449, //sleep seed 460, //slip seed //doom seed //dough seed //vile seed //via seed 345, //gravelerock //gravelyrock 346, //geo pebble 48, //stick 60, //iron thorn 642, //colbur berry 648, //kasib berry 653, //kebia berry 11 //tasty honey }; int[] tm = new int[] { 19, //toxic 558, //shadow claw 124, //torment 548, //dream eater 126, //calm mind 184, //safeguard 335, //sludge bomb 13, //rest 12, //payback 332, //psych up 552, //trick room 440, //psyshock //quash //unmade, move is unfinished //443 //vacuum-cut //make chest-only //removed }; int[] orb = new int[] { 316, //sunny orb 317, //rainy orb 315, //hail orb 320, //cloudy orb 319, //snowy orb 321, //foggy orb 293, //slumber orb 294, //totter orb 304, //petrify orb 291, //trap-see orb 500 //escape orb }; int[] treasure = new int[] { 1, //poke 110, //egg 542 //sinister box }; #endregion int rand, num, randx, randy, itemnum, amount; string para; if (imap.MaxX == 19) { rand = Server.Math.Rand(0,100); if (rand < 50) num = 0; else if (rand < 75) num = 1; else if (rand < 90) num = 2; else if (rand < 97) num = 3; else num = 4; } else { rand = Server.Math.Rand(0,142); if (rand < 55) num = 0; else if (rand < 89) num = 1; else if (rand < 110) num = 2; else if (rand < 123) num = 3; else if (rand < 131) num = 4; else if (rand < 136) num = 5; else if (rand < 139) num = 6; else if (rand < 141) num = 7; else num = 8; } //Messenger.PlayerMsg(client, "num = " + num.ToString(), Text.Black); for (int i = 0; i < num; i++) { //find a place randx = Server.Math.Rand(0, imap.MaxX + 1); randy = Server.Math.Rand(0, imap.MaxY + 1); if (imap.Tile[randx,randy].Type == Enums.TileType.Walkable) { #region generate random item rand = Server.Math.Rand(0,100); if (rand < 35) { //healing item 35 rand = Server.Math.Rand(0,83); if (rand < 10) itemnum = heal[0]; else if (rand < 15) itemnum = heal[1]; else if (rand < 18) itemnum = heal[2]; else if (rand < 27) itemnum = heal[3]; else if (rand < 36) itemnum = heal[4]; else if (rand < 45) itemnum = heal[5]; else if (rand < 54) itemnum = heal[6]; else if (rand < 63) itemnum = heal[7]; else if (rand < 66) itemnum = heal[8]; else if (rand < 68) itemnum = heal[9]; else if (rand < 69) itemnum = heal[10]; else if (rand < 73) itemnum = heal[11]; else if (rand < 77) itemnum = heal[12]; else itemnum = heal[13]; } else if (rand < 92) { //one-use item 92 rand = Server.Math.Rand(0,203); //203 if (rand < 86) { rand = rand / 8; itemnum = orb[rand]; } else if (rand < 98) itemnum = tm[rand-86]; else if (rand < 108) itemnum = oneuse[0]; else if (rand < 158) itemnum = oneuse[1]; else if (rand < 166) itemnum = oneuse[2]; else if (rand < 170) itemnum = oneuse[3]; else if (rand < 175) itemnum = oneuse[4]; else if (rand < 182) itemnum = oneuse[5]; else if (rand < 188) itemnum = oneuse[6]; else if (rand < 192) itemnum = oneuse[7]; else if (rand < 195) itemnum = oneuse[8]; else if (rand < 198) itemnum = oneuse[9]; else if (rand < 201) itemnum = oneuse[10]; else itemnum = oneuse[11]; } else if (rand < 95) { //held item 95 rand = Server.Math.Rand(0,10); if (rand < 9) { itemnum = held[rand]; } else { rand = Server.Math.Rand(0,3); itemnum = held[rand+9]; } } else { //treasure 100 rand = Server.Math.Rand(0,10); if (rand < 8) itemnum = treasure[0]; else itemnum = treasure[rand-7]; } #endregion //spawn item, check for egg and Poke for appropriate extras //also check for other stackables amount = 1; para = ""; if (itemnum == 1) { //Poke amount = Server.Math.Rand(1,201); } else if (itemnum == 110) { //egg rand = Server.Math.Rand(0,8); switch (rand) { case 0: para = "23;1000"; break; case 1: para = "41;1000"; break; case 2: para = "96;1000"; break; case 3: para = "167;1000"; break; case 4: para = "177;1000"; break; case 5: para = "215;1000"; break; case 6: para = "353;1000"; break; case 7: para = "355;1000"; break; } } else if (itemnum == 542) { //Sinister Box rand = Server.Math.Rand(0,4); if (rand < 3) { //TMs for(int j = 0; j < tm.Count(); j++) { para = para + tm[i].ToString(); if (j != tm.Count() - 1) para = para + ";"; } } else para = "450;451;452;489;702;117;238;461"; } else if (Server.Items.ItemManager.Items[itemnum].StackCap > 0) { amount = Server.Math.Rand(1,7); } //Messenger.PlayerMsg(client, "item spawning", Text.Black); //imap.SetAttribute(randx, randy, Enums.TileType.Item, itemnum, amount, 0, "", para, ""); imap.SpawnItem(itemnum, amount, false, false, para, randx, randy, null); } else i--; } } public static void SpawnNpcsBad(Client client, IMap imap) { //super-hack-ish code, just making it work int rand, n; int[] npcs = new int[] { 558, 559, 560, 571, 572, 854, 855, 856, 857, 858, 859, 860, 861, 862, 863 }; if (imap.MaxX == 19) { rand = Server.Math.Rand(0, 20); if (rand == 0) { //no NPCs n = 0; } else if (rand > 0 && rand <= 3) { //1 NPC n = 1; } else if (rand > 3 && rand <= 9) { //2 NPCs n = 2; } else if (rand > 9 && rand <= 15) { //3 NPCs n = 3; } else if (rand > 15 && rand <= 18) { //4 NPCs n = 4; } else { //rand == 19, 5 NPCs n = 5; } } else { rand = Server.Math.Rand(0,25); if (rand == 0) { //no NPCs n = 0; } else if (rand > 0 && rand <= 2) { //1 NPC n = 1; } else if (rand > 2 && rand <= 5) { //2 NPCs n = 2; } else if (rand > 5 && rand <= 9) { //3 NPCs n = 3; } else if (rand > 9 && rand <= 14) { //4 NPCs n = 4; } else if (rand > 14 && rand <= 18) { //5 NPCs n = 5; } else if (rand > 18 && rand <= 21) { //6 NPCs n = 6; } else if (rand > 21 && rand <= 23) { //7 NPCs n = 7; } else { //rand == 24, 8 NPCs n = 8; } } for (int i = 1; i <= n; i++) { MapNpcPreset npc = new MapNpcPreset(); rand = Server.Math.Rand(0, npcs.Length); npc.NpcNum = npcs[rand]; if (npcs[rand] == 859) { npc.MinLevel = 10; npc.MaxLevel = 10; } else { npc.MinLevel = 50; npc.MaxLevel = 80; } //npc.AppearanceRate = 100; imap.SpawnNpc(npc); } } public static void SpawnNpcs(Client client, IMap imap) { //new NPC code //hack it in for now, make it clean later... int rand; int[] npcs = new int[] { 558, 559, 560, 571, 572, 854, 855, 856, 857, 858, 859, 860, 861, 862, 863 }; if (imap.MaxX == 19) imap.MaxNpcs = 8; else imap.MaxNpcs = 16; imap.MinNpcs = 2; imap.NpcSpawnTime = 300; for (int i = 1; i <= 9; i++) { MapNpcPreset npc = new MapNpcPreset(); rand = Server.Math.Rand(0, npcs.Length); npc.NpcNum = npcs[rand]; if (npcs[rand] == 859) { npc.MinLevel = 10; npc.MaxLevel = 10; } else { npc.MinLevel = 70; npc.MaxLevel = 100; } npc.AppearanceRate = 100; imap.Npc.Add(npc); } if (imap.MaxX == 19) { rand = Server.Math.Rand(0, 20); if (rand == 0) { //no NPCs //do nothing } else if (rand > 0 && rand <= 3) { //1 NPC imap.MinNpcs = 1; } else if (rand > 3 && rand <= 9) { //2 NPCs imap.MinNpcs = 2; } else if (rand > 9 && rand <= 15) { //3 NPCs imap.MinNpcs = 3; } else if (rand > 15 && rand <= 18) { //4 NPCs imap.MinNpcs = 4; } else { //rand == 19, 5 NPCs imap.MinNpcs = 5; } } else { rand = Server.Math.Rand(0,25); if (rand == 0) { //no NPCs //do nothing } else if (rand > 0 && rand <= 2) { //1 NPC imap.MinNpcs = 1; } else if (rand > 2 && rand <= 5) { //2 NPCs imap.MinNpcs = 2; } else if (rand > 5 && rand <= 9) { //3 NPCs imap.MinNpcs = 3; } else if (rand > 9 && rand <= 14) { //4 NPCs imap.MinNpcs = 4; } else if (rand > 14 && rand <= 18) { //5 NPCs imap.MinNpcs = 5; } else if (rand > 18 && rand <= 21) { //6 NPCs imap.MinNpcs = 6; } else if (rand > 21 && rand <= 23) { //7 NPCs imap.MinNpcs = 7; } else { //rand == 24, 8 NPCs imap.MinNpcs = 8; } } } public static void GenerateMap(Client client) { //creates a new PBA map for a player and saves it in exPlayers //note: this is generated even if players are in a party; leader's map is used though //notes on party system: //GenerateMap will only be called once per party, using leader's seed //GenerateMap will be called once each time the map switches Random rng = new Random(exPlayer.Get(client).DungeonSeed); int rand; bool done = false; exPlayer.Get(client).DungeonMap = new PitchBlackAbyss.Room[ exPlayer.Get(client).DungeonMaxX, exPlayer.Get(client).DungeonMaxY]; for (int j = 0; j < exPlayer.Get(client).DungeonMaxY; j++) { for (int i = 0; i < exPlayer.Get(client).DungeonMaxX; i++) { rand = rng.Next() % 100; if (rand < 5) { exPlayer.Get(client).DungeonMap[i,j] = Room.One; } else if (rand < 20) { exPlayer.Get(client).DungeonMap[i,j] = Room.Two; } else if (rand < 55) { exPlayer.Get(client).DungeonMap[i,j] = Room.Three; } else if (rand < 65) { exPlayer.Get(client).DungeonMap[i,j] = Room.Four; } else if (rand < 96) { exPlayer.Get(client).DungeonMap[i,j] = Room.Random; } else if (rand < 99) { exPlayer.Get(client).DungeonMap[i,j] = Room.Maze; } else { //rand == 99 exPlayer.Get(client).DungeonMap[i,j] = Room.Heal; } } } //don't bother separating 1s, the player can hope to skip/warp out if they get stuck //generate S rand = rng.Next() % (exPlayer.Get(client).DungeonMaxX * exPlayer.Get(client).DungeonMaxY); exPlayer.Get(client).DungeonMap[rand%exPlayer.Get(client).DungeonMaxX,rand/exPlayer.Get(client).DungeonMaxX] = Room.Start; //generate E while (!done) { rand = rng.Next() % (exPlayer.Get(client).DungeonMaxX * exPlayer.Get(client).DungeonMaxY); if (!(exPlayer.Get(client).DungeonMap[rand%exPlayer.Get(client).DungeonMaxX,rand/exPlayer.Get(client).DungeonMaxX] == Room.Start)) { exPlayer.Get(client).DungeonMap[rand%exPlayer.Get(client).DungeonMaxX,rand/exPlayer.Get(client).DungeonMaxX] = Room.End; done = true; } } exPlayer.Get(client).DungeonGenerated = true; } public static void InitializeMap(Client client, Difficulty diff) { Random rng = new Random(); exPlayer.Get(client).DungeonSeed = rng.Next(); if (diff == Difficulty.Easy) { exPlayer.Get(client).DungeonMaxX = 15; exPlayer.Get(client).DungeonMaxY = 15; } //else if diff = normal //20? 25? //else if diff = OmgWthIsThisEvenPossible //30? 35? 40? exPlayer.Get(client).DungeonMap = new Room[exPlayer.Get(client).DungeonMaxX,exPlayer.Get(client).DungeonMaxY]; //generate initial coords of player exPlayer.Get(client).DungeonX = (rng.Next() % exPlayer.Get(client).DungeonMaxX) + 1; exPlayer.Get(client).DungeonY = (rng.Next() % exPlayer.Get(client).DungeonMaxY) + 1; } public static void GenerateMaze(Client client, Server.Enums.Direction dir) { //generates a brand-new maze map for the player and sends it as their current map //warning: code copy-pasted (and revised) from C++, so it won't be neat int x; int y; int r; int[] order = new int[4]; InstancedMap imap = new InstancedMap(MapManager.GenerateMapID("i")); MapCloner.CloneMapTiles(MapManager.RetrieveMap(1543), imap); //Server.Enums.TileType[,] maze = new Server.Enums.TileType[47,35]; int[,] cells = new int[22,16]; for(int i = 2; i < 45; i++) { //initialize map for (int j = 2; j < 33; j++) { //maze[i,j] = Server.Enums.TileType.Blocked; imap.SetAttribute(i, j, Server.Enums.TileType.Blocked, 0, 0, 0, "", "", ""); imap.SetTile(i, j, 446, 9, 1); } } for(int i = 0; i < 22; i++) { //initialize cells used for prim's algorithm for (int j = 0; j < 16; j++) { cells[i,j] = 0; } } List<int> list1 = new List<int>(); x = Server.Math.Rand(1,22); y = Server.Math.Rand(1,16); cells[x,y] = 2; //maze[2*(x+1),2*(y+1)] = Server.Enums.TileType.Walkable; imap.SetAttribute(2*(x+1), 2*(y+1), Server.Enums.TileType.Walkable, 0, 0, 0, "", "", ""); imap.SetTile(2*(x+1), 2*(y+1), 0, 0, 1); order = GenerateOrder(); for (int i = 0; i < 4; i++) { switch(order[i]) { case 1: //up if (y > 0) { cells[x,y-1] = 1; list1.Add(x + 22*(y-1)); } break; case 2: //right if (x < 21) { cells[x+1,y] = 1; list1.Add(x+1 + 22*y); } break; case 3: //down if (y < 15) { cells[x,y+1] = 1; list1.Add(x + 22*(y+1)); } break; case 4: //left if (x > 0) { cells[x-1,y] = 1; list1.Add(x-1 + 22*y); } break; } } while(list1.Count > 0) { //Messenger.PlayerMsg(client, list1.Count.ToString(), Text.Black); if (Server.Math.Rand(1,3) > 1) { //take random item from list r = Server.Math.Rand(0, list1.Count); x = list1[r]; list1.RemoveAt(r); } else { //take last element x = list1.Last(); list1.RemoveAt(list1.Count-1); } y = x / 22; x = x % 22; //attach it to random neighbor and add neighbors to queue in random order order = GenerateOrder(); for(int i = 0; i < 4; i++) { switch(order[i]) { case 1: //up if (y > 0) { if (cells[x,y-1] == 0) { //add to queue cells[x,y-1] = 1; list1.Add(x + 22*(y-1)); } else if (cells[x,y-1] == 2 && cells[x,y] == 1) { //attach cells[x,y] = 2; //maze[2*(x+1),2*(y+1)-1] = Server.Enums.TileType.Walkable; //maze[2*(x+1),2*(y+1)] = Server.Enums.TileType.Walkable; imap.SetAttribute(2*(x+1), 2*(y+1)-1, Server.Enums.TileType.Walkable, 0, 0, 0, "", "", ""); imap.SetTile(2*(x+1), 2*(y+1)-1, 0, 0, 1); imap.SetAttribute(2*(x+1), 2*(y+1), Server.Enums.TileType.Walkable, 0, 0, 0, "", "", ""); imap.SetTile(2*(x+1), 2*(y+1), 0, 0, 1); } } break; case 2: //right if (x < 21) { if (cells[x+1,y] == 0) { //add to queue cells[x+1,y] = 1; list1.Add(x+1 + 22*y); } else if (cells[x+1,y] == 2 && cells[x,y] == 1) { //attach cells[x,y] = 2; //maze[2*(x+1)+1,2*(y+1)] = Server.Enums.TileType.Walkable; //maze[2*(x+1),2*(y+1)] = Server.Enums.TileType.Walkable; imap.SetAttribute(2*(x+1)+1, 2*(y+1), Server.Enums.TileType.Walkable, 0, 0, 0, "", "", ""); imap.SetTile(2*(x+1)+1, 2*(y+1), 0, 0, 1); imap.SetAttribute(2*(x+1), 2*(y+1), Server.Enums.TileType.Walkable, 0, 0, 0, "", "", ""); imap.SetTile(2*(x+1), 2*(y+1), 0, 0, 1); } } break; case 3: //down if (y < 15) { if (cells[x,y+1] == 0) { //add to queue cells[x,y+1] = 1; list1.Add(x + 22*(y+1)); } else if (cells[x,y+1] == 2 && cells[x,y] == 1) { //attach cells[x,y] = 2; //maze[2*(x+1),2*(y+1)+1] = Server.Enums.TileType.Walkable; //maze[2*(x+1),2*(y+1)] = Server.Enums.TileType.Walkable; imap.SetAttribute(2*(x+1), 2*(y+1)+1, Server.Enums.TileType.Walkable, 0, 0, 0, "", "", ""); imap.SetTile(2*(x+1), 2*(y+1)+1, 0, 0, 1); imap.SetAttribute(2*(x+1), 2*(y+1), Server.Enums.TileType.Walkable, 0, 0, 0, "", "", ""); imap.SetTile(2*(x+1), 2*(y+1), 0, 0, 1); } } break; case 4: //left if (x > 0) { if (cells[x-1,y] == 0) { //add to queue cells[x-1,y] = 1; list1.Add(x-1 + 22*y); } else if (cells[x-1,y] == 2 && cells[x,y] == 1) { //attach cells[x,y] = 2; //maze[2*(x+1)-1,2*(y+1)] = Server.Enums.TileType.Walkable; //maze[2*(x+1),2*(y+1)] = Server.Enums.TileType.Walkable; imap.SetAttribute(2*(x+1)-1, 2*(y+1), Server.Enums.TileType.Walkable, 0, 0, 0, "", "", ""); imap.SetTile(2*(x+1)-1, 2*(y+1), 0, 0, 1); imap.SetAttribute(2*(x+1), 2*(y+1), Server.Enums.TileType.Walkable, 0, 0, 0, "", "", ""); imap.SetTile(2*(x+1), 2*(y+1), 0, 0, 1); } } break; } } } imap.SetTile(23, 32, 0, 0, 1); imap.SetAttribute(23, 32, Server.Enums.TileType.Walkable, 0, 0, 0, "", "", ""); imap.SetTile(23, 2, 0, 0, 1); imap.SetAttribute(23, 32, Server.Enums.TileType.Walkable, 0, 0, 0, "", "", ""); imap.SetTile(2, 17, 0, 0, 1); imap.SetAttribute(23, 32, Server.Enums.TileType.Walkable, 0, 0, 0, "", "", ""); imap.SetTile(44, 17, 0, 0, 1); imap.SetAttribute(44, 17, Server.Enums.TileType.Walkable, 0, 0, 0, "", "", ""); DecorateMap(client, imap); //make decoratemap use map's max x/y? //warp player to maze if (dir == Server.Enums.Direction.Up) { x = client.Player.X + 14; if (x > 24) x = 24; y = 32; } else if (dir == Server.Enums.Direction.Down) { x = client.Player.X + 14; if (x > 24) x = 24; y = 2; } else if (dir == Server.Enums.Direction.Left) { x = 44; y = client.Player.Y + 10; } else { //dir == Server.Enums.Direction.Right x = 2; y = client.Player.Y + 10; } Messenger.PlayerWarp(client, imap, x, y); } static int[] GenerateOrder() { //used by GenerateMaze int[] order = new int[4]; order[0] = Server.Math.Rand(1,5); do { order[1] = Server.Math.Rand(1,5); } while (order[0] == order[1]); do { order[2] = Server.Math.Rand(1,5); } while (order[0] == order[2] || order[1] == order[2]); do { order[3] = Server.Math.Rand(1,5); } while (order[0] == order[3] || order[1] == order[3] || order[2] == order[3]); return order; } public static Room GetRoomType(Client client) { //check to make sure that the array is properly sized first... if not, generate the array try { if (client.Player.IsInParty()) { Server.Players.Parties.Party party = Server.Players.Parties.PartyManager.FindPlayerParty(client); return exPlayer.Get(party.GetLeader()).DungeonMap[exPlayer.Get(client).DungeonX,exPlayer.Get(client).DungeonY]; } return exPlayer.Get(client).DungeonMap[exPlayer.Get(client).DungeonX,exPlayer.Get(client).DungeonY]; } catch (Exception ex) { Messenger.AdminMsg("Error: PBA:GetRoomType", Text.Black); Messenger.AdminMsg(ex.ToString(), Text.Black); return Room.Error; } } } }
using System; using System.Collections.Generic; using System.Linq; using AutoMapper; using FizzWare.NBuilder; using Moq; using NUnit.Framework; using ReMi.BusinessEntities.Auth; using ReMi.BusinessEntities.ReleasePlan; using ReMi.Common.Constants.ReleasePlan; using ReMi.Common.Utils.Repository; using ReMi.TestUtils.UnitTests; using ReMi.DataAccess.BusinessEntityGateways.ReleasePlan; using ReMi.DataEntities.ReleaseCalendar; using ReMi.DataEntities.ReleasePlan; namespace ReMi.DataAccess.Tests.ReleasePlan { [TestFixture] public class ReleaseContentGatewayTests : TestClassFor<ReleaseContentGateway> { private Mock<IRepository<ReleaseContent>> _releaseContentRepositoryMock; private Mock<IRepository<DataEntities.Auth.Account>> _accountRepositoryMock; private Mock<IRepository<ReleaseWindow>> _releaseWindowRepositoryMock; private Mock<IMappingEngine> _mappingEngineMock; protected override ReleaseContentGateway ConstructSystemUnderTest() { return new ReleaseContentGateway { ReleaseContentRepository = _releaseContentRepositoryMock.Object, Mapper = _mappingEngineMock.Object, AccountRepository = _accountRepositoryMock.Object, ReleaseWindowRepository = _releaseWindowRepositoryMock.Object }; } protected override void TestInitialize() { _releaseContentRepositoryMock = new Mock<IRepository<ReleaseContent>>(MockBehavior.Strict); _accountRepositoryMock = new Mock<IRepository<DataEntities.Auth.Account>>(MockBehavior.Strict); _mappingEngineMock = new Mock<IMappingEngine>(MockBehavior.Strict); _releaseWindowRepositoryMock = new Mock<IRepository<ReleaseWindow>>(MockBehavior.Strict); base.TestInitialize(); } [Test] public void GetTicketInformations_ShouldReturnListOfTicket_WhenMatchSomething() { var tickets = new List<ReleaseContent> { new ReleaseContent {TicketId = new Guid(1, 0, 0, new byte[8])}, new ReleaseContent {TicketId = new Guid(2, 0, 0, new byte[8])}, new ReleaseContent {TicketId = new Guid(3, 0, 0, new byte[8])} }; _releaseContentRepositoryMock.SetupEntities(tickets); _mappingEngineMock.Setup(x => x.Map<ReleaseContent, ReleaseContentTicket>(It.IsAny<ReleaseContent>())) .Returns(new ReleaseContentTicket()); var actual = Sut.GetTicketInformations(new[] { new Guid(1, 0, 0, new byte[8]), new Guid(4, 0, 0, new byte[8]), new Guid(5, 0, 0, new byte[8]), new Guid(3, 0, 0, new byte[8]), }); Assert.AreEqual(2, actual.Count()); _mappingEngineMock.Verify(x => x.Map<ReleaseContent, ReleaseContentTicket>(It.Is<ReleaseContent>(y => y.TicketId == tickets.ElementAt(0).TicketId)), Times.Once()); _mappingEngineMock.Verify(x => x.Map<ReleaseContent, ReleaseContentTicket>(It.Is<ReleaseContent>(y => y.TicketId == tickets.ElementAt(2).TicketId)), Times.Once()); _mappingEngineMock.Verify(x => x.Map<ReleaseContent, ReleaseContentTicket>(It.IsAny<ReleaseContent>()), Times.Exactly(2)); } [Test] public void GetTicketInformations_ShouldReturnNull_WhenReleaseWindowNotHavingAssociatedTickets() { var releaseWindow = new ReleaseWindow { ExternalId = Guid.NewGuid() }; _releaseWindowRepositoryMock.SetupEntities(new[] { releaseWindow }); var actual = Sut.GetTicketInformations(releaseWindow.ExternalId); Assert.IsNull(actual); } [Test] public void GetTicketInformations_ShouldReturnTickets_WhenReleaseWindowHaveAssociatedTickets() { var releaseWindow = new ReleaseWindow { ExternalId = Guid.NewGuid(), ReleaseContent = new List<ReleaseContent> { new ReleaseContent { TicketId = Guid.NewGuid(), IncludeToReleaseNotes = true }, new ReleaseContent { TicketId = Guid.NewGuid(), IncludeToReleaseNotes = true }, new ReleaseContent { TicketId = Guid.NewGuid() } } }; _releaseWindowRepositoryMock.SetupEntities(new[] { releaseWindow }); _mappingEngineMock.Setup(x => x.Map<ReleaseContent, ReleaseContentTicket>(It.IsAny<ReleaseContent>())) .Returns(new ReleaseContentTicket()); var actual = Sut.GetTicketInformations(releaseWindow.ExternalId); Assert.AreEqual(2, actual.Count()); _mappingEngineMock.Verify(x => x.Map<ReleaseContent, ReleaseContentTicket>(It.Is<ReleaseContent>( y => y.TicketId == releaseWindow.ReleaseContent.ElementAt(0).TicketId)), Times.Once()); _mappingEngineMock.Verify(x => x.Map<ReleaseContent, ReleaseContentTicket>(It.Is<ReleaseContent>( y => y.TicketId == releaseWindow.ReleaseContent.ElementAt(1).TicketId)), Times.Once()); } [Test] public void AddOrUpdateTicketComment_ShouldInsertNewTicket_WhenEntityNotExists() { var accounts = BuildAccounts(); var ticketInformations = BuildTicketInformations(accounts); var newValue = new ReleaseContentTicket { TicketId = Guid.NewGuid(), Comment = RandomData.RandomString(10), LastChangedByAccount = accounts.First().ExternalId }; _accountRepositoryMock.SetupEntities(accounts); _releaseContentRepositoryMock.SetupEntities(ticketInformations); _releaseContentRepositoryMock.Setup(x => x.Insert(It.IsAny<ReleaseContent>())); _mappingEngineMock.Setup(x => x.Map<ReleaseContentTicket, ReleaseContent>(newValue)) .Returns(new ReleaseContent { TicketId = newValue.TicketId, Comment = newValue.Comment }); Sut.AddOrUpdateTicketComment(newValue); _releaseContentRepositoryMock.Verify(x => x.Insert(It.Is<ReleaseContent>( y => y.Comment == newValue.Comment && y.TicketId == newValue.TicketId && y.LastChangedByAccountId == accounts.First().AccountId)), Times.Once()); _mappingEngineMock.Verify(x => x.Map<ReleaseContentTicket, ReleaseContent>(newValue), Times.Once()); } [Test] public void AddOrUpdateTicketComment_ShouldUpdateTicketInformationWithNewComment_WhenEntityExists() { var accounts = BuildAccounts(); var ticketInformations = BuildTicketInformations(accounts); var newValue = new ReleaseContentTicket { TicketId = new Guid(2, 0, 0, new byte[8]), Comment = RandomData.RandomString(10), LastChangedByAccount = accounts.First().ExternalId }; _accountRepositoryMock.SetupEntities(accounts); _releaseContentRepositoryMock.SetupEntities(ticketInformations); _releaseContentRepositoryMock.Setup(x => x.Update(It.IsAny<ReleaseContent>())) .Returns(new ChangedFields<ReleaseContent>()); Sut.AddOrUpdateTicketComment(newValue); _releaseContentRepositoryMock.Verify(x => x.Update(It.Is<ReleaseContent>( y => y.TicketId == newValue.TicketId && y.LastChangedByAccountId == accounts.First().AccountId)), Times.Once()); } [Test] public void UpdateTicketReleaseRelation_ShouldUpdateTicketInformation() { var accounts = BuildAccounts(); var account = new Account { ExternalId = accounts.First().ExternalId }; var ticketInformations = BuildTicketInformations(accounts); var newValue = new ReleaseContentTicket { TicketId = new Guid(2, 0, 0, new byte[8]), IncludeToReleaseNotes = true, LastChangedByAccount = accounts.First().ExternalId }; _releaseContentRepositoryMock.Setup(x => x.Update(It.IsAny<ReleaseContent>())) .Returns(new ChangedFields<ReleaseContent>()); _accountRepositoryMock.SetupEntities(accounts); _releaseContentRepositoryMock.SetupEntities(ticketInformations); _mappingEngineMock.Setup(x => x.Map<ReleaseContentTicket, ReleaseContent>(newValue)) .Returns(new ReleaseContent { TicketId = newValue.TicketId }); Sut.UpdateTicketReleaseNotesRelation(newValue, account.ExternalId); _releaseContentRepositoryMock.Verify(x => x.Update(It.Is<ReleaseContent>( y => y.IncludeToReleaseNotes == newValue.IncludeToReleaseNotes && y.TicketId == newValue.TicketId && y.LastChangedByAccountId == accounts.First().AccountId)), Times.Once()); } [Test] public void AddOrUpdateTicketRisk_ShouldInsertNewTicket_WhenEntityNotExists() { var accounts = BuildAccounts(); var ticketInformations = BuildTicketInformations(accounts); var newValue = new ReleaseContentTicket { TicketId = Guid.NewGuid(), Risk = RandomData.RandomEnum<TicketRisk>(), LastChangedByAccount = accounts.First().ExternalId }; _accountRepositoryMock.SetupEntities(accounts); _releaseContentRepositoryMock.SetupEntities(ticketInformations); _releaseContentRepositoryMock.Setup(x => x.Insert(It.IsAny<ReleaseContent>())); _mappingEngineMock.Setup(x => x.Map<ReleaseContentTicket, ReleaseContent>(newValue)) .Returns(new ReleaseContent { TicketId = newValue.TicketId, TicketRisk = newValue.Risk }); Sut.AddOrUpdateTicketRisk(newValue); _releaseContentRepositoryMock.Verify(x => x.Insert(It.Is<ReleaseContent>( y => y.TicketRisk == newValue.Risk && y.TicketId == newValue.TicketId && y.LastChangedByAccountId == accounts.First().AccountId)), Times.Once()); _mappingEngineMock.Verify(x => x.Map<ReleaseContentTicket, ReleaseContent>(newValue), Times.Once()); } [Test] public void CreateTicket_ShouldInsertNewTicket_WhenEntityNotExists() { var accounts = BuildAccounts(); var account = new Account { ExternalId = accounts.First().ExternalId }; var ticketInformations = BuildTicketInformations(accounts); var newValue = new ReleaseContentTicket { TicketId = Guid.NewGuid(), Risk = RandomData.RandomEnum<TicketRisk>(), IncludeToReleaseNotes = RandomData.RandomBool(), Comment = RandomData.RandomString(33) }; _releaseContentRepositoryMock.SetupEntities(ticketInformations); _releaseContentRepositoryMock.Setup(x => x.Insert(It.IsAny<ReleaseContent>())); _mappingEngineMock.Setup(x => x.Map<ReleaseContentTicket, ReleaseContent>(newValue)) .Returns(new ReleaseContent { TicketId = newValue.TicketId, TicketRisk = newValue.Risk, Comment = newValue.Comment, IncludeToReleaseNotes = newValue.IncludeToReleaseNotes }); _accountRepositoryMock.SetupEntities(accounts); Sut.CreateTicket(newValue, account.ExternalId); _releaseContentRepositoryMock.Verify(x => x.Insert(It.Is<ReleaseContent>( y => y.TicketRisk == newValue.Risk && y.IncludeToReleaseNotes == newValue.IncludeToReleaseNotes && y.Comment == newValue.Comment && y.TicketId == newValue.TicketId && y.LastChangedByAccountId == accounts.First().AccountId)), Times.Once()); _mappingEngineMock.Verify(x => x.Map<ReleaseContentTicket, ReleaseContent>(newValue), Times.Once()); } [Test] public void AddOrUpdateTicketRisk_ShouldUpdateTicketInformationWithNewRisk_WhenEntityExists() { var accounts = BuildAccounts(); var ticketInformations = BuildTicketInformations(accounts); var newValue = new ReleaseContentTicket { TicketId = new Guid(2, 0, 0, new byte[8]), Risk = RandomData.RandomEnum<TicketRisk>(), LastChangedByAccount = accounts.First().ExternalId }; _accountRepositoryMock.SetupEntities(accounts); _releaseContentRepositoryMock.SetupEntities(ticketInformations); _releaseContentRepositoryMock.Setup(x => x.Update(It.IsAny<ReleaseContent>())) .Returns(new ChangedFields<ReleaseContent>()); Sut.AddOrUpdateTicketRisk(newValue); _releaseContentRepositoryMock.Verify(x => x.Update(It.Is<ReleaseContent>( y => y.TicketRisk == newValue.Risk && y.TicketId == newValue.TicketId && y.LastChangedByAccountId == accounts.First().AccountId)), Times.Once()); } [Test] public void AddOrUpdateTickets_ShouldAddOrUpdateTicketInformation_WhenInvoked() { var accounts = BuildAccounts(); var account = new Account { ExternalId = accounts.First().ExternalId }; var ticketInformations = BuildTicketInformations(accounts); var tickets = BuildTickets(accounts); var releaseWindow = new BusinessEntities.ReleaseCalendar.ReleaseWindow { ExternalId = Guid.NewGuid() }; _accountRepositoryMock.SetupEntities(accounts); _releaseContentRepositoryMock.SetupEntities(ticketInformations); _releaseContentRepositoryMock.Setup(x => x.Update(It.IsAny<ReleaseContent>())) .Returns(new ChangedFields<ReleaseContent>()); _releaseContentRepositoryMock.Setup(x => x.Insert(It.IsAny<ReleaseContent>())); _releaseWindowRepositoryMock.SetupEntities(new[] { new ReleaseWindow { ReleaseWindowId = 5, ExternalId = releaseWindow.ExternalId } }); _mappingEngineMock.Setup(x => x.Map<ReleaseContentTicket, ReleaseContent>(tickets[2])) .Returns(new ReleaseContent { TicketId = tickets[2].TicketId, TicketRisk = tickets[2].Risk, Comment = tickets[2].Comment, IncludeToReleaseNotes = tickets[2].IncludeToReleaseNotes }); Sut.AddOrUpdateTickets(tickets, account.ExternalId, releaseWindow.ExternalId); _releaseContentRepositoryMock.Verify(x => x.Update(It.Is<ReleaseContent>( y => y.TicketId == new Guid(2, 0, 0, new byte[8]) && y.LastChangedByAccountId == accounts.First().AccountId)), Times.Once()); _releaseContentRepositoryMock.Verify(x => x.Update(It.Is<ReleaseContent>( y => y.TicketId == new Guid(3, 0, 0, new byte[8]) && y.LastChangedByAccountId == accounts.First().AccountId && !y.IncludeToReleaseNotes)), Times.Once()); _releaseContentRepositoryMock.Verify(x => x.Insert(It.Is<ReleaseContent>( y => y.IncludeToReleaseNotes == tickets[2].IncludeToReleaseNotes && y.Comment == tickets[2].Comment && y.TicketId == tickets[2].TicketId && y.LastChangedByAccountId == accounts.First().AccountId)), Times.Once()); _mappingEngineMock.Verify(x => x.Map<ReleaseContentTicket, ReleaseContent>(tickets[2]), Times.Once()); } [Test] public void RemoveTicketsFromRelease_ShouldCleanReleaseWindowField_WhenInvoked() { var accounts = BuildAccounts(); var releaseWindow = new BusinessEntities.ReleaseCalendar.ReleaseWindow { ExternalId = Guid.NewGuid() }; var ticketInformations = BuildTicketInformations(accounts, releaseWindow); _releaseContentRepositoryMock.SetupEntities(ticketInformations); _releaseContentRepositoryMock.Setup(x => x.Update(It.IsAny<ReleaseContent>())) .Returns(new ChangedFields<ReleaseContent>()); Sut.RemoveTicketsFromRelease(releaseWindow.ExternalId); _releaseContentRepositoryMock.Verify(x => x.Update(It.Is<ReleaseContent>( j => j.TicketId == new Guid(1, 0, 0, new byte[8]) && j.ReleaseWindow == null && j.ReleaseWindowsId == null)), Times.Once()); _releaseContentRepositoryMock.Verify(x => x.Update(It.Is<ReleaseContent>( j => j.TicketId == new Guid(2, 0, 0, new byte[8]) && j.ReleaseWindow == null && j.ReleaseWindowsId == null)), Times.Once()); _releaseContentRepositoryMock.Verify(x => x.Update(It.Is<ReleaseContent>( j => j.TicketId == new Guid(3, 0, 0, new byte[8]) && j.ReleaseWindow == null && j.ReleaseWindowsId == null)), Times.Once()); _releaseContentRepositoryMock.Verify(x => x.Update(It.IsAny<ReleaseContent>()), Times.Exactly(3)); } private static List<ReleaseContentTicket> BuildTickets(IList<DataEntities.Auth.Account> accounts) { return new List<ReleaseContentTicket> { new ReleaseContentTicket { TicketId = new Guid(2, 0, 0, new byte[8]), Risk = RandomData.RandomEnum<TicketRisk>(), LastChangedByAccount = accounts.First().ExternalId }, new ReleaseContentTicket { TicketId = new Guid(3, 0, 0, new byte[8]), Risk = RandomData.RandomEnum<TicketRisk>(), LastChangedByAccount = accounts.First().ExternalId }, new ReleaseContentTicket { TicketId = new Guid(4, 0, 0, new byte[8]), Risk = RandomData.RandomEnum<TicketRisk>(), LastChangedByAccount = accounts.First().ExternalId } }; } private static IEnumerable<ReleaseContent> BuildTicketInformations(IList<DataEntities.Auth.Account> accounts, BusinessEntities.ReleaseCalendar.ReleaseWindow releaseWindow = null) { return new List<ReleaseContent> { new ReleaseContent { TicketId = new Guid(1, 0, 0, new byte[8]), Comment = RandomData.RandomString(10), LastChangedByAccount = accounts.First(), ReleaseWindow = new ReleaseWindow{ExternalId = releaseWindow != null ? releaseWindow.ExternalId : Guid.NewGuid()}, ReleaseWindowsId = releaseWindow != null ? RandomData.RandomInt(1, 99) : (int?)null }, new ReleaseContent { TicketId = new Guid(2, 0, 0, new byte[8]), Comment = RandomData.RandomString(10), LastChangedByAccount = accounts.First(), IncludeToReleaseNotes = false, ReleaseWindow = new ReleaseWindow{ExternalId = releaseWindow != null ? releaseWindow.ExternalId : Guid.NewGuid()}, ReleaseWindowsId = releaseWindow != null ? RandomData.RandomInt(1, 99) : (int?)null }, new ReleaseContent { TicketId = new Guid(3, 0, 0, new byte[8]), Comment = RandomData.RandomString(10), LastChangedByAccount = accounts.First(), ReleaseWindow = new ReleaseWindow{ExternalId = releaseWindow != null ? releaseWindow.ExternalId : Guid.NewGuid()}, ReleaseWindowsId = releaseWindow != null ? RandomData.RandomInt(1, 99) : (int?)null, IncludeToReleaseNotes = true } }; } private static IList<DataEntities.Auth.Account> BuildAccounts() { return Builder<DataEntities.Auth.Account>.CreateListOfSize(1).All() .Do(x => x.ExternalId = Guid.NewGuid()) .Do(x => x.AccountId = RandomData.RandomInt(4)) .Build(); } } }
namespace KabMan.Client { partial class frmServerListe { /// <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() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmServerListe)); this.barManager1 = new DevExpress.XtraBars.BarManager(this.components); this.bar1 = new DevExpress.XtraBars.Bar(); this.btnNeu = new DevExpress.XtraBars.BarButtonItem(); this.btnDetail = new DevExpress.XtraBars.BarButtonItem(); this.btnLoeschen = new DevExpress.XtraBars.BarButtonItem(); this.btnListe = new DevExpress.XtraBars.BarButtonItem(); this.btnErstellen = new DevExpress.XtraBars.BarButtonItem(); this.barSubItem1 = new DevExpress.XtraBars.BarSubItem(); this.barCheckItem1 = new DevExpress.XtraBars.BarCheckItem(); this.barCheckItem2 = new DevExpress.XtraBars.BarCheckItem(); this.barCheckItem3 = new DevExpress.XtraBars.BarCheckItem(); this.barCheckItem4 = new DevExpress.XtraBars.BarCheckItem(); this.barCheckItem5 = new DevExpress.XtraBars.BarCheckItem(); this.btnSchliessen = new DevExpress.XtraBars.BarButtonItem(); this.barDockControlTop = new DevExpress.XtraBars.BarDockControl(); this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl(); this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl(); this.barDockControlRight = new DevExpress.XtraBars.BarDockControl(); this.barButtonItem1 = new DevExpress.XtraBars.BarButtonItem(); this.barButtonItem2 = new DevExpress.XtraBars.BarButtonItem(); this.barButtonItem3 = new DevExpress.XtraBars.BarButtonItem(); this.barButtonItem4 = new DevExpress.XtraBars.BarButtonItem(); this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl(); this.gridControl1 = new DevExpress.XtraGrid.GridControl(); this.gridView1 = new DevExpress.XtraGrid.Views.Grid.GridView(); this.ServerId = new DevExpress.XtraGrid.Columns.GridColumn(); this.ServerName = new DevExpress.XtraGrid.Columns.GridColumn(); this.OPSys = new DevExpress.XtraGrid.Columns.GridColumn(); this.LocationName = new DevExpress.XtraGrid.Columns.GridColumn(); this.Standort = new DevExpress.XtraGrid.Columns.GridColumn(); this.Size = new DevExpress.XtraGrid.Columns.GridColumn(); this.layoutControlGroup1 = new DevExpress.XtraLayout.LayoutControlGroup(); this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem(); this.popupMenu1 = new DevExpress.XtraBars.PopupMenu(this.components); ((System.ComponentModel.ISupportInitialize)(this.barManager1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit(); this.layoutControl1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.gridControl1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.gridView1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.popupMenu1)).BeginInit(); this.SuspendLayout(); // // barManager1 // this.barManager1.AllowCustomization = false; this.barManager1.AllowQuickCustomization = false; this.barManager1.AllowShowToolbarsPopup = false; this.barManager1.Bars.AddRange(new DevExpress.XtraBars.Bar[] { this.bar1}); this.barManager1.DockControls.Add(this.barDockControlTop); this.barManager1.DockControls.Add(this.barDockControlBottom); this.barManager1.DockControls.Add(this.barDockControlLeft); this.barManager1.DockControls.Add(this.barDockControlRight); this.barManager1.Form = this; this.barManager1.Items.AddRange(new DevExpress.XtraBars.BarItem[] { this.btnNeu, this.btnDetail, this.btnLoeschen, this.btnSchliessen, this.barButtonItem1, this.barButtonItem2, this.barButtonItem3, this.barButtonItem4, this.btnListe, this.btnErstellen, this.barSubItem1, this.barCheckItem1, this.barCheckItem2, this.barCheckItem3, this.barCheckItem4, this.barCheckItem5}); this.barManager1.MaxItemId = 16; // // bar1 // this.bar1.BarName = "Tools"; this.bar1.DockCol = 0; this.bar1.DockRow = 0; this.bar1.DockStyle = DevExpress.XtraBars.BarDockStyle.Top; this.bar1.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.btnNeu), new DevExpress.XtraBars.LinkPersistInfo(this.btnDetail), new DevExpress.XtraBars.LinkPersistInfo(this.btnLoeschen), new DevExpress.XtraBars.LinkPersistInfo(this.btnListe, true), new DevExpress.XtraBars.LinkPersistInfo(this.btnErstellen, true), new DevExpress.XtraBars.LinkPersistInfo(this.barSubItem1, true), new DevExpress.XtraBars.LinkPersistInfo(this.btnSchliessen, true)}); this.bar1.OptionsBar.AllowQuickCustomization = false; this.bar1.OptionsBar.DrawDragBorder = false; this.bar1.OptionsBar.UseWholeRow = true; resources.ApplyResources(this.bar1, "bar1"); // // btnNeu // resources.ApplyResources(this.btnNeu, "btnNeu"); this.btnNeu.Glyph = global::KabMan.Client.Properties.Resources.neu; this.btnNeu.Id = 0; this.btnNeu.Name = "btnNeu"; this.btnNeu.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.btnNeu_ItemClick); // // btnDetail // resources.ApplyResources(this.btnDetail, "btnDetail"); this.btnDetail.Glyph = global::KabMan.Client.Properties.Resources.detail; this.btnDetail.Id = 1; this.btnDetail.Name = "btnDetail"; this.btnDetail.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.btnDetail_ItemClick); // // btnLoeschen // resources.ApplyResources(this.btnLoeschen, "btnLoeschen"); this.btnLoeschen.Glyph = global::KabMan.Client.Properties.Resources.loeschen; this.btnLoeschen.Id = 2; this.btnLoeschen.Name = "btnLoeschen"; this.btnLoeschen.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.btnLoeschen_ItemClick); // // btnListe // resources.ApplyResources(this.btnListe, "btnListe"); this.btnListe.Glyph = global::KabMan.Client.Properties.Resources.form_green; this.btnListe.Id = 8; this.btnListe.Name = "btnListe"; this.btnListe.PaintStyle = DevExpress.XtraBars.BarItemPaintStyle.CaptionGlyph; this.btnListe.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.btnListe_ItemClick); // // btnErstellen // resources.ApplyResources(this.btnErstellen, "btnErstellen"); this.btnErstellen.Id = 9; this.btnErstellen.Name = "btnErstellen"; this.btnErstellen.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.btnErstellen_ItemClick); // // barSubItem1 // resources.ApplyResources(this.barSubItem1, "barSubItem1"); this.barSubItem1.Id = 10; this.barSubItem1.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.barCheckItem1), new DevExpress.XtraBars.LinkPersistInfo(this.barCheckItem2), new DevExpress.XtraBars.LinkPersistInfo(this.barCheckItem3), new DevExpress.XtraBars.LinkPersistInfo(this.barCheckItem4), new DevExpress.XtraBars.LinkPersistInfo(this.barCheckItem5)}); this.barSubItem1.Name = "barSubItem1"; // // barCheckItem1 // resources.ApplyResources(this.barCheckItem1, "barCheckItem1"); this.barCheckItem1.Checked = true; this.barCheckItem1.Id = 11; this.barCheckItem1.Name = "barCheckItem1"; this.barCheckItem1.CheckedChanged += new DevExpress.XtraBars.ItemClickEventHandler(this.barCheckItem1_CheckedChanged); // // barCheckItem2 // resources.ApplyResources(this.barCheckItem2, "barCheckItem2"); this.barCheckItem2.Checked = true; this.barCheckItem2.Id = 12; this.barCheckItem2.Name = "barCheckItem2"; this.barCheckItem2.CheckedChanged += new DevExpress.XtraBars.ItemClickEventHandler(this.barCheckItem2_CheckedChanged); // // barCheckItem3 // resources.ApplyResources(this.barCheckItem3, "barCheckItem3"); this.barCheckItem3.Checked = true; this.barCheckItem3.Id = 13; this.barCheckItem3.Name = "barCheckItem3"; this.barCheckItem3.CheckedChanged += new DevExpress.XtraBars.ItemClickEventHandler(this.barCheckItem3_CheckedChanged); // // barCheckItem4 // resources.ApplyResources(this.barCheckItem4, "barCheckItem4"); this.barCheckItem4.Checked = true; this.barCheckItem4.Id = 14; this.barCheckItem4.Name = "barCheckItem4"; this.barCheckItem4.CheckedChanged += new DevExpress.XtraBars.ItemClickEventHandler(this.barCheckItem4_CheckedChanged); // // barCheckItem5 // resources.ApplyResources(this.barCheckItem5, "barCheckItem5"); this.barCheckItem5.Checked = true; this.barCheckItem5.Id = 15; this.barCheckItem5.Name = "barCheckItem5"; this.barCheckItem5.CheckedChanged += new DevExpress.XtraBars.ItemClickEventHandler(this.barCheckItem5_CheckedChanged); // // btnSchliessen // resources.ApplyResources(this.btnSchliessen, "btnSchliessen"); this.btnSchliessen.Glyph = global::KabMan.Client.Properties.Resources.exit; this.btnSchliessen.Id = 3; this.btnSchliessen.Name = "btnSchliessen"; this.btnSchliessen.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.btnSchliessen_ItemClick); // // barButtonItem1 // resources.ApplyResources(this.barButtonItem1, "barButtonItem1"); this.barButtonItem1.Id = 4; this.barButtonItem1.Name = "barButtonItem1"; // // barButtonItem2 // resources.ApplyResources(this.barButtonItem2, "barButtonItem2"); this.barButtonItem2.Id = 5; this.barButtonItem2.Name = "barButtonItem2"; // // barButtonItem3 // resources.ApplyResources(this.barButtonItem3, "barButtonItem3"); this.barButtonItem3.Id = 6; this.barButtonItem3.Name = "barButtonItem3"; // // barButtonItem4 // resources.ApplyResources(this.barButtonItem4, "barButtonItem4"); this.barButtonItem4.Id = 7; this.barButtonItem4.Name = "barButtonItem4"; // // layoutControl1 // this.layoutControl1.AllowCustomizationMenu = false; this.layoutControl1.Appearance.DisabledLayoutGroupCaption.ForeColor = System.Drawing.SystemColors.GrayText; this.layoutControl1.Appearance.DisabledLayoutGroupCaption.Options.UseForeColor = true; this.layoutControl1.Appearance.DisabledLayoutItem.ForeColor = System.Drawing.SystemColors.GrayText; this.layoutControl1.Appearance.DisabledLayoutItem.Options.UseForeColor = true; this.layoutControl1.Controls.Add(this.gridControl1); resources.ApplyResources(this.layoutControl1, "layoutControl1"); this.layoutControl1.Name = "layoutControl1"; this.layoutControl1.Root = this.layoutControlGroup1; // // gridControl1 // resources.ApplyResources(this.gridControl1, "gridControl1"); this.gridControl1.MainView = this.gridView1; this.gridControl1.Name = "gridControl1"; this.gridControl1.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] { this.gridView1}); this.gridControl1.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.gridControl1_MouseDoubleClick); // // gridView1 // this.gridView1.Appearance.ColumnFilterButton.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.ColumnFilterButton.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212))))); this.gridView1.Appearance.ColumnFilterButton.BorderColor = System.Drawing.Color.Silver; this.gridView1.Appearance.ColumnFilterButton.ForeColor = System.Drawing.Color.Gray; this.gridView1.Appearance.ColumnFilterButton.Options.UseBackColor = true; this.gridView1.Appearance.ColumnFilterButton.Options.UseBorderColor = true; this.gridView1.Appearance.ColumnFilterButton.Options.UseForeColor = true; this.gridView1.Appearance.ColumnFilterButtonActive.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212))))); this.gridView1.Appearance.ColumnFilterButtonActive.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(223)))), ((int)(((byte)(223))))); this.gridView1.Appearance.ColumnFilterButtonActive.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212))))); this.gridView1.Appearance.ColumnFilterButtonActive.ForeColor = System.Drawing.Color.Blue; this.gridView1.Appearance.ColumnFilterButtonActive.Options.UseBackColor = true; this.gridView1.Appearance.ColumnFilterButtonActive.Options.UseBorderColor = true; this.gridView1.Appearance.ColumnFilterButtonActive.Options.UseForeColor = true; this.gridView1.Appearance.Empty.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243))))); this.gridView1.Appearance.Empty.Options.UseBackColor = true; this.gridView1.Appearance.EvenRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(223)))), ((int)(((byte)(223))))); this.gridView1.Appearance.EvenRow.BackColor2 = System.Drawing.Color.GhostWhite; this.gridView1.Appearance.EvenRow.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.EvenRow.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.gridView1.Appearance.EvenRow.Options.UseBackColor = true; this.gridView1.Appearance.EvenRow.Options.UseForeColor = true; this.gridView1.Appearance.FilterCloseButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.gridView1.Appearance.FilterCloseButton.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(118)))), ((int)(((byte)(170)))), ((int)(((byte)(225))))); this.gridView1.Appearance.FilterCloseButton.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.gridView1.Appearance.FilterCloseButton.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.FilterCloseButton.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.gridView1.Appearance.FilterCloseButton.Options.UseBackColor = true; this.gridView1.Appearance.FilterCloseButton.Options.UseBorderColor = true; this.gridView1.Appearance.FilterCloseButton.Options.UseForeColor = true; this.gridView1.Appearance.FilterPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(28)))), ((int)(((byte)(80)))), ((int)(((byte)(135))))); this.gridView1.Appearance.FilterPanel.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.gridView1.Appearance.FilterPanel.ForeColor = System.Drawing.Color.White; this.gridView1.Appearance.FilterPanel.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.gridView1.Appearance.FilterPanel.Options.UseBackColor = true; this.gridView1.Appearance.FilterPanel.Options.UseForeColor = true; this.gridView1.Appearance.FixedLine.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(58)))), ((int)(((byte)(58))))); this.gridView1.Appearance.FixedLine.Options.UseBackColor = true; this.gridView1.Appearance.FocusedCell.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(225))))); this.gridView1.Appearance.FocusedCell.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.FocusedCell.Options.UseBackColor = true; this.gridView1.Appearance.FocusedCell.Options.UseForeColor = true; this.gridView1.Appearance.FocusedRow.BackColor = System.Drawing.Color.Navy; this.gridView1.Appearance.FocusedRow.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(50)))), ((int)(((byte)(50)))), ((int)(((byte)(178))))); this.gridView1.Appearance.FocusedRow.ForeColor = System.Drawing.Color.White; this.gridView1.Appearance.FocusedRow.Options.UseBackColor = true; this.gridView1.Appearance.FocusedRow.Options.UseForeColor = true; this.gridView1.Appearance.FooterPanel.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.FooterPanel.BorderColor = System.Drawing.Color.Silver; this.gridView1.Appearance.FooterPanel.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.FooterPanel.Options.UseBackColor = true; this.gridView1.Appearance.FooterPanel.Options.UseBorderColor = true; this.gridView1.Appearance.FooterPanel.Options.UseForeColor = true; this.gridView1.Appearance.GroupButton.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.GroupButton.BorderColor = System.Drawing.Color.Silver; this.gridView1.Appearance.GroupButton.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.GroupButton.Options.UseBackColor = true; this.gridView1.Appearance.GroupButton.Options.UseBorderColor = true; this.gridView1.Appearance.GroupButton.Options.UseForeColor = true; this.gridView1.Appearance.GroupFooter.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(202)))), ((int)(((byte)(202))))); this.gridView1.Appearance.GroupFooter.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(202)))), ((int)(((byte)(202))))); this.gridView1.Appearance.GroupFooter.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.GroupFooter.Options.UseBackColor = true; this.gridView1.Appearance.GroupFooter.Options.UseBorderColor = true; this.gridView1.Appearance.GroupFooter.Options.UseForeColor = true; this.gridView1.Appearance.GroupPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(110)))), ((int)(((byte)(165))))); this.gridView1.Appearance.GroupPanel.BackColor2 = System.Drawing.Color.White; this.gridView1.Appearance.GroupPanel.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold); this.gridView1.Appearance.GroupPanel.ForeColor = System.Drawing.Color.White; this.gridView1.Appearance.GroupPanel.Options.UseBackColor = true; this.gridView1.Appearance.GroupPanel.Options.UseFont = true; this.gridView1.Appearance.GroupPanel.Options.UseForeColor = true; this.gridView1.Appearance.GroupRow.BackColor = System.Drawing.Color.Gray; this.gridView1.Appearance.GroupRow.ForeColor = System.Drawing.Color.Silver; this.gridView1.Appearance.GroupRow.Options.UseBackColor = true; this.gridView1.Appearance.GroupRow.Options.UseForeColor = true; this.gridView1.Appearance.HeaderPanel.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.HeaderPanel.BorderColor = System.Drawing.Color.Silver; this.gridView1.Appearance.HeaderPanel.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold); this.gridView1.Appearance.HeaderPanel.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.HeaderPanel.Options.UseBackColor = true; this.gridView1.Appearance.HeaderPanel.Options.UseBorderColor = true; this.gridView1.Appearance.HeaderPanel.Options.UseFont = true; this.gridView1.Appearance.HeaderPanel.Options.UseForeColor = true; this.gridView1.Appearance.HideSelectionRow.BackColor = System.Drawing.Color.Gray; this.gridView1.Appearance.HideSelectionRow.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.gridView1.Appearance.HideSelectionRow.Options.UseBackColor = true; this.gridView1.Appearance.HideSelectionRow.Options.UseForeColor = true; this.gridView1.Appearance.HorzLine.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.HorzLine.Options.UseBackColor = true; this.gridView1.Appearance.OddRow.BackColor = System.Drawing.Color.White; this.gridView1.Appearance.OddRow.BackColor2 = System.Drawing.Color.White; this.gridView1.Appearance.OddRow.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.OddRow.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.BackwardDiagonal; this.gridView1.Appearance.OddRow.Options.UseBackColor = true; this.gridView1.Appearance.OddRow.Options.UseForeColor = true; this.gridView1.Appearance.Preview.BackColor = System.Drawing.Color.White; this.gridView1.Appearance.Preview.ForeColor = System.Drawing.Color.Navy; this.gridView1.Appearance.Preview.Options.UseBackColor = true; this.gridView1.Appearance.Preview.Options.UseForeColor = true; this.gridView1.Appearance.Row.BackColor = System.Drawing.Color.White; this.gridView1.Appearance.Row.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.Row.Options.UseBackColor = true; this.gridView1.Appearance.Row.Options.UseForeColor = true; this.gridView1.Appearance.RowSeparator.BackColor = System.Drawing.Color.White; this.gridView1.Appearance.RowSeparator.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243))))); this.gridView1.Appearance.RowSeparator.Options.UseBackColor = true; this.gridView1.Appearance.SelectedRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(10)))), ((int)(((byte)(10)))), ((int)(((byte)(138))))); this.gridView1.Appearance.SelectedRow.ForeColor = System.Drawing.Color.White; this.gridView1.Appearance.SelectedRow.Options.UseBackColor = true; this.gridView1.Appearance.SelectedRow.Options.UseForeColor = true; this.gridView1.Appearance.VertLine.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.VertLine.Options.UseBackColor = true; this.gridView1.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] { this.ServerId, this.ServerName, this.OPSys, this.LocationName, this.Standort, this.Size}); this.gridView1.GridControl = this.gridControl1; this.gridView1.Name = "gridView1"; this.gridView1.OptionsBehavior.AllowIncrementalSearch = true; this.gridView1.OptionsBehavior.Editable = false; this.gridView1.OptionsCustomization.AllowFilter = false; this.gridView1.OptionsMenu.EnableColumnMenu = false; this.gridView1.OptionsMenu.EnableFooterMenu = false; this.gridView1.OptionsMenu.EnableGroupPanelMenu = false; this.gridView1.OptionsView.EnableAppearanceEvenRow = true; this.gridView1.OptionsView.EnableAppearanceOddRow = true; this.gridView1.OptionsView.ShowAutoFilterRow = true; this.gridView1.OptionsView.ShowGroupPanel = false; this.gridView1.OptionsView.ShowIndicator = false; // // ServerId // resources.ApplyResources(this.ServerId, "ServerId"); this.ServerId.FieldName = "ServerId"; this.ServerId.Name = "ServerId"; // // ServerName // resources.ApplyResources(this.ServerName, "ServerName"); this.ServerName.FieldName = "ServerName"; this.ServerName.Name = "ServerName"; // // OPSys // resources.ApplyResources(this.OPSys, "OPSys"); this.OPSys.FieldName = "OPSys"; this.OPSys.Name = "OPSys"; // // LocationName // resources.ApplyResources(this.LocationName, "LocationName"); this.LocationName.FieldName = "LocationName"; this.LocationName.Name = "LocationName"; // // Standort // resources.ApplyResources(this.Standort, "Standort"); this.Standort.FieldName = "Standort"; this.Standort.Name = "Standort"; // // Size // resources.ApplyResources(this.Size, "Size"); this.Size.FieldName = "Size"; this.Size.Name = "Size"; // // layoutControlGroup1 // resources.ApplyResources(this.layoutControlGroup1, "layoutControlGroup1"); this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] { this.layoutControlItem1}); this.layoutControlGroup1.Location = new System.Drawing.Point(0, 0); this.layoutControlGroup1.Name = "layoutControlGroup1"; this.layoutControlGroup1.Size = new System.Drawing.Size(540, 318); this.layoutControlGroup1.Spacing = new DevExpress.XtraLayout.Utils.Padding(0, 0, 0, 0); this.layoutControlGroup1.TextVisible = false; // // layoutControlItem1 // this.layoutControlItem1.Control = this.gridControl1; resources.ApplyResources(this.layoutControlItem1, "layoutControlItem1"); this.layoutControlItem1.Location = new System.Drawing.Point(0, 0); this.layoutControlItem1.Name = "layoutControlItem1"; this.layoutControlItem1.Size = new System.Drawing.Size(538, 316); this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem1.TextSize = new System.Drawing.Size(0, 0); this.layoutControlItem1.TextToControlDistance = 0; this.layoutControlItem1.TextVisible = false; // // popupMenu1 // this.popupMenu1.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.barButtonItem1), new DevExpress.XtraBars.LinkPersistInfo(this.barButtonItem2), new DevExpress.XtraBars.LinkPersistInfo(this.barButtonItem3), new DevExpress.XtraBars.LinkPersistInfo(this.barButtonItem4, true)}); this.popupMenu1.Manager = this.barManager1; this.popupMenu1.Name = "popupMenu1"; // // frmServerListe // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.layoutControl1); this.Controls.Add(this.barDockControlLeft); this.Controls.Add(this.barDockControlRight); this.Controls.Add(this.barDockControlBottom); this.Controls.Add(this.barDockControlTop); this.Name = "frmServerListe"; this.Load += new System.EventHandler(this.frmServerListe_Load); ((System.ComponentModel.ISupportInitialize)(this.barManager1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit(); this.layoutControl1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.gridControl1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.gridView1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.popupMenu1)).EndInit(); this.ResumeLayout(false); } #endregion private DevExpress.XtraBars.BarManager barManager1; private DevExpress.XtraBars.Bar bar1; private DevExpress.XtraBars.BarDockControl barDockControlTop; private DevExpress.XtraBars.BarDockControl barDockControlBottom; private DevExpress.XtraBars.BarDockControl barDockControlLeft; private DevExpress.XtraBars.BarDockControl barDockControlRight; private DevExpress.XtraLayout.LayoutControl layoutControl1; private DevExpress.XtraGrid.GridControl gridControl1; private DevExpress.XtraGrid.Views.Grid.GridView gridView1; private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup1; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1; private DevExpress.XtraBars.BarButtonItem btnNeu; private DevExpress.XtraBars.BarButtonItem btnDetail; private DevExpress.XtraBars.BarButtonItem btnLoeschen; private DevExpress.XtraBars.BarButtonItem btnSchliessen; private DevExpress.XtraGrid.Columns.GridColumn ServerId; private DevExpress.XtraGrid.Columns.GridColumn ServerName; private DevExpress.XtraGrid.Columns.GridColumn OPSys; private DevExpress.XtraBars.PopupMenu popupMenu1; private DevExpress.XtraBars.BarButtonItem barButtonItem1; private DevExpress.XtraBars.BarButtonItem barButtonItem2; private DevExpress.XtraBars.BarButtonItem barButtonItem3; private DevExpress.XtraBars.BarButtonItem barButtonItem4; private DevExpress.XtraGrid.Columns.GridColumn LocationName; private DevExpress.XtraBars.BarButtonItem btnListe; private DevExpress.XtraGrid.Columns.GridColumn Standort; private DevExpress.XtraGrid.Columns.GridColumn Size; private DevExpress.XtraBars.BarButtonItem btnErstellen; private DevExpress.XtraBars.BarSubItem barSubItem1; private DevExpress.XtraBars.BarCheckItem barCheckItem1; private DevExpress.XtraBars.BarCheckItem barCheckItem2; private DevExpress.XtraBars.BarCheckItem barCheckItem3; private DevExpress.XtraBars.BarCheckItem barCheckItem4; private DevExpress.XtraBars.BarCheckItem barCheckItem5; } }
/* Copyright (c) Microsoft Corporation All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.CodeDom; using System.Xml; using System.Diagnostics; using Microsoft.Research.DryadLinq.Internal; namespace Microsoft.Research.DryadLinq { internal class NodeInfoEdge { public QueryNodeInfo Parent; public QueryNodeInfo Child; public NodeInfoEdge(QueryNodeInfo parent, QueryNodeInfo child) { this.Parent = parent; this.Child = child; } // Replace all occurences of oldEdge in edges by newEdge. public static bool UpdateEdge(List<NodeInfoEdge> edges, NodeInfoEdge oldEdge, NodeInfoEdge newEdge) { for (int i = 0; i < edges.Count; i++) { if (Object.ReferenceEquals(oldEdge, edges[i])) { edges[i] = newEdge; return true; } } return false; } // Insert a node info on this edge. public void Insert(QueryNodeInfo nextInfo) { Debug.Assert(nextInfo.Children.Count == 0 && nextInfo.Parents.Count == 0); NodeInfoEdge edge1 = new NodeInfoEdge(this.Parent, nextInfo); NodeInfoEdge edge2 = new NodeInfoEdge(nextInfo, this.Child); UpdateEdge(this.Parent.Children, this, edge1); nextInfo.Parents.Add(edge1); UpdateEdge(this.Child.Parents, this, edge2); nextInfo.Children.Add(edge2); } } internal class QueryNodeInfo { public Expression QueryExpression; public List<NodeInfoEdge> Children; public List<NodeInfoEdge> Parents; public bool IsQueryOperator; public DLinqQueryNode QueryNode; public QueryNodeInfo(Expression queryExpression, bool isQueryOperator, params QueryNodeInfo[] children) { this.QueryExpression = queryExpression; this.IsQueryOperator = isQueryOperator; this.Children = new List<NodeInfoEdge>(children.Length); foreach (QueryNodeInfo childInfo in children) { NodeInfoEdge edge = new NodeInfoEdge(this, childInfo); this.Children.Add(edge); childInfo.Parents.Add(edge); } this.Parents = new List<NodeInfoEdge>(); this.QueryNode = null; } public string OperatorName { get { if (!this.IsQueryOperator) return null; return ((MethodCallExpression)this.QueryExpression).Method.Name; } } public Type Type { get { return this.QueryExpression.Type; } } public bool IsForked { get { return this.Parents.Count > 1; } } public virtual QueryNodeInfo Clone() { return new QueryNodeInfo(this.QueryExpression, this.IsQueryOperator); } // Delete this NodeInfo. // Precondition: this.children.Count < 2 public void Delete() { Debug.Assert(this.Children.Count < 2); if (this.Children.Count == 0) { foreach (NodeInfoEdge edge in this.Parents) { edge.Parent.Children.Remove(edge); } } else { QueryNodeInfo child = this.Children[0].Child; child.Parents.Remove(this.Children[0]); foreach (NodeInfoEdge edge in this.Parents) { NodeInfoEdge newEdge = new NodeInfoEdge(edge.Parent, child); NodeInfoEdge.UpdateEdge(edge.Parent.Children, edge, newEdge); child.Parents.Add(newEdge); } } this.Parents.Clear(); this.Children.Clear(); } // Return true if this is not in the NodeInfo graph. public bool IsOrphaned { get { return (this.Children.Count == 0 && this.Parents.Count == 0); } } public void Swap(QueryNodeInfo other) { Debug.Assert(this.IsQueryOperator && other.IsQueryOperator); Debug.Assert(this.QueryNode == null && other.QueryNode == null); Expression queryExpr = this.QueryExpression; this.QueryExpression = other.QueryExpression; other.QueryExpression = queryExpr; } } internal class DummyQueryNodeInfo : QueryNodeInfo { public bool NeedsMerge; public DummyQueryNodeInfo(Expression queryExpression, bool needsMerge, params QueryNodeInfo[] children) : base(queryExpression, false, children) { NeedsMerge = needsMerge; } public override QueryNodeInfo Clone() { throw new InvalidOperationException("Internal error."); } } internal class DoWhileQueryNodeInfo : QueryNodeInfo { public QueryNodeInfo Body; public QueryNodeInfo Cond; public QueryNodeInfo BodySource; public QueryNodeInfo CondSource1; public QueryNodeInfo CondSource2; public DoWhileQueryNodeInfo(Expression queryExpression, QueryNodeInfo body, QueryNodeInfo cond, QueryNodeInfo bodySource, QueryNodeInfo condSource1, QueryNodeInfo condSource2, params QueryNodeInfo[] children) : base(queryExpression, false, children) { this.Body = body; this.Cond = cond; this.BodySource = bodySource; this.CondSource1 = condSource1; this.CondSource2 = condSource2; } } internal class SimpleRewriter { private List<QueryNodeInfo> m_nodeInfos; public SimpleRewriter(List<QueryNodeInfo> nodeInfos) { this.m_nodeInfos = nodeInfos; } public void Rewrite() { bool isDone = false; while (!isDone) { isDone = true; int idx = 0; while (idx < this.m_nodeInfos.Count) { if (this.m_nodeInfos[idx].IsOrphaned) { this.m_nodeInfos[idx] = this.m_nodeInfos[this.m_nodeInfos.Count - 1]; this.m_nodeInfos.RemoveAt(this.m_nodeInfos.Count - 1); } else { bool changed = this.RewriteOne(idx); isDone = isDone && !changed; idx++; } } } } // Return true iff EPG is modified by this method. public bool RewriteOne(int idx) { QueryNodeInfo curNode = this.m_nodeInfos[idx]; if (curNode.OperatorName == "Where" && !curNode.Children[0].Child.IsForked) { LambdaExpression lambda = DryadLinqExpression.GetLambda(((MethodCallExpression)curNode.QueryExpression).Arguments[1]); if (lambda.Type.GetGenericArguments().Length == 2) { QueryNodeInfo child = curNode.Children[0].Child; string[] names = new string[] { "OrderBy", "Distinct", "RangePartition", "HashPartition" }; if (names.Contains(child.OperatorName)) { curNode.Swap(child); return true; } if (child.OperatorName == "Concat") { curNode.Delete(); for (int i = 0; i < child.Children.Count; i++) { NodeInfoEdge edge = child.Children[i]; QueryNodeInfo node = curNode.Clone(); this.m_nodeInfos.Add(node); edge.Insert(node); } return true; } } } else if ((curNode.OperatorName == "Select" || curNode.OperatorName == "SelectMany") && !curNode.Children[0].Child.IsForked) { LambdaExpression lambda = DryadLinqExpression.GetLambda(((MethodCallExpression)curNode.QueryExpression).Arguments[1]); if (lambda.Type.GetGenericArguments().Length == 2) { QueryNodeInfo child = curNode.Children[0].Child; if (child.OperatorName == "Concat") { curNode.Delete(); for (int i = 0; i < child.Children.Count; i++) { NodeInfoEdge edge = child.Children[i]; QueryNodeInfo node = curNode.Clone(); this.m_nodeInfos.Add(node); edge.Insert(node); } return true; } } } else if (curNode.OperatorName == "Take" && !curNode.Children[0].Child.IsForked) { QueryNodeInfo child = curNode.Children[0].Child; if (child.OperatorName == "Select") { QueryNodeInfo cchild = child.Children[0].Child; if (cchild.OperatorName != "GroupBy") { curNode.Swap(child); return true; } } } else if ((curNode.OperatorName == "Contains" || curNode.OperatorName == "ContainsAsQuery" || curNode.OperatorName == "All" || curNode.OperatorName == "AllAsQuery" || curNode.OperatorName == "Any" || curNode.OperatorName == "AnyAsQuery") && !curNode.Children[0].Child.IsForked) { QueryNodeInfo child = curNode.Children[0].Child; string[] names = new string[] { "OrderBy", "Distinct", "RangePartition", "HashPartition" }; if (names.Contains(child.OperatorName)) { child.Delete(); return true; } } return false; } } }
using System; using Microsoft.Win32; namespace AudioFileInspector { /// <summary> /// Helper class for registering Windows Explorer File associations /// </summary> public class FileAssociations { [System.Runtime.InteropServices.DllImport("shell32.dll")] static extern void SHChangeNotify(HChangeNotifyEventID wEventId, HChangeNotifyFlags uFlags, IntPtr dwItem1, IntPtr dwItem2); /// <summary> /// Determines if the specified file type is registered /// </summary> /// <param name="extension">The file extension including the leading period (e.g. ".wav")</param> /// <returns>True if it is registered</returns> public static bool IsFileTypeRegistered(string extension) { RegistryKey key = Registry.ClassesRoot.OpenSubKey(extension); if(key == null) return false; key.Close(); return true; } /// <summary> /// Gets the HKCR key name for the extenstion /// </summary> /// <param name="extension">The file extension including the leading period (e.g. ".wav")</param> /// <returns>The HKCR key name or null if not registered</returns> public static string GetFileTypeKey(string extension) { RegistryKey key = Registry.ClassesRoot.OpenSubKey(extension); string fileTypeKey = null; if (key != null) { fileTypeKey = (string) key.GetValue(null); key.Close(); } return fileTypeKey; } /// <summary> /// Registers a file type in Windows /// </summary> /// <param name="extension">Extension include leading '.'</param> /// <param name="description">The description of this file type</param> /// <param name="iconPath">Null for no icon or e.g c:\windows\regedit.exe,0</param> public static void RegisterFileType(string extension, string description, string iconPath) { if (IsFileTypeRegistered(extension)) throw new ArgumentException(extension + "is already registered"); RegistryKey key = Registry.ClassesRoot.CreateSubKey(extension); string fileKey = extension.Substring(1) + "File"; key.SetValue(null, fileKey); key.Close(); key = Registry.ClassesRoot.CreateSubKey(fileKey); key.SetValue(null, description); key.Close(); if (iconPath != null) { key = Registry.ClassesRoot.CreateSubKey(fileKey + "\\DefaultIcon"); key.SetValue(null, iconPath); key.Close(); } SHChangeNotify(HChangeNotifyEventID.SHCNE_ASSOCCHANGED, HChangeNotifyFlags.SHCNF_IDLIST, IntPtr.Zero, IntPtr.Zero); } /// <summary> /// Adds a new explorer context menu action for this file type /// Will overwrite any existing action with this key /// </summary> /// <param name="extension">The file extension (include the leading dot)</param> /// <param name="actionKey">A unique key for this action</param> /// <param name="actionDescription">What will appear on the context menu</param> /// <param name="command">The command to execute</param> public static void AddAction(string extension, string actionKey, string actionDescription, string command) { // command e.g. notepad.exe "%1" string fileTypeKey = GetFileTypeKey(extension); if (fileTypeKey == null) throw new ArgumentException(extension + "is not a registered file type"); RegistryKey key = Registry.ClassesRoot.CreateSubKey(fileTypeKey + "\\shell\\" + actionKey); key.SetValue(null, actionDescription); key.Close(); key = Registry.ClassesRoot.CreateSubKey(fileTypeKey + "\\shell\\" + actionKey + "\\command"); key.SetValue(null, command); key.Close(); SHChangeNotify(HChangeNotifyEventID.SHCNE_ASSOCCHANGED, HChangeNotifyFlags.SHCNF_IDLIST, IntPtr.Zero, IntPtr.Zero); } /// <summary> /// Removes an explorer context menu action from a file extension /// </summary> /// <param name="extension">The file extension (include the leading dot)</param> /// <param name="actionKey">The unique key used to register this action</param> public static void RemoveAction(string extension, string actionKey) { string fileTypeKey = GetFileTypeKey(extension); if (fileTypeKey == null) { return; //throw new ArgumentException(extension + "is not a registered file type"); } Registry.ClassesRoot.DeleteSubKey(fileTypeKey + "\\shell\\" + actionKey + "\\command"); Registry.ClassesRoot.DeleteSubKey(fileTypeKey + "\\shell\\" + actionKey); } // TODO: add ourselves as an "Open With" application // TODO: better error handling // TODO: unregistering stuff // TODO: set default action } #region enum HChangeNotifyEventID /// <summary> /// Describes the event that has occurred. /// Typically, only one event is specified at a time. /// If more than one event is specified, the values contained /// in the <i>dwItem1</i> and <i>dwItem2</i> /// parameters must be the same, respectively, for all specified events. /// This parameter can be one or more of the following values. /// </summary> /// <remarks> /// <para><b>Windows NT/2000/XP:</b> <i>dwItem2</i> contains the index /// in the system image list that has changed. /// <i>dwItem1</i> is not used and should be <see langword="null"/>.</para> /// <para><b>Windows 95/98:</b> <i>dwItem1</i> contains the index /// in the system image list that has changed. /// <i>dwItem2</i> is not used and should be <see langword="null"/>.</para> /// </remarks> [Flags] enum HChangeNotifyEventID { /// <summary> /// All events have occurred. /// </summary> SHCNE_ALLEVENTS = 0x7FFFFFFF, /// <summary> /// A file type association has changed. <see cref="HChangeNotifyFlags.SHCNF_IDLIST"/> /// must be specified in the <i>uFlags</i> parameter. /// <i>dwItem1</i> and <i>dwItem2</i> are not used and must be <see langword="null"/>. /// </summary> SHCNE_ASSOCCHANGED = 0x08000000, /// <summary> /// The attributes of an item or folder have changed. /// <see cref="HChangeNotifyFlags.SHCNF_IDLIST"/> or /// <see cref="HChangeNotifyFlags.SHCNF_PATHA"/> must be specified in <i>uFlags</i>. /// <i>dwItem1</i> contains the item or folder that has changed. /// <i>dwItem2</i> is not used and should be <see langword="null"/>. /// </summary> SHCNE_ATTRIBUTES = 0x00000800, /// <summary> /// A nonfolder item has been created. /// <see cref="HChangeNotifyFlags.SHCNF_IDLIST"/> or /// <see cref="HChangeNotifyFlags.SHCNF_PATHA"/> must be specified in <i>uFlags</i>. /// <i>dwItem1</i> contains the item that was created. /// <i>dwItem2</i> is not used and should be <see langword="null"/>. /// </summary> SHCNE_CREATE = 0x00000002, /// <summary> /// A nonfolder item has been deleted. /// <see cref="HChangeNotifyFlags.SHCNF_IDLIST"/> or /// <see cref="HChangeNotifyFlags.SHCNF_PATHA"/> must be specified in <i>uFlags</i>. /// <i>dwItem1</i> contains the item that was deleted. /// <i>dwItem2</i> is not used and should be <see langword="null"/>. /// </summary> SHCNE_DELETE = 0x00000004, /// <summary> /// A drive has been added. /// <see cref="HChangeNotifyFlags.SHCNF_IDLIST"/> or /// <see cref="HChangeNotifyFlags.SHCNF_PATHA"/> must be specified in <i>uFlags</i>. /// <i>dwItem1</i> contains the root of the drive that was added. /// <i>dwItem2</i> is not used and should be <see langword="null"/>. /// </summary> SHCNE_DRIVEADD = 0x00000100, /// <summary> /// A drive has been added and the Shell should create a new window for the drive. /// <see cref="HChangeNotifyFlags.SHCNF_IDLIST"/> or /// <see cref="HChangeNotifyFlags.SHCNF_PATHA"/> must be specified in <i>uFlags</i>. /// <i>dwItem1</i> contains the root of the drive that was added. /// <i>dwItem2</i> is not used and should be <see langword="null"/>. /// </summary> SHCNE_DRIVEADDGUI = 0x00010000, /// <summary> /// A drive has been removed. <see cref="HChangeNotifyFlags.SHCNF_IDLIST"/> or /// <see cref="HChangeNotifyFlags.SHCNF_PATHA"/> must be specified in <i>uFlags</i>. /// <i>dwItem1</i> contains the root of the drive that was removed. /// <i>dwItem2</i> is not used and should be <see langword="null"/>. /// </summary> SHCNE_DRIVEREMOVED = 0x00000080, /// <summary> /// Not currently used. /// </summary> SHCNE_EXTENDED_EVENT = 0x04000000, /// <summary> /// The amount of free space on a drive has changed. /// <see cref="HChangeNotifyFlags.SHCNF_IDLIST"/> or /// <see cref="HChangeNotifyFlags.SHCNF_PATHA"/> must be specified in <i>uFlags</i>. /// <i>dwItem1</i> contains the root of the drive on which the free space changed. /// <i>dwItem2</i> is not used and should be <see langword="null"/>. /// </summary> SHCNE_FREESPACE = 0x00040000, /// <summary> /// Storage media has been inserted into a drive. /// <see cref="HChangeNotifyFlags.SHCNF_IDLIST"/> or /// <see cref="HChangeNotifyFlags.SHCNF_PATHA"/> must be specified in <i>uFlags</i>. /// <i>dwItem1</i> contains the root of the drive that contains the new media. /// <i>dwItem2</i> is not used and should be <see langword="null"/>. /// </summary> SHCNE_MEDIAINSERTED = 0x00000020, /// <summary> /// Storage media has been removed from a drive. /// <see cref="HChangeNotifyFlags.SHCNF_IDLIST"/> or /// <see cref="HChangeNotifyFlags.SHCNF_PATHA"/> must be specified in <i>uFlags</i>. /// <i>dwItem1</i> contains the root of the drive from which the media was removed. /// <i>dwItem2</i> is not used and should be <see langword="null"/>. /// </summary> SHCNE_MEDIAREMOVED = 0x00000040, /// <summary> /// A folder has been created. <see cref="HChangeNotifyFlags.SHCNF_IDLIST"/> /// or <see cref="HChangeNotifyFlags.SHCNF_PATHA"/> must be specified in <i>uFlags</i>. /// <i>dwItem1</i> contains the folder that was created. /// <i>dwItem2</i> is not used and should be <see langword="null"/>. /// </summary> SHCNE_MKDIR = 0x00000008, /// <summary> /// A folder on the local computer is being shared via the network. /// <see cref="HChangeNotifyFlags.SHCNF_IDLIST"/> or /// <see cref="HChangeNotifyFlags.SHCNF_PATHA"/> must be specified in <i>uFlags</i>. /// <i>dwItem1</i> contains the folder that is being shared. /// <i>dwItem2</i> is not used and should be <see langword="null"/>. /// </summary> SHCNE_NETSHARE = 0x00000200, /// <summary> /// A folder on the local computer is no longer being shared via the network. /// <see cref="HChangeNotifyFlags.SHCNF_IDLIST"/> or /// <see cref="HChangeNotifyFlags.SHCNF_PATHA"/> must be specified in <i>uFlags</i>. /// <i>dwItem1</i> contains the folder that is no longer being shared. /// <i>dwItem2</i> is not used and should be <see langword="null"/>. /// </summary> SHCNE_NETUNSHARE = 0x00000400, /// <summary> /// The name of a folder has changed. /// <see cref="HChangeNotifyFlags.SHCNF_IDLIST"/> or /// <see cref="HChangeNotifyFlags.SHCNF_PATHA"/> must be specified in <i>uFlags</i>. /// <i>dwItem1</i> contains the previous pointer to an item identifier list (PIDL) or name of the folder. /// <i>dwItem2</i> contains the new PIDL or name of the folder. /// </summary> SHCNE_RENAMEFOLDER = 0x00020000, /// <summary> /// The name of a nonfolder item has changed. /// <see cref="HChangeNotifyFlags.SHCNF_IDLIST"/> or /// <see cref="HChangeNotifyFlags.SHCNF_PATHA"/> must be specified in <i>uFlags</i>. /// <i>dwItem1</i> contains the previous PIDL or name of the item. /// <i>dwItem2</i> contains the new PIDL or name of the item. /// </summary> SHCNE_RENAMEITEM = 0x00000001, /// <summary> /// A folder has been removed. /// <see cref="HChangeNotifyFlags.SHCNF_IDLIST"/> or /// <see cref="HChangeNotifyFlags.SHCNF_PATHA"/> must be specified in <i>uFlags</i>. /// <i>dwItem1</i> contains the folder that was removed. /// <i>dwItem2</i> is not used and should be <see langword="null"/>. /// </summary> SHCNE_RMDIR = 0x00000010, /// <summary> /// The computer has disconnected from a server. /// <see cref="HChangeNotifyFlags.SHCNF_IDLIST"/> or /// <see cref="HChangeNotifyFlags.SHCNF_PATHA"/> must be specified in <i>uFlags</i>. /// <i>dwItem1</i> contains the server from which the computer was disconnected. /// <i>dwItem2</i> is not used and should be <see langword="null"/>. /// </summary> SHCNE_SERVERDISCONNECT = 0x00004000, /// <summary> /// The contents of an existing folder have changed, /// but the folder still exists and has not been renamed. /// <see cref="HChangeNotifyFlags.SHCNF_IDLIST"/> or /// <see cref="HChangeNotifyFlags.SHCNF_PATHA"/> must be specified in <i>uFlags</i>. /// <i>dwItem1</i> contains the folder that has changed. /// <i>dwItem2</i> is not used and should be <see langword="null"/>. /// If a folder has been created, deleted, or renamed, use SHCNE_MKDIR, SHCNE_RMDIR, or /// SHCNE_RENAMEFOLDER, respectively, instead. /// </summary> SHCNE_UPDATEDIR = 0x00001000, /// <summary> /// An image in the system image list has changed. /// <see cref="HChangeNotifyFlags.SHCNF_DWORD"/> must be specified in <i>uFlags</i>. /// </summary> SHCNE_UPDATEIMAGE = 0x00008000, } #endregion // enum HChangeNotifyEventID #region public enum HChangeNotifyFlags /// <summary> /// Flags that indicate the meaning of the <i>dwItem1</i> and <i>dwItem2</i> parameters. /// The uFlags parameter must be one of the following values. /// </summary> [Flags] public enum HChangeNotifyFlags { /// <summary> /// The <i>dwItem1</i> and <i>dwItem2</i> parameters are DWORD values. /// </summary> SHCNF_DWORD = 0x0003, /// <summary> /// <i>dwItem1</i> and <i>dwItem2</i> are the addresses of ITEMIDLIST structures that /// represent the item(s) affected by the change. /// Each ITEMIDLIST must be relative to the desktop folder. /// </summary> SHCNF_IDLIST = 0x0000, /// <summary> /// <i>dwItem1</i> and <i>dwItem2</i> are the addresses of null-terminated strings of /// maximum length MAX_PATH that contain the full path names /// of the items affected by the change. /// </summary> SHCNF_PATHA = 0x0001, /// <summary> /// <i>dwItem1</i> and <i>dwItem2</i> are the addresses of null-terminated strings of /// maximum length MAX_PATH that contain the full path names /// of the items affected by the change. /// </summary> SHCNF_PATHW = 0x0005, /// <summary> /// <i>dwItem1</i> and <i>dwItem2</i> are the addresses of null-terminated strings that /// represent the friendly names of the printer(s) affected by the change. /// </summary> SHCNF_PRINTERA = 0x0002, /// <summary> /// <i>dwItem1</i> and <i>dwItem2</i> are the addresses of null-terminated strings that /// represent the friendly names of the printer(s) affected by the change. /// </summary> SHCNF_PRINTERW = 0x0006, /// <summary> /// The function should not return until the notification /// has been delivered to all affected components. /// As this flag modifies other data-type flags, it cannot by used by itself. /// </summary> SHCNF_FLUSH = 0x1000, /// <summary> /// The function should begin delivering notifications to all affected components /// but should return as soon as the notification process has begun. /// As this flag modifies other data-type flags, it cannot by used by itself. /// </summary> SHCNF_FLUSHNOWAIT = 0x2000 } #endregion // enum HChangeNotifyFlags }
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ using System; using System.Collections.Generic; using Antlr4.Runtime.Misc; using Antlr4.Runtime.Sharpen; using Antlr4.Runtime.Tree; using Antlr4.Runtime.Tree.Pattern; namespace Antlr4.Runtime.Tree.Pattern { /// <summary> /// Represents the result of matching a /// <see cref="Antlr4.Runtime.Tree.IParseTree"/> /// against a tree pattern. /// </summary> public class ParseTreeMatch { /// <summary> /// This is the backing field for /// <see cref="Tree()"/> /// . /// </summary> private readonly IParseTree tree; /// <summary> /// This is the backing field for /// <see cref="Pattern()"/> /// . /// </summary> private readonly ParseTreePattern pattern; /// <summary> /// This is the backing field for /// <see cref="Labels()"/> /// . /// </summary> private readonly MultiMap<string, IParseTree> labels; /// <summary> /// This is the backing field for /// <see cref="MismatchedNode()"/> /// . /// </summary> private readonly IParseTree mismatchedNode; /// <summary> /// Constructs a new instance of /// <see cref="ParseTreeMatch"/> /// from the specified /// parse tree and pattern. /// </summary> /// <param name="tree">The parse tree to match against the pattern.</param> /// <param name="pattern">The parse tree pattern.</param> /// <param name="labels"> /// A mapping from label names to collections of /// <see cref="Antlr4.Runtime.Tree.IParseTree"/> /// objects located by the tree pattern matching process. /// </param> /// <param name="mismatchedNode"> /// The first node which failed to match the tree /// pattern during the matching process. /// </param> /// <exception> /// IllegalArgumentException /// if /// <paramref name="tree"/> /// is /// <see langword="null"/> /// </exception> /// <exception> /// IllegalArgumentException /// if /// <paramref name="pattern"/> /// is /// <see langword="null"/> /// </exception> /// <exception> /// IllegalArgumentException /// if /// <paramref name="labels"/> /// is /// <see langword="null"/> /// </exception> public ParseTreeMatch(IParseTree tree, ParseTreePattern pattern, MultiMap<string, IParseTree> labels, IParseTree mismatchedNode) { if (tree == null) { throw new ArgumentException("tree cannot be null"); } if (pattern == null) { throw new ArgumentException("pattern cannot be null"); } if (labels == null) { throw new ArgumentException("labels cannot be null"); } this.tree = tree; this.pattern = pattern; this.labels = labels; this.mismatchedNode = mismatchedNode; } /// <summary> /// Get the last node associated with a specific /// <paramref name="label"/> /// . /// <p>For example, for pattern /// <c>&lt;id:ID&gt;</c> /// , /// <c>get("id")</c> /// returns the /// node matched for that /// <c>ID</c> /// . If more than one node /// matched the specified label, only the last is returned. If there is /// no node associated with the label, this returns /// <see langword="null"/> /// .</p> /// <p>Pattern tags like /// <c>&lt;ID&gt;</c> /// and /// <c>&lt;expr&gt;</c> /// without labels are /// considered to be labeled with /// <c>ID</c> /// and /// <c>expr</c> /// , respectively.</p> /// </summary> /// <param name="label">The label to check.</param> /// <returns> /// The last /// <see cref="Antlr4.Runtime.Tree.IParseTree"/> /// to match a tag with the specified /// label, or /// <see langword="null"/> /// if no parse tree matched a tag with the label. /// </returns> [return: Nullable] public virtual IParseTree Get(string label) { IList<IParseTree> parseTrees = labels.Get(label); if (parseTrees == null || parseTrees.Count == 0) { return null; } return parseTrees[parseTrees.Count - 1]; } // return last if multiple /// <summary>Return all nodes matching a rule or token tag with the specified label.</summary> /// <remarks> /// Return all nodes matching a rule or token tag with the specified label. /// <p>If the /// <paramref name="label"/> /// is the name of a parser rule or token in the /// grammar, the resulting list will contain both the parse trees matching /// rule or tags explicitly labeled with the label and the complete set of /// parse trees matching the labeled and unlabeled tags in the pattern for /// the parser rule or token. For example, if /// <paramref name="label"/> /// is /// <c>"foo"</c> /// , /// the result will contain <em>all</em> of the following.</p> /// <ul> /// <li>Parse tree nodes matching tags of the form /// <c>&lt;foo:anyRuleName&gt;</c> /// and /// <c>&lt;foo:AnyTokenName&gt;</c> /// .</li> /// <li>Parse tree nodes matching tags of the form /// <c>&lt;anyLabel:foo&gt;</c> /// .</li> /// <li>Parse tree nodes matching tags of the form /// <c>&lt;foo&gt;</c> /// .</li> /// </ul> /// </remarks> /// <param name="label">The label.</param> /// <returns> /// A collection of all /// <see cref="Antlr4.Runtime.Tree.IParseTree"/> /// nodes matching tags with /// the specified /// <paramref name="label"/> /// . If no nodes matched the label, an empty list /// is returned. /// </returns> [return: NotNull] public virtual IList<IParseTree> GetAll(string label) { IList<IParseTree> nodes = labels.Get(label); if (nodes == null) { return Sharpen.Collections.EmptyList<IParseTree>(); } return nodes; } /// <summary>Return a mapping from label &#x2192; [list of nodes].</summary> /// <remarks> /// Return a mapping from label &#x2192; [list of nodes]. /// <p>The map includes special entries corresponding to the names of rules and /// tokens referenced in tags in the original pattern. For additional /// information, see the description of /// <see cref="GetAll(string)"/> /// .</p> /// </remarks> /// <returns> /// A mapping from labels to parse tree nodes. If the parse tree /// pattern did not contain any rule or token tags, this map will be empty. /// </returns> [NotNull] public virtual MultiMap<string, IParseTree> Labels { get { return labels; } } /// <summary>Get the node at which we first detected a mismatch.</summary> /// <remarks>Get the node at which we first detected a mismatch.</remarks> /// <returns> /// the node at which we first detected a mismatch, or /// <see langword="null"/> /// if the match was successful. /// </returns> [Nullable] public virtual IParseTree MismatchedNode { get { return mismatchedNode; } } /// <summary>Gets a value indicating whether the match operation succeeded.</summary> /// <remarks>Gets a value indicating whether the match operation succeeded.</remarks> /// <returns> /// /// <see langword="true"/> /// if the match operation succeeded; otherwise, /// <see langword="false"/> /// . /// </returns> public virtual bool Succeeded { get { return mismatchedNode == null; } } /// <summary>Get the tree pattern we are matching against.</summary> /// <remarks>Get the tree pattern we are matching against.</remarks> /// <returns>The tree pattern we are matching against.</returns> [NotNull] public virtual ParseTreePattern Pattern { get { return pattern; } } /// <summary>Get the parse tree we are trying to match to a pattern.</summary> /// <remarks>Get the parse tree we are trying to match to a pattern.</remarks> /// <returns> /// The /// <see cref="Antlr4.Runtime.Tree.IParseTree"/> /// we are trying to match to a pattern. /// </returns> [NotNull] public virtual IParseTree Tree { get { return tree; } } /// <summary><inheritDoc/></summary> public override string ToString() { return string.Format("Match {0}; found {1} labels", Succeeded ? "succeeded" : "failed", Labels.Count); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //--------------------------------------------------------------------------- // // Description: // //--------------------------------------------------------------------------- using System; using System.IO; using System.Xml; // For XmlReader using System.Diagnostics; // For Debug.Assert using System.Text; // For Encoding namespace System.IO.Packaging { internal static class PackagingUtilities { //------------------------------------------------------ // // Internal Fields // //------------------------------------------------------ internal static readonly string RelationshipNamespaceUri = "http://schemas.openxmlformats.org/package/2006/relationships"; internal static readonly ContentType RelationshipPartContentType = new ContentType("application/vnd.openxmlformats-package.relationships+xml"); internal const string ContainerFileExtension = "xps"; internal const string XamlFileExtension = "xaml"; //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods /// <summary> /// This method is used to determine if we support a given Encoding as per the /// OPC and XPS specs. Currently the only two encodings supported are UTF-8 and /// UTF-16 (Little Endian and Big Endian) /// </summary> /// <param name="reader">XmlReader</param> /// <returns>throws an exception if the encoding is not UTF-8 or UTF-16</returns> internal static void PerformInitialReadAndVerifyEncoding(XmlReader reader) { Debug.Assert(reader != null && reader.ReadState == ReadState.Initial); //If the first node is XmlDeclaration we check to see if the encoding attribute is present if (reader.Read() && reader.NodeType == XmlNodeType.XmlDeclaration && reader.Depth == 0) { string encoding = reader.GetAttribute(EncodingAttribute); if (!string.IsNullOrEmpty(encoding)) { //If a non-empty encoding attribute is present [for example - <?xml version="1.0" encoding="utf-8" ?>] //we check to see if the value is either "utf-8" or "utf-16". Only these two values are supported //Note: For Byte order markings that require additional information to be specified in //the encoding attribute in XmlDeclaration have already been ruled out by this check as we allow for //only two valid values. if (string.Equals(encoding, WebNameUTF8, StringComparison.OrdinalIgnoreCase) || string.Equals(encoding, WebNameUnicode, StringComparison.OrdinalIgnoreCase)) { return; } else { //if the encoding attribute has any other value we throw an exception throw new FileFormatException(SR.EncodingNotSupported); } } } //Previously, the logic in System.IO.Packaging was that if the XmlDeclaration is not present, or encoding attribute //is not present, we base our decision on byte order marking. Previously, reader was an XmlTextReader, which would //take that into account and return the correct value. //However, we can't use XmlTextReader, as it is not in COREFX. Therefore, if there is no XmlDeclaration, or the encoding //attribute is not set, then we will throw now exception, and UTF-8 will be assumed. //TODO: in the future, we can do the work to detect the BOM, and throw an exception if the file is in an invalid encoding. // Eric White: IMO, this is not a serious problem. Office will never write with the wrong encoding, nor will any of the // other suites. The Open XML SDK will always write with the correct encoding. //The future logic would be: //- determine the encoding from the BOM //- if the encoding is not UTF-8 or UTF-16, then throw new FileFormatException(SR.EncodingNotSupported) } /// <summary> /// VerifyStreamReadArgs /// </summary> /// <param name="s">stream</param> /// <param name="buffer">buffer</param> /// <param name="offset">offset</param> /// <param name="count">count</param> /// <remarks>Common argument verification for Stream.Read()</remarks> static internal void VerifyStreamReadArgs(Stream s, byte[] buffer, int offset, int count) { if (!s.CanRead) throw new NotSupportedException(SR.ReadNotSupported); if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", SR.OffsetNegative); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ReadCountNegative); } checked // catch any integer overflows { if (offset + count > buffer.Length) { throw new ArgumentException(SR.ReadBufferTooSmall, "buffer"); } } } /// <summary> /// VerifyStreamWriteArgs /// </summary> /// <param name="s"></param> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="count"></param> /// <remarks>common argument verification for Stream.Write</remarks> static internal void VerifyStreamWriteArgs(Stream s, byte[] buffer, int offset, int count) { if (!s.CanWrite) throw new NotSupportedException(SR.WriteNotSupported); if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", SR.OffsetNegative); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.WriteCountNegative); } checked { if (offset + count > buffer.Length) throw new ArgumentException(SR.WriteBufferTooSmall, "buffer"); } } /// <summary> /// Read utility that is guaranteed to return the number of bytes requested /// if they are available. /// </summary> /// <param name="stream">stream to read from</param> /// <param name="buffer">buffer to read into</param> /// <param name="offset">offset in buffer to write to</param> /// <param name="count">bytes to read</param> /// <returns>bytes read</returns> /// <remarks>Normal Stream.Read does not guarantee how many bytes it will /// return. This one does.</remarks> internal static int ReliableRead(Stream stream, byte[] buffer, int offset, int count) { return ReliableRead(stream, buffer, offset, count, count); } /// <summary> /// Read utility that is guaranteed to return the number of bytes requested /// if they are available. /// </summary> /// <param name="stream">stream to read from</param> /// <param name="buffer">buffer to read into</param> /// <param name="offset">offset in buffer to write to</param> /// <param name="requestedCount">count of bytes that we would like to read (max read size to try)</param> /// <param name="requiredCount">minimal count of bytes that we would like to read (min read size to achieve)</param> /// <returns>bytes read</returns> /// <remarks>Normal Stream.Read does not guarantee how many bytes it will /// return. This one does.</remarks> internal static int ReliableRead(Stream stream, byte[] buffer, int offset, int requestedCount, int requiredCount) { Debug.Assert(stream != null); Debug.Assert(buffer != null); Debug.Assert(buffer.Length > 0); Debug.Assert(offset >= 0); Debug.Assert(requestedCount >= 0); Debug.Assert(requiredCount >= 0); Debug.Assert(checked(offset + requestedCount <= buffer.Length)); Debug.Assert(requiredCount <= requestedCount); // let's read the whole block into our buffer int totalBytesRead = 0; while (totalBytesRead < requiredCount) { int bytesRead = stream.Read(buffer, offset + totalBytesRead, requestedCount - totalBytesRead); if (bytesRead == 0) { break; } totalBytesRead += bytesRead; } return totalBytesRead; } /// <summary> /// Read utility that is guaranteed to return the number of bytes requested /// if they are available. /// </summary> /// <param name="reader">BinaryReader to read from</param> /// <param name="buffer">buffer to read into</param> /// <param name="offset">offset in buffer to write to</param> /// <param name="count">bytes to read</param> /// <returns>bytes read</returns> /// <remarks>Normal Stream.Read does not guarantee how many bytes it will /// return. This one does.</remarks> internal static int ReliableRead(BinaryReader reader, byte[] buffer, int offset, int count) { return ReliableRead(reader, buffer, offset, count, count); } /// <summary> /// Read utility that is guaranteed to return the number of bytes requested /// if they are available. /// </summary> /// <param name="reader">BinaryReader to read from</param> /// <param name="buffer">buffer to read into</param> /// <param name="offset">offset in buffer to write to</param> /// <param name="requestedCount">count of bytes that we would like to read (max read size to try)</param> /// <param name="requiredCount">minimal count of bytes that we would like to read (min read size to achieve)</param> /// <returns>bytes read</returns> /// <remarks>Normal Stream.Read does not guarantee how many bytes it will /// return. This one does.</remarks> internal static int ReliableRead(BinaryReader reader, byte[] buffer, int offset, int requestedCount, int requiredCount) { Debug.Assert(reader != null); Debug.Assert(buffer != null); Debug.Assert(buffer.Length > 0); Debug.Assert(offset >= 0); Debug.Assert(requestedCount >= 0); Debug.Assert(requiredCount >= 0); Debug.Assert(checked(offset + requestedCount <= buffer.Length)); Debug.Assert(requiredCount <= requestedCount); // let's read the whole block into our buffer int totalBytesRead = 0; while (totalBytesRead < requiredCount) { int bytesRead = reader.Read(buffer, offset + totalBytesRead, requestedCount - totalBytesRead); if (bytesRead == 0) { break; } totalBytesRead += bytesRead; } return totalBytesRead; } /// <summary> /// CopyStream utility that is guaranteed to return the number of bytes copied (may be less then requested, /// if source stream doesn't have enough data) /// </summary> /// <param name="sourceStream">stream to read from</param> /// <param name="targetStream">stream to write to </param> /// <param name="bytesToCopy">number of bytes to be copied(use Int64.MaxValue if the whole stream needs to be copied)</param> /// <param name="bufferSize">number of bytes to be copied (usually it is 4K for scenarios where we expect a lot of data /// like in SparseMemoryStream case it could be larger </param> /// <returns>bytes copied (might be less than requested if source stream is too short</returns> /// <remarks>Neither source nor target stream are seeked; it is up to the caller to make sure that their positions are properly set. /// Target stream isn't truncated even if it has more data past the area that was copied.</remarks> internal static long CopyStream(Stream sourceStream, Stream targetStream, long bytesToCopy, int bufferSize) { Debug.Assert(sourceStream != null); Debug.Assert(targetStream != null); Debug.Assert(bytesToCopy >= 0); Debug.Assert(bufferSize > 0); byte[] buffer = new byte[bufferSize]; // let's read the whole block into our buffer long bytesLeftToCopy = bytesToCopy; while (bytesLeftToCopy > 0) { int bytesRead = sourceStream.Read(buffer, 0, (int)Math.Min(bytesLeftToCopy, (long)bufferSize)); if (bytesRead == 0) { targetStream.Flush(); return bytesToCopy - bytesLeftToCopy; } targetStream.Write(buffer, 0, bytesRead); bytesLeftToCopy -= bytesRead; } // It must not be negative Debug.Assert(bytesLeftToCopy == 0); targetStream.Flush(); return bytesToCopy; } /// <summary> /// Calculate overlap between two blocks, returning the offset and length of the overlap /// </summary> /// <param name="block1Offset"></param> /// <param name="block1Size"></param> /// <param name="block2Offset"></param> /// <param name="block2Size"></param> /// <param name="overlapBlockOffset"></param> /// <param name="overlapBlockSize"></param> internal static void CalculateOverlap(long block1Offset, long block1Size, long block2Offset, long block2Size, out long overlapBlockOffset, out long overlapBlockSize) { checked { overlapBlockOffset = Math.Max(block1Offset, block2Offset); overlapBlockSize = Math.Min(block1Offset + block1Size, block2Offset + block2Size) - overlapBlockOffset; if (overlapBlockSize <= 0) { overlapBlockSize = 0; } } } /// <summary> /// This method returns the count of xml attributes other than: /// 1. xmlns="namespace" /// 2. xmlns:someprefix="namespace" /// Reader should be positioned at the Element whose attributes /// are to be counted. /// </summary> /// <param name="reader"></param> /// <returns>An integer indicating the number of non-xmlns attributes</returns> internal static int GetNonXmlnsAttributeCount(XmlReader reader) { Debug.Assert(reader != null, "xmlReader should not be null"); Debug.Assert(reader.NodeType == XmlNodeType.Element, "XmlReader should be positioned at an Element"); int readerCount = 0; //If true, reader moves to the attribute //If false, there are no more attributes (or none) //and in that case the position of the reader is unchanged. //First time through, since the reader will be positioned at an Element, //MoveToNextAttribute is the same as MoveToFirstAttribute. while (reader.MoveToNextAttribute()) { if (!string.Equals(reader.Name, XmlNamespace, StringComparison.Ordinal) && !string.Equals(reader.Prefix, XmlNamespace, StringComparison.Ordinal)) { readerCount++; } } //re-position the reader to the element reader.MoveToElement(); return readerCount; } #endregion Internal Methods //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ /// <summary> /// Synchronize access to IsolatedStorage methods that can step on each-other /// </summary> /// <remarks>See PS 1468964 for details.</remarks> private const string XmlNamespace = "xmlns"; private const string EncodingAttribute = "encoding"; private const string WebNameUTF8 = "utf-8"; private const string WebNameUnicode = "utf-16"; } }
// // Copyright 2012, Xamarin Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Threading.Tasks; using System.Linq; using System.Collections.Generic; using Xamarin.Utilities; using System.Net; using System.Text; namespace Xamarin.Auth { /// <summary> /// Implements OAuth 2.0 implicit granting. http://tools.ietf.org/html/draft-ietf-oauth-v2-31#section-4.2 /// </summary> #if XAMARIN_AUTH_INTERNAL internal class OAuth2Authenticator : WebRedirectAuthenticator #else public class OAuth2Authenticator : WebRedirectAuthenticator #endif { string clientId; string clientSecret; string scope; Uri authorizeUrl; Uri redirectUrl; Uri accessTokenUrl; GetUsernameAsyncFunc getUsernameAsync; string requestState; bool reportedForgery = false; /// <summary> /// Initializes a new <see cref="Xamarin.Auth.OAuth2Authenticator"/> /// that authenticates using implicit granting (token). /// </summary> /// <param name='clientId'> /// Client identifier. /// </param> /// <param name='scope'> /// Authorization scope. /// </param> /// <param name='authorizeUrl'> /// Authorize URL. /// </param> /// <param name='redirectUrl'> /// Redirect URL. /// </param> /// <param name='getUsernameAsync'> /// Method used to fetch the username of an account /// after it has been successfully authenticated. /// </param> public OAuth2Authenticator (string clientId, string scope, Uri authorizeUrl, Uri redirectUrl, GetUsernameAsyncFunc getUsernameAsync = null) : this (redirectUrl) { if (string.IsNullOrEmpty (clientId)) { throw new ArgumentException ("clientId must be provided", "clientId"); } this.clientId = clientId; this.scope = scope ?? ""; if (authorizeUrl == null) { throw new ArgumentNullException ("authorizeUrl"); } this.authorizeUrl = authorizeUrl; if (redirectUrl == null) { throw new ArgumentNullException ("redirectUrl"); } this.redirectUrl = redirectUrl; this.getUsernameAsync = getUsernameAsync; this.accessTokenUrl = null; } /// <summary> /// Initializes a new instance <see cref="Xamarin.Auth.OAuth2Authenticator"/> /// that authenticates using authorization codes (code). /// </summary> /// <param name='clientId'> /// Client identifier. /// </param> /// <param name='clientSecret'> /// Client secret. /// </param> /// <param name='scope'> /// Authorization scope. /// </param> /// <param name='authorizeUrl'> /// Authorize URL. /// </param> /// <param name='redirectUrl'> /// Redirect URL. /// </param> /// <param name='accessTokenUrl'> /// URL used to request access tokens after an authorization code was received. /// </param> /// <param name='getUsernameAsync'> /// Method used to fetch the username of an account /// after it has been successfully authenticated. /// </param> public OAuth2Authenticator (string clientId, string clientSecret, string scope, Uri authorizeUrl, Uri redirectUrl, Uri accessTokenUrl, GetUsernameAsyncFunc getUsernameAsync = null) : this (redirectUrl, clientSecret, accessTokenUrl) { if (string.IsNullOrEmpty (clientId)) { throw new ArgumentException ("clientId must be provided", "clientId"); } this.clientId = clientId; if (string.IsNullOrEmpty (clientSecret)) { throw new ArgumentException ("clientSecret must be provided", "clientSecret"); } this.clientSecret = clientSecret; this.scope = scope ?? ""; if (authorizeUrl == null) { throw new ArgumentNullException ("authorizeUrl"); } this.authorizeUrl = authorizeUrl; if (redirectUrl == null) { throw new ArgumentNullException ("redirectUrl"); } this.redirectUrl = redirectUrl; if (accessTokenUrl == null) { throw new ArgumentNullException ("accessTokenUrl"); } this.accessTokenUrl = accessTokenUrl; this.getUsernameAsync = getUsernameAsync; } OAuth2Authenticator (Uri redirectUrl, string clientSecret = null, Uri accessTokenUrl = null) : base (redirectUrl, redirectUrl) { if (redirectUrl == null) { throw new ArgumentNullException ("redirectUrl"); } this.redirectUrl = redirectUrl; this.clientSecret = clientSecret; this.accessTokenUrl = accessTokenUrl; // // Generate a unique state string to check for forgeries // var chars = new char[16]; var rand = new Random (); for (var i = 0; i < chars.Length; i++) { chars [i] = (char)rand.Next ((int)'a', (int)'z' + 1); } this.requestState = new string (chars); } bool IsImplicit { get { return accessTokenUrl == null; } } /// <summary> /// Method that returns the initial URL to be displayed in the web browser. /// </summary> /// <returns> /// A task that will return the initial URL. /// </returns> public override Task<Uri> GetInitialUrlAsync () { var url = new Uri (string.Format ( "{0}?client_id={1}&redirect_uri={2}&response_type={3}&scope={4}&state={5}", authorizeUrl.AbsoluteUri, Uri.EscapeDataString (clientId), Uri.EscapeDataString (redirectUrl.AbsoluteUri), IsImplicit ? "token" : "code", Uri.EscapeDataString (scope), Uri.EscapeDataString (requestState))); var tcs = new TaskCompletionSource<Uri> (); tcs.SetResult (url); return tcs.Task; } /// <summary> /// Raised when a new page has been loaded. /// </summary> /// <param name='url'> /// URL of the page. /// </param> /// <param name='query'> /// The parsed query of the URL. /// </param> /// <param name='fragment'> /// The parsed fragment of the URL. /// </param> protected override void OnPageEncountered (Uri url, IDictionary<string, string> query, IDictionary<string, string> fragment) { var all = new Dictionary<string, string> (query); foreach (var kv in fragment) all [kv.Key] = kv.Value; // // Check for forgeries // if (all.ContainsKey ("state")) { if (all ["state"] != requestState && !reportedForgery) { reportedForgery = true; OnError ("Invalid state from server. Possible forgery!"); return; } } // // Continue processing // base.OnPageEncountered (url, query, fragment); } /// <summary> /// Raised when a new page has been loaded. /// </summary> /// <param name='url'> /// URL of the page. /// </param> /// <param name='query'> /// The parsed query string of the URL. /// </param> /// <param name='fragment'> /// The parsed fragment of the URL. /// </param> protected override void OnRedirectPageLoaded (Uri url, IDictionary<string, string> query, IDictionary<string, string> fragment) { // // Look for the access_token // if (fragment.ContainsKey ("access_token")) { // // We found an access_token // OnRetrievedAccountProperties (fragment); } else if (!IsImplicit) { // // Look for the code // if (query.ContainsKey ("code")) { var code = query ["code"]; RequestAccessTokenAsync (code).ContinueWith (task => { if (task.IsFaulted) { OnError (task.Exception); } else { OnRetrievedAccountProperties (task.Result); } }, TaskScheduler.FromCurrentSynchronizationContext ()); } else { OnError ("Expected code in response, but did not receive one."); return; } } else { OnError ("Expected access_token in response, but did not receive one."); return; } } /// <summary> /// Asynchronously requests an access token with an authorization <paramref name="code"/>. /// </summary> /// <returns> /// A dictionary of data returned from the authorization request. /// </returns> /// <param name='code'>The authorization code.</param> /// <remarks>Implements: http://tools.ietf.org/html/rfc6749#section-4.1</remarks> Task<IDictionary<string,string>> RequestAccessTokenAsync (string code) { var queryValues = new Dictionary<string, string> { { "grant_type", "authorization_code" }, { "code", code }, { "redirect_uri", redirectUrl.AbsoluteUri }, { "client_id", clientId }, }; if (!string.IsNullOrEmpty (clientSecret)) { queryValues ["client_secret"] = clientSecret; } return RequestAccessTokenAsync (queryValues); } /// <summary> /// Asynchronously makes a request to the access token URL with the given parameters. /// </summary> /// <param name="queryValues">The parameters to make the request with.</param> /// <returns>The data provided in the response to the access token request.</returns> protected Task<IDictionary<string,string>> RequestAccessTokenAsync (IDictionary<string, string> queryValues) { var query = queryValues.FormEncode (); var req = WebRequest.Create (accessTokenUrl); req.Method = "POST"; var body = Encoding.UTF8.GetBytes (query); req.ContentLength = body.Length; req.ContentType = "application/x-www-form-urlencoded"; using (var s = req.GetRequestStream ()) { s.Write (body, 0, body.Length); } return req.GetResponseAsync ().ContinueWith (task => { var text = task.Result.GetResponseText (); // Parse the response var data = text.Contains ("{") ? WebEx.JsonDecode (text) : WebEx.FormDecode (text); if (data.ContainsKey ("error")) { throw new AuthException ("Error authenticating: " + data ["error"]); } else if (data.ContainsKey ("access_token")) { return data; } else { throw new AuthException ("Expected access_token in access token response, but did not receive one."); } }); } /// <summary> /// Event handler that is fired when an access token has been retreived. /// </summary> /// <param name='accountProperties'> /// The retrieved account properties /// </param> protected virtual void OnRetrievedAccountProperties (IDictionary<string, string> accountProperties) { // // Now we just need a username for the account // if (getUsernameAsync != null) { getUsernameAsync (accountProperties).ContinueWith (task => { if (task.IsFaulted) { OnError (task.Exception); } else { OnSucceeded (task.Result, accountProperties); } }, TaskScheduler.FromCurrentSynchronizationContext ()); } else { OnSucceeded ("", accountProperties); } } } }
// // SimpleEffectDialog.cs // // Author: // Jonathan Pobst <monkey@jpobst.com> // // Copyright (c) 2010 Jonathan Pobst // // 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. // // Inspiration and reflection code is from Miguel de Icaza's MIT Licensed MonoTouch.Dialog: // http://github.com/migueldeicaza/MonoTouch.Dialog using System; using System.Reflection; using System.Text; using System.Collections.Generic; using System.ComponentModel; using System.Collections; using Mono.Addins.Localization; using Mono.Unix; namespace Pinta.Gui.Widgets { public class SimpleEffectDialog : Gtk.Dialog { [ThreadStatic] Random random = new Random (); const uint event_delay_millis = 100; uint event_delay_timeout_id; /// Since this dialog is used by add-ins, the IAddinLocalizer allows for translations to be /// fetched from the appropriate place. /// </param> public SimpleEffectDialog (string title, Gdk.Pixbuf icon, object effectData, IAddinLocalizer localizer) : base (title, Pinta.Core.PintaCore.Chrome.MainWindow, Gtk.DialogFlags.Modal, Gtk.Stock.Cancel, Gtk.ResponseType.Cancel, Gtk.Stock.Ok, Gtk.ResponseType.Ok) { Icon = icon; EffectData = effectData; BorderWidth = 6; VBox.Spacing = 12; WidthRequest = 400; Resizable = false; DefaultResponse = Gtk.ResponseType.Ok; AlternativeButtonOrder = new int[] { (int)Gtk.ResponseType.Ok, (int)Gtk.ResponseType.Cancel }; BuildDialog (localizer); } public object EffectData { get; private set; } public event PropertyChangedEventHandler EffectDataChanged; #region EffectData Parser private void BuildDialog (IAddinLocalizer localizer) { var members = EffectData.GetType ().GetMembers (); foreach (var mi in members) { Type mType = GetTypeForMember (mi); if (mType == null) continue; string caption = null; string hint = null; bool skip = false; bool combo = false; object[] attrs = mi.GetCustomAttributes (false); foreach (var attr in attrs) { if (attr is SkipAttribute) skip = true; else if (attr is CaptionAttribute) caption = ((CaptionAttribute)attr).Caption; else if (attr is HintAttribute) hint = ((HintAttribute)attr).Hint; else if (attr is StaticListAttribute) combo = true; } if (skip || string.Compare (mi.Name, "IsDefault", true) == 0) continue; if (caption == null) caption = MakeCaption (mi.Name); if (mType == typeof (int) && (caption == "Seed")) AddWidget (CreateSeed (localizer.GetString (caption), EffectData, mi, attrs)); else if (mType == typeof (int)) AddWidget (CreateSlider (localizer.GetString (caption), EffectData, mi, attrs)); else if (mType == typeof (double) && (caption == "Angle" || caption == "Rotation")) AddWidget (CreateAnglePicker (localizer.GetString (caption), EffectData, mi, attrs)); else if (mType == typeof (double)) AddWidget (CreateDoubleSlider (localizer.GetString (caption), EffectData, mi, attrs)); else if (combo && mType == typeof (string)) AddWidget (CreateComboBox (localizer.GetString (caption), EffectData, mi, attrs)); else if (mType == typeof (bool)) AddWidget (CreateCheckBox (localizer.GetString (caption), EffectData, mi, attrs)); else if (mType == typeof (Gdk.Point)) AddWidget (CreatePointPicker (localizer.GetString (caption), EffectData, mi, attrs)); else if (mType == typeof (Cairo.PointD)) AddWidget (CreateOffsetPicker (localizer.GetString (caption), EffectData, mi, attrs)); else if (mType.IsEnum) AddWidget (CreateEnumComboBox (localizer.GetString (caption), EffectData, mi, attrs)); if (hint != null) AddWidget (CreateHintLabel (localizer.GetString (hint))); } } private void AddWidget (Gtk.Widget widget) { widget.Show (); this.VBox.Add (widget); } #endregion #region Control Builders private ComboBoxWidget CreateEnumComboBox (string caption, object o, System.Reflection.MemberInfo member, System.Object[] attributes) { Type myType = GetTypeForMember (member); string[] entries = Enum.GetNames (myType); ComboBoxWidget widget = new ComboBoxWidget (entries); widget.Label = caption; widget.AddEvents ((int)Gdk.EventMask.ButtonPressMask); widget.Active = ((IList)entries).IndexOf (GetValue (member, o).ToString ()); widget.Changed += delegate (object sender, EventArgs e) { SetValue (member, o, Enum.Parse (myType, widget.ActiveText)); }; return widget; } private ComboBoxWidget CreateComboBox (string caption, object o, System.Reflection.MemberInfo member, System.Object[] attributes) { Dictionary<string, object> dict = null; foreach (var attr in attributes) { if (attr is StaticListAttribute) dict = (Dictionary<string, object>)GetValue (((StaticListAttribute)attr).dictionaryName, o); } List<string> entries = new List<string> (); foreach (string str in dict.Keys) entries.Add (str); ComboBoxWidget widget = new ComboBoxWidget (entries.ToArray ()); widget.Label = caption; widget.AddEvents ((int)Gdk.EventMask.ButtonPressMask); widget.Active = entries.IndexOf ((string)GetValue (member, o)); widget.Changed += delegate (object sender, EventArgs e) { SetValue (member, o, widget.ActiveText); }; return widget; } private HScaleSpinButtonWidget CreateDoubleSlider (string caption, object o, MemberInfo member, object[] attributes) { HScaleSpinButtonWidget widget = new HScaleSpinButtonWidget (); int min_value = -100; int max_value = 100; double inc_value = 0.01; int digits_value = 2; foreach (var attr in attributes) { if (attr is MinimumValueAttribute) min_value = ((MinimumValueAttribute)attr).Value; else if (attr is MaximumValueAttribute) max_value = ((MaximumValueAttribute)attr).Value; else if (attr is IncrementValueAttribute) inc_value = ((IncrementValueAttribute)attr).Value; else if (attr is DigitsValueAttribute) digits_value = ((DigitsValueAttribute)attr).Value; } widget.Label = caption; widget.MinimumValue = min_value; widget.MaximumValue = max_value; widget.IncrementValue = inc_value; widget.DigitsValue = digits_value; widget.DefaultValue = (double)GetValue (member, o); widget.ValueChanged += delegate (object sender, EventArgs e) { if (event_delay_timeout_id != 0) GLib.Source.Remove (event_delay_timeout_id); event_delay_timeout_id = GLib.Timeout.Add (event_delay_millis, () => { event_delay_timeout_id = 0; SetValue (member, o, widget.Value); return false; }); }; return widget; } private HScaleSpinButtonWidget CreateSlider (string caption, object o, MemberInfo member, object[] attributes) { HScaleSpinButtonWidget widget = new HScaleSpinButtonWidget (); int min_value = -100; int max_value = 100; double inc_value = 1.0; int digits_value = 0; foreach (var attr in attributes) { if (attr is MinimumValueAttribute) min_value = ((MinimumValueAttribute)attr).Value; else if (attr is MaximumValueAttribute) max_value = ((MaximumValueAttribute)attr).Value; else if (attr is IncrementValueAttribute) inc_value = ((IncrementValueAttribute)attr).Value; else if (attr is DigitsValueAttribute) digits_value = ((DigitsValueAttribute)attr).Value; } widget.Label = caption; widget.MinimumValue = min_value; widget.MaximumValue = max_value; widget.IncrementValue = inc_value; widget.DigitsValue = digits_value; widget.DefaultValue = (int)GetValue (member, o); widget.ValueChanged += delegate (object sender, EventArgs e) { if (event_delay_timeout_id != 0) GLib.Source.Remove (event_delay_timeout_id); event_delay_timeout_id = GLib.Timeout.Add (event_delay_millis, () => { event_delay_timeout_id = 0; SetValue (member, o, widget.ValueAsInt); return false; }); }; return widget; } private Gtk.CheckButton CreateCheckBox (string caption, object o, MemberInfo member, object[] attributes) { Gtk.CheckButton widget = new Gtk.CheckButton (); widget.Label = caption; widget.Active = (bool)GetValue (member, o); widget.Toggled += delegate (object sender, EventArgs e) { SetValue (member, o, widget.Active); }; return widget; } private PointPickerWidget CreateOffsetPicker (string caption, object o, MemberInfo member, object[] attributes) { PointPickerWidget widget = new PointPickerWidget (); widget.Label = caption; widget.DefaultOffset = (Cairo.PointD)GetValue (member, o); widget.PointPicked += delegate (object sender, EventArgs e) { SetValue (member, o, widget.Offset); }; return widget; } private PointPickerWidget CreatePointPicker (string caption, object o, MemberInfo member, object[] attributes) { PointPickerWidget widget = new PointPickerWidget (); widget.Label = caption; widget.DefaultPoint = (Gdk.Point)GetValue (member, o); widget.PointPicked += delegate (object sender, EventArgs e) { SetValue (member, o, widget.Point); }; return widget; } private AnglePickerWidget CreateAnglePicker (string caption, object o, MemberInfo member, object[] attributes) { AnglePickerWidget widget = new AnglePickerWidget (); widget.Label = caption; widget.DefaultValue = (double)GetValue (member, o); widget.ValueChanged += delegate (object sender, EventArgs e) { if (event_delay_timeout_id != 0) GLib.Source.Remove (event_delay_timeout_id); event_delay_timeout_id = GLib.Timeout.Add (event_delay_millis, () => { event_delay_timeout_id = 0; SetValue (member, o, widget.Value); return false; }); }; return widget; } private Gtk.Label CreateHintLabel (string hint) { Gtk.Label label = new Gtk.Label (hint); label.LineWrap = true; return label; } private ReseedButtonWidget CreateSeed (string caption, object o, MemberInfo member, object[] attributes) { ReseedButtonWidget widget = new ReseedButtonWidget (); widget.Clicked += delegate (object sender, EventArgs e) { SetValue (member, o, random.Next ()); }; return widget; } #endregion #region Static Reflection Methods private static object GetValue (MemberInfo mi, object o) { var fi = mi as FieldInfo; if (fi != null) return fi.GetValue (o); var pi = mi as PropertyInfo; var getMethod = pi.GetGetMethod (); return getMethod.Invoke (o, new object[0]); } private void SetValue (MemberInfo mi, object o, object val) { var fi = mi as FieldInfo; var pi = mi as PropertyInfo; string fieldName = null; if (fi != null) { fi.SetValue (o, val); fieldName = fi.Name; } else if (pi != null) { var setMethod = pi.GetSetMethod (); setMethod.Invoke (o, new object[] { val }); fieldName = pi.Name; } if (EffectDataChanged != null) EffectDataChanged (this, new PropertyChangedEventArgs (fieldName)); } // Returns the type for fields and properties and null for everything else private static Type GetTypeForMember (MemberInfo mi) { if (mi is FieldInfo) return ((FieldInfo)mi).FieldType; else if (mi is PropertyInfo) return ((PropertyInfo)mi).PropertyType; return null; } private static string MakeCaption (string name) { var sb = new StringBuilder (name.Length); bool nextUp = true; foreach (char c in name) { if (nextUp) { sb.Append (Char.ToUpper (c)); nextUp = false; } else { if (c == '_') { sb.Append (' '); nextUp = true; continue; } if (Char.IsUpper (c)) sb.Append (' '); sb.Append (c); } } return sb.ToString (); } private object GetValue (string name, object o) { var fi = o.GetType ().GetField (name); if (fi != null) return fi.GetValue (o); var pi = o.GetType ().GetProperty (name); if (pi == null) return null; var getMethod = pi.GetGetMethod (); return getMethod.Invoke (o, new object[0]); } #endregion } /// <summary> /// Wrapper around Pinta's translation template. /// </summary> public class PintaLocalizer : IAddinLocalizer { public string GetString (string msgid) { return Mono.Unix.Catalog.GetString (msgid); } }; }
using System; using NUnit.Framework; using System.Drawing; using System.Text.RegularExpressions; using OpenQA.Selenium.Environment; namespace OpenQA.Selenium.Interactions { [TestFixture] public class DragAndDropTest : DriverTestFixture { [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit)] [IgnoreBrowser(Browser.Android, "Mobile browser does not support drag-and-drop")] [IgnoreBrowser(Browser.IPhone, "Mobile browser does not support drag-and-drop")] [IgnoreBrowser(Browser.Safari, "Advanced User Interactions not implmented on Safari")] public void DragAndDropRelative() { driver.Url = dragAndDropPage; IWebElement img = driver.FindElement(By.Id("test1")); Point expectedLocation = drag(img, img.Location, 150, 200); Assert.AreEqual(expectedLocation, img.Location); expectedLocation = drag(img, img.Location, -50, -25); Assert.AreEqual(expectedLocation, img.Location); expectedLocation = drag(img, img.Location, 0, 0); Assert.AreEqual(expectedLocation, img.Location); expectedLocation = drag(img, img.Location, 1, -1); Assert.AreEqual(expectedLocation, img.Location); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit)] [IgnoreBrowser(Browser.Android, "Mobile browser does not support drag-and-drop")] [IgnoreBrowser(Browser.IPhone, "Mobile browser does not support drag-and-drop")] [IgnoreBrowser(Browser.Safari, "Advanced User Interactions not implmented on Safari")] public void DragAndDropToElement() { driver.Url = dragAndDropPage; IWebElement img1 = driver.FindElement(By.Id("test1")); IWebElement img2 = driver.FindElement(By.Id("test2")); Actions actionProvider = new Actions(driver); actionProvider.DragAndDrop(img2, img1).Perform(); Assert.AreEqual(img1.Location, img2.Location); } [Test] [Category("Javascript")] public void DragAndDropToElementInIframe() { driver.Url = iframePage; IWebElement iframe = driver.FindElement(By.TagName("iframe")); ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].src = arguments[1]", iframe, dragAndDropPage); driver.SwitchTo().Frame(0); IWebElement img1 = WaitFor<IWebElement>(() => { try { IWebElement element1 = driver.FindElement(By.Id("test1")); return element1; } catch (NoSuchElementException) { return null; } }, "Element with ID 'test1' not found"); IWebElement img2 = driver.FindElement(By.Id("test2")); new Actions(driver).DragAndDrop(img2, img1).Perform(); Assert.AreEqual(img1.Location, img2.Location); } [Test] [Category("Javascript")] public void DragAndDropElementWithOffsetInIframeAtBottom() { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("iframeAtBottom.html"); IWebElement iframe = driver.FindElement(By.TagName("iframe")); driver.SwitchTo().Frame(iframe); IWebElement img1 = driver.FindElement(By.Id("test1")); Point initial = img1.Location; new Actions(driver).DragAndDropToOffset(img1, 20, 20).Perform(); initial.Offset(20, 20); Assert.AreEqual(initial, img1.Location); } [Test] [Category("Javascript")] public void DragAndDropElementWithOffsetInScrolledDiv() { if (TestUtilities.IsFirefox(driver) && TestUtilities.IsNativeEventsEnabled(driver)) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("dragAndDropInsideScrolledDiv.html"); IWebElement el = driver.FindElement(By.Id("test1")); Point initial = el.Location; new Actions(driver).DragAndDropToOffset(el, 3700, 3700).Perform(); initial.Offset(3700, 3700); Assert.AreEqual(initial, el.Location); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit)] [IgnoreBrowser(Browser.Android, "Mobile browser does not support drag-and-drop")] [IgnoreBrowser(Browser.IPhone, "Mobile browser does not support drag-and-drop")] [IgnoreBrowser(Browser.Safari, "Advanced User Interactions not implmented on Safari")] public void ElementInDiv() { driver.Url = dragAndDropPage; IWebElement img = driver.FindElement(By.Id("test3")); Point startLocation = img.Location; Point expectedLocation = drag(img, startLocation, 100, 100); Point endLocation = img.Location; Assert.AreEqual(expectedLocation, endLocation); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.IE, "Dragging too far in IE causes the element not to move, instead of moving to 0,0.")] [IgnoreBrowser(Browser.Chrome, "Dragging too far in Chrome causes the element not to move, instead of moving to 0,0.")] [IgnoreBrowser(Browser.PhantomJS, "Dragging too far in PhantomJS causes the element not to move, as PhantomJS doesn't support dragging outside the viewport.")] [IgnoreBrowser(Browser.HtmlUnit)] [IgnoreBrowser(Browser.Android, "Mobile browser does not support drag-and-drop")] [IgnoreBrowser(Browser.IPhone, "Mobile browser does not support drag-and-drop")] [IgnoreBrowser(Browser.Safari, "Advanced User Interactions not implmented on Safari")] public void DragTooFar() { driver.Url = dragAndDropPage; IWebElement img = driver.FindElement(By.Id("test1")); // Dragging too far left and up does not move the element. It will be at // its original location after the drag. Point originalLocation = new Point(0, 0); Actions actionProvider = new Actions(driver); actionProvider.DragAndDropToOffset(img, int.MinValue, int.MinValue).Perform(); Point newLocation = img.Location; Assert.LessOrEqual(newLocation.X, 0); Assert.LessOrEqual(newLocation.Y, 0); // TODO(jimevans): re-enable this test once moveto does not exceed the // coordinates accepted by the browsers (Firefox in particular). At the // moment, even though the maximal coordinates are limited, mouseUp // fails because it cannot get the element at the given coordinates. //actionProvider.DragAndDropToOffset(img, int.MaxValue, int.MaxValue).Perform(); //We don't know where the img is dragged to , but we know it's not too //far, otherwise this function will not return for a long long time } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit)] [IgnoreBrowser(Browser.Android, "Mobile browser does not support drag-and-drop")] [IgnoreBrowser(Browser.IPhone, "Mobile browser does not support drag-and-drop")] [IgnoreBrowser(Browser.Firefox, "Problem with drag off viewport. See issue #1771")] [IgnoreBrowser(Browser.Safari, "Advanced User Interactions not implmented on Safari")] public void ShouldAllowUsersToDragAndDropToElementsOffTheCurrentViewPort() { driver.Url = dragAndDropPage; IJavaScriptExecutor js = (IJavaScriptExecutor)driver; int height = Convert.ToInt32(js.ExecuteScript("return window.outerHeight;")); int width = Convert.ToInt32(js.ExecuteScript("return window.outerWidth;")); bool mustUseOffsetHeight = width == 0 && height == 0; if (mustUseOffsetHeight) { width = Convert.ToInt32(js.ExecuteScript("return document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth;")); height = Convert.ToInt32(js.ExecuteScript("return document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;")); } js.ExecuteScript("window.resizeTo(300, 300);"); if (mustUseOffsetHeight) { width = width + 300 - Convert.ToInt32(js.ExecuteScript("return document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth;")); height = height + 300 - Convert.ToInt32(js.ExecuteScript("return document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;")); } try { driver.Url = dragAndDropPage; IWebElement img = driver.FindElement(By.Id("test3")); Point expectedLocation = drag(img, img.Location, 100, 100); Assert.AreEqual(expectedLocation, img.Location); } finally { js.ExecuteScript("window.resizeTo(arguments[0], arguments[1]);", width, height); } } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit)] [IgnoreBrowser(Browser.Android, "Mobile browser does not support drag-and-drop")] [IgnoreBrowser(Browser.IPhone, "Mobile browser does not support drag-and-drop")] [IgnoreBrowser(Browser.Safari, "Advanced User Interactions not implmented on Safari")] public void DragAndDropOnJQueryItems() { driver.Url = droppableItems; IWebElement toDrag = driver.FindElement(By.Id("draggable")); IWebElement dropInto = driver.FindElement(By.Id("droppable")); // Wait until all event handlers are installed. System.Threading.Thread.Sleep(500); Actions actionProvider = new Actions(driver); actionProvider.DragAndDrop(toDrag, dropInto).Perform(); string text = dropInto.FindElement(By.TagName("p")).Text; DateTime endTime = DateTime.Now.Add(TimeSpan.FromSeconds(15)); while (text != "Dropped!" && (DateTime.Now < endTime)) { System.Threading.Thread.Sleep(200); text = dropInto.FindElement(By.TagName("p")).Text; } Assert.AreEqual("Dropped!", text); IWebElement reporter = driver.FindElement(By.Id("drop_reports")); // Assert that only one mouse click took place and the mouse was moved // during it. string reporterText = reporter.Text; Assert.IsTrue(Regex.IsMatch(reporterText, "start( move)* down( move)+ up")); Assert.AreEqual(1, Regex.Matches(reporterText, "down").Count, "Reporter text:" + reporterText); Assert.AreEqual(1, Regex.Matches(reporterText, "up").Count, "Reporter text:" + reporterText); Assert.IsTrue(reporterText.Contains("move"), "Reporter text:" + reporterText); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit)] [IgnoreBrowser(Browser.Opera, "Untested")] [IgnoreBrowser(Browser.PhantomJS, "Untested")] [IgnoreBrowser(Browser.Safari, "Advanced User Interactions not implmented on Safari")] public void CanDragAnElementNotVisibleInTheCurrentViewportDueToAParentOverflow() { driver.Url = dragDropOverflowPage; IWebElement toDrag = driver.FindElement(By.Id("time-marker")); IWebElement dragTo = driver.FindElement(By.Id("11am")); Point srcLocation = toDrag.Location; Point targetLocation = dragTo.Location; int yOffset = targetLocation.Y - srcLocation.Y; Assert.AreNotEqual(0, yOffset); new Actions(driver).DragAndDropToOffset(toDrag, 0, yOffset).Perform(); Assert.AreEqual(dragTo.Location, toDrag.Location); } //[Test] public void MemoryTest() { driver.Url = dragAndDropPage; IWebElement img1 = driver.FindElement(By.Id("test1")); IWebElement img2 = driver.FindElement(By.Id("test2")); System.Threading.Thread.Sleep(1000); for (int i = 0; i < 500; i++) { string foo = img1.GetAttribute("id"); //img1 = driver.FindElement(By.Id("test1")); //Actions a = new Actions(driver); //a.MoveToElement(img1).Perform(); } driver.Url = simpleTestPage; } private Point drag(IWebElement elem, Point initialLocation, int moveRightBy, int moveDownBy) { Point expectedLocation = new Point(initialLocation.X, initialLocation.Y); expectedLocation.Offset(moveRightBy, moveDownBy); Actions actionProvider = new Actions(driver); actionProvider.DragAndDropToOffset(elem, moveRightBy, moveDownBy).Perform(); return expectedLocation; } } }
// 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 Debug = System.Diagnostics.Debug; namespace Internal.TypeSystem { /// <summary> /// Specifies the target CPU architecture. /// </summary> public enum TargetArchitecture { Unknown, ARM, ARMEL, ARM64, X64, X86, } /// <summary> /// Specifies the target ABI. /// </summary> public enum TargetOS { Unknown, Windows, Linux, OSX, FreeBSD, NetBSD, } public enum TargetAbi { Unknown, /// <summary> /// Cross-platform console model /// </summary> CoreRT, /// <summary> /// Windows-specific UWP model /// </summary> ProjectN, /// <summary> /// Jit runtime ABI /// </summary> Jit } /// <summary> /// Represents various details about the compilation target that affect /// layout, padding, allocations, or ABI. /// </summary> public class TargetDetails { /// <summary> /// Gets the target CPU architecture. /// </summary> public TargetArchitecture Architecture { get; } /// <summary> /// Gets the target ABI. /// </summary> public TargetOS OperatingSystem { get; } public TargetAbi Abi { get; } /// <summary> /// Gets the size of a pointer for the target of the compilation. /// </summary> public int PointerSize { get { switch (Architecture) { case TargetArchitecture.ARM64: case TargetArchitecture.X64: return 8; case TargetArchitecture.ARM: case TargetArchitecture.ARMEL: case TargetArchitecture.X86: return 4; default: throw new NotImplementedException(); } } } /// <summary> /// Gets the default field packing size. /// </summary> public int DefaultPackingSize { get { // We use default packing size of 8 irrespective of the platform. return 8; } } /// <summary> /// Gets the minimum required method alignment. /// </summary> public int MinimumFunctionAlignment { get { // We use a minimum alignment of 4 irrespective of the platform. return 4; } } public TargetDetails(TargetArchitecture architecture, TargetOS targetOS, TargetAbi abi) { Architecture = architecture; OperatingSystem = targetOS; Abi = abi; } /// <summary> /// Retrieves the size of a well known type. /// </summary> public int GetWellKnownTypeSize(DefType type) { switch (type.Category) { case TypeFlags.Void: return PointerSize; case TypeFlags.Boolean: return 1; case TypeFlags.Char: return 2; case TypeFlags.Byte: case TypeFlags.SByte: return 1; case TypeFlags.UInt16: case TypeFlags.Int16: return 2; case TypeFlags.UInt32: case TypeFlags.Int32: return 4; case TypeFlags.UInt64: case TypeFlags.Int64: return 8; case TypeFlags.Single: return 4; case TypeFlags.Double: return 8; case TypeFlags.UIntPtr: case TypeFlags.IntPtr: return PointerSize; } // Add new well known types if necessary throw new InvalidOperationException(); } /// <summary> /// Retrieves the alignment required by a well known type. /// </summary> public int GetWellKnownTypeAlignment(DefType type) { // Size == Alignment for all platforms. return GetWellKnownTypeSize(type); } /// <summary> /// Given an alignment of the fields of a type, determine the alignment that is necessary for allocating the object on the GC heap /// </summary> /// <returns></returns> public int GetObjectAlignment(int fieldAlignment) { switch (Architecture) { case TargetArchitecture.ARM: case TargetArchitecture.ARMEL: // ARM supports two alignments for objects on the GC heap (4 byte and 8 byte) if (fieldAlignment <= 4) return 4; else return 8; case TargetArchitecture.X64: return 8; case TargetArchitecture.X86: return 4; default: throw new NotImplementedException(); } } /// <summary> /// Returns True if compiling for Windows /// </summary> public bool IsWindows { get { return OperatingSystem == TargetOS.Windows; } } /// <summary> /// Maximum number of elements in a HFA type. /// </summary> public int MaximumHfaElementCount { get { // There is a hard limit of 4 elements on an HFA type, see // http://blogs.msdn.com/b/vcblog/archive/2013/07/12/introducing-vector-calling-convention.aspx Debug.Assert(Architecture == TargetArchitecture.ARM || Architecture == TargetArchitecture.ARMEL || Architecture == TargetArchitecture.ARM64 || Architecture == TargetArchitecture.X64 || Architecture == TargetArchitecture.X86); return 4; } } } }
using System.IO; using Core.Library; namespace Syntax_Analyzer { /** * <remarks>A token stream parser.</remarks> */ public class SyntaxParser : RecursiveDescentParser { /** * <summary>An enumeration with the generated production node * identity constants.</summary> */ private enum SynteticPatterns { } /** * <summary>Creates a new parser with a default analyzer.</summary> * * <param name='input'>the input stream to read from</param> * * <exception cref='ParserCreationException'>if the parser * couldn't be initialized correctly</exception> */ public SyntaxParser(TextReader input) : base(input) { CreatePatterns(); } /** * <summary>Creates a new parser.</summary> * * <param name='input'>the input stream to read from</param> * * <param name='analyzer'>the analyzer to parse with</param> * * <exception cref='ParserCreationException'>if the parser * couldn't be initialized correctly</exception> */ public SyntaxParser(TextReader input, SyntaxAnalyzer analyzer) : base(input, analyzer) { CreatePatterns(); } /** * <summary>Creates a new tokenizer for this parser. Can be overridden * by a subclass to provide a custom implementation.</summary> * * <param name='input'>the input stream to read from</param> * * <returns>the tokenizer created</returns> * * <exception cref='ParserCreationException'>if the tokenizer * couldn't be initialized correctly</exception> */ protected override Tokenizer NewTokenizer(TextReader input) { return new SyntaxTokenizer(input); } /** * <summary>Initializes the parser by creating all the production * patterns.</summary> * * <exception cref='ParserCreationException'>if the parser * couldn't be initialized correctly</exception> */ private void CreatePatterns() { ProductionPattern pattern; ProductionPatternAlternative alt; pattern = new ProductionPattern((int) SyntaxConstants.PROD_START_PROGRAM, "Prod_StartProgram"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_PROGRAM, 1, 1); alt.AddToken((int) SyntaxConstants.DIE, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_PROGRAM, "Prod_program"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_GLOBAL, 0, 1); alt.AddProduction((int) SyntaxConstants.PROD_LEAD, 1, 1); alt.AddToken((int) SyntaxConstants.END, 1, 1); alt.AddToken((int) SyntaxConstants.PER, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_TASKDEF, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_LEAD, "Prod_lead"); alt = new ProductionPatternAlternative(); alt.AddToken((int)SyntaxConstants.LEAD, 1, 1); alt.AddToken((int)SyntaxConstants.COL, 1, 1); alt.AddToken((int)SyntaxConstants.START, 1, 1); alt.AddProduction((int)SyntaxConstants.PROD_STATEMENTS, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_GLOBAL, "Prod_global"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_GLOBAL_CHOICE, 1, 1); alt.AddToken((int) SyntaxConstants.PER, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_GLOBAL, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_GLOBAL_CHOICE, "Prod_global_choice"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_LET_GLOBAL, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_VARDEC, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_ARRAY, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_TASK, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_OBJECT, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_DATATYPE, "Prod_datatype"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.INT, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.DOUBLE, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.CHAR, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.STRING, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.BOOLEAN, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_LET_GLOBAL, "Prod_let_global"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.LET, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddToken((int) SyntaxConstants.IS, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_VALUES, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_VALUES, "Prod_values"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.INTLIT, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.DOUBLELIT, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.STRINGLIT, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.CHARLIT, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.BOOLLIT, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_VARDEC, "Prod_vardec"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.VAR, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_VARDTYPE, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_VARDTYPE, "Prod_vardtype"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.INT, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_VARINIT_INT, 0, 1); alt.AddProduction((int) SyntaxConstants.PROD_VARTAIL_INT, 0, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.DOUBLE, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_VARINIT_DOUBLE, 0, 1); alt.AddProduction((int) SyntaxConstants.PROD_VARTAIL_DOUBLE, 0, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.CHAR, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_VARINIT_CHAR, 0, 1); alt.AddProduction((int) SyntaxConstants.PROD_VARTAIL_CHAR, 0, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.STRING, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_VARINIT_STRING, 0, 1); alt.AddProduction((int) SyntaxConstants.PROD_VARTAIL_STRING, 0, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.BOOLEAN, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_VARINIT_BOOLEAN, 0, 1); alt.AddProduction((int) SyntaxConstants.PROD_VARTAIL_BOOLEAN, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_VARINIT_INT, "Prod_varinitINT"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.IS, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_MATHOP_INT, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_VARINIT_DOUBLE, "Prod_varinitDOUBLE"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.IS, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_MATHOP_DOUBLE, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_VARINIT_CHAR, "Prod_varinitCHAR"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.IS, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_VALUE_CHAR, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_VARINIT_STRING, "Prod_varinitSTRING"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.IS, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_VALUE_STRING, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_VARINIT_BOOLEAN, "Prod_varinitBOOLEAN"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.IS, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_VALUE_BOOLEAN, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_VARTAIL_INT, "Prod_vartailINT"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.SEM, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_VARINIT_INT, 0, 1); alt.AddProduction((int) SyntaxConstants.PROD_VARTAIL_INT, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_VARTAIL_DOUBLE, "Prod_vartailDOUBLE"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.SEM, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_VARINIT_DOUBLE, 0, 1); alt.AddProduction((int) SyntaxConstants.PROD_VARTAIL_DOUBLE, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_VARTAIL_CHAR, "Prod_vartailCHAR"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.SEM, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_VARINIT_CHAR, 0, 1); alt.AddProduction((int) SyntaxConstants.PROD_VARTAIL_CHAR, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_VARTAIL_STRING, "Prod_vartailSTRING"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.SEM, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_VARINIT_STRING, 0, 1); alt.AddProduction((int) SyntaxConstants.PROD_VARTAIL_STRING, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_VARTAIL_BOOLEAN, "Prod_vartailBOOLEAN"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.SEM, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_VARINIT_BOOLEAN, 0, 1); alt.AddProduction((int) SyntaxConstants.PROD_VARTAIL_BOOLEAN, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_VALUE_CHAR, "Prod_valueCHAR"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.CHARLIT, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_ID_TAIL, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_VALUE_STRING, "Prod_valueSTRING"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.STRINGLIT, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_ID_TAIL, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_VALUE_BOOLEAN, "Prod_valueBOOLEAN"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.BOOLLIT, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_ID_TAIL, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_ID_TAIL, "Prod_id_tail"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_IDS_TAIL, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.OP, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_TASK_PARAM, 0, 1); alt.AddToken((int) SyntaxConstants.CP, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_IDS_TAIL, "Prod_ids_tail"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_ID_CHOICES, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_ID_CHOICES, "Prod_id_choices"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.AT, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_ELEMENTS, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.OB, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_INDEX, 1, 1); alt.AddToken((int) SyntaxConstants.CB, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_INDEX_TAIL, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_TASK_PARAM, "Prod_task_param"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_VALUE, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_TASK_PARAM_TAIL, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_TASK_PARAM_TAIL, "Prod_task_param_tail"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.SEM, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_TASK_PARAM, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_VALUE, "Prod_value"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_VALUES, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_ELEMENTS, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_INDEX, "Prod_index"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_INDEX_VALUE, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_INDEXOP, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_INDEXOP, "Prod_indexop"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_ADD_MIN, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_INDEX_VALUE, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_ADD_MIN, "Prod_add_min"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.ADD, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.MIN, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_INDEX_VALUE, "Prod_index_value"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.ID, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.INTLIT, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_INDEX_TAIL, "Prod_index_tail"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.OB, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_INDEX, 1, 1); alt.AddToken((int) SyntaxConstants.CB, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_ELEMENTS, "Prod_elements"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_ELEMENTS_TAIL, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_ELEMENTS_TAIL, "Prod_elements_tail"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.AT, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_ELEMENTS, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_ARRAY, "Prod_array"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.ARRAY, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_DATATYPE, 1, 1); alt.AddToken((int) SyntaxConstants.OF, 1, 1); alt.AddToken((int) SyntaxConstants.INTLIT, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_SIZE_TAIL, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_SIZE_TAIL, "Prod_size_tail"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.BY, 1, 1); alt.AddToken((int) SyntaxConstants.INTLIT, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_TASK, "Prod_task"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.TASK, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_RETURN_TYPE, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_PARAMETERS, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_RETURN_TYPE, "Prod_return_type"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_DATATYPE, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.NULL, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_PARAMETERS, "Prod_parameters"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.OP, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_DATATYPE, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_PARAM_TAIL, 0, 1); alt.AddToken((int) SyntaxConstants.CP, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_PARAM_TAIL, "Prod_param_tail"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.SEM, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_DATATYPE, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_PARAM_TAIL, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_OBJECT, "Prod_object"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.OBJECT, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddToken((int) SyntaxConstants.START, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_OBJECT_ELEM, 1, 1); alt.AddToken((int) SyntaxConstants.END, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_OBJECT_VAR, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_OBJECT_ELEM, "Prod_object_elem"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.VAR, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_DATATYPE, 1, 1); alt.AddToken((int) SyntaxConstants.PER, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_OBJECT_ELEM_TAIL, 0, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.OBJECT, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddToken((int) SyntaxConstants.PER, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_OBJECT_ELEM_TAIL, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_OBJECT_ELEM_TAIL, "Prod_object_elem_tail"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_OBJECT_ELEM, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_OBJECT_VAR, "Prod_object_var"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_OBJECT_VAR_TAIL, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_OBJECT_VAR_TAIL, "Prod_object_var_tail"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.SEM, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_OBJECT_VAR, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_STATEMENTS, "Prod_statements"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_FUNCTIONS, 1, 1); alt.AddToken((int) SyntaxConstants.PER, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_STATEMENTS, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_FUNCTIONS, "Prod_functions"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_VARDEC, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_ARRAY, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.OBJECT, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_IO_STATEMENT, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_PRE_INCDEC, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.CLEAR, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_OPTION, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_IF_OTHERWISE, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_LOOPSTATE, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_ID_STMT, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_IO_STATEMENT, "Prod_io_statement"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.READ, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_IDS_TAIL, 0, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.SAY, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_OUTPUT_STATEMENT, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_OUTPUT_STATEMENT, "Prod_output_statement"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.STRINGLIT, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_CONCAT, 0, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_IDS_TAIL, 0, 1); alt.AddProduction((int) SyntaxConstants.PROD_CONCAT, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_CONCAT, "Prod_concat"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.COMMA, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_OUTPUT_STATEMENT, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_PRE_INCDEC, "Prod_pre_incdec"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.INC, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.DEC, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_OPTION, "Prod_option"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.OPTION, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_ELEMENTS, 1, 1); alt.AddToken((int) SyntaxConstants.START, 1, 1); alt.AddToken((int) SyntaxConstants.STATE, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_OPTION_CHOICES, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_OPTION_CHOICES, "Prod_option_choices"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_OPTION_INT, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_OPTION_CHAR, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_OPTION_STRING, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_OPTION_INT, "Prod_optionINT"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.INTLIT, 1, 1); alt.AddToken((int) SyntaxConstants.COL, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_STATEMENTS, 0, 1); alt.AddToken((int) SyntaxConstants.STOP, 1, 1); alt.AddToken((int) SyntaxConstants.PER, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_STATE_INT, 0, 1); alt.AddProduction((int) SyntaxConstants.PROD_DEFAULT, 0, 1); alt.AddToken((int) SyntaxConstants.END, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_OPTION_CHAR, "Prod_optionCHAR"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.CHARLIT, 1, 1); alt.AddToken((int) SyntaxConstants.COL, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_STATEMENTS, 0, 1); alt.AddToken((int) SyntaxConstants.STOP, 1, 1); alt.AddToken((int) SyntaxConstants.PER, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_STATE_CHAR, 0, 1); alt.AddProduction((int) SyntaxConstants.PROD_DEFAULT, 0, 1); alt.AddToken((int) SyntaxConstants.END, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_OPTION_STRING, "Prod_optionSTRING"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.STRINGLIT, 1, 1); alt.AddToken((int) SyntaxConstants.COL, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_STATEMENTS, 0, 1); alt.AddToken((int) SyntaxConstants.STOP, 1, 1); alt.AddToken((int) SyntaxConstants.PER, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_STATE_STRING, 0, 1); alt.AddProduction((int) SyntaxConstants.PROD_DEFAULT, 0, 1); alt.AddToken((int) SyntaxConstants.END, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_STATE_INT, "Prod_stateINT"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.STATE, 1, 1); alt.AddToken((int) SyntaxConstants.INTLIT, 1, 1); alt.AddToken((int) SyntaxConstants.COL, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_STATEMENTS, 0, 1); alt.AddToken((int) SyntaxConstants.STOP, 1, 1); alt.AddToken((int) SyntaxConstants.PER, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_STATE_INT, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_STATE_CHAR, "Prod_stateCHAR"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.STATE, 1, 1); alt.AddToken((int) SyntaxConstants.CHARLIT, 1, 1); alt.AddToken((int) SyntaxConstants.COL, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_STATEMENTS, 0, 1); alt.AddToken((int) SyntaxConstants.STOP, 1, 1); alt.AddToken((int) SyntaxConstants.PER, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_STATE_CHAR, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_STATE_STRING, "Prod_stateSTRING"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.STATE, 1, 1); alt.AddToken((int) SyntaxConstants.STRINGLIT, 1, 1); alt.AddToken((int) SyntaxConstants.COL, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_STATEMENTS, 0, 1); alt.AddToken((int) SyntaxConstants.STOP, 1, 1); alt.AddToken((int) SyntaxConstants.PER, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_STATE_STRING, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_DEFAULT, "Prod_default"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.DEFAULT, 1, 1); alt.AddToken((int) SyntaxConstants.COL, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_STATEMENTS, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_CONDITIONS, "Prod_conditions"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_CONDITION_CHOICES, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_NEGATE, 0, 1); alt.AddToken((int) SyntaxConstants.OP, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_CONDITION_CHOICES, 1, 1); alt.AddToken((int) SyntaxConstants.CP, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_LOG_OP_TAIL, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_CONDITION_CHOICES, "Prod_condition_choices"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_CONDITION_IDS, 0, 1); alt.AddProduction((int) SyntaxConstants.PROD_REL_OP, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_CONDITION_TAIL, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_VALUES, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_REL_OP, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_CONDITION_TAIL, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_CONDITION_TAIL, "Prod_condition_tail"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_CONDITION_IDS, 0, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_VALUES, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_CONDITION_IDS, "Prod_condition_ids"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_ID_CHOICES, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.OP, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_TASK_PARAM, 0, 1); alt.AddToken((int) SyntaxConstants.CP, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_LOG_OP_TAIL, "Prod_logOp_tail"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_LOG_OP, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_LOG_OP_CHOICES, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_LOG_OP_TAIL, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_LOG_OP_CHOICES, "Prod_logOp_choices"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_NEGATE, 0, 1); alt.AddToken((int) SyntaxConstants.OP, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_CONDITION_CHOICES, 1, 1); alt.AddToken((int) SyntaxConstants.CP, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.BOOLLIT, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_LOG_OP_TAIL, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_REL_OP, "Prod_relOp"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.ISEQ, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.NOTEQ, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.GREAT, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.GEQ, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.LESS, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.LEQ, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_LOG_OP, "Prod_logOp"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.LOGAND, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.LOGOR, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_NEGATE, "Prod_negate"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.NOT, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_IF_OTHERWISE, "Prod_IfOtherwise"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.IF, 1, 1); alt.AddToken((int) SyntaxConstants.OP, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_CONDITIONS, 1, 1); alt.AddToken((int) SyntaxConstants.CP, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_COND_LOOP, 0, 1); alt.AddProduction((int) SyntaxConstants.PROD_OR, 0, 1); alt.AddProduction((int) SyntaxConstants.PROD_OTHERWISE, 0, 1); alt.AddToken((int) SyntaxConstants.ENDIF, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_OR, "Prod_or"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.OR, 1, 1); alt.AddToken((int) SyntaxConstants.OP, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_CONDITIONS, 1, 1); alt.AddToken((int) SyntaxConstants.CP, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_COND_LOOP, 0, 1); alt.AddProduction((int) SyntaxConstants.PROD_OR, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_OTHERWISE, "Prod_otherwise"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.OTHERWISE, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_COND_LOOP, 0, 1); alt.AddProduction((int) SyntaxConstants.PROD_CONTROL, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_COND_LOOP, "Prod_cond_loop"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_FUNCTIONS, 1, 1); alt.AddToken((int) SyntaxConstants.PER, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_CONTROL, 0, 1); alt.AddProduction((int) SyntaxConstants.PROD_COND_LOOP, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_CONTROL, "Prod_control"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.SKIP, 1, 1); alt.AddToken((int) SyntaxConstants.PER, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.STOP, 1, 1); alt.AddToken((int) SyntaxConstants.PER, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_LOOPSTATE, "Prod_loopstate"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.UNTIL, 1, 1); alt.AddToken((int) SyntaxConstants.OP, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_CONDITIONS, 1, 1); alt.AddToken((int) SyntaxConstants.CP, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_COND_LOOP, 0, 1); alt.AddToken((int) SyntaxConstants.LOOP, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.DO, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_COND_LOOP, 0, 1); alt.AddToken((int) SyntaxConstants.LOOPIF, 1, 1); alt.AddToken((int) SyntaxConstants.OP, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_CONDITIONS, 1, 1); alt.AddToken((int) SyntaxConstants.CP, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.FOR, 1, 1); alt.AddToken((int) SyntaxConstants.OP, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_INITIALIZE, 0, 1); alt.AddToken((int) SyntaxConstants.SEM, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_COND, 0, 1); alt.AddToken((int) SyntaxConstants.SEM, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_INCDECVAR, 1, 1); alt.AddToken((int) SyntaxConstants.CP, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_COND_LOOP, 0, 1); alt.AddToken((int) SyntaxConstants.LOOP, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_INITIALIZE, "Prod_initialize"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddToken((int) SyntaxConstants.EQ, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_INIT_CHOICES, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_INIT_CHOICES, "Prod_init_choices"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.INTLIT, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.ID, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_COND, "Prod_cond"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_INIT_CHOICES, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_REL_OP, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_INIT_CHOICES, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_INCDECVAR, "Prod_incdecvar"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_PRE_INCDEC, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_ID_STMT, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_ID_STMT, "Prod_id_stmt"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_ID_STMT_TAIL, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_ID_STMT_TAIL, "Prod_id_stmt_tail"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_IDS_TAIL, 0, 1); alt.AddToken((int) SyntaxConstants.EQ, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_INITVALUES, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.OP, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_TASK_PARAM, 0, 1); alt.AddToken((int) SyntaxConstants.CP, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddProduction((int)SyntaxConstants.PROD_INCDEC, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_INITVALUES, "Prod_initvalues"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_MATHOP_NUM, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.CHARLIT, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.STRINGLIT, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.BOOLLIT, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_MATHOP_INT, "Prod_mathopINT"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_INTVALUE, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_MATHOP_INT_TAIL, 0, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.OP, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_MATHOP_INT, 1, 1); alt.AddToken((int) SyntaxConstants.CP, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_MATHOP_INT_TAIL, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_MATHOP_DOUBLE, "Prod_mathopDOUBLE"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_DOUBLEVALUE, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_MATHOP_DOUBLE_TAIL, 0, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.OP, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_MATHOP_DOUBLE, 1, 1); alt.AddToken((int) SyntaxConstants.CP, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_MATHOP_DOUBLE_TAIL, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_MATHOP_NUM, "Prod_mathopNUM"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_NUMVALUE, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_MATHOP_NUM_TAIL, 0, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.OP, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_MATHOP_NUM, 1, 1); alt.AddToken((int) SyntaxConstants.CP, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_MATHOP_NUM_TAIL, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_INTVALUE, "Prod_intvalue"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.INTLIT, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_EXPR_ID, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_DOUBLEVALUE, "Prod_doublevalue"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.DOUBLELIT, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_EXPR_ID, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_NUMVALUE, "Prod_numvalue"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.INTLIT, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.DOUBLELIT, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_EXPR_ID, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_EXPR_ID, "Prod_exprID"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_ID_TAIL, 0, 1); alt.AddProduction((int) SyntaxConstants.PROD_INCDEC_NULL, 0, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_PRE_INCDEC, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_ID_TAIL, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_MATHOP_INT_TAIL, "Prod_mathopINT_tail"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_OPERATORS, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_MATHOP_INT, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_MATHOP_DOUBLE_TAIL, "Prod_mathopDOUBLE_tail"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_OPERATORS, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_MATHOP_DOUBLE, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_MATHOP_NUM_TAIL, "Prod_mathopNUM_tail"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_OPERATORS, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_MATHOP_NUM, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_OPERATORS, "Prod_operators"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.ADD, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.MIN, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.MUL, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.DIV, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.MOD, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_INCDEC, "Prod_incdec"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.INC, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.DEC, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_INCDEC_NULL, "Prod_incdec_null"); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_INCDEC, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_TASKDEF, "Prod_taskdef"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.TASK, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_RETURN_ID, 1, 1); alt.AddToken((int) SyntaxConstants.END, 1, 1); alt.AddToken((int) SyntaxConstants.PER, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_TASKDEF, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_RETURN_ID, "Prod_return_id"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.INT, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddToken((int) SyntaxConstants.COL, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_TASKBODY, 1, 1); alt.AddToken((int) SyntaxConstants.RESPONSE, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_RETURN_INT, 1, 1); alt.AddToken((int) SyntaxConstants.PER, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.DOUBLE, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddToken((int) SyntaxConstants.COL, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_TASKBODY, 1, 1); alt.AddToken((int) SyntaxConstants.RESPONSE, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_RETURN_DOUBLE, 1, 1); alt.AddToken((int) SyntaxConstants.PER, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.CHAR, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddToken((int) SyntaxConstants.COL, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_TASKBODY, 1, 1); alt.AddToken((int) SyntaxConstants.RESPONSE, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_RETURN_CHAR, 1, 1); alt.AddToken((int) SyntaxConstants.PER, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.STRING, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddToken((int) SyntaxConstants.COL, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_TASKBODY, 1, 1); alt.AddToken((int) SyntaxConstants.RESPONSE, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_RETURN_STRING, 1, 1); alt.AddToken((int) SyntaxConstants.PER, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.BOOLEAN, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddToken((int) SyntaxConstants.COL, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_TASKBODY, 1, 1); alt.AddToken((int) SyntaxConstants.RESPONSE, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_RETURN_BOOLEAN, 1, 1); alt.AddToken((int) SyntaxConstants.PER, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.NULL, 1, 1); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddToken((int) SyntaxConstants.COL, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_TASKBODY, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_TASKBODY, "Prod_taskbody"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.START, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_STATEMENTS, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_RETURN_INT, "Prod_returnINT"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.INTLIT, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_RETURNTAIL, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_RETURN_DOUBLE, "Prod_returnDOUBLE"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.DOUBLELIT, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_RETURNTAIL, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_RETURN_CHAR, "Prod_returnCHAR"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.CHARLIT, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_RETURNTAIL, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_RETURN_STRING, "Prod_returnSTRING"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.STRINGLIT, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_RETURNTAIL, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_RETURN_BOOLEAN, "Prod_returnBOOLEAN"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.BOOLLIT, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.ID, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_RETURNTAIL, 0, 1); pattern.AddAlternative(alt); AddPattern(pattern); pattern = new ProductionPattern((int) SyntaxConstants.PROD_RETURNTAIL, "Prod_returntail"); alt = new ProductionPatternAlternative(); alt.AddToken((int) SyntaxConstants.OP, 1, 1); alt.AddProduction((int) SyntaxConstants.PROD_TASK_PARAM, 0, 1); alt.AddToken((int) SyntaxConstants.CP, 1, 1); pattern.AddAlternative(alt); alt = new ProductionPatternAlternative(); alt.AddProduction((int) SyntaxConstants.PROD_ELEMENTS, 1, 1); pattern.AddAlternative(alt); AddPattern(pattern); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.RecaptchaEnterprise.V1Beta1.Snippets { using Google.Api.Gax; using Google.Api.Gax.ResourceNames; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedRecaptchaEnterpriseServiceV1Beta1ClientSnippets { /// <summary>Snippet for CreateAssessment</summary> public void CreateAssessmentRequestObject() { // Snippet: CreateAssessment(CreateAssessmentRequest, CallSettings) // Create client RecaptchaEnterpriseServiceV1Beta1Client recaptchaEnterpriseServiceV1Beta1Client = RecaptchaEnterpriseServiceV1Beta1Client.Create(); // Initialize request argument(s) CreateAssessmentRequest request = new CreateAssessmentRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), Assessment = new Assessment(), }; // Make the request Assessment response = recaptchaEnterpriseServiceV1Beta1Client.CreateAssessment(request); // End snippet } /// <summary>Snippet for CreateAssessmentAsync</summary> public async Task CreateAssessmentRequestObjectAsync() { // Snippet: CreateAssessmentAsync(CreateAssessmentRequest, CallSettings) // Additional: CreateAssessmentAsync(CreateAssessmentRequest, CancellationToken) // Create client RecaptchaEnterpriseServiceV1Beta1Client recaptchaEnterpriseServiceV1Beta1Client = await RecaptchaEnterpriseServiceV1Beta1Client.CreateAsync(); // Initialize request argument(s) CreateAssessmentRequest request = new CreateAssessmentRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), Assessment = new Assessment(), }; // Make the request Assessment response = await recaptchaEnterpriseServiceV1Beta1Client.CreateAssessmentAsync(request); // End snippet } /// <summary>Snippet for CreateAssessment</summary> public void CreateAssessment() { // Snippet: CreateAssessment(string, Assessment, CallSettings) // Create client RecaptchaEnterpriseServiceV1Beta1Client recaptchaEnterpriseServiceV1Beta1Client = RecaptchaEnterpriseServiceV1Beta1Client.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; Assessment assessment = new Assessment(); // Make the request Assessment response = recaptchaEnterpriseServiceV1Beta1Client.CreateAssessment(parent, assessment); // End snippet } /// <summary>Snippet for CreateAssessmentAsync</summary> public async Task CreateAssessmentAsync() { // Snippet: CreateAssessmentAsync(string, Assessment, CallSettings) // Additional: CreateAssessmentAsync(string, Assessment, CancellationToken) // Create client RecaptchaEnterpriseServiceV1Beta1Client recaptchaEnterpriseServiceV1Beta1Client = await RecaptchaEnterpriseServiceV1Beta1Client.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; Assessment assessment = new Assessment(); // Make the request Assessment response = await recaptchaEnterpriseServiceV1Beta1Client.CreateAssessmentAsync(parent, assessment); // End snippet } /// <summary>Snippet for CreateAssessment</summary> public void CreateAssessmentResourceNames() { // Snippet: CreateAssessment(ProjectName, Assessment, CallSettings) // Create client RecaptchaEnterpriseServiceV1Beta1Client recaptchaEnterpriseServiceV1Beta1Client = RecaptchaEnterpriseServiceV1Beta1Client.Create(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); Assessment assessment = new Assessment(); // Make the request Assessment response = recaptchaEnterpriseServiceV1Beta1Client.CreateAssessment(parent, assessment); // End snippet } /// <summary>Snippet for CreateAssessmentAsync</summary> public async Task CreateAssessmentResourceNamesAsync() { // Snippet: CreateAssessmentAsync(ProjectName, Assessment, CallSettings) // Additional: CreateAssessmentAsync(ProjectName, Assessment, CancellationToken) // Create client RecaptchaEnterpriseServiceV1Beta1Client recaptchaEnterpriseServiceV1Beta1Client = await RecaptchaEnterpriseServiceV1Beta1Client.CreateAsync(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); Assessment assessment = new Assessment(); // Make the request Assessment response = await recaptchaEnterpriseServiceV1Beta1Client.CreateAssessmentAsync(parent, assessment); // End snippet } /// <summary>Snippet for AnnotateAssessment</summary> public void AnnotateAssessmentRequestObject() { // Snippet: AnnotateAssessment(AnnotateAssessmentRequest, CallSettings) // Create client RecaptchaEnterpriseServiceV1Beta1Client recaptchaEnterpriseServiceV1Beta1Client = RecaptchaEnterpriseServiceV1Beta1Client.Create(); // Initialize request argument(s) AnnotateAssessmentRequest request = new AnnotateAssessmentRequest { AssessmentName = AssessmentName.FromProjectAssessment("[PROJECT]", "[ASSESSMENT]"), Annotation = AnnotateAssessmentRequest.Types.Annotation.Unspecified, }; // Make the request AnnotateAssessmentResponse response = recaptchaEnterpriseServiceV1Beta1Client.AnnotateAssessment(request); // End snippet } /// <summary>Snippet for AnnotateAssessmentAsync</summary> public async Task AnnotateAssessmentRequestObjectAsync() { // Snippet: AnnotateAssessmentAsync(AnnotateAssessmentRequest, CallSettings) // Additional: AnnotateAssessmentAsync(AnnotateAssessmentRequest, CancellationToken) // Create client RecaptchaEnterpriseServiceV1Beta1Client recaptchaEnterpriseServiceV1Beta1Client = await RecaptchaEnterpriseServiceV1Beta1Client.CreateAsync(); // Initialize request argument(s) AnnotateAssessmentRequest request = new AnnotateAssessmentRequest { AssessmentName = AssessmentName.FromProjectAssessment("[PROJECT]", "[ASSESSMENT]"), Annotation = AnnotateAssessmentRequest.Types.Annotation.Unspecified, }; // Make the request AnnotateAssessmentResponse response = await recaptchaEnterpriseServiceV1Beta1Client.AnnotateAssessmentAsync(request); // End snippet } /// <summary>Snippet for AnnotateAssessment</summary> public void AnnotateAssessment() { // Snippet: AnnotateAssessment(string, AnnotateAssessmentRequest.Types.Annotation, CallSettings) // Create client RecaptchaEnterpriseServiceV1Beta1Client recaptchaEnterpriseServiceV1Beta1Client = RecaptchaEnterpriseServiceV1Beta1Client.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/assessments/[ASSESSMENT]"; AnnotateAssessmentRequest.Types.Annotation annotation = AnnotateAssessmentRequest.Types.Annotation.Unspecified; // Make the request AnnotateAssessmentResponse response = recaptchaEnterpriseServiceV1Beta1Client.AnnotateAssessment(name, annotation); // End snippet } /// <summary>Snippet for AnnotateAssessmentAsync</summary> public async Task AnnotateAssessmentAsync() { // Snippet: AnnotateAssessmentAsync(string, AnnotateAssessmentRequest.Types.Annotation, CallSettings) // Additional: AnnotateAssessmentAsync(string, AnnotateAssessmentRequest.Types.Annotation, CancellationToken) // Create client RecaptchaEnterpriseServiceV1Beta1Client recaptchaEnterpriseServiceV1Beta1Client = await RecaptchaEnterpriseServiceV1Beta1Client.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/assessments/[ASSESSMENT]"; AnnotateAssessmentRequest.Types.Annotation annotation = AnnotateAssessmentRequest.Types.Annotation.Unspecified; // Make the request AnnotateAssessmentResponse response = await recaptchaEnterpriseServiceV1Beta1Client.AnnotateAssessmentAsync(name, annotation); // End snippet } /// <summary>Snippet for AnnotateAssessment</summary> public void AnnotateAssessmentResourceNames() { // Snippet: AnnotateAssessment(AssessmentName, AnnotateAssessmentRequest.Types.Annotation, CallSettings) // Create client RecaptchaEnterpriseServiceV1Beta1Client recaptchaEnterpriseServiceV1Beta1Client = RecaptchaEnterpriseServiceV1Beta1Client.Create(); // Initialize request argument(s) AssessmentName name = AssessmentName.FromProjectAssessment("[PROJECT]", "[ASSESSMENT]"); AnnotateAssessmentRequest.Types.Annotation annotation = AnnotateAssessmentRequest.Types.Annotation.Unspecified; // Make the request AnnotateAssessmentResponse response = recaptchaEnterpriseServiceV1Beta1Client.AnnotateAssessment(name, annotation); // End snippet } /// <summary>Snippet for AnnotateAssessmentAsync</summary> public async Task AnnotateAssessmentResourceNamesAsync() { // Snippet: AnnotateAssessmentAsync(AssessmentName, AnnotateAssessmentRequest.Types.Annotation, CallSettings) // Additional: AnnotateAssessmentAsync(AssessmentName, AnnotateAssessmentRequest.Types.Annotation, CancellationToken) // Create client RecaptchaEnterpriseServiceV1Beta1Client recaptchaEnterpriseServiceV1Beta1Client = await RecaptchaEnterpriseServiceV1Beta1Client.CreateAsync(); // Initialize request argument(s) AssessmentName name = AssessmentName.FromProjectAssessment("[PROJECT]", "[ASSESSMENT]"); AnnotateAssessmentRequest.Types.Annotation annotation = AnnotateAssessmentRequest.Types.Annotation.Unspecified; // Make the request AnnotateAssessmentResponse response = await recaptchaEnterpriseServiceV1Beta1Client.AnnotateAssessmentAsync(name, annotation); // End snippet } /// <summary>Snippet for CreateKey</summary> public void CreateKeyRequestObject() { // Snippet: CreateKey(CreateKeyRequest, CallSettings) // Create client RecaptchaEnterpriseServiceV1Beta1Client recaptchaEnterpriseServiceV1Beta1Client = RecaptchaEnterpriseServiceV1Beta1Client.Create(); // Initialize request argument(s) CreateKeyRequest request = new CreateKeyRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), Key = new Key(), }; // Make the request Key response = recaptchaEnterpriseServiceV1Beta1Client.CreateKey(request); // End snippet } /// <summary>Snippet for CreateKeyAsync</summary> public async Task CreateKeyRequestObjectAsync() { // Snippet: CreateKeyAsync(CreateKeyRequest, CallSettings) // Additional: CreateKeyAsync(CreateKeyRequest, CancellationToken) // Create client RecaptchaEnterpriseServiceV1Beta1Client recaptchaEnterpriseServiceV1Beta1Client = await RecaptchaEnterpriseServiceV1Beta1Client.CreateAsync(); // Initialize request argument(s) CreateKeyRequest request = new CreateKeyRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), Key = new Key(), }; // Make the request Key response = await recaptchaEnterpriseServiceV1Beta1Client.CreateKeyAsync(request); // End snippet } /// <summary>Snippet for ListKeys</summary> public void ListKeysRequestObject() { // Snippet: ListKeys(ListKeysRequest, CallSettings) // Create client RecaptchaEnterpriseServiceV1Beta1Client recaptchaEnterpriseServiceV1Beta1Client = RecaptchaEnterpriseServiceV1Beta1Client.Create(); // Initialize request argument(s) ListKeysRequest request = new ListKeysRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), }; // Make the request PagedEnumerable<ListKeysResponse, Key> response = recaptchaEnterpriseServiceV1Beta1Client.ListKeys(request); // Iterate over all response items, lazily performing RPCs as required foreach (Key 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 (ListKeysResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Key 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<Key> 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 (Key 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 ListKeysAsync</summary> public async Task ListKeysRequestObjectAsync() { // Snippet: ListKeysAsync(ListKeysRequest, CallSettings) // Create client RecaptchaEnterpriseServiceV1Beta1Client recaptchaEnterpriseServiceV1Beta1Client = await RecaptchaEnterpriseServiceV1Beta1Client.CreateAsync(); // Initialize request argument(s) ListKeysRequest request = new ListKeysRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), }; // Make the request PagedAsyncEnumerable<ListKeysResponse, Key> response = recaptchaEnterpriseServiceV1Beta1Client.ListKeysAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Key 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((ListKeysResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Key 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<Key> 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 (Key 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 GetKey</summary> public void GetKeyRequestObject() { // Snippet: GetKey(GetKeyRequest, CallSettings) // Create client RecaptchaEnterpriseServiceV1Beta1Client recaptchaEnterpriseServiceV1Beta1Client = RecaptchaEnterpriseServiceV1Beta1Client.Create(); // Initialize request argument(s) GetKeyRequest request = new GetKeyRequest { KeyName = KeyName.FromProjectKey("[PROJECT]", "[KEY]"), }; // Make the request Key response = recaptchaEnterpriseServiceV1Beta1Client.GetKey(request); // End snippet } /// <summary>Snippet for GetKeyAsync</summary> public async Task GetKeyRequestObjectAsync() { // Snippet: GetKeyAsync(GetKeyRequest, CallSettings) // Additional: GetKeyAsync(GetKeyRequest, CancellationToken) // Create client RecaptchaEnterpriseServiceV1Beta1Client recaptchaEnterpriseServiceV1Beta1Client = await RecaptchaEnterpriseServiceV1Beta1Client.CreateAsync(); // Initialize request argument(s) GetKeyRequest request = new GetKeyRequest { KeyName = KeyName.FromProjectKey("[PROJECT]", "[KEY]"), }; // Make the request Key response = await recaptchaEnterpriseServiceV1Beta1Client.GetKeyAsync(request); // End snippet } /// <summary>Snippet for UpdateKey</summary> public void UpdateKeyRequestObject() { // Snippet: UpdateKey(UpdateKeyRequest, CallSettings) // Create client RecaptchaEnterpriseServiceV1Beta1Client recaptchaEnterpriseServiceV1Beta1Client = RecaptchaEnterpriseServiceV1Beta1Client.Create(); // Initialize request argument(s) UpdateKeyRequest request = new UpdateKeyRequest { Key = new Key(), UpdateMask = new FieldMask(), }; // Make the request Key response = recaptchaEnterpriseServiceV1Beta1Client.UpdateKey(request); // End snippet } /// <summary>Snippet for UpdateKeyAsync</summary> public async Task UpdateKeyRequestObjectAsync() { // Snippet: UpdateKeyAsync(UpdateKeyRequest, CallSettings) // Additional: UpdateKeyAsync(UpdateKeyRequest, CancellationToken) // Create client RecaptchaEnterpriseServiceV1Beta1Client recaptchaEnterpriseServiceV1Beta1Client = await RecaptchaEnterpriseServiceV1Beta1Client.CreateAsync(); // Initialize request argument(s) UpdateKeyRequest request = new UpdateKeyRequest { Key = new Key(), UpdateMask = new FieldMask(), }; // Make the request Key response = await recaptchaEnterpriseServiceV1Beta1Client.UpdateKeyAsync(request); // End snippet } /// <summary>Snippet for DeleteKey</summary> public void DeleteKeyRequestObject() { // Snippet: DeleteKey(DeleteKeyRequest, CallSettings) // Create client RecaptchaEnterpriseServiceV1Beta1Client recaptchaEnterpriseServiceV1Beta1Client = RecaptchaEnterpriseServiceV1Beta1Client.Create(); // Initialize request argument(s) DeleteKeyRequest request = new DeleteKeyRequest { KeyName = KeyName.FromProjectKey("[PROJECT]", "[KEY]"), }; // Make the request recaptchaEnterpriseServiceV1Beta1Client.DeleteKey(request); // End snippet } /// <summary>Snippet for DeleteKeyAsync</summary> public async Task DeleteKeyRequestObjectAsync() { // Snippet: DeleteKeyAsync(DeleteKeyRequest, CallSettings) // Additional: DeleteKeyAsync(DeleteKeyRequest, CancellationToken) // Create client RecaptchaEnterpriseServiceV1Beta1Client recaptchaEnterpriseServiceV1Beta1Client = await RecaptchaEnterpriseServiceV1Beta1Client.CreateAsync(); // Initialize request argument(s) DeleteKeyRequest request = new DeleteKeyRequest { KeyName = KeyName.FromProjectKey("[PROJECT]", "[KEY]"), }; // Make the request await recaptchaEnterpriseServiceV1Beta1Client.DeleteKeyAsync(request); // End snippet } } }
public class LimObjectArrayList : ArrayList { public override string ToString() { string s = " ("; for (int i = 0; i < Count; i++) { s += base.Get(i).ToString(); if (i != Count - 1) s += ","; } s += ")"; return s; } } // SYMBOL HANDLING HELPER public class LimSeqObjectHashtable : System.Collections.Hashtable { public LimState state = null; public LimSeqObjectHashtable(LimState s) { state = s; } public object Get(object key) { object res; try { res = base[state.IOSYMBOL(key.ToString())]; } catch (System.Exception) { res = null; } return res; } public void Set(object key, object value) { base[state.IOSYMBOL(key.ToString())] = value; } } public class LimStateProto { public string name; public LimStateProtoFunc func; public LimObject proto; public LimStateProto(string name, LimObject proto, LimStateProtoFunc func) { this.name = name; this.func = func; this.proto = proto; } } public delegate LimObject LimStateProtoFunc(LimState state); public class LimObject { public LimState _state = null; public LimState getState() { return _state; } public void setState(LimState value) { _state = value; if (slots != null) slots.state = value; } public static long uniqueIdCounter = 0; public long uniqueId = 0; public virtual string getName() { return "Object"; } public LimSeqObjectHashtable slots; public LimObjectArrayList listeners; public LimObjectArrayList protos; public bool hasDoneLookup; public bool isActivatable; public bool isLocals; public static LimObject createProto(LimState state) { LimObject pro = new LimObject(); return pro.proto(state); } public static LimObject createObject(LimState state) { LimObject pro = new LimObject(); return pro.clone(state); } public virtual LimObject proto(LimState state) { LimObject pro = new LimObject(); pro.setState(state); pro.createSlots(); pro.createProtos(); pro.uniqueId = 0; state.registerProtoWithFunc(getName(), new LimStateProto(pro.getName(), pro, new LimStateProtoFunc(pro.proto))); return pro; } public virtual LimObject clone(LimState state) { LimObject proto = state.protoWithInitFunc(getName()); LimObject o = System.Activator.CreateInstance(this.GetType()) as LimObject;//typeof(this)new LimObject(); uniqueIdCounter++; o.uniqueId = uniqueIdCounter; o.setState(proto.getState()); o.createSlots(); o.createProtos(); o.protos.Add(proto); cloneSpecific(this, o); return o; } public virtual void cloneSpecific(LimObject from, LimObject to) { } // proto finish must be called only before first Sequence proto created public LimObject protoFinish(LimState state) { LimCFunction[] methodTable = new LimCFunction[] { new LimCFunction("compare", new LimMethodFunc(LimObject.slotCompare)), new LimCFunction("==", new LimMethodFunc(LimObject.slotEquals)), new LimCFunction("!=", new LimMethodFunc(LimObject.slotNotEquals)), new LimCFunction(">=", new LimMethodFunc(LimObject.slotGreaterThanOrEqual)), new LimCFunction("<=", new LimMethodFunc(LimObject.slotLessThanOrEqual)), new LimCFunction(">", new LimMethodFunc(LimObject.slotGreaterThan)), new LimCFunction("<", new LimMethodFunc(LimObject.slotLessThan)), new LimCFunction("-", new LimMethodFunc(LimObject.slotSubstract)), new LimCFunction("", new LimMethodFunc(LimObject.slotEevalArg)), new LimCFunction("self", new LimMethodFunc(LimObject.slotSelf)), new LimCFunction("clone", new LimMethodFunc(LimObject.slotClone)), new LimCFunction("return", new LimMethodFunc(LimObject.slotReturn)), new LimCFunction("cloneWithoutInit", new LimMethodFunc(LimObject.slotCloneWithoutInit)), new LimCFunction("doMessage", new LimMethodFunc(LimObject.slotDoMessage)), new LimCFunction("print", new LimMethodFunc(LimObject.slotPrint)), new LimCFunction("println", new LimMethodFunc(LimObject.slotPrintln)), new LimCFunction("slotNames", new LimMethodFunc(LimObject.slotSlotNames)), new LimCFunction("type", new LimMethodFunc(LimObject.slotType)), new LimCFunction("evalArg", new LimMethodFunc(LimObject.slotEevalArg)), new LimCFunction("evalArgAndReturnSelf", new LimMethodFunc(LimObject.slotEevalArgAndReturnSelf)), new LimCFunction("do", new LimMethodFunc(LimObject.slotDo)), new LimCFunction("getSlot", new LimMethodFunc(LimObject.slotGetSlot)), new LimCFunction("updateSlot", new LimMethodFunc(LimObject.slotUpdateSlot)), new LimCFunction("setSlot", new LimMethodFunc(LimObject.slotSetSlot)), new LimCFunction("setSlotWithType", new LimMethodFunc(LimObject.slotSetSlotWithType)), new LimCFunction("message", new LimMethodFunc(LimObject.slotMessage)), new LimCFunction("method", new LimMethodFunc(LimObject.slotMethod)), new LimCFunction("block", new LimMethodFunc(LimObject.slotBlock)), new LimCFunction("init", new LimMethodFunc(LimObject.slotSelf)), new LimCFunction("thisContext", new LimMethodFunc(LimObject.slotSelf)), new LimCFunction("thisMessage", new LimMethodFunc(LimObject.slotThisMessage)), new LimCFunction("thisLocals", new LimMethodFunc(LimObject.slotThisLocals)), new LimCFunction("init", new LimMethodFunc(LimObject.slotSelf)), new LimCFunction("if", new LimMethodFunc(LimObject.slotIf)), new LimCFunction("yield", new LimMethodFunc(LimObject.slotYield)), new LimCFunction("yieldingCoros", new LimMethodFunc(LimObject.slotYieldingCoros)), new LimCFunction("while", new LimMethodFunc(LimObject.slotWhile)) }; LimObject o = state.protoWithInitFunc(getName()); o.addTaglessMethodTable(state, methodTable); return o; } // Published Slots public static LimObject slotCompare(LimObject self, LimObject locals, LimObject message) { LimMessage m = message as LimMessage; LimObject o = m.localsValueArgAt(locals, 0); return LimNumber.newWithDouble(self.getState(), System.Convert.ToDouble(self.compare(o))); } public virtual int compare(LimObject v) { return uniqueId.CompareTo(v.uniqueId); } public static LimObject slotEquals(LimObject self, LimObject locals, LimObject message) { LimMessage m = message as LimMessage; LimObject o = m.localsValueArgAt(locals, 0); return self.compare(o) == 0 ? self.getState().LimTrue : self.getState().LimFalse; } public static LimObject slotNotEquals(LimObject self, LimObject locals, LimObject message) { LimMessage m = message as LimMessage; LimObject o = m.localsValueArgAt(locals, 0); return self.compare(o) != 0 ? self.getState().LimTrue : self.getState().LimFalse; } public static LimObject slotGreaterThanOrEqual(LimObject self, LimObject locals, LimObject message) { LimMessage m = message as LimMessage; LimObject o = m.localsValueArgAt(locals, 0); return self.compare(o) >= 0 ? self.getState().LimTrue : self.getState().LimFalse; } public static LimObject slotLessThanOrEqual(LimObject self, LimObject locals, LimObject message) { LimMessage m = message as LimMessage; LimObject o = m.localsValueArgAt(locals, 0); return self.compare(o) <= 0 ? self.getState().LimTrue : self.getState().LimFalse; } public static LimObject slotLessThan(LimObject self, LimObject locals, LimObject message) { LimMessage m = message as LimMessage; LimObject o = m.localsValueArgAt(locals, 0); return self.compare(o) < 0 ? self.getState().LimTrue : self.getState().LimFalse; } public static LimObject slotSubstract(LimObject self, LimObject locals, LimObject message) { LimMessage m = message as LimMessage; LimNumber o = m.localsNumberArgAt(locals, 0); return LimNumber.newWithDouble(self.getState(), -o.asDouble()); } public static LimObject slotGreaterThan(LimObject self, LimObject locals, LimObject message) { LimMessage m = message as LimMessage; LimObject o = m.localsValueArgAt(locals, 0); return self.compare(o) > 0 ? self.getState().LimTrue : self.getState().LimFalse; } public static LimObject slotSelf(LimObject self, LimObject locals, LimObject m) { return self; } public static LimObject slotThisMessage(LimObject self, LimObject locals, LimObject m) { return m; } public static LimObject slotThisLocals(LimObject self, LimObject locals, LimObject m) { return locals; } public static LimObject slotClone(LimObject target, LimObject locals, LimObject m) { //LimObject newObject = target.tag.cloneFunc(target.state); LimObject newObject = target.clone(target.getState()); //newObject.protos.Clear(); newObject.protos.Add(target); return target.initClone(target, locals, m as LimMessage, newObject); } public static LimObject slotReturn(LimObject target, LimObject locals, LimObject message) { LimMessage m = message as LimMessage; LimObject v = m.localsValueArgAt(locals, 0); target.getState().Return(v); return target; } public static LimObject slotCloneWithoutInit(LimObject target, LimObject locals, LimObject m) { return target.clone(target.getState()); } public static LimObject slotDoMessage(LimObject self, LimObject locals, LimObject m) { LimMessage msg = m as LimMessage; LimMessage aMessage = msg.localsMessageArgAt(locals, 0) as LimMessage; LimObject context = self; if (msg.args.Count >= 2) { context = msg.localsValueArgAt(locals, 1); } return aMessage.localsPerformOn(context, self); } public static LimObject slotPrint(LimObject target, LimObject locals, LimObject m) { target.print(); return target; } public static LimObject slotPrintln(LimObject target, LimObject locals, LimObject m) { target.print(); System.Console.WriteLine(); return target; } public static LimObject slotSlotNames(LimObject target, LimObject locals, LimObject message) { if (target.slots == null || target.slots.Count == 0) return target; foreach (object key in target.slots.Keys) { System.Console.Write(key.ToString() + " "); } System.Console.WriteLine(); return target; } public static LimObject slotType(LimObject target, LimObject locals, LimObject message) { return LimSeq.createObject(target.getState(), target.getName()); } public static LimObject slotEevalArg(LimObject target, LimObject locals, LimObject message) { LimMessage m = message as LimMessage; return m.localsValueArgAt(locals, 0); } public static LimObject slotEevalArgAndReturnSelf(LimObject target, LimObject locals, LimObject message) { LimObject.slotEevalArg(target, locals, message); return target; } public static LimObject slotDo(LimObject target, LimObject locals, LimObject message) { LimMessage m = message as LimMessage; if (m.args.Count != 0) { LimMessage argMessage = m.rawArgAt(0); argMessage.localsPerformOn(target, target); } return target; } public static LimObject slotGetSlot(LimObject target, LimObject locals, LimObject message) { LimMessage m = message as LimMessage; LimSeq slotName = m.localsSymbolArgAt(locals, 0); LimObject slot = target.rawGetSlot(slotName); return slot == null ? target.getState().LimNil : slot; } public static LimObject slotSetSlot(LimObject target, LimObject locals, LimObject message) { LimMessage m = message as LimMessage; LimSeq slotName = m.localsSymbolArgAt(locals, 0); LimObject slotValue = m.localsValueArgAt(locals, 1); if (slotName == null) return target; target.slots.Set(slotName,slotValue); return slotValue; } public static LimObject localsUpdateSlot(LimObject target, LimObject locals, LimObject message) { LimMessage m = message as LimMessage; LimSeq slotName = m.localsSymbolArgAt(locals, 0); if (slotName == null) return target; LimObject obj = target.rawGetSlot(slotName); if (obj != null) { LimObject slotValue = m.localsValueArgAt(locals, 1); target.slots.Set(slotName,slotValue); return slotValue; } else { LimObject theSelf = target.rawGetSlot(target.getState().selfMessage.messageName); if (theSelf != null) { return theSelf.perform(theSelf, locals, m); } } return target.getState().LimNil; } public static LimObject slotUpdateSlot(LimObject target, LimObject locals, LimObject message) { LimMessage m = message as LimMessage; LimSeq slotName = m.localsSymbolArgAt(locals, 0); LimObject slotValue = m.localsValueArgAt(locals, 1); if (slotName == null) return target; if (target.rawGetSlot(slotName) != null) { target.slots.Set(slotName,slotValue); } else { System.Console.WriteLine("Slot {0} not found. Must define slot using := operator before updating.", slotName.value); } return slotValue; } public static LimObject slotSetSlotWithType(LimObject target, LimObject locals, LimObject message) { LimMessage m = message as LimMessage; LimSeq slotName = m.localsSymbolArgAt(locals, 0); LimObject slotValue = m.localsValueArgAt(locals, 1); target.slots[slotName] = slotValue; if (slotValue.slots.Get(target.getState().typeSymbol) == null) { slotValue.slots.Set(target.getState().typeSymbol,slotName); } return slotValue; } public static LimObject slotMessage(LimObject target, LimObject locals, LimObject message) { LimMessage m = message as LimMessage; return m.args.Count > 0 ? m.rawArgAt(0) : target.getState().LimNil; } public static LimObject slotMethod(LimObject target, LimObject locals, LimObject message) { return LimBlock.slotMethod(target, locals, message); } public static LimObject slotBlock(LimObject target, LimObject locals, LimObject message) { return LimBlock.slotBlock(target, locals, message); } public static LimObject slotLocalsForward(LimObject target, LimObject locals, LimObject message) { LimObject o = target.slots.Get(target.getState().selfSymbol) as LimObject; if (o != null && o != target) return target.perform(o, locals, message); return target.getState().LimNil; } public static LimObject slotIf(LimObject target, LimObject locals, LimObject message) { LimMessage m = message as LimMessage; LimObject r = m.localsValueArgAt(locals, 0); bool condition = r != target.getState().LimNil && r != target.getState().LimFalse; int index = condition ? 1 : 2; if (index < m.args.Count) return m.localsValueArgAt(locals, index); return condition ? target.getState().LimTrue : target.getState().LimFalse; } public static LimObject slotYieldingCoros(LimObject target, LimObject locals, LimObject message) { return LimNumber.newWithDouble(target.getState(), target.getState().contextList.Count); } public static LimObject slotYield(LimObject target, LimObject locals, LimObject message) { LimState state = target.getState(); ArrayList toDeleteThread = new ArrayList(); for (int i = 0; i < state.contextList.Count; i++) { System.Collections.IEnumerator e = state.contextList.Get(i) as System.Collections.IEnumerator; bool end = e.MoveNext(); if (!end) toDeleteThread.Add(e); } foreach (object e in toDeleteThread.getIter()) state.contextList.Remove(e); return LimNumber.newWithDouble(state, state.contextList.Count); } public class EvaluateArgsEventArgs : System.EventArgs { public int Position = 0; public EvaluateArgsEventArgs(int pos) { Position = pos; } } public delegate void EvaluateArgsEventHandler(LimMessage msg, EvaluateArgsEventArgs e, out LimObject res); public static LimObject slotWhile(LimObject target, LimObject locals, LimObject message) { LimMessage m = message as LimMessage; LimObject result = target.getState().LimNil; while (true) { LimObject cond = m.localsValueArgAt(locals, 0); if (cond == target.getState().LimFalse || cond == target.getState().LimNil) { break; } result = m.localsValueArgAt(locals, 1); if (target.getState().handleStatus() != 0) { break; } } return result; } // Object Public Raw Methods public LimObject initClone(LimObject target, LimObject locals, LimMessage m, LimObject newObject) { LimObject context = null; LimObject initSlot = target.rawGetSlotContext(target.getState().initMessage.messageName, out context); if (initSlot != null) initSlot.activate(initSlot, newObject, locals, target.getState().initMessage, context); return newObject; } public void addTaglessMethodTable(LimState state, LimCFunction[] table) { foreach (LimCFunction entry in table) { entry.setState(state); slots.Set(entry.funcName,entry); } } public LimObject forward(LimObject target, LimObject locals, LimObject message) { LimMessage m = message as LimMessage; LimObject context = null; LimObject forwardSlot = target.rawGetSlotContext(target.getState().forwardMessage.messageName, out context); System.Console.WriteLine("'{0}' does not respond to message '{1}'", target.getName(), m.messageName.ToString()); return target; } public LimObject perform(LimObject target, LimObject locals, LimObject message) { LimMessage msg = message as LimMessage; LimObject context = null; LimObject slotValue = target.rawGetSlotContext(msg.messageName, out context); if (slotValue != null) { return slotValue.activate(slotValue, target, locals, msg, context); } if (target.isLocals) { return LimObject.slotLocalsForward(target, locals, message); } return target.forward(target, locals, message); } public LimObject localsProto(LimState state) { LimObject obj = LimObject.createObject(state); LimObject firstProto = obj.protos.Get(0) as LimObject; foreach (object key in firstProto.slots.Keys) obj.slots.Set(key,firstProto.slots.Get(key)); firstProto.protos.Clear(); obj.slots.Set("setSlot", new LimCFunction(state, "setSlot", new LimMethodFunc(LimObject.slotSetSlot))); obj.slots.Set("setSlotWithType", new LimCFunction(state, "setSlotWithType", new LimMethodFunc(LimObject.slotSetSlotWithType))); obj.slots.Set("updateSlot", new LimCFunction(state, "updateSlot", new LimMethodFunc(LimObject.localsUpdateSlot))); obj.slots.Set("thisLocalContext", new LimCFunction(state, "thisLocalContext", new LimMethodFunc(LimObject.slotThisLocals))); obj.slots.Set("forward", new LimCFunction(state, "forward", new LimMethodFunc(LimObject.slotLocalsForward))); return obj; } public virtual LimObject activate(LimObject self, LimObject target, LimObject locals, LimMessage m, LimObject slotContext) { return self.isActivatable ? self.activate(self, target, locals, m) : self; } public LimObject activate(LimObject self, LimObject target, LimObject locals, LimMessage m) { if (self.isActivatable) { LimObject context = null; LimObject slotValue = self.rawGetSlotContext(self.getState().activateMessage.messageName, out context); if (slotValue != null) { return activate(slotValue, target, locals, m, context); } return getState().LimNil; } else return self; } public void createSlots() { if (slots == null) slots = new LimSeqObjectHashtable(getState()); } public void createProtos() { if (protos == null) protos = new LimObjectArrayList(); } public LimObject slotsBySymbol(LimSeq symbol) { LimSeq s = this.getState().symbols[symbol.value] as LimSeq; if (s == null) return null; return slots.Get(s) as LimObject; } public LimObject rawGetSlot(LimSeq slot) { LimObject context = null; LimObject v = rawGetSlotContext(slot, out context); return v; } public LimObject rawGetSlotContext(LimSeq slot, out LimObject context) { if (slot == null) { context = null; return null; } LimObject v = null; context = null; if (slotsBySymbol(slot) != null) { v = slotsBySymbol(slot) as LimObject; if (v != null) { context = this; return v; } } hasDoneLookup = true; foreach (LimObject proto in protos.getIter()) { if (proto.hasDoneLookup) continue; v = proto.rawGetSlotContext(slot, out context); if (v != null) break; } hasDoneLookup = false; return v; } public virtual void print() { System.Console.Write(this); } public override string ToString() { return getName() + "+" + uniqueId; } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using Cosmos.Build.Common; using Cosmos.IL2CPU; namespace Cosmos.TestRunner.Core { partial class Engine { private string FindCosmosRoot() { var xCurrentDirectory = AppContext.BaseDirectory; var xCurrentInfo = new DirectoryInfo(xCurrentDirectory); while (xCurrentInfo.Parent != null) { if (xCurrentInfo.GetDirectories("source").Any()) { return xCurrentDirectory; } xCurrentInfo = xCurrentInfo.Parent; xCurrentDirectory = xCurrentInfo.FullName; } return string.Empty; } private void RunDotnetPublish(string aProjectPath, string aOutputPath, string aRuntimeTarget) { var xArgsString = $"publish \"{aProjectPath}\" -o \"{aOutputPath}\" -r {aRuntimeTarget}"; RunProcess("dotnet", aProjectPath, xArgsString); } private void RunProcess(string aProcess, string aWorkingDirectory, List<string> aArguments, bool aAttachDebugger = false) { if (string.IsNullOrWhiteSpace(aProcess)) { throw new ArgumentNullException(aProcess); } var xArgsString = aArguments.Aggregate("", (aArgs, aArg) => $"{aArgs} \"{aArg}\""); RunProcess(aProcess, aWorkingDirectory, xArgsString, aAttachDebugger); } private void RunProcess(string aProcess, string aWorkingDirectory, string aArguments, bool aAttachDebugger = false) { if (string.IsNullOrWhiteSpace(aProcess)) { throw new ArgumentNullException(aProcess); } if (aAttachDebugger) { aArguments += " \"AttachVsDebugger:True\""; } Action<string> xErrorReceived = OutputHandler.LogError; Action<string> xOutputReceived = OutputHandler.LogMessage; bool xResult = false; var xProcessStartInfo = new ProcessStartInfo { WorkingDirectory = aWorkingDirectory, FileName = aProcess, Arguments = aArguments, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true }; xOutputReceived($"Executing command line '{aProcess} {aArguments}'"); xOutputReceived($"Working directory = '{aWorkingDirectory}'"); using (var xProcess = new Process()) { xProcess.StartInfo = xProcessStartInfo; xProcess.ErrorDataReceived += delegate (object aSender, DataReceivedEventArgs e) { if (e.Data != null) { xErrorReceived(e.Data); } }; xProcess.OutputDataReceived += delegate (object aSender, DataReceivedEventArgs e) { if (e.Data != null) { xOutputReceived(e.Data); } }; xProcess.Start(); xProcess.BeginErrorReadLine(); xProcess.BeginOutputReadLine(); xProcess.WaitForExit(AllowedSecondsInKernel * 1000); if (!xProcess.HasExited) { xProcess.Kill(); xErrorReceived($"'{aProcess}' timed out."); } else { if (xProcess.ExitCode == 0) { xResult = true; } else { xErrorReceived($"Error invoking '{aProcess}'."); } } } if (!xResult) { throw new Exception("Error running process!"); } } public static string RunObjDump(string cosmosBuildDir, string workingDir, string inputFile, Action<string> errorReceived, Action<string> outputReceived) { var xMapFile = Path.ChangeExtension(inputFile, "map"); File.Delete(xMapFile); if (File.Exists(xMapFile)) { throw new Exception("Could not delete " + xMapFile); } var xTempBatFile = Path.Combine(workingDir, "ExtractElfMap.bat"); File.WriteAllText(xTempBatFile, "@ECHO OFF\r\n\"" + Path.Combine(cosmosBuildDir, @"tools\cygwin\objdump.exe") + "\" --wide --syms \"" + inputFile + "\" > \"" + Path.GetFileName(xMapFile) + "\""); var xProcessStartInfo = new ProcessStartInfo { WorkingDirectory = workingDir, FileName = xTempBatFile, Arguments = "", UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true }; var xProcess = Process.Start(xProcessStartInfo); xProcess.WaitForExit(20000); File.Delete(xTempBatFile); return xMapFile; } private void RunExtractMapFromElfFile(string workingDir, string kernelFileName) { RunObjDump(CosmosPaths.Build, workingDir, kernelFileName, OutputHandler.LogError, OutputHandler.LogMessage); } private void RunTheRingMaster(string kernelFileName) { var xArgs = new List<string>() { kernelFileName }; bool xUsingUserKit = false; string xTheRingMasterPath = Path.Combine(FindCosmosRoot(), "source", "TheRingMaster"); if (!Directory.Exists(xTheRingMasterPath)) { xUsingUserKit = true; xTheRingMasterPath = Path.Combine(GetCosmosUserkitFolder(), "Build", "TheRingMaster"); } if (xUsingUserKit) { RunProcess("TheRingMaster.exe", xTheRingMasterPath, xArgs); } else { xArgs.Insert(0, "run"); xArgs.Insert(1, "--no-build"); RunProcess("dotnet", xTheRingMasterPath, xArgs); } } private void RunIL2CPU(string kernelFileName, string outputFile) { var refsFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".refs"); var workingDirectory = Path.Combine(FindCosmosRoot(), "Tests", "TestKernels"); RunProcess("dotnet", workingDirectory, $"msbuild /t:Restore;WriteReferenceAssembliesToFile \"/p:ReferencesFile={refsFilePath}\" /nologo"); var xReferences = File.ReadAllLines(refsFilePath); File.Delete(refsFilePath); var xPlugsReferences = new List<string>(); if (KernelPkg == "X86") { xPlugsReferences.Add(Assembly.Load(new AssemblyName("Cosmos.CPU_Plugs")).Location); xPlugsReferences.Add(Assembly.Load(new AssemblyName("Cosmos.CPU_Asm")).Location); xPlugsReferences.Add(Assembly.Load(new AssemblyName("Cosmos.Plugs.TapRoot")).Location); } else { xPlugsReferences.Add(Assembly.Load(new AssemblyName("Cosmos.Core_Plugs")).Location); xPlugsReferences.Add(Assembly.Load(new AssemblyName("Cosmos.Core_Asm")).Location); xPlugsReferences.Add(Assembly.Load(new AssemblyName("Cosmos.System2_Plugs")).Location); xPlugsReferences.Add(Assembly.Load(new AssemblyName("Cosmos.Debug.Kernel.Plugs.Asm")).Location); } var xArgs = new List<string> { "KernelPkg:" + KernelPkg, "EnableDebug:True", "EnableStackCorruptionDetection:" + EnableStackCorruptionChecks, "StackCorruptionDetectionLevel:" + StackCorruptionDetectionLevel, "DebugMode:Source", "TraceAssemblies:" + TraceAssembliesLevel, "DebugCom:1", "TargetAssembly:" + kernelFileName, "OutputFilename:" + outputFile, "EnableLogging:True", "EmitDebugSymbols:True", "IgnoreDebugStubAttribute:False" }; xArgs.AddRange(xReferences.Select(r => "References:" + r)); xArgs.AddRange(xPlugsReferences.Select(r => "PlugsReferences:" + r)); bool xUsingUserkit = false; string xIL2CPUPath = Path.Combine(FindCosmosRoot(), "..", "IL2CPU", "source", "IL2CPU"); if (!Directory.Exists(xIL2CPUPath)) { xUsingUserkit = true; xIL2CPUPath = Path.Combine(GetCosmosUserkitFolder(), "Build", "IL2CPU"); } if (xUsingUserkit) { RunProcess("IL2CPU.exe", xIL2CPUPath, xArgs, DebugIL2CPU); } else { if (DebugIL2CPU) { if (KernelsToRun.Count() > 1) { throw new Exception("Cannot run multiple kernels with in-process compilation!"); } // ensure we're using the referenced (= solution) version Cosmos.IL2CPU.CosmosAssembler.ReadDebugStubFromDisk = false; Program.Run(xArgs.ToArray(), OutputHandler.LogMessage, OutputHandler.LogError); } else { xArgs.Insert(0, "run"); xArgs.Insert(1, "--no-build"); xArgs.Insert(2, " -- "); RunProcess("dotnet", xIL2CPUPath, xArgs); } } } private void RunNasm(string inputFile, string outputFile, bool isElf) { bool xUsingUserkit = false; string xNasmPath = Path.Combine(FindCosmosRoot(), "Tools", "NASM"); if (!Directory.Exists(xNasmPath)) { xUsingUserkit = true; xNasmPath = Path.Combine(GetCosmosUserkitFolder(), "Build", "NASM"); } if (!Directory.Exists(xNasmPath)) { throw new DirectoryNotFoundException("NASM path not found."); } var xArgs = new List<string> { $"ExePath:{Path.Combine(xUsingUserkit ? GetCosmosUserkitFolder() : FindCosmosRoot(), "Build", "Tools", "NAsm", "nasm.exe")}", $"InputFile:{inputFile}", $"OutputFile:{outputFile}", $"IsELF:{isElf}" }; if (xUsingUserkit) { RunProcess("NASM.exe", xNasmPath, xArgs); } else { xArgs.Insert(0, "run"); xArgs.Insert(1, " -- "); RunProcess("dotnet", xNasmPath, xArgs); } } private void RunLd(string inputFile, string outputFile) { string[] arguments = new[] { "-Ttext", "0x2000000", "-Tdata", " 0x1000000", "-e", "Kernel_Start", "-o",outputFile.Replace('\\', '/'), inputFile.Replace('\\', '/') }; var xArgsString = arguments.Aggregate("", (a, b) => a + " \"" + b + "\""); var xProcess = Process.Start(Path.Combine(GetCosmosUserkitFolder(), "build", "tools", "cygwin", "ld.exe"), xArgsString); xProcess.WaitForExit(10000); //RunProcess(Path.Combine(GetCosmosUserkitFolder(), "build", "tools", "cygwin", "ld.exe"), // mBaseWorkingDirectory, // new[] // { // "-Ttext", "0x2000000", // "-Tdata", " 0x1000000", // "-e", "Kernel_Start", // "-o",outputFile.Replace('\\', '/'), // inputFile.Replace('\\', '/') // }); } private static string GetCosmosUserkitFolder() { CosmosPaths.Initialize(); return CosmosPaths.UserKit; } private void MakeIso(string objectFile, string isoFile) { IsoMaker.Generate(objectFile, isoFile); if (!File.Exists(isoFile)) { throw new Exception("Error building iso"); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; namespace SIL.Lift.Options { /// <summary> /// Used to refer to this option from a field /// </summary> public class OptionRefCollection : IPalasoDataObjectProperty, INotifyPropertyChanged, IReportEmptiness, IComparable { // private readonly List<string> _keys; private readonly BindingList<OptionRef> _members; /// <summary> /// This "backreference" is used to notify the parent of changes. /// IParentable gives access to this during explicit construction. /// </summary> private IReceivePropertyChangeNotifications _parent; public OptionRefCollection(): this(null) {} public OptionRefCollection(IReceivePropertyChangeNotifications parent) { _parent = parent; //_keys = new List<string>(); _members = new BindingList<OptionRef>(); _members.ListChanged += _members_ListChanged; } private void _members_ListChanged(object sender, ListChangedEventArgs e) { NotifyPropertyChanged(); } public bool IsEmpty => _members.Count == 0; #region ICollection<string> Members // void ICollection<string>.Add(string key) // { // if (Keys.Contains(key)) // { // throw new ArgumentOutOfRangeException("key", key, // "OptionRefCollection already contains that key"); // } // // Add(key); // } private OptionRef FindByKey(string key) { foreach (OptionRef _member in _members) { if (_member.Key == key) { return _member; } } return null; } /// <summary> /// Removes a key from the OptionRefCollection /// </summary> /// <param name="key">The OptionRef key to be removed</param> /// <returns>true when removed, false when doesn't already exists in collection</returns> public bool Remove(string key) { OptionRef or = FindByKey(key); if (or != null) { _members.Remove(or); NotifyPropertyChanged(); return true; } return false; } public bool Contains(string key) { foreach (OptionRef _member in _members) { if (_member.Key == key) { return true; } } return false; //return Keys.Contains(key); } public int Count => _members.Count; public void Clear() { _members.Clear(); NotifyPropertyChanged(); } // public void CopyTo(string[] array, int arrayIndex) // { // Keys.CopyTo(array, arrayIndex); // } // // public bool IsReadOnly // { // get { return false; } // } // // public IEnumerator<string> GetEnumerator() // { // return Keys.GetEnumerator(); // } // // IEnumerator IEnumerable.GetEnumerator() // { // return Keys.GetEnumerator(); // } #endregion #region INotifyPropertyChanged Members /// <summary> /// For INotifyPropertyChanged /// </summary> public event PropertyChangedEventHandler PropertyChanged; #endregion #region IParentable Members public PalasoDataObject Parent { set => _parent = value; } #endregion protected void NotifyPropertyChanged() { //tell any data binding PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("option")); //tell our parent _parent?.NotifyPropertyChanged("option"); } /// <summary> /// Adds a key to the OptionRefCollection /// </summary> /// <param name="key">The OptionRef key to be added</param> /// <returns>true when added, false when already exists in collection</returns> public bool Add(string key) { if (Contains(key)) { return false; } _members.Add(new OptionRef(key)); NotifyPropertyChanged(); return true; } /// <summary> /// Adds a set of keys to the OptionRefCollection /// </summary> /// <param name="keys">A set of keys to be added</param> public void AddRange(IEnumerable<string> keys) { bool changed = false; foreach (string key in keys) { if (Contains(key)) { continue; } Add(key); changed = true; } if (changed) { NotifyPropertyChanged(); } } #region IReportEmptiness Members public bool ShouldHoldUpDeletionOfParentObject => //this one is a conundrum. Semantic domain gathering involves making senses //and adding to their semantic domain collection, without (necessarily) adding //a definition. We don't want this info lost just because some eager-beaver decides //to clean up. // OTOH, we would like to have this *not* prevent deletion, if it looks like //the user is trying to delete the sense. //It will take more code to have both of these desiderata at the same time. For //now, we'll choose the first one, in interest of not loosing data. It will just //be impossible to delete such a sense until we have SD editing. ShouldBeRemovedFromParentDueToEmptiness; public bool ShouldCountAsFilledForPurposesOfConditionalDisplay => !(IsEmpty); public bool ShouldBeRemovedFromParentDueToEmptiness { get { foreach (string s in Keys) { if (!string.IsNullOrEmpty(s)) { return false; // one non-empty is enough to keep us around } } return true; } } public IEnumerable<string> Keys { get { foreach (OptionRef _member in _members) { yield return _member.Key; } } } public IBindingList Members => _members; public string KeyAtIndex(int index) { if (index < 0) { throw new ArgumentException("index"); } if (index >= _members.Count) { throw new ArgumentException("index"); } return _members[index].Key; } // public IEnumerable<OptionRef> AsEnumeratorOfOptionRefs // { // get // { // foreach (string key in _keys) // { // OptionRef or = new OptionRef(); // or.Value = key; // yield return or; // } // } // } // public IBindingList GetConnectedBindingListOfOptionRefs() // { // foreach (string key in _keys) // { // OptionRef or = new OptionRef(); // or.Key = key; // or.Parent = (PalasoDataObject) _parent ; // // _optionRefProxyList.Add(or); // } // // } public void RemoveEmptyStuff() { List<OptionRef> condemened = new List<OptionRef>(); foreach (OptionRef _member in _members) { if (_member.IsEmpty) { condemened.Add(_member); } } foreach (OptionRef or in condemened) { Members.Remove(or); } } #endregion public int CompareTo(object obj) { if (obj == null) { return 1; } if (!(obj is OptionRefCollection)) { throw new ArgumentException($"Can not compare to anything but {nameof(OptionRefCollection)}s."); } OptionRefCollection other = (OptionRefCollection) obj; int order = _members.Count.CompareTo(other.Members.Count); if(order != 0) { return order; } for (int i = 0; i < _members.Count; i++) { order = _members[i].CompareTo(other.Members[i]); if(order != 0) { return order; } } return 0; } public override string ToString() { var builder = new StringBuilder(); foreach (var optionRef in _members) { builder.Append(optionRef.ToString()+", "); } return builder.ToString().TrimEnd(new char[] {',', ' '}); } public bool MergeByKey(OptionRefCollection incoming) { var combined = new List<OptionRef>(_members); foreach (OptionRef optionRef in incoming.Members) { var match = this.FindByKey(optionRef.Key); if(match == null) { combined.Add(optionRef); } else { //now, if we don't have embedded xml and they do, take on theirs if (match.EmbeddedXmlElements == null || match.EmbeddedXmlElements.Count == 0) match.EmbeddedXmlElements = optionRef.EmbeddedXmlElements; else if(optionRef.EmbeddedXmlElements.Count>0) { return false; //we don't know how to combine these } } } _members.Clear(); foreach (var optionRef in combined) { _members.Add(optionRef); } return true; } public IPalasoDataObjectProperty Clone() { var clone = new OptionRefCollection(); foreach (var memberToClone in _members) { clone._members.Add((OptionRef) memberToClone.Clone()); } return clone; } public override bool Equals(object obj) { return Equals(obj as OptionRefCollection); } public bool Equals(IPalasoDataObjectProperty other) { return Equals(other as OptionRefCollection); } public bool Equals(OptionRefCollection other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; if (!_members.SequenceEqual(other._members)) return false; return true; } public override int GetHashCode() { // https://stackoverflow.com/a/263416/487503 unchecked // Overflow is fine, just wrap { var hash = 23; hash *= 29 + _members?.GetHashCode() ?? 0; return hash; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // using Microsoft.Xunit.Performance; using System; using System.Runtime.CompilerServices; using Xunit; [assembly: OptimizeForBenchmarks] [assembly: MeasureInstructionsRetired] public class Puzzle { #if DEBUG public const int Iterations = 1; #else public const int Iterations = 400; #endif private const int PuzzleSize = 511; private const int ClassMax = 3; private const int TypeMax = 12; private const int D = 8; private int[] _pieceCount = new int[ClassMax + 1]; private int[] _class = new int[TypeMax + 1]; private int[] _pieceMax = new int[TypeMax + 1]; private bool[] _puzzle = new bool[PuzzleSize + 1]; private bool[][] _p; private int _count; private static T[][] AllocArray<T>(int n1, int n2) { T[][] a = new T[n1][]; for (int i = 0; i < n1; ++i) { a[i] = new T[n2]; } return a; } private bool Fit(int i, int j) { for (int k = 0; k <= _pieceMax[i]; k++) { if (_p[i][k]) { if (_puzzle[j + k]) { return false; } } } return true; } private int Place(int i, int j) { int k; for (k = 0; k <= _pieceMax[i]; k++) { if (_p[i][k]) { _puzzle[j + k] = true; } } _pieceCount[_class[i]] = _pieceCount[_class[i]] - 1; for (k = j; k <= PuzzleSize; k++) { if (!_puzzle[k]) { return k; } } return 0; } private void RemoveLocal(int i, int j) { for (int k = 0; k <= _pieceMax[i]; k++) { if (_p[i][k]) { _puzzle[j + k] = false; } } _pieceCount[_class[i]] = _pieceCount[_class[i]] + 1; } private bool Trial(int j) { for (int i = 0; i <= TypeMax; i++) { if (_pieceCount[_class[i]] != 0) { if (Fit(i, j)) { int k = Place(i, j); if (Trial(k) || (k == 0)) { _count = _count + 1; return true; } else { RemoveLocal(i, j); } } } } _count = _count + 1; return false; } private bool DoIt() { int i, j, k, m, n; for (m = 0; m <= PuzzleSize; m++) { _puzzle[m] = true; } for (i = 1; i <= 5; i++) { for (j = 1; j <= 5; j++) { for (k = 1; k <= 5; k++) { _puzzle[i + D * (j + D * k)] = false; } } } for (i = 0; i <= TypeMax; i++) { for (m = 0; m <= PuzzleSize; m++) { _p[i][m] = false; } } for (i = 0; i <= 3; i++) { for (j = 0; j <= 1; j++) { for (k = 0; k <= 0; k++) { _p[0][i + D * (j + D * k)] = true; } } } _class[0] = 0; _pieceMax[0] = 3 + D * 1 + D * D * 0; for (i = 0; i <= 1; i++) { for (j = 0; j <= 0; j++) { for (k = 0; k <= 3; k++) { _p[1][i + D * (j + D * k)] = true; } } } _class[1] = 0; _pieceMax[1] = 1 + D * 0 + D * D * 3; for (i = 0; i <= 0; i++) { for (j = 0; j <= 3; j++) { for (k = 0; k <= 1; k++) { _p[2][i + D * (j + D * k)] = true; } } } _class[2] = 0; _pieceMax[2] = 0 + D * 3 + D * D * 1; for (i = 0; i <= 1; i++) { for (j = 0; j <= 3; j++) { for (k = 0; k <= 0; k++) { _p[3][i + D * (j + D * k)] = true; } } } _class[3] = 0; _pieceMax[3] = 1 + D * 3 + D * D * 0; for (i = 0; i <= 3; i++) { for (j = 0; j <= 0; j++) { for (k = 0; k <= 1; k++) { _p[4][i + D * (j + D * k)] = true; } } } _class[4] = 0; _pieceMax[4] = 3 + D * 0 + D * D * 1; for (i = 0; i <= 0; i++) { for (j = 0; j <= 1; j++) { for (k = 0; k <= 3; k++) { _p[5][i + D * (j + D * k)] = true; } } } _class[5] = 0; _pieceMax[5] = 0 + D * 1 + D * D * 3; for (i = 0; i <= 2; i++) { for (j = 0; j <= 0; j++) { for (k = 0; k <= 0; k++) { _p[6][i + D * (j + D * k)] = true; } } } _class[6] = 1; _pieceMax[6] = 2 + D * 0 + D * D * 0; for (i = 0; i <= 0; i++) { for (j = 0; j <= 2; j++) { for (k = 0; k <= 0; k++) { _p[7][i + D * (j + D * k)] = true; } } } _class[7] = 1; _pieceMax[7] = 0 + D * 2 + D * D * 0; for (i = 0; i <= 0; i++) { for (j = 0; j <= 0; j++) { for (k = 0; k <= 2; k++) { _p[8][i + D * (j + D * k)] = true; } } } _class[8] = 1; _pieceMax[8] = 0 + D * 0 + D * D * 2; for (i = 0; i <= 1; i++) { for (j = 0; j <= 1; j++) { for (k = 0; k <= 0; k++) { _p[9][i + D * (j + D * k)] = true; } } } _class[9] = 2; _pieceMax[9] = 1 + D * 1 + D * D * 0; for (i = 0; i <= 1; i++) { for (j = 0; j <= 0; j++) { for (k = 0; k <= 1; k++) { _p[10][i + D * (j + D * k)] = true; } } } _class[10] = 2; _pieceMax[10] = 1 + D * 0 + D * D * 1; for (i = 0; i <= 0; i++) { for (j = 0; j <= 1; j++) { for (k = 0; k <= 1; k++) { _p[11][i + D * (j + D * k)] = true; } } } _class[11] = 2; _pieceMax[11] = 0 + D * 1 + D * D * 1; for (i = 0; i <= 1; i++) { for (j = 0; j <= 1; j++) { for (k = 0; k <= 1; k++) { _p[12][i + D * (j + D * k)] = true; } } } _class[12] = 3; _pieceMax[12] = 1 + D * 1 + D * D * 1; _pieceCount[0] = 13; _pieceCount[1] = 3; _pieceCount[2] = 1; _pieceCount[3] = 1; m = 1 + D * (1 + D * 1); _count = 0; bool result = true; if (Fit(0, m)) { n = Place(0, m); result = Trial(n); } else { result = false; } return result; } [MethodImpl(MethodImplOptions.NoInlining)] private bool Bench() { _p = AllocArray<bool>(TypeMax + 1, PuzzleSize + 1); bool result = true; for (int i = 0; i < Iterations; ++i) { result &= DoIt(); } return result; } [Benchmark] public static void Test() { Puzzle P = new Puzzle(); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { P.Bench(); } } } private static bool TestBase() { Puzzle P = new Puzzle(); bool result = P.Bench(); return result; } public static int Main() { bool result = TestBase(); return (result ? 100 : -1); } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { internal partial class CrefCompletionProvider : AbstractCompletionProvider { public static readonly SymbolDisplayFormat CrefFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, parameterOptions: SymbolDisplayParameterOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); public override bool IsCommitCharacter(CompletionItem completionItem, char ch, string textTypedSoFar) { if (ch == '{' && completionItem.DisplayText.Contains('{')) { return false; } if (ch == '(' && completionItem.DisplayText.Contains('(')) { return false; } return CompletionUtilities.IsCommitCharacter(completionItem, ch, textTypedSoFar); } public override bool SendEnterThroughToEditor(CompletionItem completionItem, string textTypedSoFar) { return CompletionUtilities.SendEnterThroughToEditor(completionItem, textTypedSoFar); } public override bool IsTriggerCharacter(SourceText text, int characterPosition, OptionSet options) { return CompletionUtilities.IsTriggerCharacter(text, characterPosition, options); } protected override Task<bool> IsExclusiveAsync(Document document, int position, CompletionTriggerInfo triggerInfo, CancellationToken cancellationToken) { return SpecializedTasks.True; } protected override async Task<IEnumerable<CompletionItem>> GetItemsWorkerAsync(Document document, int position, CompletionTriggerInfo triggerInfo, System.Threading.CancellationToken cancellationToken) { var tree = await document.GetCSharpSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (!tree.IsEntirelyWithinCrefSyntax(position, cancellationToken)) { return null; } var token = tree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); if (token.Kind() == SyntaxKind.None) { return null; } var result = SpecializedCollections.EmptyEnumerable<ISymbol>(); var semanticModel = await document.GetCSharpSemanticModelForNodeAsync(token.Parent, cancellationToken).ConfigureAwait(false); // cref ""|, ""|"", ""a|"" if (token.IsKind(SyntaxKind.DoubleQuoteToken, SyntaxKind.SingleQuoteToken) && token.Parent.IsKind(SyntaxKind.XmlCrefAttribute)) { result = semanticModel.LookupSymbols(token.SpanStart) .FilterToVisibleAndBrowsableSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation); result = result.Concat(GetOperatorsAndIndexers(token, semanticModel, cancellationToken)); } else if (IsSignatureContext(token)) { result = semanticModel.LookupNamespacesAndTypes(token.SpanStart) .FilterToVisibleAndBrowsableSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation); } else if (token.IsKind(SyntaxKind.DotToken) && token.Parent.IsKind(SyntaxKind.QualifiedCref)) { // cref "a.|" var parent = token.Parent as QualifiedCrefSyntax; var leftType = semanticModel.GetTypeInfo(parent.Container, cancellationToken).Type; var leftSymbol = semanticModel.GetSymbolInfo(parent.Container, cancellationToken).Symbol; var container = leftSymbol ?? leftType; result = semanticModel.LookupSymbols(token.SpanStart, container: (INamespaceOrTypeSymbol)container) .FilterToVisibleAndBrowsableSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation); if (container is INamedTypeSymbol) { result = result.Concat(((INamedTypeSymbol)container).InstanceConstructors); } } return await CreateItemsAsync(document.Project.Solution.Workspace, semanticModel, position, result, token, cancellationToken).ConfigureAwait(false); } private bool IsSignatureContext(SyntaxToken token) { return token.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken, SyntaxKind.RefKeyword, SyntaxKind.OutKeyword) && token.Parent.IsKind(SyntaxKind.CrefParameterList, SyntaxKind.CrefBracketedParameterList); } // LookupSymbols doesn't return indexers or operators because they can't be referred to by name, so we'll have to try to // find the innermost type declaration and return its operators and indexers private IEnumerable<ISymbol> GetOperatorsAndIndexers(SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken) { var typeDeclaration = token.GetAncestor<TypeDeclarationSyntax>(); var result = new List<ISymbol>(); if (typeDeclaration != null) { var type = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken); result.AddRange(type.GetMembers().OfType<IPropertySymbol>().Where(p => p.IsIndexer)); result.AddRange(type.GetAccessibleMembersInThisAndBaseTypes<IMethodSymbol>(type) .Where(m => m.MethodKind == MethodKind.UserDefinedOperator)); } return result; } private async Task<IEnumerable<CompletionItem>> CreateItemsAsync( Workspace workspace, SemanticModel semanticModel, int textChangeSpanPosition, IEnumerable<ISymbol> symbols, SyntaxToken token, CancellationToken cancellationToken) { var items = new List<CompletionItem>(); foreach (var symbol in symbols) { var item = await CreateItemAsync(workspace, semanticModel, textChangeSpanPosition, symbol, token, cancellationToken).ConfigureAwait(false); items.Add(item); } return items; } private async Task<CompletionItem> CreateItemAsync( Workspace workspace, SemanticModel semanticModel, int textChangeSpanPosition, ISymbol symbol, SyntaxToken token, CancellationToken cancellationToken) { int tokenPosition = token.SpanStart; string symbolText = string.Empty; if (symbol is INamespaceOrTypeSymbol && token.IsKind(SyntaxKind.DotToken)) { symbolText = symbol.Name.EscapeIdentifier(); if (symbol.GetArity() > 0) { symbolText += "{"; symbolText += string.Join(", ", ((INamedTypeSymbol)symbol).TypeParameters); symbolText += "}"; } } else { symbolText = symbol.ToMinimalDisplayString(semanticModel, tokenPosition, CrefFormat); var parameters = symbol.GetParameters().Select(p => { var displayName = p.Type.ToMinimalDisplayString(semanticModel, tokenPosition); if (p.RefKind == RefKind.Out) { return "out " + displayName; } if (p.RefKind == RefKind.Ref) { return "ref " + displayName; } return displayName; }); var parameterList = !symbol.IsIndexer() ? string.Format("({0})", string.Join(", ", parameters)) : string.Format("[{0}]", string.Join(", ", parameters)); symbolText += parameterList; } var insertionText = symbolText .Replace('<', '{') .Replace('>', '}') .Replace("()", ""); var text = await semanticModel.SyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false); return new CrefCompletionItem( workspace, completionProvider: this, displayText: insertionText, insertionText: insertionText, textSpan: GetTextChangeSpan(text, textChangeSpanPosition), descriptionFactory: CommonCompletionUtilities.CreateDescriptionFactory(workspace, semanticModel, tokenPosition, symbol), glyph: symbol.GetGlyph(), sortText: symbolText); } private TextSpan GetTextChangeSpan(SourceText text, int position) { return CommonCompletionUtilities.GetTextChangeSpan( text, position, (ch) => CompletionUtilities.IsTextChangeSpanStartCharacter(ch) || ch == '{', (ch) => CompletionUtilities.IsWordCharacter(ch) || ch == '{' || ch == '}'); } private string CreateParameters(IEnumerable<ITypeSymbol> arguments, SemanticModel semanticModel, int position) { return string.Join(", ", arguments.Select(t => t.ToMinimalDisplayString(semanticModel, position))); } public override TextChange GetTextChange(CompletionItem selectedItem, char? ch = null, string textTypedSoFar = null) { return new TextChange(selectedItem.FilterSpan, ((CrefCompletionItem)selectedItem).InsertionText); } } }
/* * NodeManager.cs - Implementation of the * "System.Xml.Private.NodeManager" class. * * Copyright (C) 2004 Free Software Foundation, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Xml.Private { using System; using System.Xml; internal sealed class NodeManager { // Internal state. private int current; private Attributes attributes; private ErrorHandler error; private NodeInfo[] nodes; private String xml; // Constructor. public NodeManager(XmlNameTable nt, ErrorHandler eh) { current = (int)Type.None; attributes = null; error = eh; nodes = new NodeInfo[11]; nodes[current] = new DefaultNodeInfo(); xml = nt.Add("xml"); } // Get an attribute information node. public AttributeInfo Attribute { get { current = (int)Type.Attribute; if(nodes[current] == null) { nodes[current] = new AttributeInfo(); } return (AttributeInfo)nodes[current]; } } // Get or set an array of attribute information nodes. public Attributes Attributes { get { if(attributes == null) { attributes = new Attributes(error); } return attributes; } set { attributes = value; } } // Get a character data information node. public CDATAInfo CDATA { get { current = (int)Type.CDATA; if(nodes[current] == null) { nodes[current] = new CDATAInfo(); } return (CDATAInfo)nodes[current]; } } // Get a comment information node. public CommentInfo Comment { get { current = (int)Type.Comment; if(nodes[current] == null) { nodes[current] = new CommentInfo(); } return (CommentInfo)nodes[current]; } } // Get the current node information. public NodeInfo Current { get { return nodes[current]; } } // Get a doctype declaration information node. public DoctypeDeclarationInfo DoctypeDeclaration { get { current = (int)Type.DoctypeDeclaration; if(nodes[current] == null) { nodes[current] = new DoctypeDeclarationInfo(); } return (DoctypeDeclarationInfo)nodes[current]; } } // Get an element information node. public ElementInfo Element { get { current = (int)Type.Element; if(nodes[current] == null) { nodes[current] = new ElementInfo(); } return (ElementInfo)nodes[current]; } } // Get an end element information node. public EndElementInfo EndElement { get { current = (int)Type.EndElement; if(nodes[current] == null) { nodes[current] = new EndElementInfo(); } return (EndElementInfo)nodes[current]; } } // Get a processing instruction information node. public ProcessingInstructionInfo ProcessingInstruction { get { current = (int)Type.ProcessingInstruction; if(nodes[current] == null) { nodes[current] = new ProcessingInstructionInfo(); } return (ProcessingInstructionInfo)nodes[current]; } } // Get a text information node. public TextInfo Text { get { current = (int)Type.Text; if(nodes[current] == null) { nodes[current] = new TextInfo(); } return (TextInfo)nodes[current]; } } // Get a whitespace information node. public WhitespaceInfo Whitespace { get { current = (int)Type.Whitespace; if(nodes[current] == null) { nodes[current] = new WhitespaceInfo(); } return (WhitespaceInfo)nodes[current]; } } // Get an xml declaration information node. public XmlDeclarationInfo XmlDeclaration { get { current = (int)Type.XmlDeclaration; if(nodes[current] == null) { nodes[current] = new XmlDeclarationInfo(xml); } return (XmlDeclarationInfo)nodes[current]; } } // Reset to the default state. public void Reset() { current = (int)Type.None; } private enum Type { None = 0x00, Attribute = 0x01, CDATA = 0x02, Comment = 0x03, DoctypeDeclaration = 0x04, Element = 0x05, EndElement = 0x06, ProcessingInstruction = 0x07, Text = 0x08, Whitespace = 0x09, XmlDeclaration = 0x0A }; // enum Type private sealed class DefaultNodeInfo : NodeInfo { // Constructor. public DefaultNodeInfo() { } }; // class DefaultNodeInfo }; // class NodeManager }; // namespace System.Xml.Private
using System; using System.Globalization; using System.Reactive; using System.Reactive.Linq; using System.Threading.Tasks; using GitHub.Authentication; using GitHub.Extensions; using GitHub.Extensions.Reactive; using GitHub.Info; using GitHub.Models; using GitHub.Primitives; using GitHub.Services; using GitHub.Validation; using NLog; using NullGuard; using ReactiveUI; namespace GitHub.ViewModels { public abstract class LoginTabViewModel : ReactiveObject { static readonly Logger log = LogManager.GetCurrentClassLogger(); protected LoginTabViewModel(IRepositoryHosts repositoryHosts, IVisualStudioBrowser browser) { RepositoryHosts = repositoryHosts; UsernameOrEmailValidator = ReactivePropertyValidator.For(this, x => x.UsernameOrEmail) .IfNullOrEmpty(Resources.UsernameOrEmailValidatorEmpty) .IfMatch(@"\s", Resources.UsernameOrEmailValidatorSpaces); PasswordValidator = ReactivePropertyValidator.For(this, x => x.Password) .IfNullOrEmpty(Resources.PasswordValidatorEmpty); canLogin = this.WhenAny( x => x.UsernameOrEmailValidator.ValidationResult.IsValid, x => x.PasswordValidator.ValidationResult.IsValid, (x, y) => x.Value && y.Value).ToProperty(this, x => x.CanLogin); Login = ReactiveCommand.CreateAsyncObservable(this.WhenAny(x => x.CanLogin, x => x.Value), LogIn); Login.ThrownExceptions.Subscribe(ex => { if (ex.IsCriticalException()) return; log.Info(string.Format(CultureInfo.InvariantCulture, "Error logging into '{0}' as '{1}'", BaseUri, UsernameOrEmail), ex); if (ex is Octokit.ForbiddenException) { ShowLogInFailedError = true; LoginFailedMessage = Resources.LoginFailedForbiddenMessage; } else { ShowConnectingToHostFailed = true; } }); isLoggingIn = Login.IsExecuting.ToProperty(this, x => x.IsLoggingIn); Reset = ReactiveCommand.CreateAsyncTask(_ => Clear()); NavigateForgotPassword = ReactiveCommand.CreateAsyncObservable(_ => { browser.OpenUrl(new Uri(BaseUri, GitHubUrls.ForgotPasswordPath)); return Observable.Return(Unit.Default); }); SignUp = ReactiveCommand.CreateAsyncObservable(_ => { browser.OpenUrl(GitHubUrls.Plans); return Observable.Return(Unit.Default); }); } protected IRepositoryHosts RepositoryHosts { get; } protected abstract Uri BaseUri { get; } public IReactiveCommand<Unit> SignUp { get; } public IReactiveCommand<AuthenticationResult> Login { get; } public IReactiveCommand<Unit> Reset { get; } public IReactiveCommand<Unit> NavigateForgotPassword { get; } string loginFailedMessage = Resources.LoginFailedMessage; public string LoginFailedMessage { get { return loginFailedMessage; } set { this.RaiseAndSetIfChanged(ref loginFailedMessage, value); } } string usernameOrEmail; [AllowNull] public string UsernameOrEmail { [return: AllowNull] get { return usernameOrEmail; } set { this.RaiseAndSetIfChanged(ref usernameOrEmail, value); } } ReactivePropertyValidator usernameOrEmailValidator; public ReactivePropertyValidator UsernameOrEmailValidator { get { return usernameOrEmailValidator; } private set { this.RaiseAndSetIfChanged(ref usernameOrEmailValidator, value); } } string password; [AllowNull] public string Password { [return: AllowNull] get { return password; } set { this.RaiseAndSetIfChanged(ref password, value); } } ReactivePropertyValidator passwordValidator; public ReactivePropertyValidator PasswordValidator { get { return passwordValidator; } private set { this.RaiseAndSetIfChanged(ref passwordValidator, value); } } readonly ObservableAsPropertyHelper<bool> isLoggingIn; public bool IsLoggingIn { get { return isLoggingIn.Value; } } protected ObservableAsPropertyHelper<bool> canLogin; public bool CanLogin { get { return canLogin.Value; } } bool showLogInFailedError; public bool ShowLogInFailedError { get { return showLogInFailedError; } protected set { this.RaiseAndSetIfChanged(ref showLogInFailedError, value); } } bool showConnectingToHostFailed; public bool ShowConnectingToHostFailed { get { return showConnectingToHostFailed; } set { this.RaiseAndSetIfChanged(ref showConnectingToHostFailed, value); } } protected abstract IObservable<AuthenticationResult> LogIn(object args); protected IObservable<AuthenticationResult> LogInToHost(HostAddress hostAddress) { return Observable.Defer(() => { ShowLogInFailedError = false; ShowConnectingToHostFailed = false; return hostAddress != null ? RepositoryHosts.LogIn(hostAddress, UsernameOrEmail, Password) : Observable.Return(AuthenticationResult.CredentialFailure); }) .ObserveOn(RxApp.MainThreadScheduler) .Do(authResult => { switch (authResult) { case AuthenticationResult.CredentialFailure: ShowLogInFailedError = true; break; case AuthenticationResult.VerificationFailure: break; case AuthenticationResult.EnterpriseServerNotFound: ShowConnectingToHostFailed = true; break; } }) .SelectMany(authResult => { switch (authResult) { case AuthenticationResult.CredentialFailure: case AuthenticationResult.EnterpriseServerNotFound: case AuthenticationResult.VerificationFailure: Password = ""; return Observable.FromAsync(PasswordValidator.ResetAsync) .Select(_ => AuthenticationResult.CredentialFailure); case AuthenticationResult.Success: return Reset.ExecuteAsync() .ContinueAfter(() => Observable.Return(AuthenticationResult.Success)); default: return Observable.Throw<AuthenticationResult>( new InvalidOperationException("Unknown EnterpriseLoginResult: " + authResult)); } }); } async Task Clear() { UsernameOrEmail = null; Password = null; await UsernameOrEmailValidator.ResetAsync(); await PasswordValidator.ResetAsync(); await ResetValidation(); ShowLogInFailedError = false; } protected virtual Task ResetValidation() { // noop return Task.FromResult(0); } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using Gallio.Common.Concurrency; using Gallio.Icarus.Controllers; using Gallio.Icarus.Controllers.Interfaces; using Gallio.Icarus.Events; using Gallio.Icarus.Models; using Gallio.Icarus.Services; using Gallio.Icarus.Tests.Utilities; using Gallio.Icarus.TreeBuilders; using Gallio.Model; using Gallio.Model.Filters; using Gallio.Model.Schema; using Gallio.Runner; using Gallio.Runner.Events; using Gallio.Runner.Extensions; using Gallio.Runner.Reports.Schema; using Gallio.Runtime.Logging; using Gallio.UI.Events; using MbUnit.Framework; using Rhino.Mocks; namespace Gallio.Icarus.Tests.Controllers { [MbUnit.Framework.Category("Controllers"), Author("Graham Hay"), TestsOn(typeof(TestController))] public class TestControllerTest { private TestController testController; private ITestTreeModel testTreeModel; private IOptionsController optionsController; private IEventAggregator eventAggregator; private ITestRunnerEvents testRunnerEvents; private ITestRunner testRunner; private IFilterService filterService; [SetUp] public void EstablishContext() { testTreeModel = MockRepository.GenerateStub<ITestTreeModel>(); optionsController = MockRepository.GenerateStub<IOptionsController>(); eventAggregator = MockRepository.GenerateStub<IEventAggregator>(); filterService = MockRepository.GenerateStub<IFilterService>(); testController = new TestController(testTreeModel, optionsController, new TestTaskManager(), eventAggregator, filterService); } [Test] public void Explore_should_send_an_ExploreStarted_event() { var progressMonitor = MockProgressMonitor.Instance; optionsController.Stub(oc => oc.TestRunnerExtensions).Return(new BindingList<string>(new List<string>())); StubTestRunnerFactory(); testController.Explore(progressMonitor, new List<string>()); eventAggregator.AssertWasCalled(ea => ea.Send(Arg.Is(testController), Arg<ExploreStarted>.Is.Anything)); } private void StubTestRunnerFactory() { var testRunnerFactory = MockRepository.GenerateStub<ITestRunnerFactory>(); testRunner = MockRepository.GenerateStub<ITestRunner>(); testRunnerEvents = MockRepository.GenerateStub<ITestRunnerEvents>(); testRunner.Stub(tr => tr.Events).Return(testRunnerEvents); testRunnerFactory.Stub(trf => trf.CreateTestRunner()).Return(testRunner); testController.SetTestRunnerFactory(testRunnerFactory); } // TODO: split this into multiple tests [Test] public void Explore_Test() { var progressMonitor = MockProgressMonitor.Instance; optionsController.Stub(oc => oc.TestRunnerExtensions).Return(new BindingList<string>(new List<string>())); StubTestRunnerFactory(); testController.Explore(progressMonitor, new List<string>()); testRunner.AssertWasCalled(tr => tr.Initialize(Arg<TestRunnerOptions>.Is.Anything, Arg<ILogger>.Is.Anything, Arg.Is(progressMonitor))); testRunner.AssertWasCalled(tr => tr.Explore(Arg<TestPackage>.Is.Anything, Arg<TestExplorationOptions>.Is.Anything, Arg.Is(progressMonitor))); testTreeModel.AssertWasCalled(ttm => ttm.BuildTestTree(Arg.Is(progressMonitor), Arg<TestModelData>.Is.Anything, Arg<TreeBuilderOptions>.Is.Anything)); } [Test] public void Explore_should_send_an_ExploreFinished_event() { var progressMonitor = MockProgressMonitor.Instance; optionsController.Stub(oc => oc.TestRunnerExtensions).Return(new BindingList<string>(new List<string>())); StubTestRunnerFactory(); testController.Explore(progressMonitor, new List<string>()); eventAggregator.AssertWasCalled(ea => ea.Send(Arg.Is(testController), Arg<ExploreFinished>.Is.Anything)); } [Test] public void TestStepFinished_should_bubble_up_from_test_runner() { var progressMonitor = MockProgressMonitor.Instance; var testRunnerExtensions = new BindingList<string>(new List<string>()); optionsController.Stub(oc => oc.TestRunnerExtensions).Return(testRunnerExtensions); StubTestRunnerFactory(); testController.Explore(progressMonitor, new List<string>()); var testData = new TestData("id", "name", "fullName"); var testStepData = new TestStepData("id", "name", "fullName", "testId") { IsTestCase = true }; var testStepRun = new TestStepRun(testStepData); var testStepFinishedEventArgs = new TestStepFinishedEventArgs(new Report(), testData, testStepRun); testRunnerEvents.Raise(tre => tre.TestStepFinished += null, testRunner, testStepFinishedEventArgs); eventAggregator.AssertWasCalled(ea => ea.Send(Arg.Is(testController), Arg<TestStepFinished>.Matches(tsf => tsf.TestData == testData && tsf.TestStepRun == testStepRun))); } [Test] public void If_any_tests_have_failed_an_event_should_be_raised() { var progressMonitor = MockProgressMonitor.Instance; optionsController.Stub(oc => oc.TestRunnerExtensions).Return(new BindingList<string>(new List<string>())); StubTestRunnerFactory(); testController.Explore(progressMonitor, new List<string>()); var testStepRun = new TestStepRun(new TestStepData("id", "name", "fullName", "testId")) { Result = new TestResult(TestOutcome.Failed) }; var report = new Report(); var testData = new TestData("id", "name", "fullName"); var testStepFinishedEventArgs = new TestStepFinishedEventArgs(report, testData, testStepRun); testRunnerEvents.Raise(tre => tre.TestStepFinished += null, testRunner, testStepFinishedEventArgs); eventAggregator.AssertWasCalled(ea => ea.Send(Arg.Is(testController), Arg<TestsFailed>.Is.Anything)); } [Test] public void RunStarted_Test() { var progressMonitor = MockProgressMonitor.Instance; optionsController.Stub(oc => oc.TestRunnerExtensions).Return(new BindingList<string>(new List<string>())); StubTestRunnerFactory(); testController.Explore(progressMonitor, new List<string>()); Report report = new Report(); testRunnerEvents.Raise(tre => tre.RunStarted += null, testRunner, new RunStartedEventArgs(new TestPackage(), new TestExplorationOptions(), new TestExecutionOptions(), new LockBox<Report>(report))); testController.ReadReport(r => Assert.AreEqual(r, report)); } [Test] public void ExploreStarted_Test() { var progressMonitor = MockProgressMonitor.Instance; optionsController.Stub(oc => oc.TestRunnerExtensions).Return(new BindingList<string>(new List<string>())); StubTestRunnerFactory(); testController.Explore(progressMonitor, new List<string>()); Report report = new Report(); testRunnerEvents.Raise(tre => tre.ExploreStarted += null, testRunner, new ExploreStartedEventArgs(new TestPackage(), new TestExplorationOptions(), new LockBox<Report>(report))); testController.ReadReport(r => Assert.AreEqual(r, report)); } [Test] public void DoWithTestRunner_should_throw_if_testRunnerFactory_is_null() { var progressMonitor = MockProgressMonitor.Instance; optionsController.Stub(oc => oc.TestRunnerExtensions).Return(new BindingList<string>(new List<string>())); Assert.Throws<InvalidOperationException>(() => testController.Explore(progressMonitor, new List<string>())); } [Test] public void ResetTestStatus_Test() { var progressMonitor = MockProgressMonitor.Instance; testController.ResetTestStatus(progressMonitor); testTreeModel.AssertWasCalled(ttm => ttm.ResetTestStatus(progressMonitor)); } [Test] public void RunStarted_is_fired_when_running_tests() { var progressMonitor = MockProgressMonitor.Instance; var filter = new FilterSet<ITestDescriptor>(new NoneFilter<ITestDescriptor>()); filterService.Stub(fs => fs.GenerateFilterSetFromSelectedTests()).Return(filter); var testRunnerExtensions = new BindingList<string>(new List<string>()); optionsController.Stub(oc => oc.TestRunnerExtensions).Return(testRunnerExtensions); StubTestRunnerFactory(); testController.Run(false, progressMonitor, new List<string>()); eventAggregator.AssertWasCalled(ea => ea.Send(Arg.Is(testController), Arg<RunStarted>.Is.Anything)); } [Test] public void Run_Test() { var progressMonitor = MockProgressMonitor.Instance; var filter = new FilterSet<ITestDescriptor>(new NoneFilter<ITestDescriptor>()); filterService.Stub(fs => fs.GenerateFilterSetFromSelectedTests()).Return(filter); optionsController.Stub(oc => oc.TestRunnerExtensions).Return(new BindingList<string>(new List<string>())); StubTestRunnerFactory(); var testPackage = new TestPackage(); testPackage.AddFile(new FileInfo("test")); testController.SetTestPackage(testPackage); testController.Run(false, progressMonitor, new List<string>()); testRunner.AssertWasCalled(tr => tr.Run(Arg<TestPackage>.Matches(tpc => tpc.Files.Count == 1), Arg<TestExplorationOptions>.Is.Anything, Arg<TestExecutionOptions>.Matches(teo => ((teo.FilterSet == filter) && !teo.ExactFilter)), Arg.Is(progressMonitor))); } [Test] public void RunFinished_is_fired_when_running_tests() { var progressMonitor = MockProgressMonitor.Instance; var filter = new FilterSet<ITestDescriptor>(new NoneFilter<ITestDescriptor>()); filterService.Stub(fs => fs.GenerateFilterSetFromSelectedTests()).Return(filter); optionsController.Stub(oc => oc.TestRunnerExtensions).Return(new BindingList<string>(new List<string>())); StubTestRunnerFactory(); testController.Run(false, progressMonitor, new List<string>()); eventAggregator.AssertWasCalled(ea => ea.Send(Arg.Is(testController), Arg<RunFinished>.Is.Anything)); } [Test] public void TestRunnerExtensions_are_found_from_OptionsController() { var progressMonitor = MockProgressMonitor.Instance; var filter = new FilterSet<ITestDescriptor>(new NoneFilter<ITestDescriptor>()); filterService.Stub(ttm => ttm.GenerateFilterSetFromSelectedTests()).Return(filter); var testRunnerExtensions = new BindingList<string>(new List<string>(new[] {"DebugExtension, Gallio"})); optionsController.Stub(oc => oc.TestRunnerExtensions).Return(testRunnerExtensions); StubTestRunnerFactory(); testController.Run(false, progressMonitor, new List<string>()); testRunner.AssertWasCalled(tr => tr.RegisterExtension(Arg<DebugExtension>.Is.Anything)); } [Test] public void TestRunnerExtensions_are_found_from_Project() { var progressMonitor = MockProgressMonitor.Instance; var filter = new FilterSet<ITestDescriptor>(new NoneFilter<ITestDescriptor>()); filterService.Stub(ttm => ttm.GenerateFilterSetFromSelectedTests()).Return(filter); var testRunnerExtensions = new BindingList<string>(new List<string>()); optionsController.Stub(oc => oc.TestRunnerExtensions).Return(testRunnerExtensions); StubTestRunnerFactory(); testController.Run(false, progressMonitor, new List<string>(new[] { "DebugExtension, Gallio" })); testRunner.AssertWasCalled(tr => tr.RegisterExtension(Arg<DebugExtension>.Is.Anything)); } [Test] public void Duplicate_TestRunnerExtensions_are_only_added_once() { var progressMonitor = MockProgressMonitor.Instance; var filter = new FilterSet<ITestDescriptor>(new NoneFilter<ITestDescriptor>()); filterService.Stub(ttm => ttm.GenerateFilterSetFromSelectedTests()).Return(filter); var testRunnerExtensions = new BindingList<string>(new List<string>()); optionsController.Stub(oc => oc.TestRunnerExtensions).Return(testRunnerExtensions); StubTestRunnerFactory(); testController.Run(false, progressMonitor, new List<string>(new[] { "DebugExtension, Gallio", "DebugExtension, Gallio" })); testRunner.AssertWasCalled(tr => tr.RegisterExtension(Arg<DebugExtension>.Is.Anything)); } [Test] public void SetTestPackage_should_throw_if_test_package_is_null() { Assert.Throws<ArgumentNullException>(() => testController.SetTestPackage(null)); } [Test] public void SetTestRunnerFactory_should_throw_if_test_factory_is_null() { Assert.Throws<ArgumentNullException>(() => testController.SetTestRunnerFactory(null)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using Internal.NativeFormat; using Debug = Internal.Runtime.CompilerHelpers.StartupDebug; namespace Internal.Runtime.CompilerHelpers { [McgIntrinsics] internal static class StartupCodeHelpers { public static IntPtr[] Modules { get; private set; } [NativeCallable(EntryPoint = "InitializeModules", CallingConvention = CallingConvention.Cdecl)] internal static void InitializeModules(IntPtr moduleHeaders, int count) { IntPtr[] modules = CreateModuleManagers(moduleHeaders, count); foreach (var moduleManager in modules) { InitializeGlobalTablesForModule(moduleManager); } // We are now at a stage where we can use GC statics - publish the list of modules // so that the eager constructors can access it. Modules = modules; // These two loops look funny but it's important to initialize the global tables before running // the first class constructor to prevent them calling into another uninitialized module foreach (var moduleManager in modules) { InitializeEagerClassConstructorsForModule(moduleManager); } } internal static unsafe void InitializeCommandLineArgsW(int argc, char** argv) { string[] args = new string[argc]; for (int i = 0; i < argc; ++i) { args[i] = new string(argv[i]); } Environment.SetCommandLineArgs(args); } internal static unsafe void InitializeCommandLineArgs(int argc, byte** argv) { string[] args = new string[argc]; for (int i = 0; i < argc; ++i) { byte* argval = argv[i]; int len = CStrLen(argval); args[i] = Encoding.UTF8.GetString(argval, len); } Environment.SetCommandLineArgs(args); } private static string[] GetMainMethodArguments() { // GetCommandLineArgs includes the executable name, Main() arguments do not. string[] args = Environment.GetCommandLineArgs(); Debug.Assert(args.Length > 0); string[] mainArgs = new string[args.Length - 1]; Array.Copy(args, 1, mainArgs, 0, mainArgs.Length); return mainArgs; } private static unsafe IntPtr[] CreateModuleManagers(IntPtr moduleHeaders, int count) { // Count the number of modules so we can allocate an array to hold the ModuleManager objects. // At this stage of startup, complex collection classes will not work. int moduleCount = 0; for (int i = 0; i < count; i++) { // The null pointers are sentinel values and padding inserted as side-effect of // the section merging. (The global static constructors section used by C++ has // them too.) if (((IntPtr *)moduleHeaders)[i] != IntPtr.Zero) moduleCount++; } IntPtr[] modules = new IntPtr[moduleCount]; int moduleIndex = 0; for (int i = 0; i < count; i++) { if (((IntPtr *)moduleHeaders)[i] != IntPtr.Zero) modules[moduleIndex++] = CreateModuleManager(((IntPtr *)moduleHeaders)[i]); } return modules; } /// <summary> /// Each managed module linked into the final binary may have its own global tables for strings, /// statics, etc that need initializing. InitializeGlobalTables walks through the modules /// and offers each a chance to initialize its global tables. /// </summary> private static unsafe void InitializeGlobalTablesForModule(IntPtr moduleManager) { // Configure the module indirection cell with the newly created ModuleManager. This allows EETypes to find // their interface dispatch map tables. int length; IntPtr* section = (IntPtr*)GetModuleSection(moduleManager, ReadyToRunSectionType.ModuleManagerIndirection, out length); *section = moduleManager; // Initialize strings if any are present IntPtr stringSection = GetModuleSection(moduleManager, ReadyToRunSectionType.StringTable, out length); if (stringSection != IntPtr.Zero) { Debug.Assert(length % IntPtr.Size == 0); InitializeStringTable(stringSection, length); } // Initialize statics if any are present IntPtr staticsSection = GetModuleSection(moduleManager, ReadyToRunSectionType.GCStaticRegion, out length); if (staticsSection != IntPtr.Zero) { Debug.Assert(length % IntPtr.Size == 0); InitializeStatics(staticsSection, length); } } private static unsafe void InitializeEagerClassConstructorsForModule(IntPtr moduleManager) { int length; // Run eager class constructors if any are present IntPtr eagerClassConstructorSection = GetModuleSection(moduleManager, ReadyToRunSectionType.EagerCctor, out length); if (eagerClassConstructorSection != IntPtr.Zero) { Debug.Assert(length % IntPtr.Size == 0); RunEagerClassConstructors(eagerClassConstructorSection, length); } } private static unsafe void InitializeStringTable(IntPtr stringTableStart, int length) { IntPtr stringTableEnd = (IntPtr)((byte*)stringTableStart + length); for (IntPtr* tab = (IntPtr*)stringTableStart; tab < (IntPtr*)stringTableEnd; tab++) { byte* bytes = (byte*)*tab; int len = (int)NativePrimitiveDecoder.DecodeUnsigned(ref bytes); int count = LowLevelUTF8Encoding.GetCharCount(bytes, len); Debug.Assert(count >= 0); string newStr = RuntimeImports.RhNewArrayAsString(EETypePtr.EETypePtrOf<string>(), count); fixed (char* dest = newStr) { int newCount = LowLevelUTF8Encoding.GetChars(bytes, len, dest, count); Debug.Assert(newCount == count); } GCHandle handle = GCHandle.Alloc(newStr); *tab = (IntPtr)handle; } } private static void Call(System.IntPtr pfn) { } private static unsafe void RunEagerClassConstructors(IntPtr cctorTableStart, int length) { IntPtr cctorTableEnd = (IntPtr)((byte*)cctorTableStart + length); for (IntPtr* tab = (IntPtr*)cctorTableStart; tab < (IntPtr*)cctorTableEnd; tab++) { Call(*tab); } } private static unsafe void InitializeStatics(IntPtr gcStaticRegionStart, int length) { IntPtr gcStaticRegionEnd = (IntPtr)((byte*)gcStaticRegionStart + length); for (IntPtr* block = (IntPtr*)gcStaticRegionStart; block < (IntPtr*)gcStaticRegionEnd; block++) { // Gc Static regions can be shared by modules linked together during compilation. To ensure each // is initialized once, the static region pointer is stored with lowest bit set in the image. // The first time we initialize the static region its pointer is replaced with an object reference // whose lowest bit is no longer set. IntPtr* pBlock = (IntPtr*)*block; if (((*pBlock).ToInt64() & 0x1L) == 1) { object obj = RuntimeImports.RhNewObject(new EETypePtr(new IntPtr((*pBlock).ToInt64() & ~0x1L))); *pBlock = RuntimeImports.RhHandleAlloc(obj, GCHandleType.Normal); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static unsafe int CStrLen(byte* str) { int len = 0; for (; str[len] != 0; len++) { } return len; } [RuntimeImport(".", "RhpGetModuleSection")] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern IntPtr GetModuleSection(IntPtr module, ReadyToRunSectionType section, out int length); [RuntimeImport(".", "RhpCreateModuleManager")] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static unsafe extern IntPtr CreateModuleManager(IntPtr moduleHeader); } }
namespace FakeItEasy.Tests.Configuration { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Reflection; using FakeItEasy.Configuration; using FakeItEasy.Core; using FakeItEasy.Tests.TestHelpers; using FluentAssertions; using Xunit; using static FakeItEasy.Tests.TestHelpers.ExpressionHelper; public class BuildableCallRuleTests { private readonly TestableCallRule rule; public BuildableCallRuleTests() { this.rule = new TestableCallRule(); } private interface IOutAndRef { void OutAndRef(object input, out int first, string input2, ref string second, string input3); } private interface IHaveDifferentReturnValues { int IntReturn(); string StringReturn(); DummyableClass DummyableReturn(); } public static IEnumerable<object> DefaultReturnValueCases() { return TestCases.FromProperties( new { Method = GetMethodInfo<IHaveDifferentReturnValues>(x => x.IntReturn()), ExpectedReturnValue = (object)0 }, new { Method = GetMethodInfo<IHaveDifferentReturnValues>(x => x.StringReturn()), ExpectedReturnValue = (object)string.Empty }, new { Method = GetMethodInfo<IHaveDifferentReturnValues>(x => x.DummyableReturn()), ExpectedReturnValue = (object)A.Dummy<DummyableClass>() }); } [Fact] public void Apply_should_invoke_all_actions_in_the_actions_collection() { // Arrange bool firstWasCalled = false; bool secondWasCalled = false; this.rule.Actions.Add(x => firstWasCalled = true); this.rule.Actions.Add(x => secondWasCalled = true); this.rule.UseApplicator(x => { }); // Act this.rule.Apply(A.Fake<IInterceptedFakeObjectCall>()); // Assert firstWasCalled.Should().BeTrue(); secondWasCalled.Should().BeTrue(); } [Fact] public void Apply_should_pass_the_call_to_specified_actions() { var call = A.Fake<IInterceptedFakeObjectCall>(); IFakeObjectCall? passedCall = null; this.rule.UseApplicator(x => { }); this.rule.Actions.Add(x => passedCall = x); this.rule.Apply(call); passedCall.Should().BeSameAs(call); } [Fact] public void Apply_should_call_CallBaseMethod_on_intercepted_call_when_CallBaseMethod_is_set_to_true() { var call = A.Fake<IInterceptedFakeObjectCall>(); this.rule.UseApplicator(x => { }); this.rule.CallBaseMethod = true; this.rule.Apply(call); A.CallTo(() => call.CallBaseMethod()).MustHaveHappened(); } [Fact] public void Apply_should_set_ref_and_out_parameters_when_specified() { // Arrange this.rule.SetOutAndRefParametersValueProducer(x => new object[] { 1, "foo" }); this.rule.UseApplicator(x => { }); var call = A.Fake<IInterceptedFakeObjectCall>(); A.CallTo(() => call.Method).Returns(OutAndRefMethod); // Act this.rule.Apply(call); A.CallTo(() => call.SetArgumentValue(1, 1)).MustHaveHappened(); A.CallTo(() => call.SetArgumentValue(3, "foo")).MustHaveHappened(); } [Fact] public void Apply_should_throw_when_OutAndRefParametersValues_length_differs_from_the_number_of_out_and_ref_parameters_in_the_call() { // Arrange this.rule.SetOutAndRefParametersValueProducer(x => new object[] { 1, "foo", "bar" }); this.rule.UseApplicator(x => { }); var call = A.Fake<IInterceptedFakeObjectCall>(); A.CallTo(() => call.Method).Returns(OutAndRefMethod); var exception = Record.Exception(() => this.rule.Apply(call)); exception.Should().BeAnExceptionOfType<InvalidOperationException>() .WithMessage("The number of values for out and ref parameters specified does not match the number of out and ref parameters in the call."); } [Theory] [MemberData(nameof(DefaultReturnValueCases))] public void Apply_should_set_return_value_to_default_value_when_applicator_is_not_set(MethodInfo method, object expectedResponse) { // Arrange var call = A.Fake<IInterceptedFakeObjectCall>(); A.CallTo(() => call.Method).Returns(method); // Act this.rule.Apply(call); // Assert A.CallTo(() => call.SetReturnValue(expectedResponse)) .MustHaveHappened(); } [Theory] [InlineData(true, true)] [InlineData(false, false)] public void Apply_should_return_return_value_from_on_is_applicable_to_when_a_where_predicate_is_not_set( bool resultFromOnIsApplicableTo, bool expectedResult) { // Arrange this.rule.ReturnValueFromOnIsApplicableTo = resultFromOnIsApplicableTo; // Act var result = this.rule.IsApplicableTo(null!); // Assert result.Should().Be(expectedResult); } [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "andon", Justification = "False positive")] [Fact] public void IsApplicableTo_should_return_false_when_a_predicate_fails_and_on_is_applicable_to_passes() { // Arrange this.rule.ReturnValueFromOnIsApplicableTo = true; this.rule.ApplyWherePredicate(x => true, x => { }); this.rule.ApplyWherePredicate(x => false, x => { }); // Act var isThisRuleApplicable = this.rule.IsApplicableTo(A.Dummy<IFakeObjectCall>()); // Assert isThisRuleApplicable.Should().BeFalse(); } [Fact] public void Should_not_call_OnIsApplicableTo_when_a_where_predicate_returns_false() { // Arrange this.rule.ApplyWherePredicate(x => false, x => { }); // Act this.rule.IsApplicableTo(A.Dummy<IFakeObjectCall>()); // Assert this.rule.OnIsApplicableToWasCalled.Should().BeFalse(); } [Fact] public void Apply_should_return_true_when_on_is_applicable_to_is_true_and_all_where_predicates_returns_true() { // Arrange this.rule.ReturnValueFromOnIsApplicableTo = true; this.rule.ApplyWherePredicate(x => true, x => { }); this.rule.ApplyWherePredicate(x => true, x => { }); // Act // Assert this.rule.IsApplicableTo(A.Dummy<IFakeObjectCall>()).Should().BeTrue(); } [Fact] public void Should_pass_call_to_where_predicates() { // Arrange var call = A.Fake<IFakeObjectCall>(); A.CallTo(() => call.ToString()).Returns("foo"); this.rule.ApplyWherePredicate(x => x.ToString() == "foo", x => { }); // Act var isApplicableTo = this.rule.IsApplicableTo(call); // Assert isApplicableTo.Should().BeTrue(); } [Fact] public void Should_write_description_of_valid_call_by_calling_the_description_property() { // Arrange this.rule.DescriptionOfValidCallReturnValue = "description"; var writer = ServiceLocator.Resolve<StringBuilderOutputWriter.Factory>().Invoke(); // Act this.rule.WriteDescriptionOfValidCall(writer); // Assert writer.Builder.ToString().Should().Be("description"); } [Fact] public void Should_append_where_predicates_to_description_correctly() { // Arrange this.rule.DescriptionOfValidCallReturnValue = "description"; this.rule.ApplyWherePredicate(x => true, x => x.Write("description of first where")); this.rule.ApplyWherePredicate(x => true, x => x.Write("description of second where")); var descriptionWriter = ServiceLocator.Resolve<StringBuilderOutputWriter.Factory>().Invoke(); // Act this.rule.WriteDescriptionOfValidCall(descriptionWriter); // Assert var expectedDescription = @"description where description of first where and description of second where"; descriptionWriter.Builder.ToString().Should().BeModuloLineEndings(expectedDescription); } [Fact] public void UseApplicator_should_not_be_callable_more_than_once() { this.rule.UseApplicator(x => { }); var exception = Record.Exception(() => this.rule.UseApplicator(x => { })); exception.Should().BeAnExceptionOfType<InvalidOperationException>(); } [Fact] public void OutAndRefParameterProducer_should_not_be_settable_more_than_once() { this.rule.SetOutAndRefParametersValueProducer(x => Array.Empty<object>()); var exception = Record.Exception(() => this.rule.SetOutAndRefParametersValueProducer(x => new object[] { "test" })); exception.Should().BeAnExceptionOfType<InvalidOperationException>(); } private class DummyableClass { } private static MethodInfo OutAndRefMethod { get { string s = string.Empty; int i = 0; var method = GetMethodInfo<IOutAndRef>(x => x.OutAndRef(new object(), out i, string.Empty, ref s, string.Empty)); return method; } } [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "This class is loaded dynamically as an extension point")] private class DummyableClassFactory : DummyFactory<DummyableClass> { private static readonly DummyableClass Instance = new DummyableClass(); protected override DummyableClass Create() { return Instance; } } private class TestableCallRule : BuildableCallRule { public TestableCallRule() { this.ReturnValueFromOnIsApplicableTo = true; this.DescriptionOfValidCallReturnValue = string.Empty; } public bool ReturnValueFromOnIsApplicableTo { get; set; } public string DescriptionOfValidCallReturnValue { get; set; } public bool OnIsApplicableToWasCalled { get; private set; } public override void DescribeCallOn(IOutputWriter writer) => writer.Write(this.DescriptionOfValidCallReturnValue); public override void UsePredicateToValidateArguments(Func<ArgumentCollection, bool> argumentsPredicate) { } protected override bool OnIsApplicableTo(IFakeObjectCall fakeObjectCall) { this.OnIsApplicableToWasCalled = true; return this.ReturnValueFromOnIsApplicableTo; } protected override BuildableCallRule CloneCallSpecificationCore() { return new TestableCallRule { ReturnValueFromOnIsApplicableTo = this.ReturnValueFromOnIsApplicableTo, DescriptionOfValidCallReturnValue = this.DescriptionOfValidCallReturnValue }; } } } }
// 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: Create a Memorystream over an UnmanagedMemoryStream ** ===========================================================*/ using System; using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Threading; using System.Threading.Tasks; namespace System.IO { // Needed for backwards compatibility with V1.x usages of the // ResourceManager, where a MemoryStream is now returned as an // UnmanagedMemoryStream from ResourceReader. internal sealed class UnmanagedMemoryStreamWrapper : MemoryStream { private UnmanagedMemoryStream _unmanagedStream; internal UnmanagedMemoryStreamWrapper(UnmanagedMemoryStream stream) { _unmanagedStream = stream; } public override bool CanRead { get { return _unmanagedStream.CanRead; } } public override bool CanSeek { get { return _unmanagedStream.CanSeek; } } public override bool CanWrite { get { return _unmanagedStream.CanWrite; } } protected override void Dispose(bool disposing) { try { if (disposing) _unmanagedStream.Dispose(); } finally { base.Dispose(disposing); } } public override void Flush() { _unmanagedStream.Flush(); } public override byte[] GetBuffer() { throw new UnauthorizedAccessException(SR.UnauthorizedAccess_MemStreamBuffer); } public override bool TryGetBuffer(out ArraySegment<byte> buffer) { buffer = default(ArraySegment<byte>); return false; } public override int Capacity { get { return (int)_unmanagedStream.Capacity; } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. set { throw new IOException(SR.IO_FixedCapacity); } } public override long Length { get { return _unmanagedStream.Length; } } public override long Position { get { return _unmanagedStream.Position; } set { _unmanagedStream.Position = value; } } public override int Read(byte[] buffer, int offset, int count) { return _unmanagedStream.Read(buffer, offset, count); } public override int ReadByte() { return _unmanagedStream.ReadByte(); } public override long Seek(long offset, SeekOrigin loc) { return _unmanagedStream.Seek(offset, loc); } public unsafe override byte[] ToArray() { byte[] buffer = new byte[_unmanagedStream.Length]; _unmanagedStream.Read(buffer, 0, (int)_unmanagedStream.Length); return buffer; } public override void Write(byte[] buffer, int offset, int count) { _unmanagedStream.Write(buffer, offset, count); } public override void WriteByte(byte value) { _unmanagedStream.WriteByte(value); } // Writes this MemoryStream to another stream. public unsafe override void WriteTo(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream), SR.ArgumentNull_Stream); Contract.EndContractBlock(); byte[] buffer = ToArray(); stream.Write(buffer, 0, buffer.Length); } public override void SetLength(Int64 value) { // This was probably meant to call _unmanagedStream.SetLength(value), but it was forgotten in V.4.0. // Now this results in a call to the base which touches the underlying array which is never actually used. // We cannot fix it due to compat now, but we should fix this at the next SxS release oportunity. base.SetLength(value); } public override Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) { // The parameter checks must be in sync with the base version: if (destination == null) throw new ArgumentNullException(nameof(destination)); if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); if (!CanRead && !CanWrite) throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); if (!destination.CanRead && !destination.CanWrite) throw new ObjectDisposedException(nameof(destination), SR.ObjectDisposed_StreamClosed); if (!CanRead) throw new NotSupportedException(SR.NotSupported_UnreadableStream); if (!destination.CanWrite) throw new NotSupportedException(SR.NotSupported_UnwritableStream); Contract.EndContractBlock(); return _unmanagedStream.CopyToAsync(destination, bufferSize, cancellationToken); } public override Task FlushAsync(CancellationToken cancellationToken) { return _unmanagedStream.FlushAsync(cancellationToken); } public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) { return _unmanagedStream.ReadAsync(buffer, offset, count, cancellationToken); } public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) { return _unmanagedStream.WriteAsync(buffer, offset, count, cancellationToken); } } // class UnmanagedMemoryStreamWrapper } // namespace
using System; namespace LumiSoft.Net.IMAP.Server { /// <summary> /// Provides utility methods for IMAP. /// </summary> public class IMAP_Utils { #region method ParseMessageFalgs /// <summary> /// Parses message flags from string. /// </summary> /// <param name="falgsString"></param> /// <returns></returns> public static IMAP_MessageFlags ParseMessageFalgs(string falgsString) { IMAP_MessageFlags mFlags = 0; falgsString = falgsString.ToUpper(); if(falgsString.IndexOf("ANSWERED") > -1){ mFlags |= IMAP_MessageFlags.Answered; } if(falgsString.IndexOf("FLAGGED") > -1){ mFlags |= IMAP_MessageFlags.Flagged; } if(falgsString.IndexOf("DELETED") > -1){ mFlags |= IMAP_MessageFlags.Deleted; } if(falgsString.IndexOf("SEEN") > -1){ mFlags |= IMAP_MessageFlags.Seen; } if(falgsString.IndexOf("DRAFT") > -1){ mFlags |= IMAP_MessageFlags.Draft; } return mFlags; } #endregion #region method MessageFlagsToString /// <summary> /// Converts message flags to string. Eg. \SEEN \DELETED . /// </summary> /// <returns></returns> public static string MessageFlagsToString(IMAP_MessageFlags msgFlags) { string retVal = ""; if(((int)IMAP_MessageFlags.Answered & (int)msgFlags) != 0){ retVal += " \\ANSWERED"; } if(((int)IMAP_MessageFlags.Flagged & (int)msgFlags) != 0){ retVal += " \\FLAGGED"; } if(((int)IMAP_MessageFlags.Deleted & (int)msgFlags) != 0){ retVal += " \\DELETED"; } if(((int)IMAP_MessageFlags.Seen & (int)msgFlags) != 0){ retVal += " \\SEEN"; } if(((int)IMAP_MessageFlags.Draft & (int)msgFlags) != 0){ retVal += " \\DRAFT"; } return retVal.Trim(); } #endregion #region method ACL_to_String /// <summary> /// Converts IMAP_ACL_Flags to string. /// </summary> /// <param name="flags">Flags to convert.</param> /// <returns></returns> public static string ACL_to_String(IMAP_ACL_Flags flags) { string retVal = ""; if((flags & IMAP_ACL_Flags.l) != 0){ retVal += "l"; } if((flags & IMAP_ACL_Flags.r) != 0){ retVal += "r"; } if((flags & IMAP_ACL_Flags.s) != 0){ retVal += "s"; } if((flags & IMAP_ACL_Flags.w) != 0){ retVal += "w"; } if((flags & IMAP_ACL_Flags.i) != 0){ retVal += "i"; } if((flags & IMAP_ACL_Flags.p) != 0){ retVal += "p"; } if((flags & IMAP_ACL_Flags.c) != 0){ retVal += "c"; } if((flags & IMAP_ACL_Flags.d) != 0){ retVal += "d"; } if((flags & IMAP_ACL_Flags.a) != 0){ retVal += "a"; } return retVal; } #endregion #region method ACL_From_String /// <summary> /// Parses IMAP_ACL_Flags from string. /// </summary> /// <param name="aclString">String from where to convert</param> /// <returns></returns> public static IMAP_ACL_Flags ACL_From_String(string aclString) { IMAP_ACL_Flags retVal = IMAP_ACL_Flags.None; aclString = aclString.ToLower(); if(aclString.IndexOf('l') > -1){ retVal |= IMAP_ACL_Flags.l; } if(aclString.IndexOf('r') > -1){ retVal |= IMAP_ACL_Flags.r; } if(aclString.IndexOf('s') > -1){ retVal |= IMAP_ACL_Flags.s; } if(aclString.IndexOf('w') > -1){ retVal |= IMAP_ACL_Flags.w; } if(aclString.IndexOf('i') > -1){ retVal |= IMAP_ACL_Flags.i; } if(aclString.IndexOf('p') > -1){ retVal |= IMAP_ACL_Flags.p; } if(aclString.IndexOf('c') > -1){ retVal |= IMAP_ACL_Flags.c; } if(aclString.IndexOf('d') > -1){ retVal |= IMAP_ACL_Flags.d; } if(aclString.IndexOf('a') > -1){ retVal |= IMAP_ACL_Flags.a; } return retVal; } #endregion #region method NormalizeFolder /// <summary> /// Normalizes folder path. Example: /Inbox/SubFolder/ will be Inbox/SubFolder. /// </summary> /// <param name="folder">Folder path to normalize.</param> /// <returns>Returns normalized folder path.</returns> public static string NormalizeFolder(string folder) { folder = folder.Replace("\\","/"); if(folder.StartsWith("/")){ folder = folder.Substring(1); } if(folder.EndsWith("/")){ folder = folder.Substring(0,folder.Length - 1); } return folder; } #endregion #region method ParseQuotedParam /// <summary> /// Parses [quoted] parameter from args text. Parameter may be not quoted, then parameter is /// terminated by SP. Example: argsText="string gdkga agkgs";argsText=stringValue 10. /// /// This method also removes parsed parameter from argsText. /// </summary> /// <param name="argsText">Arguments line from where to parse param.</param> /// <returns></returns> public static string ParseQuotedParam(ref string argsText) { string paramValue = ""; // Get value, it is between "" if(argsText.StartsWith("\"")){ // Find next " not escaped " char lastChar = ' '; int qIndex = -1; for(int i=1;i<argsText.Length;i++){ if(argsText[i] == '\"' && lastChar != '\\'){ qIndex = i; break; } lastChar = argsText[i]; } if(qIndex == -1){ throw new Exception("qouted-string doesn't have enclosing quote(\")"); } paramValue = argsText.Substring(1,qIndex - 1).Replace("\\\"","\""); // Remove <string> value from argsText argsText = argsText.Substring(qIndex + 1).Trim(); } else{ paramValue = argsText.Split(' ')[0]; // Remove <string> value from argsText argsText = argsText.Substring(paramValue.Length).Trim(); } return paramValue; } #endregion #region method ParseBracketParam /// <summary> /// Parses bracket parameter from args text. Parameter may be not between (), then /// then args text is considered as value. Example: (test test);test test. /// /// This method also removes parsed parameter from argsText. /// </summary> /// <param name="argsText"></param> /// <returns></returns> public static string ParseBracketParam(ref string argsText) { string paramValue = ""; if(argsText.StartsWith("(")){ // Find matching ) char lastChar = ' '; int bIndex = -1; int nestedBracketCount = 0; for(int i=1;i<argsText.Length;i++){ // There is nested () if(argsText[i] == '('){ nestedBracketCount++; } else if(argsText[i] == ')'){ if(nestedBracketCount == 0){ bIndex = i; break; } // This was nested bracket ) else{ nestedBracketCount--; } } lastChar = argsText[i]; } if(bIndex == -1){ throw new Exception("bracket doesn't have enclosing bracket ')'"); } paramValue = argsText.Substring(1,bIndex - 1); // Remove <string> value from argsText argsText = argsText.Substring(bIndex + 1).Trim(); } else{ paramValue = argsText; argsText = ""; } return paramValue; } #endregion } }
using System; using System.Runtime.InteropServices; using System.Text; namespace LuaInterface { #pragma warning disable 414 public class MonoPInvokeCallbackAttribute : System.Attribute { private Type type; public MonoPInvokeCallbackAttribute(Type t) { type = t; } } #pragma warning restore 414 public enum LuaTypes : int { LUA_TNONE = -1, LUA_TNIL = 0, LUA_TBOOLEAN = 1, LUA_TLIGHTUSERDATA = 2, LUA_TNUMBER = 3, LUA_TSTRING = 4, LUA_TTABLE = 5, LUA_TFUNCTION = 6, LUA_TUSERDATA = 7, LUA_TTHREAD = 8, } public enum LuaGCOptions { LUA_GCSTOP = 0, LUA_GCRESTART = 1, LUA_GCCOLLECT = 2, LUA_GCCOUNT = 3, LUA_GCCOUNTB = 4, LUA_GCSTEP = 5, LUA_GCSETPAUSE = 6, LUA_GCSETSTEPMUL = 7, } public enum LuaThreadStatus : int { LUA_YIELD = 1, LUA_ERRRUN = 2, LUA_ERRSYNTAX = 3, LUA_ERRMEM = 4, LUA_ERRERR = 5, } public sealed class LuaIndexes { #if LUA_5_3 // for lua5.3 public static int LUA_REGISTRYINDEX = -1000000 - 1000; #else // for lua5.1 or luajit public static int LUA_REGISTRYINDEX = -10000; public static int LUA_GLOBALSINDEX = -10002; #endif } [StructLayout(LayoutKind.Sequential)] public struct ReaderInfo { public String chunkData; public bool finished; } #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int LuaCSFunction(IntPtr luaState); #else public delegate int LuaCSFunction(IntPtr luaState); #endif public delegate string LuaChunkReader(IntPtr luaState, ref ReaderInfo data, ref uint size); public delegate int LuaFunctionCallback(IntPtr luaState); public class LuaDLL { public static int LUA_MULTRET = -1; #if UNITY_IPHONE && !UNITY_EDITOR const string LUADLL = "__Internal"; #else const string LUADLL = "slua"; #endif [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_openextlibs(IntPtr L); // Thread Funcs [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_tothread(IntPtr L, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_xmove(IntPtr from, IntPtr to, int n); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_newthread(IntPtr L); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_status(IntPtr L); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_pushthread(IntPtr L); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_gc(IntPtr luaState, LuaGCOptions what, int data); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_typename(IntPtr luaState, int type); public static string lua_typenamestr(IntPtr luaState, LuaTypes type) { IntPtr p = lua_typename(luaState, (int)type); return Marshal.PtrToStringAnsi(p); } public static string luaL_typename(IntPtr luaState, int stackPos) { return LuaDLL.lua_typenamestr(luaState, LuaDLL.lua_type(luaState, stackPos)); } public static bool lua_isfunction(IntPtr luaState, int stackPos) { return lua_type(luaState, stackPos) == LuaTypes.LUA_TFUNCTION; } public static bool lua_islightuserdata(IntPtr luaState, int stackPos) { return lua_type(luaState, stackPos) == LuaTypes.LUA_TLIGHTUSERDATA; } public static bool lua_istable(IntPtr luaState, int stackPos) { return lua_type(luaState, stackPos) == LuaTypes.LUA_TTABLE; } public static bool lua_isthread(IntPtr luaState, int stackPos) { return lua_type(luaState, stackPos) == LuaTypes.LUA_TTHREAD; } public static void luaL_error(IntPtr luaState, string message) { LuaDLL.luaL_where(luaState, 1); LuaDLL.lua_pushstring(luaState, message); LuaDLL.lua_concat(luaState, 2); LuaDLL.lua_error(luaState); } public static void luaL_error(IntPtr luaState, string fmt, params object[] args) { string str = string.Format(fmt, args); luaL_error(luaState, str); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern string luaL_gsub(IntPtr luaState, string str, string pattern, string replacement); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_isuserdata(IntPtr luaState, int stackPos); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_rawequal(IntPtr luaState, int stackPos1, int stackPos2); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_setfield(IntPtr luaState, int stackPos, string name); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_callmeta(IntPtr luaState, int stackPos, string name); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr luaL_newstate(); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_close(IntPtr luaState); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaL_openlibs(IntPtr luaState); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_loadstring(IntPtr luaState, string chunk); public static int luaL_dostring(IntPtr luaState, string chunk) { int result = LuaDLL.luaL_loadstring(luaState, chunk); if (result != 0) return result; return LuaDLL.lua_pcall(luaState, 0, -1, 0); } public static int lua_dostring(IntPtr luaState, string chunk) { return LuaDLL.luaL_dostring(luaState, chunk); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_createtable(IntPtr luaState, int narr, int nrec); public static void lua_newtable(IntPtr luaState) { LuaDLL.lua_createtable(luaState, 0, 0); } #if LUA_5_3 [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_getglobal(IntPtr luaState, string name); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_setglobal(IntPtr luaState, string name); public static void lua_insert(IntPtr luaState, int newTop) { lua_rotate(luaState, newTop, 1); } public static void lua_pushglobaltable(IntPtr l) { lua_rawgeti(l, LuaIndexes.LUA_REGISTRYINDEX, 2); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_rotate(IntPtr luaState, int index, int n); public static int lua_rawlen(IntPtr luaState, int stackPos) { return LuaDLLWrapper.luaS_rawlen(luaState, stackPos); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_loadbufferx(IntPtr luaState, byte[] buff, int size, string name, IntPtr x); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_callk(IntPtr luaState, int nArgs, int nResults,int ctx,IntPtr k); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_pcallk(IntPtr luaState, int nArgs, int nResults, int errfunc,int ctx,IntPtr k); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_pcall(IntPtr luaState, int nArgs, int nResults, int errfunc); public static int lua_call(IntPtr luaState, int nArgs, int nResults) { return lua_callk(luaState, nArgs, nResults, 0, IntPtr.Zero); } public static int lua_pcall(IntPtr luaState, int nArgs, int nResults, int errfunc) { return luaS_pcall(luaState, nArgs, nResults, errfunc); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern double lua_tonumberx(IntPtr luaState, int index, IntPtr x); public static double lua_tonumber(IntPtr luaState, int index) { return lua_tonumberx(luaState, index, IntPtr.Zero); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern Int64 lua_tointegerx(IntPtr luaState, int index,IntPtr x); public static int lua_tointeger(IntPtr luaState, int index) { return (int)lua_tointegerx(luaState, index, IntPtr.Zero); } public static int luaL_loadbuffer(IntPtr luaState, byte[] buff, int size, string name) { return luaL_loadbufferx(luaState, buff, size, name, IntPtr.Zero); } public static void lua_remove(IntPtr l, int idx) { lua_rotate(l, (idx), -1); lua_pop(l, 1); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawgeti(IntPtr luaState, int tableIndex, Int64 index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawseti(IntPtr luaState, int tableIndex, Int64 index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushinteger(IntPtr luaState, Int64 i); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern Int64 luaL_checkinteger(IntPtr luaState, int stackPos); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_yield(IntPtr luaState,int nrets); public static int lua_yield(IntPtr luaState,int nrets) { return luaS_yield(luaState,nrets); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_resume(IntPtr L, IntPtr from, int narg); public static void lua_replace(IntPtr luaState, int index) { lua_copy(luaState, -1, (index)); lua_pop(luaState, 1); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_copy(IntPtr luaState,int from,int toidx); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_isinteger(IntPtr luaState, int p); #else [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_resume(IntPtr L, int narg); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_lessthan(IntPtr luaState, int stackPos1, int stackPos2); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_getfenv(IntPtr luaState, int stackPos); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_yield(IntPtr L, int nresults); public static void lua_getglobal(IntPtr luaState, string name) { LuaDLL.lua_pushstring(luaState, name); LuaDLL.lua_gettable(luaState, LuaIndexes.LUA_GLOBALSINDEX); } public static void lua_setglobal(IntPtr luaState, string name) { LuaDLL.lua_pushstring(luaState, name); LuaDLL.lua_insert(luaState, -2); LuaDLL.lua_settable(luaState, LuaIndexes.LUA_GLOBALSINDEX); } public static void lua_pushglobaltable(IntPtr l) { LuaDLL.lua_pushvalue(l, LuaIndexes.LUA_GLOBALSINDEX); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_insert(IntPtr luaState, int newTop); public static int lua_rawlen(IntPtr luaState, int stackPos) { return LuaDLLWrapper.luaS_objlen(luaState, stackPos); } public static int lua_strlen(IntPtr luaState, int stackPos) { return lua_rawlen(luaState, stackPos); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_call(IntPtr luaState, int nArgs, int nResults); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_pcall(IntPtr luaState, int nArgs, int nResults, int errfunc); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern double lua_tonumber(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_tointeger(IntPtr luaState, int index); public static int luaL_loadbuffer(IntPtr luaState, byte[] buff, int size, string name) { return LuaDLLWrapper.luaLS_loadbuffer(luaState, buff, size, name); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_remove(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawgeti(IntPtr luaState, int tableIndex, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawseti(IntPtr luaState, int tableIndex, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushinteger(IntPtr luaState, int i); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_checkinteger(IntPtr luaState, int stackPos); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_replace(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_setfenv(IntPtr luaState, int stackPos); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_equal(IntPtr luaState, int index1, int index2); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_loadfile(IntPtr luaState, string filename); #endif [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_settop(IntPtr luaState, int newTop); public static void lua_pop(IntPtr luaState, int amount) { LuaDLL.lua_settop(luaState, -(amount) - 1); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_gettable(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawget(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_settable(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawset(IntPtr luaState, int index); #if LUA_5_3 [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_setmetatable(IntPtr luaState, int objIndex); #else [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_setmetatable(IntPtr luaState, int objIndex); #endif [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_getmetatable(IntPtr luaState, int objIndex); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushvalue(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_gettop(IntPtr luaState); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern LuaTypes lua_type(IntPtr luaState, int index); public static bool lua_isnil(IntPtr luaState, int index) { return (LuaDLL.lua_type(luaState, index) == LuaTypes.LUA_TNIL); } public static bool lua_isnumber(IntPtr luaState, int index) { return LuaDLLWrapper.lua_isnumber(luaState, index) > 0; } public static bool lua_isboolean(IntPtr luaState, int index) { return LuaDLL.lua_type(luaState, index) == LuaTypes.LUA_TBOOLEAN; } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_ref(IntPtr luaState, int registryIndex); public static void lua_getref(IntPtr luaState, int reference) { LuaDLL.lua_rawgeti(luaState, LuaIndexes.LUA_REGISTRYINDEX, reference); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaL_unref(IntPtr luaState, int registryIndex, int reference); public static void lua_unref(IntPtr luaState, int reference) { LuaDLL.luaL_unref(luaState, LuaIndexes.LUA_REGISTRYINDEX, reference); } public static bool lua_isstring(IntPtr luaState, int index) { return LuaDLLWrapper.lua_isstring(luaState, index) > 0; } public static bool lua_iscfunction(IntPtr luaState, int index) { return LuaDLLWrapper.lua_iscfunction(luaState, index) > 0; } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushnil(IntPtr luaState); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaL_checktype(IntPtr luaState, int p, LuaTypes t); public static void lua_pushcfunction(IntPtr luaState, LuaCSFunction function) { IntPtr fn = Marshal.GetFunctionPointerForDelegate(function); lua_pushcclosure(luaState, fn, 0); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_tocfunction(IntPtr luaState, int index); public static bool lua_toboolean(IntPtr luaState, int index) { return LuaDLLWrapper.lua_toboolean(luaState, index) > 0; } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr luaS_tolstring32(IntPtr luaState, int index, out int strLen); public static string lua_tostring(IntPtr luaState, int index) { int strlen; IntPtr str = luaS_tolstring32(luaState, index, out strlen); // fix il2cpp 64 bit if (str != IntPtr.Zero) { return Marshal.PtrToStringAnsi(str, strlen); } return null; } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_atpanic(IntPtr luaState, LuaCSFunction panicf); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushnumber(IntPtr luaState, double number); public static void lua_pushboolean(IntPtr luaState, bool value) { LuaDLLWrapper.lua_pushboolean(luaState, value ? 1 : 0); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushstring(IntPtr luaState, string str); public static void lua_pushlstring(IntPtr luaState, byte[] str, int size) { LuaDLLWrapper.luaS_pushlstring(luaState, str, size); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_newmetatable(IntPtr luaState, string meta); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_getfield(IntPtr luaState, int stackPos, string meta); public static void luaL_getmetatable(IntPtr luaState, string meta) { LuaDLL.lua_getfield(luaState, LuaIndexes.LUA_REGISTRYINDEX, meta); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr luaL_checkudata(IntPtr luaState, int stackPos, string meta); public static bool luaL_getmetafield(IntPtr luaState, int stackPos, string field) { return LuaDLLWrapper.luaL_getmetafield(luaState, stackPos, field) > 0; } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_load(IntPtr luaState, LuaChunkReader chunkReader, ref ReaderInfo data, string chunkName); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_error(IntPtr luaState); public static bool lua_checkstack(IntPtr luaState, int extra) { return LuaDLLWrapper.lua_checkstack(luaState, extra) > 0; } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_next(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushlightuserdata(IntPtr luaState, IntPtr udata); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaL_where(IntPtr luaState, int level); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern double luaL_checknumber(IntPtr luaState, int stackPos); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_concat(IntPtr luaState, int n); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_newuserdata(IntPtr luaState, int val); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_rawnetobj(IntPtr luaState, int obj); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_touserdata(IntPtr luaState, int index); public static int lua_absindex(IntPtr luaState, int index) { return index > 0 ? index : lua_gettop(luaState) + index + 1; } public static int lua_upvalueindex(int i) { #if LUA_5_3 return LuaIndexes.LUA_REGISTRYINDEX - i; #else return LuaIndexes.LUA_GLOBALSINDEX - i; #endif } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushcclosure(IntPtr l, IntPtr f, int nup); public static void lua_pushcclosure(IntPtr l, LuaCSFunction f, int nup) { IntPtr fn = Marshal.GetFunctionPointerForDelegate(f); lua_pushcclosure(l, fn, nup); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_checkVector2(IntPtr l, int p, out float x, out float y); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_checkVector3(IntPtr l, int p, out float x, out float y, out float z); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_checkVector4(IntPtr l, int p, out float x, out float y, out float z, out float w); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_checkQuaternion(IntPtr l, int p, out float x, out float y, out float z, out float w); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_checkColor(IntPtr l, int p, out float x, out float y, out float z, out float w); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_pushVector2(IntPtr l, float x, float y); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_pushVector3(IntPtr l, float x, float y, float z); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_pushVector4(IntPtr l, float x, float y, float z, float w); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_pushQuaternion(IntPtr l, float x, float y, float z, float w); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_pushColor(IntPtr l, float x, float y, float z, float w); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_setData(IntPtr l, int p, float x, float y, float z, float w); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_setDataVec(IntPtr l, int p, float x, float y, float z, float w); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_checkluatype(IntPtr l, int p, string t); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_pushobject(IntPtr l, int index, string t, bool gco, int cref); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_getcacheud(IntPtr l, int index, int cref); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_subclassof(IntPtr l, int index, string t); } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/devtools/cloudtrace/v1/trace.proto // Original file comments: // Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using Grpc.Core; namespace Google.Cloud.Trace.V1 { /// <summary> /// This file describes an API for collecting and viewing traces and spans /// within a trace. A Trace is a collection of spans corresponding to a single /// operation or set of operations for an application. A span is an individual /// timed event which forms a node of the trace tree. Spans for a single trace /// may span multiple services. /// </summary> public static class TraceService { static readonly string __ServiceName = "google.devtools.cloudtrace.v1.TraceService"; static readonly Marshaller<global::Google.Cloud.Trace.V1.ListTracesRequest> __Marshaller_ListTracesRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Trace.V1.ListTracesRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Cloud.Trace.V1.ListTracesResponse> __Marshaller_ListTracesResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Trace.V1.ListTracesResponse.Parser.ParseFrom); static readonly Marshaller<global::Google.Cloud.Trace.V1.GetTraceRequest> __Marshaller_GetTraceRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Trace.V1.GetTraceRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Cloud.Trace.V1.Trace> __Marshaller_Trace = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Trace.V1.Trace.Parser.ParseFrom); static readonly Marshaller<global::Google.Cloud.Trace.V1.PatchTracesRequest> __Marshaller_PatchTracesRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Trace.V1.PatchTracesRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom); static readonly Method<global::Google.Cloud.Trace.V1.ListTracesRequest, global::Google.Cloud.Trace.V1.ListTracesResponse> __Method_ListTraces = new Method<global::Google.Cloud.Trace.V1.ListTracesRequest, global::Google.Cloud.Trace.V1.ListTracesResponse>( MethodType.Unary, __ServiceName, "ListTraces", __Marshaller_ListTracesRequest, __Marshaller_ListTracesResponse); static readonly Method<global::Google.Cloud.Trace.V1.GetTraceRequest, global::Google.Cloud.Trace.V1.Trace> __Method_GetTrace = new Method<global::Google.Cloud.Trace.V1.GetTraceRequest, global::Google.Cloud.Trace.V1.Trace>( MethodType.Unary, __ServiceName, "GetTrace", __Marshaller_GetTraceRequest, __Marshaller_Trace); static readonly Method<global::Google.Cloud.Trace.V1.PatchTracesRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_PatchTraces = new Method<global::Google.Cloud.Trace.V1.PatchTracesRequest, global::Google.Protobuf.WellKnownTypes.Empty>( MethodType.Unary, __ServiceName, "PatchTraces", __Marshaller_PatchTracesRequest, __Marshaller_Empty); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Google.Cloud.Trace.V1.TraceReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of TraceService</summary> public abstract class TraceServiceBase { /// <summary> /// Returns of a list of traces that match the specified filter conditions. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Trace.V1.ListTracesResponse> ListTraces(global::Google.Cloud.Trace.V1.ListTracesRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Gets a single trace by its ID. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Trace.V1.Trace> GetTrace(global::Google.Cloud.Trace.V1.GetTraceRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Sends new traces to Stackdriver Trace or updates existing traces. If the ID /// of a trace that you send matches that of an existing trace, any fields /// in the existing trace and its spans are overwritten by the provided values, /// and any new fields provided are merged with the existing trace data. If the /// ID does not match, a new trace is created. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> PatchTraces(global::Google.Cloud.Trace.V1.PatchTracesRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } } /// <summary>Client for TraceService</summary> public class TraceServiceClient : ClientBase<TraceServiceClient> { /// <summary>Creates a new client for TraceService</summary> /// <param name="channel">The channel to use to make remote calls.</param> public TraceServiceClient(Channel channel) : base(channel) { } /// <summary>Creates a new client for TraceService that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public TraceServiceClient(CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected TraceServiceClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected TraceServiceClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// Returns of a list of traces that match the specified filter conditions. /// </summary> public virtual global::Google.Cloud.Trace.V1.ListTracesResponse ListTraces(global::Google.Cloud.Trace.V1.ListTracesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListTraces(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Returns of a list of traces that match the specified filter conditions. /// </summary> public virtual global::Google.Cloud.Trace.V1.ListTracesResponse ListTraces(global::Google.Cloud.Trace.V1.ListTracesRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListTraces, null, options, request); } /// <summary> /// Returns of a list of traces that match the specified filter conditions. /// </summary> public virtual AsyncUnaryCall<global::Google.Cloud.Trace.V1.ListTracesResponse> ListTracesAsync(global::Google.Cloud.Trace.V1.ListTracesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListTracesAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Returns of a list of traces that match the specified filter conditions. /// </summary> public virtual AsyncUnaryCall<global::Google.Cloud.Trace.V1.ListTracesResponse> ListTracesAsync(global::Google.Cloud.Trace.V1.ListTracesRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListTraces, null, options, request); } /// <summary> /// Gets a single trace by its ID. /// </summary> public virtual global::Google.Cloud.Trace.V1.Trace GetTrace(global::Google.Cloud.Trace.V1.GetTraceRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetTrace(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets a single trace by its ID. /// </summary> public virtual global::Google.Cloud.Trace.V1.Trace GetTrace(global::Google.Cloud.Trace.V1.GetTraceRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetTrace, null, options, request); } /// <summary> /// Gets a single trace by its ID. /// </summary> public virtual AsyncUnaryCall<global::Google.Cloud.Trace.V1.Trace> GetTraceAsync(global::Google.Cloud.Trace.V1.GetTraceRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetTraceAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets a single trace by its ID. /// </summary> public virtual AsyncUnaryCall<global::Google.Cloud.Trace.V1.Trace> GetTraceAsync(global::Google.Cloud.Trace.V1.GetTraceRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetTrace, null, options, request); } /// <summary> /// Sends new traces to Stackdriver Trace or updates existing traces. If the ID /// of a trace that you send matches that of an existing trace, any fields /// in the existing trace and its spans are overwritten by the provided values, /// and any new fields provided are merged with the existing trace data. If the /// ID does not match, a new trace is created. /// </summary> public virtual global::Google.Protobuf.WellKnownTypes.Empty PatchTraces(global::Google.Cloud.Trace.V1.PatchTracesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return PatchTraces(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Sends new traces to Stackdriver Trace or updates existing traces. If the ID /// of a trace that you send matches that of an existing trace, any fields /// in the existing trace and its spans are overwritten by the provided values, /// and any new fields provided are merged with the existing trace data. If the /// ID does not match, a new trace is created. /// </summary> public virtual global::Google.Protobuf.WellKnownTypes.Empty PatchTraces(global::Google.Cloud.Trace.V1.PatchTracesRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_PatchTraces, null, options, request); } /// <summary> /// Sends new traces to Stackdriver Trace or updates existing traces. If the ID /// of a trace that you send matches that of an existing trace, any fields /// in the existing trace and its spans are overwritten by the provided values, /// and any new fields provided are merged with the existing trace data. If the /// ID does not match, a new trace is created. /// </summary> public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> PatchTracesAsync(global::Google.Cloud.Trace.V1.PatchTracesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return PatchTracesAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Sends new traces to Stackdriver Trace or updates existing traces. If the ID /// of a trace that you send matches that of an existing trace, any fields /// in the existing trace and its spans are overwritten by the provided values, /// and any new fields provided are merged with the existing trace data. If the /// ID does not match, a new trace is created. /// </summary> public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> PatchTracesAsync(global::Google.Cloud.Trace.V1.PatchTracesRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_PatchTraces, null, options, request); } protected override TraceServiceClient NewInstance(ClientBaseConfiguration configuration) { return new TraceServiceClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> public static ServerServiceDefinition BindService(TraceServiceBase serviceImpl) { return ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_ListTraces, serviceImpl.ListTraces) .AddMethod(__Method_GetTrace, serviceImpl.GetTrace) .AddMethod(__Method_PatchTraces, serviceImpl.PatchTraces).Build(); } } } #endregion
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection; using System.Diagnostics; using System.Collections.Generic; using System.Reflection.Runtime.General; using System.Reflection.Runtime.TypeInfos; using System.Reflection.Runtime.Assemblies; using System.Reflection.Runtime.CustomAttributes; using Internal.LowLevelLinq; using Internal.Reflection.Tracing; using Internal.Reflection.Core.Execution; using CharSet = System.Runtime.InteropServices.CharSet; using LayoutKind = System.Runtime.InteropServices.LayoutKind; using StructLayoutAttribute = System.Runtime.InteropServices.StructLayoutAttribute; namespace System.Reflection.Runtime.TypeInfos { // // TypeInfos that represent type definitions (i.e. Foo or Foo<>) or constructed generic types (Foo<int>) // that can never be reflection-enabled due to the framework Reflection block. // // These types differ from NoMetadata TypeInfos in that properties that inquire about members, // custom attributes or interfaces return an empty list rather than throwing a MissingMetadataException. // // Since these represent "internal framework types", the app cannot prove we are lying. // internal sealed partial class RuntimeBlockedTypeInfo : RuntimeTypeInfo { private RuntimeBlockedTypeInfo(RuntimeTypeHandle typeHandle, bool isGenericTypeDefinition) { _typeHandle = typeHandle; _isGenericTypeDefinition = isGenericTypeDefinition; } public sealed override Assembly Assembly { get { return CommonRuntimeTypes.Object.Assembly; } } public sealed override bool ContainsGenericParameters { get { return _isGenericTypeDefinition; } } public sealed override IEnumerable<CustomAttributeData> CustomAttributes { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_CustomAttributes(this); #endif return Empty<CustomAttributeData>.Enumerable; } } public sealed override string FullName { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_FullName(this); #endif return GeneratedName; } } public sealed override Guid GUID { get { throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } public sealed override bool IsGenericTypeDefinition { get { return _isGenericTypeDefinition; } } public sealed override string Namespace { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_Namespace(this); #endif return null; // Reflection-blocked framework types report themselves as existing in the "root" namespace. } } public sealed override StructLayoutAttribute StructLayoutAttribute { get { return new StructLayoutAttribute(LayoutKind.Auto) { CharSet = CharSet.Ansi, Pack = 8, Size = 0, }; } } public sealed override string ToString() { return _typeHandle.LastResortString(); } public sealed override int MetadataToken { get { throw new InvalidOperationException(SR.NoMetadataTokenAvailable); } } protected sealed override TypeAttributes GetAttributeFlagsImpl() { return TypeAttributes.Class | TypeAttributes.NotPublic; } protected sealed override int InternalGetHashCode() { return _typeHandle.GetHashCode(); } // // Returns the anchoring typedef that declares the members that this type wants returned by the Declared*** properties. // The Declared*** properties will project the anchoring typedef's members by overriding their DeclaringType property with "this" // and substituting the value of this.TypeContext into any generic parameters. // // Default implementation returns null which causes the Declared*** properties to return no members. // // Note that this does not apply to DeclaredNestedTypes. Nested types and their containers have completely separate generic instantiation environments // (despite what C# might lead you to think.) Constructed generic types return the exact same same nested types that its generic type definition does // - i.e. their DeclaringTypes refer back to the generic type definition, not the constructed generic type.) // // Note also that we cannot use this anchoring concept for base types because of generic parameters. Generic parameters return // baseclass and interfaces based on its constraints. // internal sealed override RuntimeNamedTypeInfo AnchoringTypeDefinitionForDeclaredMembers { get { return null; // this causes the type to report having no members. } } internal sealed override bool CanBrowseWithoutMissingMetadataExceptions => true; internal sealed override RuntimeTypeInfo[] RuntimeGenericTypeParameters { get { throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } internal sealed override Type InternalDeclaringType { get { return null; } } public sealed override string InternalGetNameIfAvailable(ref Type rootCauseForFailure) { return GeneratedName; } internal sealed override string InternalFullNameOfAssembly { get { return GeneratedName; } } internal sealed override RuntimeTypeHandle InternalTypeHandleIfAvailable { get { return _typeHandle; } } // // Returns the base type as a typeDef, Ref, or Spec. Default behavior is to QTypeDefRefOrSpec.Null, which causes BaseType to return null. // internal sealed override QTypeDefRefOrSpec TypeRefDefOrSpecForBaseType { get { throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } // // Returns the *directly implemented* interfaces as typedefs, specs or refs. ImplementedInterfaces will take care of the transitive closure and // insertion of the TypeContext. // internal sealed override QTypeDefRefOrSpec[] TypeRefDefOrSpecsForDirectlyImplementedInterfaces { get { throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } // // Returns the generic parameter substitutions to use when enumerating declared members, base class and implemented interfaces. // internal sealed override TypeContext TypeContext { get { throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(this); } } private string GeneratedName { get { return _lazyGeneratedName ?? (_lazyGeneratedName = BlockedRuntimeTypeNameGenerator.GetNameForBlockedRuntimeType(_typeHandle)); } } private readonly RuntimeTypeHandle _typeHandle; private readonly bool _isGenericTypeDefinition; private volatile string _lazyGeneratedName; } }
/* transpiled with BefunCompile v1.3.0 (c) 2017 */ public static class Program { private static readonly string _g = "AR+LCAAAAAAABACtkrFyhCAQhl+FQ6+RMbdy4kXCMCnyECkYTJEZWioqHz4/RM85c13UUWB32f32h8Q+85t/BzzVP54j6jP2fgTJyxEk4QgSOoLEj7WtWGXuhvTgTrtw"+ "s9rMzlGzNPmq5d/ciU6vXmNrbrjtWq1HoYIbRRd15aearM6ma1BKnPE1ydJIUVotKSIJ3I2k0FZpqv180m0XlXh1baBboCFSv1XeLodxyzqhqK7Bg2Xem3FsrteFHkkH"+ "iqU2CvSqaZobRbI3CgOFr9OsiixABzX9EpNbdPD3WvyNg6JhOpCMin9wiqYSq3dQy2TW4B4d6XgVo2E2I7QndLUJgpq5S8B0rSTPujUJrekg4gfvsiwEdSwiddNTZJu0"+ "pRdWmkGDgPWRBoENwYiVfLKbZCkfFTQSRZoF8oz4yKi/YNTCJBA7cRFKhev+tMvVmJJ3ARu1NsTqPyEJ2aHJk52ZTqJxkrh79wi/Cy0JbRa6nZ/lWMZyN7IuNIpAYz6O"+ "K+TCXDZgPxd+GB4AfwDY6hCc2gQAAA=="; private static readonly long[] g = System.Array.ConvertAll(zd(System.Convert.FromBase64String(_g)),b=>(long)b); private static byte[]zd(byte[]o){byte[]d=System.Linq.Enumerable.ToArray(System.Linq.Enumerable.Skip(o, 1));for(int i=0;i<o[0];i++)d=zs(d);return d;} private static byte[]zs(byte[]o){using(var c=new System.IO.MemoryStream(o)) using(var z=new System.IO.Compression.GZipStream(c,System.IO.Compression.CompressionMode.Decompress)) using(var r=new System.IO.MemoryStream()){z.CopyTo(r);return r.ToArray();}} private static long gr(long x,long y){return(x>=0&&y>=0&&x<69&&y<18)?g[y*69+x]:0;} private static void gw(long x,long y,long v){if(x>=0&&y>=0&&x<69&&y<18)g[y*69+x]=v;} private static long td(long a,long b){ return (b==0)?0:(a/b); } private static long tm(long a,long b){ return (b==0)?0:(a%b); } private static System.Collections.Generic.Stack<long> s=new System.Collections.Generic.Stack<long>(); private static long sp(){ return (s.Count==0)?0:s.Pop(); } private static void sa(long v){ s.Push(v); } private static long sr(){ return (s.Count==0)?0:s.Peek(); } static void Main(string[]args) { long t0,t1,t2; gw(9,0,0); gw(2,0,2); sa(2); _1: sa(100); sa(10000-gr(2,0)); _2: if(sp()!=0)goto _3;else goto _26; _3: sa(sp()-1L); sa(sr()); if(sp()!=0)goto _4;else goto _5; _4: sa(sr()); sa(sr()); sa(sp()*sp()); sa(sp()-gr(2,0)); goto _2; _5: gw(68,1,0); gw(68,3,0); gw(68,5,0); sp(); sa(sr()); sa(59); sa(59); _6: if(sp()!=0)goto _34;else goto _7; _7: sp(); gw(68,1,sp()); gw(2,0,0); sa(100); _8: gw(4,0,gr(2,0)*gr(2,0)); t0=((gr(68,3)*gr(2,0)*20)+gr(4,0))%100; gw(4,0,((gr(68,3)*gr(2,0)*20)+gr(4,0))/100); gw(68,5,t0); sa(59); sa(59); _9: if(sp()!=0)goto _33;else goto _10; _10: sp(); sa(0); sa(gr(9,5)-gr(9,1)); _11: if(sp()!=0)goto _15;else goto _12; _12: sa(sp()+1L); if(sr()!=60)goto _13;else goto _14; _13: sa(sr()); t0=gr(sr()+9,5); sa(sp()+9L); sa(1); {long v0=sp();t1=gr(sp(),v0);} sa(t0-t1); goto _11; _14: gw(2,0,gr(2,0)+1); sp(); goto _8; _15: sa(sr()); t0=gr(sr()+9,5); sa(sp()+9L); sa(1); {long v0=sp();t1=gr(sp(),v0);} t2=t0>t1?1:0; if((t2)!=0)goto _16;else goto _14; _16: gw(2,0,gr(2,0)-1); gw(68,5,0); gw(4,0,gr(2,0)*gr(2,0)); gw(6,0,gr(68,1)-gr(4,0)); gw(7,0,gr(68,3)*gr(2,0)*20); sp(); sa(59); sa(59); _17: t0=0; _18: if(gr(7,0)>gr(6,0))goto _32;else goto _19; _19: gw(4,0,t0); sa(gr(6,0)-gr(7,0)); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(sp()+8L); sa(5); {long v0=sp();long v1=sp();gw(v1,v0,sp());} sa(sp()-1L); sa(sr()); if(sp()!=0)goto _20;else goto _21; _20: sa(sr()); gw(6,0,gr(sr()+9,1)-gr(4,0)); gw(7,0,gr(sr()+9,3)*gr(2,0)*20); goto _17; _21: gw(68,1,gr(68,5)); sp(); sa(59); sa(59); _22: if(sp()!=0)goto _31;else goto _23; _23: gw(9,3,((gr(9,3)%10)*10)+(gr(10,3)/10)); sp(); sa(1); sa(-58); _24: if(sp()!=0)goto _30;else goto _25; _25: gw(68,3,((gr(68,3)%10)*10)+gr(2,0)); gw(9,0,gr(2,0)+gr(9,0)); gw(2,0,0); sp(); sa(sp()-1L); sa(sr()); if(sp()!=0)goto _8;else goto _26; _26: sp(); sa(sr()+1); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(sp()-100L); if(sp()!=0)goto _28;else goto _29; _28: sa(sr()); gw(2,0,sp()); goto _1; _29: System.Console.Out.Write(gr(9,0)+" "); sp(); return; _30: sa(sr()); sa(sr()); t0=(gr(sr()+9,3)%10)*10; sa(sp()+10L); sa(3); {long v0=sp();t1=gr(sp(),v0);} t1/=10; sa(t0+t1); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(sp()+9L); sa(3); {long v0=sp();long v1=sp();gw(v1,v0,sp());} sa(sp()+1L); sa(sr()-59); goto _24; _31: sa(sp()-1L); sa(sr()); sa(gr(sr()+9,5)); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(sp()+9L); sa(1); {long v0=sp();long v1=sp();gw(v1,v0,sp());} sa(sr()); goto _22; _32: gw(6,0,gr(6,0)+100); t0++; goto _18; _33: sa(sp()-1L); sa(sr()); sa((gr(sr()+9,3)*gr(2,0)*20)+gr(4,0)); gw(4,0,sr()/100); sa(sp()%100L); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(sp()+9L); sa(5); {long v0=sp();long v1=sp();gw(v1,v0,sp());} sa(sr()); goto _9; _34: sa(sp()-1L); sa(sr()); sa(0); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(sp()+9L); sa(1); {long v0=sp();long v1=sp();gw(v1,v0,sp());} sa(sr()); sa(0); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(sp()+9L); sa(3); {long v0=sp();long v1=sp();gw(v1,v0,sp());} sa(sr()); sa(0); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(sp()+9L); sa(5); {long v0=sp();long v1=sp();gw(v1,v0,sp());} sa(sr()); goto _6; } }
using OpenSim.Framework; using OpenSim.Region.OptionalModules.Scripting; /* * 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 copyrightD * 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 OMV = OpenMetaverse; namespace OpenSim.Region.Physics.BulletSPlugin { public class BSPrimLinkable : BSPrimDisplaced { // The purpose of this subclass is to add linkset functionality to the prim. This overrides // operations necessary for keeping the linkset created and, additionally, this // calls the linkset implementation for its creation and management. #pragma warning disable 414 private static readonly string LogHeader = "[BULLETS PRIMLINKABLE]"; #pragma warning restore 414 // This adds the overrides for link() and delink() so the prim is linkable. public BSLinkset Linkset { get; set; } // The index of this child prim. public int LinksetChildIndex { get; set; } public BSLinkset.LinksetImplementation LinksetType { get; set; } public BSPrimLinkable(uint localID, String primName, BSScene parent_scene, OMV.Vector3 pos, OMV.Vector3 size, OMV.Quaternion rotation, PrimitiveBaseShape pbs, bool pisPhysical) : base(localID, primName, parent_scene, pos, size, rotation, pbs, pisPhysical) { // Default linkset implementation for this prim LinksetType = (BSLinkset.LinksetImplementation)BSParam.LinksetImplementation; Linkset = BSLinkset.Factory(PhysScene, this); Linkset.Refresh(this); } public override void Destroy() { Linkset = Linkset.RemoveMeFromLinkset(this, false /* inTaintTime */); base.Destroy(); } public override void link(Manager.PhysicsActor obj) { BSPrimLinkable parent = obj as BSPrimLinkable; if (parent != null) { BSPhysObject parentBefore = Linkset.LinksetRoot; // DEBUG int childrenBefore = Linkset.NumberOfChildren; // DEBUG Linkset = parent.Linkset.AddMeToLinkset(this); DetailLog("{0},BSPrimLinkable.link,call,parentBefore={1}, childrenBefore=={2}, parentAfter={3}, childrenAfter={4}", LocalID, parentBefore.LocalID, childrenBefore, Linkset.LinksetRoot.LocalID, Linkset.NumberOfChildren); } return; } public override void delink() { // TODO: decide if this parent checking needs to happen at taint time // Race condition here: if link() and delink() in same simulation tick, the delink will not happen BSPhysObject parentBefore = Linkset.LinksetRoot; // DEBUG int childrenBefore = Linkset.NumberOfChildren; // DEBUG Linkset = Linkset.RemoveMeFromLinkset(this, false /* inTaintTime*/); DetailLog("{0},BSPrimLinkable.delink,parentBefore={1},childrenBefore={2},parentAfter={3},childrenAfter={4}, ", LocalID, parentBefore.LocalID, childrenBefore, Linkset.LinksetRoot.LocalID, Linkset.NumberOfChildren); return; } // When simulator changes position, this might be moving a child of the linkset. public override OMV.Vector3 Position { get { return base.Position; } set { base.Position = value; PhysScene.TaintedObject(LocalID, "BSPrimLinkable.setPosition", delegate() { Linkset.UpdateProperties(UpdatedProperties.Position, this); }); } } // When simulator changes orientation, this might be moving a child of the linkset. public override OMV.Quaternion Orientation { get { return base.Orientation; } set { base.Orientation = value; PhysScene.TaintedObject(LocalID, "BSPrimLinkable.setOrientation", delegate() { Linkset.UpdateProperties(UpdatedProperties.Orientation, this); }); } } public override float TotalMass { get { return Linkset.LinksetMass; } } public override OMV.Vector3 CenterOfMass { get { return Linkset.CenterOfMass; } } public override OMV.Vector3 GeometricCenter { get { return Linkset.GeometricCenter; } } // Refresh the linkset structure and parameters when the prim's physical parameters are changed. public override void UpdatePhysicalParameters() { base.UpdatePhysicalParameters(); // Recompute any linkset parameters. // When going from non-physical to physical, this re-enables the constraints that // had been automatically disabled when the mass was set to zero. // For compound based linksets, this enables and disables interactions of the children. if (Linkset != null) // null can happen during initialization Linkset.Refresh(this); } // When the prim is made dynamic or static, the linkset needs to change. protected override void MakeDynamic(bool makeStatic) { base.MakeDynamic(makeStatic); if (Linkset != null) // null can happen during initialization { if (makeStatic) Linkset.MakeStatic(this); else Linkset.MakeDynamic(this); } } // Body is being taken apart. Remove physical dependencies and schedule a rebuild. protected override void RemoveDependencies() { Linkset.RemoveDependencies(this); base.RemoveDependencies(); } // Called after a simulation step for the changes in physical object properties. // Do any filtering/modification needed for linksets. public override void UpdateProperties(EntityProperties entprop) { if (Linkset.IsRoot(this) || Linkset.ShouldReportPropertyUpdates(this)) { // Properties are only updated for the roots of a linkset. // TODO: this will have to change when linksets are articulated. base.UpdateProperties(entprop); } /* else { // For debugging, report the movement of children DetailLog("{0},BSPrim.UpdateProperties,child,pos={1},orient={2},vel={3},accel={4},rotVel={5}", LocalID, entprop.Position, entprop.Rotation, entprop.Velocity, entprop.Acceleration, entprop.RotationalVelocity); } */ // The linkset might like to know about changing locations Linkset.UpdateProperties(UpdatedProperties.EntPropUpdates, this); } // Called after a simulation step to post a collision with this object. // This returns 'true' if the collision has been queued and the SendCollisions call must // be made at the end of the simulation step. public override bool Collide(uint collidingWith, BSPhysObject collidee, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth) { bool ret = false; // Ask the linkset if it wants to handle the collision if (!Linkset.HandleCollide(collidingWith, collidee, contactPoint, contactNormal, pentrationDepth)) { // The linkset didn't handle it so pass the collision through normal processing ret = base.Collide(collidingWith, collidee, contactPoint, contactNormal, pentrationDepth); } return ret; } // A linkset reports any collision on any part of the linkset. public long SomeCollisionSimulationStep = 0; public override bool HasSomeCollision { get { return (SomeCollisionSimulationStep == PhysScene.SimulationStep) || base.IsColliding; } set { if (value) SomeCollisionSimulationStep = PhysScene.SimulationStep; else SomeCollisionSimulationStep = 0; base.HasSomeCollision = value; } } // Convert the existing linkset of this prim into a new type. public bool ConvertLinkset(BSLinkset.LinksetImplementation newType) { bool ret = false; if (LinksetType != newType) { DetailLog("{0},BSPrimLinkable.ConvertLinkset,oldT={1},newT={2}", LocalID, LinksetType, newType); // Set the implementation type first so the call to BSLinkset.Factory gets the new type. this.LinksetType = newType; BSLinkset oldLinkset = this.Linkset; BSLinkset newLinkset = BSLinkset.Factory(PhysScene, this); this.Linkset = newLinkset; // Pick up any physical dependencies this linkset might have in the physics engine. oldLinkset.RemoveDependencies(this); // Create a list of the children (mainly because can't interate through a list that's changing) List<BSPrimLinkable> children = new List<BSPrimLinkable>(); oldLinkset.ForEachMember((child) => { if (!oldLinkset.IsRoot(child)) children.Add(child); return false; // 'false' says to continue to next member }); // Remove the children from the old linkset and add to the new (will be a new instance from the factory) foreach (BSPrimLinkable child in children) { oldLinkset.RemoveMeFromLinkset(child, true /*inTaintTime*/); } foreach (BSPrimLinkable child in children) { newLinkset.AddMeToLinkset(child); child.Linkset = newLinkset; } // Force the shape and linkset to get reconstructed newLinkset.Refresh(this); this.ForceBodyShapeRebuild(true /* inTaintTime */); } return ret; } #region Extension public override object Extension(string pFunct, params object[] pParams) { DetailLog("{0} BSPrimLinkable.Extension,op={1},nParam={2}", LocalID, pFunct, pParams.Length); object ret = null; switch (pFunct) { // physGetLinksetType(); // pParams = [ BSPhysObject root, null ] case ExtendedPhysics.PhysFunctGetLinksetType: { ret = (object)LinksetType; DetailLog("{0},BSPrimLinkable.Extension.physGetLinksetType,type={1}", LocalID, ret); break; } // physSetLinksetType(type); // pParams = [ BSPhysObject root, null, integer type ] case ExtendedPhysics.PhysFunctSetLinksetType: { if (pParams.Length > 2) { BSLinkset.LinksetImplementation linksetType = (BSLinkset.LinksetImplementation)pParams[2]; if (Linkset.IsRoot(this)) { PhysScene.TaintedObject(LocalID, "BSPrim.PhysFunctSetLinksetType", delegate() { // Cause the linkset type to change DetailLog("{0},BSPrimLinkable.Extension.physSetLinksetType, oldType={1},newType={2}", LocalID, Linkset.LinksetImpl, linksetType); ConvertLinkset(linksetType); }); } ret = (object)(int)linksetType; } break; } // physChangeLinkType(linknum, typeCode); // pParams = [ BSPhysObject root, BSPhysObject child, integer linkType ] case ExtendedPhysics.PhysFunctChangeLinkType: { ret = Linkset.Extension(pFunct, pParams); break; } // physGetLinkType(linknum); // pParams = [ BSPhysObject root, BSPhysObject child ] case ExtendedPhysics.PhysFunctGetLinkType: { ret = Linkset.Extension(pFunct, pParams); break; } // physChangeLinkParams(linknum, [code, value, code, value, ...]); // pParams = [ BSPhysObject root, BSPhysObject child, object[] [ string op, object opParam, string op, object opParam, ... ] ] case ExtendedPhysics.PhysFunctChangeLinkParams: { ret = Linkset.Extension(pFunct, pParams); break; } default: ret = base.Extension(pFunct, pParams); break; } return ret; } #endregion // Extension } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // // This file was autogenerated by a tool. // Do not modify it. // namespace Microsoft.Azure.Batch { using Models = Microsoft.Azure.Batch.Protocol.Models; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// A pool in the Azure Batch service. /// </summary> public partial class CloudPool : ITransportObjectProvider<Models.PoolAddParameter>, IInheritedBehaviors, IPropertyMetadata { private class PropertyContainer : PropertyCollection { public readonly PropertyAccessor<Common.AllocationState?> AllocationStateProperty; public readonly PropertyAccessor<DateTime?> AllocationStateTransitionTimeProperty; public readonly PropertyAccessor<IList<string>> ApplicationLicensesProperty; public readonly PropertyAccessor<IList<ApplicationPackageReference>> ApplicationPackageReferencesProperty; public readonly PropertyAccessor<bool?> AutoScaleEnabledProperty; public readonly PropertyAccessor<TimeSpan?> AutoScaleEvaluationIntervalProperty; public readonly PropertyAccessor<string> AutoScaleFormulaProperty; public readonly PropertyAccessor<AutoScaleRun> AutoScaleRunProperty; public readonly PropertyAccessor<IList<CertificateReference>> CertificateReferencesProperty; public readonly PropertyAccessor<CloudServiceConfiguration> CloudServiceConfigurationProperty; public readonly PropertyAccessor<DateTime?> CreationTimeProperty; public readonly PropertyAccessor<int?> CurrentDedicatedComputeNodesProperty; public readonly PropertyAccessor<int?> CurrentLowPriorityComputeNodesProperty; public readonly PropertyAccessor<string> DisplayNameProperty; public readonly PropertyAccessor<string> ETagProperty; public readonly PropertyAccessor<string> IdProperty; public readonly PropertyAccessor<BatchPoolIdentity> IdentityProperty; public readonly PropertyAccessor<bool?> InterComputeNodeCommunicationEnabledProperty; public readonly PropertyAccessor<DateTime?> LastModifiedProperty; public readonly PropertyAccessor<IList<MetadataItem>> MetadataProperty; public readonly PropertyAccessor<IList<MountConfiguration>> MountConfigurationProperty; public readonly PropertyAccessor<NetworkConfiguration> NetworkConfigurationProperty; public readonly PropertyAccessor<IReadOnlyList<ResizeError>> ResizeErrorsProperty; public readonly PropertyAccessor<TimeSpan?> ResizeTimeoutProperty; public readonly PropertyAccessor<StartTask> StartTaskProperty; public readonly PropertyAccessor<Common.PoolState?> StateProperty; public readonly PropertyAccessor<DateTime?> StateTransitionTimeProperty; public readonly PropertyAccessor<PoolStatistics> StatisticsProperty; public readonly PropertyAccessor<int?> TargetDedicatedComputeNodesProperty; public readonly PropertyAccessor<int?> TargetLowPriorityComputeNodesProperty; public readonly PropertyAccessor<TaskSchedulingPolicy> TaskSchedulingPolicyProperty; public readonly PropertyAccessor<int?> TaskSlotsPerNodeProperty; public readonly PropertyAccessor<string> UrlProperty; public readonly PropertyAccessor<IList<UserAccount>> UserAccountsProperty; public readonly PropertyAccessor<VirtualMachineConfiguration> VirtualMachineConfigurationProperty; public readonly PropertyAccessor<string> VirtualMachineSizeProperty; public PropertyContainer() : base(BindingState.Unbound) { this.AllocationStateProperty = this.CreatePropertyAccessor<Common.AllocationState?>(nameof(AllocationState), BindingAccess.None); this.AllocationStateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(AllocationStateTransitionTime), BindingAccess.None); this.ApplicationLicensesProperty = this.CreatePropertyAccessor<IList<string>>(nameof(ApplicationLicenses), BindingAccess.Read | BindingAccess.Write); this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor<IList<ApplicationPackageReference>>(nameof(ApplicationPackageReferences), BindingAccess.Read | BindingAccess.Write); this.AutoScaleEnabledProperty = this.CreatePropertyAccessor<bool?>(nameof(AutoScaleEnabled), BindingAccess.Read | BindingAccess.Write); this.AutoScaleEvaluationIntervalProperty = this.CreatePropertyAccessor<TimeSpan?>(nameof(AutoScaleEvaluationInterval), BindingAccess.Read | BindingAccess.Write); this.AutoScaleFormulaProperty = this.CreatePropertyAccessor<string>(nameof(AutoScaleFormula), BindingAccess.Read | BindingAccess.Write); this.AutoScaleRunProperty = this.CreatePropertyAccessor<AutoScaleRun>(nameof(AutoScaleRun), BindingAccess.None); this.CertificateReferencesProperty = this.CreatePropertyAccessor<IList<CertificateReference>>(nameof(CertificateReferences), BindingAccess.Read | BindingAccess.Write); this.CloudServiceConfigurationProperty = this.CreatePropertyAccessor<CloudServiceConfiguration>(nameof(CloudServiceConfiguration), BindingAccess.Read | BindingAccess.Write); this.CreationTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(CreationTime), BindingAccess.None); this.CurrentDedicatedComputeNodesProperty = this.CreatePropertyAccessor<int?>(nameof(CurrentDedicatedComputeNodes), BindingAccess.None); this.CurrentLowPriorityComputeNodesProperty = this.CreatePropertyAccessor<int?>(nameof(CurrentLowPriorityComputeNodes), BindingAccess.None); this.DisplayNameProperty = this.CreatePropertyAccessor<string>(nameof(DisplayName), BindingAccess.Read | BindingAccess.Write); this.ETagProperty = this.CreatePropertyAccessor<string>(nameof(ETag), BindingAccess.None); this.IdProperty = this.CreatePropertyAccessor<string>(nameof(Id), BindingAccess.Read | BindingAccess.Write); this.IdentityProperty = this.CreatePropertyAccessor<BatchPoolIdentity>(nameof(Identity), BindingAccess.Read | BindingAccess.Write); this.InterComputeNodeCommunicationEnabledProperty = this.CreatePropertyAccessor<bool?>(nameof(InterComputeNodeCommunicationEnabled), BindingAccess.Read | BindingAccess.Write); this.LastModifiedProperty = this.CreatePropertyAccessor<DateTime?>(nameof(LastModified), BindingAccess.None); this.MetadataProperty = this.CreatePropertyAccessor<IList<MetadataItem>>(nameof(Metadata), BindingAccess.Read | BindingAccess.Write); this.MountConfigurationProperty = this.CreatePropertyAccessor<IList<MountConfiguration>>(nameof(MountConfiguration), BindingAccess.Read | BindingAccess.Write); this.NetworkConfigurationProperty = this.CreatePropertyAccessor<NetworkConfiguration>(nameof(NetworkConfiguration), BindingAccess.Read | BindingAccess.Write); this.ResizeErrorsProperty = this.CreatePropertyAccessor<IReadOnlyList<ResizeError>>(nameof(ResizeErrors), BindingAccess.None); this.ResizeTimeoutProperty = this.CreatePropertyAccessor<TimeSpan?>(nameof(ResizeTimeout), BindingAccess.Read | BindingAccess.Write); this.StartTaskProperty = this.CreatePropertyAccessor<StartTask>(nameof(StartTask), BindingAccess.Read | BindingAccess.Write); this.StateProperty = this.CreatePropertyAccessor<Common.PoolState?>(nameof(State), BindingAccess.None); this.StateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(StateTransitionTime), BindingAccess.None); this.StatisticsProperty = this.CreatePropertyAccessor<PoolStatistics>(nameof(Statistics), BindingAccess.None); this.TargetDedicatedComputeNodesProperty = this.CreatePropertyAccessor<int?>(nameof(TargetDedicatedComputeNodes), BindingAccess.Read | BindingAccess.Write); this.TargetLowPriorityComputeNodesProperty = this.CreatePropertyAccessor<int?>(nameof(TargetLowPriorityComputeNodes), BindingAccess.Read | BindingAccess.Write); this.TaskSchedulingPolicyProperty = this.CreatePropertyAccessor<TaskSchedulingPolicy>(nameof(TaskSchedulingPolicy), BindingAccess.Read | BindingAccess.Write); this.TaskSlotsPerNodeProperty = this.CreatePropertyAccessor<int?>(nameof(TaskSlotsPerNode), BindingAccess.Read | BindingAccess.Write); this.UrlProperty = this.CreatePropertyAccessor<string>(nameof(Url), BindingAccess.None); this.UserAccountsProperty = this.CreatePropertyAccessor<IList<UserAccount>>(nameof(UserAccounts), BindingAccess.Read | BindingAccess.Write); this.VirtualMachineConfigurationProperty = this.CreatePropertyAccessor<VirtualMachineConfiguration>(nameof(VirtualMachineConfiguration), BindingAccess.Read | BindingAccess.Write); this.VirtualMachineSizeProperty = this.CreatePropertyAccessor<string>(nameof(VirtualMachineSize), BindingAccess.Read | BindingAccess.Write); } public PropertyContainer(Models.CloudPool protocolObject) : base(BindingState.Bound) { this.AllocationStateProperty = this.CreatePropertyAccessor( UtilitiesInternal.MapNullableEnum<Models.AllocationState, Common.AllocationState>(protocolObject.AllocationState), nameof(AllocationState), BindingAccess.Read); this.AllocationStateTransitionTimeProperty = this.CreatePropertyAccessor( protocolObject.AllocationStateTransitionTime, nameof(AllocationStateTransitionTime), BindingAccess.Read); this.ApplicationLicensesProperty = this.CreatePropertyAccessor( UtilitiesInternal.CollectionToThreadSafeCollection(protocolObject.ApplicationLicenses, o => o), nameof(ApplicationLicenses), BindingAccess.Read); this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor( ApplicationPackageReference.ConvertFromProtocolCollection(protocolObject.ApplicationPackageReferences), nameof(ApplicationPackageReferences), BindingAccess.Read | BindingAccess.Write); this.AutoScaleEnabledProperty = this.CreatePropertyAccessor( protocolObject.EnableAutoScale, nameof(AutoScaleEnabled), BindingAccess.Read); this.AutoScaleEvaluationIntervalProperty = this.CreatePropertyAccessor( protocolObject.AutoScaleEvaluationInterval, nameof(AutoScaleEvaluationInterval), BindingAccess.Read); this.AutoScaleFormulaProperty = this.CreatePropertyAccessor( protocolObject.AutoScaleFormula, nameof(AutoScaleFormula), BindingAccess.Read); this.AutoScaleRunProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.AutoScaleRun, o => new AutoScaleRun(o).Freeze()), nameof(AutoScaleRun), BindingAccess.Read); this.CertificateReferencesProperty = this.CreatePropertyAccessor( CertificateReference.ConvertFromProtocolCollection(protocolObject.CertificateReferences), nameof(CertificateReferences), BindingAccess.Read | BindingAccess.Write); this.CloudServiceConfigurationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.CloudServiceConfiguration, o => new CloudServiceConfiguration(o).Freeze()), nameof(CloudServiceConfiguration), BindingAccess.Read); this.CreationTimeProperty = this.CreatePropertyAccessor( protocolObject.CreationTime, nameof(CreationTime), BindingAccess.Read); this.CurrentDedicatedComputeNodesProperty = this.CreatePropertyAccessor( protocolObject.CurrentDedicatedNodes, nameof(CurrentDedicatedComputeNodes), BindingAccess.Read); this.CurrentLowPriorityComputeNodesProperty = this.CreatePropertyAccessor( protocolObject.CurrentLowPriorityNodes, nameof(CurrentLowPriorityComputeNodes), BindingAccess.Read); this.DisplayNameProperty = this.CreatePropertyAccessor( protocolObject.DisplayName, nameof(DisplayName), BindingAccess.Read); this.ETagProperty = this.CreatePropertyAccessor( protocolObject.ETag, nameof(ETag), BindingAccess.Read); this.IdProperty = this.CreatePropertyAccessor( protocolObject.Id, nameof(Id), BindingAccess.Read); this.IdentityProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Identity, o => new BatchPoolIdentity(o)), nameof(Identity), BindingAccess.Read | BindingAccess.Write); this.InterComputeNodeCommunicationEnabledProperty = this.CreatePropertyAccessor( protocolObject.EnableInterNodeCommunication, nameof(InterComputeNodeCommunicationEnabled), BindingAccess.Read); this.LastModifiedProperty = this.CreatePropertyAccessor( protocolObject.LastModified, nameof(LastModified), BindingAccess.Read); this.MetadataProperty = this.CreatePropertyAccessor( MetadataItem.ConvertFromProtocolCollection(protocolObject.Metadata), nameof(Metadata), BindingAccess.Read | BindingAccess.Write); this.MountConfigurationProperty = this.CreatePropertyAccessor( Batch.MountConfiguration.ConvertFromProtocolCollectionAndFreeze(protocolObject.MountConfiguration), nameof(MountConfiguration), BindingAccess.Read); this.NetworkConfigurationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.NetworkConfiguration, o => new NetworkConfiguration(o).Freeze()), nameof(NetworkConfiguration), BindingAccess.Read); this.ResizeErrorsProperty = this.CreatePropertyAccessor( ResizeError.ConvertFromProtocolCollectionReadOnly(protocolObject.ResizeErrors), nameof(ResizeErrors), BindingAccess.Read); this.ResizeTimeoutProperty = this.CreatePropertyAccessor( protocolObject.ResizeTimeout, nameof(ResizeTimeout), BindingAccess.Read); this.StartTaskProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.StartTask, o => new StartTask(o)), nameof(StartTask), BindingAccess.Read | BindingAccess.Write); this.StateProperty = this.CreatePropertyAccessor( UtilitiesInternal.MapNullableEnum<Models.PoolState, Common.PoolState>(protocolObject.State), nameof(State), BindingAccess.Read); this.StateTransitionTimeProperty = this.CreatePropertyAccessor( protocolObject.StateTransitionTime, nameof(StateTransitionTime), BindingAccess.Read); this.StatisticsProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Stats, o => new PoolStatistics(o).Freeze()), nameof(Statistics), BindingAccess.Read); this.TargetDedicatedComputeNodesProperty = this.CreatePropertyAccessor( protocolObject.TargetDedicatedNodes, nameof(TargetDedicatedComputeNodes), BindingAccess.Read); this.TargetLowPriorityComputeNodesProperty = this.CreatePropertyAccessor( protocolObject.TargetLowPriorityNodes, nameof(TargetLowPriorityComputeNodes), BindingAccess.Read); this.TaskSchedulingPolicyProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.TaskSchedulingPolicy, o => new TaskSchedulingPolicy(o).Freeze()), nameof(TaskSchedulingPolicy), BindingAccess.Read); this.TaskSlotsPerNodeProperty = this.CreatePropertyAccessor( protocolObject.TaskSlotsPerNode, nameof(TaskSlotsPerNode), BindingAccess.Read); this.UrlProperty = this.CreatePropertyAccessor( protocolObject.Url, nameof(Url), BindingAccess.Read); this.UserAccountsProperty = this.CreatePropertyAccessor( UserAccount.ConvertFromProtocolCollectionAndFreeze(protocolObject.UserAccounts), nameof(UserAccounts), BindingAccess.Read); this.VirtualMachineConfigurationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.VirtualMachineConfiguration, o => new VirtualMachineConfiguration(o).Freeze()), nameof(VirtualMachineConfiguration), BindingAccess.Read); this.VirtualMachineSizeProperty = this.CreatePropertyAccessor( protocolObject.VmSize, nameof(VirtualMachineSize), BindingAccess.Read); } } private PropertyContainer propertyContainer; private readonly BatchClient parentBatchClient; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="CloudPool"/> class. /// </summary> /// <param name='parentBatchClient'>The parent <see cref="BatchClient"/> to use.</param> /// <param name='baseBehaviors'>The base behaviors to use.</param> internal CloudPool( BatchClient parentBatchClient, IEnumerable<BatchClientBehavior> baseBehaviors) { this.propertyContainer = new PropertyContainer(); this.parentBatchClient = parentBatchClient; InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors); } /// <summary> /// Default constructor to support mocking the <see cref="CloudPool"/> class. /// </summary> protected CloudPool() { this.propertyContainer = new PropertyContainer(); } internal CloudPool( BatchClient parentBatchClient, Models.CloudPool protocolObject, IEnumerable<BatchClientBehavior> baseBehaviors) { this.parentBatchClient = parentBatchClient; InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors); this.propertyContainer = new PropertyContainer(protocolObject); } #endregion Constructors #region IInheritedBehaviors /// <summary> /// Gets or sets a list of behaviors that modify or customize requests to the Batch service /// made via this <see cref="CloudPool"/>. /// </summary> /// <remarks> /// <para>These behaviors are inherited by child objects.</para> /// <para>Modifications are applied in the order of the collection. The last write wins.</para> /// </remarks> public IList<BatchClientBehavior> CustomBehaviors { get; set; } #endregion IInheritedBehaviors #region CloudPool /// <summary> /// Gets an <see cref="Common.AllocationState"/> which indicates what node allocation activity is occurring on the /// pool. /// </summary> public Common.AllocationState? AllocationState { get { return this.propertyContainer.AllocationStateProperty.Value; } } /// <summary> /// Gets the time at which the pool entered its current <see cref="AllocationState"/>. /// </summary> public DateTime? AllocationStateTransitionTime { get { return this.propertyContainer.AllocationStateTransitionTimeProperty.Value; } } /// <summary> /// Gets or sets the list of application licenses the Batch service will make available on each compute node in the /// pool. /// </summary> /// <remarks> /// <para>The list of application licenses must be a subset of available Batch service application licenses.</para><para>The /// permitted licenses available on the pool are 'maya', 'vray', '3dsmax', 'arnold'. An additional charge applies /// for each application license added to the pool.</para> /// </remarks> public IList<string> ApplicationLicenses { get { return this.propertyContainer.ApplicationLicensesProperty.Value; } set { this.propertyContainer.ApplicationLicensesProperty.Value = ConcurrentChangeTrackedList<string>.TransformEnumerableToConcurrentList(value); } } /// <summary> /// Gets or sets a list of application packages to be installed on each compute node in the pool. /// </summary> /// <remarks> /// Changes to application package references affect all new compute nodes joining the pool, but do not affect compute /// nodes that are already in the pool until they are rebooted or reimaged. There is a maximum of 10 application /// package references on any given pool. /// </remarks> public IList<ApplicationPackageReference> ApplicationPackageReferences { get { return this.propertyContainer.ApplicationPackageReferencesProperty.Value; } set { this.propertyContainer.ApplicationPackageReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<ApplicationPackageReference>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets whether the pool size should automatically adjust according to the <see cref="AutoScaleFormula"/>. /// </summary> /// <remarks> /// <para>If true, the <see cref="AutoScaleFormula"/> property is required, the pool automatically resizes according /// to the formula, and <see cref="TargetDedicatedComputeNodes"/> and <see cref="TargetLowPriorityComputeNodes"/> /// must be null.</para> <para>If false, one of the <see cref="TargetDedicatedComputeNodes"/> or <see cref="TargetLowPriorityComputeNodes"/> /// properties is required.</para><para>The default value is false.</para> /// </remarks> public bool? AutoScaleEnabled { get { return this.propertyContainer.AutoScaleEnabledProperty.Value; } set { this.propertyContainer.AutoScaleEnabledProperty.Value = value; } } /// <summary> /// Gets or sets a time interval at which to automatically adjust the pool size according to the <see cref="AutoScaleFormula"/>. /// </summary> /// <remarks> /// The default value is 15 minutes. The minimum allowed value is 5 minutes. /// </remarks> public TimeSpan? AutoScaleEvaluationInterval { get { return this.propertyContainer.AutoScaleEvaluationIntervalProperty.Value; } set { this.propertyContainer.AutoScaleEvaluationIntervalProperty.Value = value; } } /// <summary> /// Gets or sets a formula for the desired number of compute nodes in the pool. /// </summary> /// <remarks> /// <para>For how to write autoscale formulas, see https://azure.microsoft.com/documentation/articles/batch-automatic-scaling/. /// This property is required if <see cref="AutoScaleEnabled"/> is set to true. It must be null if AutoScaleEnabled /// is false.</para><para>The formula is checked for validity before the pool is created. If the formula is not valid, /// an exception is thrown when you try to commit the <see cref="CloudPool"/>.</para> /// </remarks> public string AutoScaleFormula { get { return this.propertyContainer.AutoScaleFormulaProperty.Value; } set { this.propertyContainer.AutoScaleFormulaProperty.Value = value; } } /// <summary> /// Gets the results and errors from the last execution of the <see cref="AutoScaleFormula"/>. /// </summary> public AutoScaleRun AutoScaleRun { get { return this.propertyContainer.AutoScaleRunProperty.Value; } } /// <summary> /// Gets or sets a list of certificates to be installed on each compute node in the pool. /// </summary> public IList<CertificateReference> CertificateReferences { get { return this.propertyContainer.CertificateReferencesProperty.Value; } set { this.propertyContainer.CertificateReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<CertificateReference>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the <see cref="CloudServiceConfiguration"/> for the pool. /// </summary> public CloudServiceConfiguration CloudServiceConfiguration { get { return this.propertyContainer.CloudServiceConfigurationProperty.Value; } set { this.propertyContainer.CloudServiceConfigurationProperty.Value = value; } } /// <summary> /// Gets the creation time for the pool. /// </summary> public DateTime? CreationTime { get { return this.propertyContainer.CreationTimeProperty.Value; } } /// <summary> /// Gets the number of dedicated compute nodes currently in the pool. /// </summary> public int? CurrentDedicatedComputeNodes { get { return this.propertyContainer.CurrentDedicatedComputeNodesProperty.Value; } } /// <summary> /// Gets the number of low-priority compute nodes currently in the pool. /// </summary> /// <remarks> /// Low-priority compute nodes which have been preempted are included in this count. /// </remarks> public int? CurrentLowPriorityComputeNodes { get { return this.propertyContainer.CurrentLowPriorityComputeNodesProperty.Value; } } /// <summary> /// Gets or sets the display name of the pool. /// </summary> public string DisplayName { get { return this.propertyContainer.DisplayNameProperty.Value; } set { this.propertyContainer.DisplayNameProperty.Value = value; } } /// <summary> /// Gets the ETag for the pool. /// </summary> public string ETag { get { return this.propertyContainer.ETagProperty.Value; } } /// <summary> /// Gets or sets the id of the pool. /// </summary> public string Id { get { return this.propertyContainer.IdProperty.Value; } set { this.propertyContainer.IdProperty.Value = value; } } /// <summary> /// Gets or sets the identity of the Batch pool, if configured. /// </summary> /// <remarks> /// The list of user identities associated with the Batch pool. The user identity dictionary key references will /// be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. /// </remarks> public BatchPoolIdentity Identity { get { return this.propertyContainer.IdentityProperty.Value; } set { this.propertyContainer.IdentityProperty.Value = value; } } /// <summary> /// Gets or sets whether the pool permits direct communication between its compute nodes. /// </summary> /// <remarks> /// Enabling inter-node communication limits the maximum size of the pool due to deployment restrictions on the nodes /// of the pool. This may result in the pool not reaching its desired size. /// </remarks> public bool? InterComputeNodeCommunicationEnabled { get { return this.propertyContainer.InterComputeNodeCommunicationEnabledProperty.Value; } set { this.propertyContainer.InterComputeNodeCommunicationEnabledProperty.Value = value; } } /// <summary> /// Gets the last modified time of the pool. /// </summary> public DateTime? LastModified { get { return this.propertyContainer.LastModifiedProperty.Value; } } /// <summary> /// Gets or sets a list of name-value pairs associated with the pool as metadata. /// </summary> public IList<MetadataItem> Metadata { get { return this.propertyContainer.MetadataProperty.Value; } set { this.propertyContainer.MetadataProperty.Value = ConcurrentChangeTrackedModifiableList<MetadataItem>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets a list of file systems to mount on each node in the pool. /// </summary> /// <remarks> /// This supports Azure Files, NFS, CIFS/SMB, and Blobfuse. /// </remarks> public IList<MountConfiguration> MountConfiguration { get { return this.propertyContainer.MountConfigurationProperty.Value; } set { this.propertyContainer.MountConfigurationProperty.Value = ConcurrentChangeTrackedModifiableList<MountConfiguration>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the network configuration of the pool. /// </summary> public NetworkConfiguration NetworkConfiguration { get { return this.propertyContainer.NetworkConfigurationProperty.Value; } set { this.propertyContainer.NetworkConfigurationProperty.Value = value; } } /// <summary> /// Gets a list of errors encountered while performing the last resize on the <see cref="CloudPool"/>. Errors are /// returned only when the Batch service encountered an error while resizing the pool, and when the pool's <see cref="CloudPool.AllocationState"/> /// is <see cref="Common.AllocationState.Steady">Steady</see>. /// </summary> public IReadOnlyList<ResizeError> ResizeErrors { get { return this.propertyContainer.ResizeErrorsProperty.Value; } } /// <summary> /// Gets or sets the timeout for allocation of compute nodes to the pool. /// </summary> public TimeSpan? ResizeTimeout { get { return this.propertyContainer.ResizeTimeoutProperty.Value; } set { this.propertyContainer.ResizeTimeoutProperty.Value = value; } } /// <summary> /// Gets or sets a task to run on each compute node as it joins the pool. The task runs when the node is added to /// the pool or when the node is restarted. /// </summary> public StartTask StartTask { get { return this.propertyContainer.StartTaskProperty.Value; } set { this.propertyContainer.StartTaskProperty.Value = value; } } /// <summary> /// Gets the current state of the pool. /// </summary> public Common.PoolState? State { get { return this.propertyContainer.StateProperty.Value; } } /// <summary> /// Gets the time at which the pool entered its current state. /// </summary> public DateTime? StateTransitionTime { get { return this.propertyContainer.StateTransitionTimeProperty.Value; } } /// <summary> /// Gets the resource usage statistics for the pool. /// </summary> /// <remarks> /// This property is populated only if the <see cref="CloudPool"/> was retrieved with an <see cref="ODATADetailLevel.ExpandClause"/> /// including the 'stats' attribute; otherwise it is null. The statistics may not be immediately available. The Batch /// service performs periodic roll-up of statistics. The typical delay is about 30 minutes. /// </remarks> public PoolStatistics Statistics { get { return this.propertyContainer.StatisticsProperty.Value; } } /// <summary> /// Gets or sets the desired number of dedicated compute nodes in the pool. /// </summary> /// <remarks> /// This setting cannot be specified if <see cref="AutoScaleEnabled"/> is set to true. At least one of this property /// and <see cref="TargetLowPriorityComputeNodes"/> must be specified if <see cref="AutoScaleEnabled"/> is false. /// If not specified, the default is 0. /// </remarks> public int? TargetDedicatedComputeNodes { get { return this.propertyContainer.TargetDedicatedComputeNodesProperty.Value; } set { this.propertyContainer.TargetDedicatedComputeNodesProperty.Value = value; } } /// <summary> /// Gets or sets the desired number of low-priority compute nodes in the pool. /// </summary> /// <remarks> /// This setting cannot be specified if <see cref="AutoScaleEnabled"/> is set to true. At least one of <see cref="TargetDedicatedComputeNodes"/> /// and this property must be specified if <see cref="AutoScaleEnabled"/> is false. If not specified, the default /// is 0. /// </remarks> public int? TargetLowPriorityComputeNodes { get { return this.propertyContainer.TargetLowPriorityComputeNodesProperty.Value; } set { this.propertyContainer.TargetLowPriorityComputeNodesProperty.Value = value; } } /// <summary> /// Gets or sets how tasks are distributed among compute nodes in the pool. /// </summary> public TaskSchedulingPolicy TaskSchedulingPolicy { get { return this.propertyContainer.TaskSchedulingPolicyProperty.Value; } set { this.propertyContainer.TaskSchedulingPolicyProperty.Value = value; } } /// <summary> /// Gets or sets the number of task slots that can be used to run concurrent tasks on a single compute node in the /// pool. /// </summary> /// <remarks> /// The default value is 1. The maximum value is the smaller of 4 times the number of cores of the <see cref="VirtualMachineSize"/> /// of the pool or 256. /// </remarks> public int? TaskSlotsPerNode { get { return this.propertyContainer.TaskSlotsPerNodeProperty.Value; } set { this.propertyContainer.TaskSlotsPerNodeProperty.Value = value; } } /// <summary> /// Gets the URL of the pool. /// </summary> public string Url { get { return this.propertyContainer.UrlProperty.Value; } } /// <summary> /// Gets or sets the list of user accounts to be created on each node in the pool. /// </summary> public IList<UserAccount> UserAccounts { get { return this.propertyContainer.UserAccountsProperty.Value; } set { this.propertyContainer.UserAccountsProperty.Value = ConcurrentChangeTrackedModifiableList<UserAccount>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the <see cref="VirtualMachineConfiguration"/> of the pool. /// </summary> public VirtualMachineConfiguration VirtualMachineConfiguration { get { return this.propertyContainer.VirtualMachineConfigurationProperty.Value; } set { this.propertyContainer.VirtualMachineConfigurationProperty.Value = value; } } /// <summary> /// Gets or sets the size of the virtual machines in the pool. All virtual machines in a pool are the same size. /// </summary> /// <remarks> /// <para>For information about available sizes of virtual machines in pools, see Choose a VM size for compute nodes /// in an Azure Batch pool (https://docs.microsoft.com/azure/batch/batch-pool-vm-sizes).</para> /// </remarks> public string VirtualMachineSize { get { return this.propertyContainer.VirtualMachineSizeProperty.Value; } set { this.propertyContainer.VirtualMachineSizeProperty.Value = value; } } #endregion // CloudPool #region IPropertyMetadata bool IModifiable.HasBeenModified { get { return this.propertyContainer.HasBeenModified; } } bool IReadOnly.IsReadOnly { get { return this.propertyContainer.IsReadOnly; } set { this.propertyContainer.IsReadOnly = value; } } #endregion //IPropertyMetadata #region Internal/private methods /// <summary> /// Return a protocol object of the requested type. /// </summary> /// <returns>The protocol object of the requested type.</returns> Models.PoolAddParameter ITransportObjectProvider<Models.PoolAddParameter>.GetTransportObject() { Models.PoolAddParameter result = new Models.PoolAddParameter() { ApplicationLicenses = this.ApplicationLicenses, ApplicationPackageReferences = UtilitiesInternal.ConvertToProtocolCollection(this.ApplicationPackageReferences), EnableAutoScale = this.AutoScaleEnabled, AutoScaleEvaluationInterval = this.AutoScaleEvaluationInterval, AutoScaleFormula = this.AutoScaleFormula, CertificateReferences = UtilitiesInternal.ConvertToProtocolCollection(this.CertificateReferences), CloudServiceConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.CloudServiceConfiguration, (o) => o.GetTransportObject()), DisplayName = this.DisplayName, Id = this.Id, EnableInterNodeCommunication = this.InterComputeNodeCommunicationEnabled, Metadata = UtilitiesInternal.ConvertToProtocolCollection(this.Metadata), MountConfiguration = UtilitiesInternal.ConvertToProtocolCollection(this.MountConfiguration), NetworkConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.NetworkConfiguration, (o) => o.GetTransportObject()), ResizeTimeout = this.ResizeTimeout, StartTask = UtilitiesInternal.CreateObjectWithNullCheck(this.StartTask, (o) => o.GetTransportObject()), TargetDedicatedNodes = this.TargetDedicatedComputeNodes, TargetLowPriorityNodes = this.TargetLowPriorityComputeNodes, TaskSchedulingPolicy = UtilitiesInternal.CreateObjectWithNullCheck(this.TaskSchedulingPolicy, (o) => o.GetTransportObject()), TaskSlotsPerNode = this.TaskSlotsPerNode, UserAccounts = UtilitiesInternal.ConvertToProtocolCollection(this.UserAccounts), VirtualMachineConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.VirtualMachineConfiguration, (o) => o.GetTransportObject()), VmSize = this.VirtualMachineSize, }; return result; } #endregion // Internal/private methods } }
// ******************************************************************************************************** // Product Name: DotSpatial.Data.dll // Description: The data access libraries for the DotSpatial project. // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 2/27/2010 10:56:39 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; namespace DotSpatial.Data { /// <summary> /// Hfa /// </summary> public static class Hfa { #region Methods /// <summary> /// Gets the bitcount of a single member of the specified data type. /// </summary> /// <param name="dataType">The data type to get the byte count of</param> /// <returns>An integer that represents the bit count of the specified type</returns> public static int GetBitCount(this HfaEPT dataType) { switch (dataType) { case HfaEPT.U1: return 1; case HfaEPT.U2: return 2; case HfaEPT.U4: return 4; case HfaEPT.U8: case HfaEPT.S8: return 8; case HfaEPT.U16: case HfaEPT.S16: return 16; case HfaEPT.U32: case HfaEPT.S32: case HfaEPT.Single: return 32; case HfaEPT.Double: case HfaEPT.Char64: return 64; case HfaEPT.Char128: return 128; } return 0; } /// <summary> /// Reverses the byte order on Big-Endian systems like Unix to conform with the /// HFA standard of little endian. /// </summary> /// <param name="value"></param> /// <returns></returns> public static byte[] LittleEndian(byte[] value) { if (!BitConverter.IsLittleEndian) Array.Reverse(value); return value; } /// <summary> /// Return ReadType /// </summary> /// <param name="data"></param> /// <param name="offset"></param> /// <returns></returns> public static HfaEPT ReadType(byte[] data, long offset) { byte[] vals = new byte[2]; Array.Copy(data, offset, vals, 0, 2); return (HfaEPT)BitConverter.ToInt16(LittleEndian(vals), 0); } /// <summary> /// Given the byte array, this reads four bytes and converts this to a 32 bit integer. /// This always uses little endian byte order. /// </summary> /// <param name="data"></param> /// <param name="offset"></param> /// <returns></returns> public static short ReadInt16(byte[] data, long offset) { byte[] vals = new byte[4]; Array.Copy(data, offset, vals, 0, 4); return BitConverter.ToInt16(LittleEndian(vals), 0); } /// <summary> /// Given the byte array, this reads four bytes and converts this to a 16 bit unsigned short integer. /// This always uses little endian byte order. /// </summary> /// <param name="data"></param> /// <param name="offset"></param> /// <returns></returns> public static int ReadUInt16(byte[] data, long offset) { byte[] vals = new byte[2]; Array.Copy(data, offset, vals, 0, 2); return BitConverter.ToUInt16(LittleEndian(vals), 0); } /// <summary> /// Given the byte array, this reads four bytes and converts this to a 32 bit integer. /// This always uses little endian byte order. /// </summary> /// <param name="data"></param> /// <param name="offset"></param> /// <returns></returns> public static int ReadInt32(byte[] data, long offset) { byte[] vals = new byte[4]; Array.Copy(data, offset, vals, 0, 4); return BitConverter.ToInt32(LittleEndian(vals), 0); } /// <summary> /// Given the byte array, this reads four bytes and converts this to a 32 bit floating point value /// This always uses little endian byte order. /// </summary> /// <param name="data"></param> /// <param name="offset"></param> /// <returns></returns> public static float ReadSingle(byte[] data, long offset) { byte[] vals = new byte[4]; Array.Copy(data, offset, vals, 0, 4); return BitConverter.ToSingle(LittleEndian(vals), 0); } /// <summary> /// Given the byte array, this reads four bytes and converts this to a 64 bit floating point value /// This always uses little endian byte order. /// </summary> /// <param name="data"></param> /// <param name="offset"></param> /// <returns></returns> public static double ReadDouble(byte[] data, long offset) { byte[] vals = new byte[8]; Array.Copy(data, offset, vals, 0, 8); return BitConverter.ToSingle(LittleEndian(vals), 0); } /// <summary> /// Given the byte array, this reads four bytes and converts this to a 32 bit unsigned integer. /// This always uses little endian byte order. /// </summary> /// <param name="data"></param> /// <param name="offset"></param> /// <returns>A UInt32 value stored in a long because UInt32 is not CLS Compliant</returns> public static long ReadUInt32(byte[] data, long offset) { byte[] vals = new byte[4]; Array.Copy(data, offset, vals, 0, 4); return BitConverter.ToUInt32(LittleEndian(vals), 0); } /// <summary> /// Obtains the 4 byte equivalent for 32 bit Unsigned Integer values /// </summary> /// <param name="value">The unsigned integer value to convert into bytes</param> /// <returns>The bytes in LittleEndian standard, regardless of the system architecture</returns> public static byte[] LittleEndianAsUint32(long value) { byte[] bValue = BitConverter.GetBytes(Convert.ToUInt32(value)); return LittleEndian(bValue); } /// <summary> /// Obtains the 4 byte equivalent for 32 bit Integer values /// </summary> /// <param name="value">The unsigned integer value to convert into bytes</param> /// <returns>The bytes in LittleEndian standard, regardless of the system architecture</returns> public static byte[] LittleEndian(int value) { byte[] bValue = BitConverter.GetBytes(value); return LittleEndian(bValue); } /// <summary> /// Obtains the 4 byte equivalent for 32bit floating point values /// </summary> /// <param name="value">The unsigned integer value to convert into bytes</param> /// <returns>The bytes in LittleEndian standard, regardless of the system architecture</returns> public static byte[] LittleEndian(float value) { byte[] bValue = BitConverter.GetBytes(value); return LittleEndian(bValue); } /// <summary> /// Obtains the 8 byte equivalent for 64 bit floating point values /// </summary> /// <param name="value">The unsigned integer value to convert into bytes</param> /// <returns>The bytes in LittleEndian standard, regardless of the system architecture</returns> public static byte[] LittleEndian(double value) { byte[] bValue = BitConverter.GetBytes(value); return LittleEndian(bValue); } /// <summary> /// Gets the 2 byte equivalent of an unsigned short in little endian format /// </summary> /// <param name="value"></param> /// <returns></returns> public static byte[] LittleEndianAsUShort(int value) { byte[] bValue = BitConverter.GetBytes(Convert.ToUInt16(value)); return LittleEndian(bValue); } /// <summary> /// Gets the 2 byte equivalent of a short in little endian format /// </summary> /// <param name="value"></param> /// <returns></returns> public static byte[] LittleEndian(short value) { byte[] bValue = BitConverter.GetBytes(value); return LittleEndian(bValue); } #endregion #region Properties #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // Match is the result class for a regex search. // It returns the location, length, and substring for // the entire match as well as every captured group. // Match is also used during the search to keep track of each capture for each group. This is // done using the "_matches" array. _matches[x] represents an array of the captures for group x. // This array consists of start and length pairs, and may have empty entries at the end. _matchcount[x] // stores how many captures a group has. Note that _matchcount[x]*2 is the length of all the valid // values in _matches. _matchcount[x]*2-2 is the Start of the last capture, and _matchcount[x]*2-1 is the // Length of the last capture // // For example, if group 2 has one capture starting at position 4 with length 6, // _matchcount[2] == 1 // _matches[2][0] == 4 // _matches[2][1] == 6 // // Values in the _matches array can also be negative. This happens when using the balanced match // construct, "(?<start-end>...)". When the "end" group matches, a capture is added for both the "start" // and "end" groups. The capture added for "start" receives the negative values, and these values point to // the next capture to be balanced. They do NOT point to the capture that "end" just balanced out. The negative // values are indices into the _matches array transformed by the formula -3-x. This formula also untransforms. // using System.Collections; using System.Globalization; namespace System.Text.RegularExpressions { /// <summary> /// Represents the results from a single regular expression match. /// </summary> [Serializable] public class Match : Group { internal static readonly Match s_empty = new Match(null, 1, string.Empty, 0, 0, 0); internal GroupCollection _groupcoll; // input to the match internal Regex _regex; internal int _textbeg; internal int _textpos; internal int _textend; internal int _textstart; // output from the match internal int[][] _matches; internal int[] _matchcount; internal bool _balancing; // whether we've done any balancing with this match. If we // have done balancing, we'll need to do extra work in Tidy(). /// <summary> /// Returns an empty Match object. /// </summary> public static Match Empty { get { return s_empty; } } internal Match(Regex regex, int capcount, string text, int begpos, int len, int startpos) : base(text, new int[2], 0, "0") { _regex = regex; _matchcount = new int[capcount]; _matches = new int[capcount][]; _matches[0] = _caps; _textbeg = begpos; _textend = begpos + len; _textstart = startpos; _balancing = false; // No need for an exception here. This is only called internally, so we'll use an Assert instead System.Diagnostics.Debug.Assert(!(_textbeg < 0 || _textstart < _textbeg || _textend < _textstart || _text.Length < _textend), "The parameters are out of range."); } /* * Nonpublic set-text method */ internal virtual void Reset(Regex regex, string text, int textbeg, int textend, int textstart) { _regex = regex; _text = text; _textbeg = textbeg; _textend = textend; _textstart = textstart; for (int i = 0; i < _matchcount.Length; i++) { _matchcount[i] = 0; } _balancing = false; } public virtual GroupCollection Groups { get { if (_groupcoll == null) _groupcoll = new GroupCollection(this, null); return _groupcoll; } } /// <summary> /// Returns a new Match with the results for the next match, starting /// at the position at which the last match ended (at the character beyond the last /// matched character). /// </summary> public Match NextMatch() { if (_regex == null) return this; return _regex.Run(false, _length, _text, _textbeg, _textend - _textbeg, _textpos); } /// <summary> /// Returns the expansion of the passed replacement pattern. For /// example, if the replacement pattern is ?$1$2?, Result returns the concatenation /// of Group(1).ToString() and Group(2).ToString(). /// </summary> public virtual string Result(string replacement) { RegexReplacement repl; if (replacement == null) throw new ArgumentNullException(nameof(replacement)); if (_regex == null) throw new NotSupportedException(SR.NoResultOnFailed); repl = (RegexReplacement)_regex._replref.Get(); if (repl == null || !repl.Pattern.Equals(replacement)) { repl = RegexParser.ParseReplacement(replacement, _regex.caps, _regex.capsize, _regex.capnames, _regex.roptions); _regex._replref.Cache(repl); } return repl.Replacement(this); } /* * Used by the replacement code */ internal virtual string GroupToStringImpl(int groupnum) { int c = _matchcount[groupnum]; if (c == 0) return string.Empty; int[] matches = _matches[groupnum]; return _text.Substring(matches[(c - 1) * 2], matches[(c * 2) - 1]); } /* * Used by the replacement code */ internal string LastGroupToStringImpl() { return GroupToStringImpl(_matchcount.Length - 1); } /* * Convert to a thread-safe object by precomputing cache contents */ /// <summary> /// Returns a Match instance equivalent to the one supplied that is safe to share /// between multiple threads. /// </summary> public static Match Synchronized(Match inner) { if (inner == null) throw new ArgumentNullException(nameof(inner)); int numgroups = inner._matchcount.Length; // Populate all groups by looking at each one for (int i = 0; i < numgroups; i++) { Group group = inner.Groups[i]; // Depends on the fact that Group.Synchronized just // operates on and returns the same instance Group.Synchronized(group); } return inner; } /* * Nonpublic builder: add a capture to the group specified by "cap" */ internal virtual void AddMatch(int cap, int start, int len) { int capcount; if (_matches[cap] == null) _matches[cap] = new int[2]; capcount = _matchcount[cap]; if (capcount * 2 + 2 > _matches[cap].Length) { int[] oldmatches = _matches[cap]; int[] newmatches = new int[capcount * 8]; for (int j = 0; j < capcount * 2; j++) newmatches[j] = oldmatches[j]; _matches[cap] = newmatches; } _matches[cap][capcount * 2] = start; _matches[cap][capcount * 2 + 1] = len; _matchcount[cap] = capcount + 1; } /* * Nonpublic builder: Add a capture to balance the specified group. This is used by the balanced match construct. (?<foo-foo2>...) If there were no such thing as backtracking, this would be as simple as calling RemoveMatch(cap). However, since we have backtracking, we need to keep track of everything. */ internal virtual void BalanceMatch(int cap) { int capcount; int target; _balancing = true; // we'll look at the last capture first capcount = _matchcount[cap]; target = capcount * 2 - 2; // first see if it is negative, and therefore is a reference to the next available // capture group for balancing. If it is, we'll reset target to point to that capture. if (_matches[cap][target] < 0) target = -3 - _matches[cap][target]; // move back to the previous capture target -= 2; // if the previous capture is a reference, just copy that reference to the end. Otherwise, point to it. if (target >= 0 && _matches[cap][target] < 0) AddMatch(cap, _matches[cap][target], _matches[cap][target + 1]); else AddMatch(cap, -3 - target, -4 - target /* == -3 - (target + 1) */ ); } /* * Nonpublic builder: removes a group match by capnum */ internal virtual void RemoveMatch(int cap) { _matchcount[cap]--; } /* * Nonpublic: tells if a group was matched by capnum */ internal virtual bool IsMatched(int cap) { return cap < _matchcount.Length && _matchcount[cap] > 0 && _matches[cap][_matchcount[cap] * 2 - 1] != (-3 + 1); } /* * Nonpublic: returns the index of the last specified matched group by capnum */ internal virtual int MatchIndex(int cap) { int i = _matches[cap][_matchcount[cap] * 2 - 2]; if (i >= 0) return i; return _matches[cap][-3 - i]; } /* * Nonpublic: returns the length of the last specified matched group by capnum */ internal virtual int MatchLength(int cap) { int i = _matches[cap][_matchcount[cap] * 2 - 1]; if (i >= 0) return i; return _matches[cap][-3 - i]; } /* * Nonpublic: tidy the match so that it can be used as an immutable result */ internal virtual void Tidy(int textpos) { int[] interval; interval = _matches[0]; _index = interval[0]; _length = interval[1]; _textpos = textpos; _capcount = _matchcount[0]; if (_balancing) { // The idea here is that we want to compact all of our unbalanced captures. To do that we // use j basically as a count of how many unbalanced captures we have at any given time // (really j is an index, but j/2 is the count). First we skip past all of the real captures // until we find a balance captures. Then we check each subsequent entry. If it's a balance // capture (it's negative), we decrement j. If it's a real capture, we increment j and copy // it down to the last free position. for (int cap = 0; cap < _matchcount.Length; cap++) { int limit; int[] matcharray; limit = _matchcount[cap] * 2; matcharray = _matches[cap]; int i = 0; int j; for (i = 0; i < limit; i++) { if (matcharray[i] < 0) break; } for (j = i; i < limit; i++) { if (matcharray[i] < 0) { // skip negative values j--; } else { // but if we find something positive (an actual capture), copy it back to the last // unbalanced position. if (i != j) matcharray[j] = matcharray[i]; j++; } } _matchcount[cap] = j / 2; } _balancing = false; } } #if DEBUG internal bool Debug { get { if (_regex == null) return false; return _regex.Debug; } } internal virtual void Dump() { int i, j; for (i = 0; i < _matchcount.Length; i++) { System.Diagnostics.Debug.WriteLine("Capnum " + i.ToString(CultureInfo.InvariantCulture) + ":"); for (j = 0; j < _matchcount[i]; j++) { string text = ""; if (_matches[i][j * 2] >= 0) text = _text.Substring(_matches[i][j * 2], _matches[i][j * 2 + 1]); System.Diagnostics.Debug.WriteLine(" (" + _matches[i][j * 2].ToString(CultureInfo.InvariantCulture) + "," + _matches[i][j * 2 + 1].ToString(CultureInfo.InvariantCulture) + ") " + text); } } } #endif } /* * MatchSparse is for handling the case where slots are * sparsely arranged (e.g., if somebody says use slot 100000) */ internal class MatchSparse : Match { // the lookup hashtable new internal Hashtable _caps; /* * Nonpublic constructor */ internal MatchSparse(Regex regex, Hashtable caps, int capcount, string text, int begpos, int len, int startpos) : base(regex, capcount, text, begpos, len, startpos) { _caps = caps; } public override GroupCollection Groups { get { if (_groupcoll == null) _groupcoll = new GroupCollection(this, _caps); return _groupcoll; } } #if DEBUG internal override void Dump() { if (_caps != null) { foreach (DictionaryEntry kvp in _caps) { System.Diagnostics.Debug.WriteLine("Slot " + kvp.Key.ToString() + " -> " + kvp.Value.ToString()); } } base.Dump(); } #endif } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Xml; using System.Collections.Generic; using System.IO; using Microsoft.Build.Framework; using Microsoft.Build.BackEnd; using Microsoft.Build.Shared; using Microsoft.Build.Execution; using Microsoft.Build.Evaluation; using TaskItem = Microsoft.Build.Execution.ProjectItemInstance.TaskItem; using Xunit; namespace Microsoft.Build.UnitTests.BackEnd { using Microsoft.Build.Unittest; /// <summary> /// Tests of the scheduler. /// </summary> // Ignore: Causing issues with other tests // NOTE: marked as "internal" to disable the entire test class, as was done for MSTest. public class Scheduler_Tests : IDisposable { /// <summary> /// The host object. /// </summary> private MockHost _host; /// <summary> /// The scheduler used in each test. /// </summary> private Scheduler _scheduler; /// <summary> /// The default parent request /// </summary> private BuildRequest _defaultParentRequest; /// <summary> /// The mock logger for testing. /// </summary> private MockLogger _logger; /// <summary> /// The standard build manager for each test. /// </summary> private BuildManager _buildManager; /// <summary> /// The build parameters. /// </summary> private BuildParameters _parameters; /// <summary> /// Set up /// </summary> public Scheduler_Tests() { // Since we're creating our own BuildManager, we need to make sure that the default // one has properly relinquished the inproc node NodeProviderInProc nodeProviderInProc = ((IBuildComponentHost)BuildManager.DefaultBuildManager).GetComponent(BuildComponentType.InProcNodeProvider) as NodeProviderInProc; nodeProviderInProc?.Dispose(); _host = new MockHost(); _scheduler = new Scheduler(); _scheduler.InitializeComponent(_host); CreateConfiguration(99, "parent.proj"); _defaultParentRequest = CreateBuildRequest(99, 99, new string[] { }, null); // Set up the scheduler with one node to start with. _scheduler.ReportNodesCreated(new NodeInfo[] { new NodeInfo(1, NodeProviderType.InProc) }); _scheduler.ReportRequestBlocked(1, new BuildRequestBlocker(-1, new string[] { }, new BuildRequest[] { _defaultParentRequest })); _logger = new MockLogger(); _parameters = new BuildParameters(); _parameters.Loggers = new ILogger[] { _logger }; _parameters.ShutdownInProcNodeOnBuildFinish = true; _buildManager = new BuildManager(); } /// <summary> /// Tear down /// </summary> public void Dispose() { if (_buildManager != null) { NodeProviderInProc nodeProviderInProc = ((IBuildComponentHost)_buildManager).GetComponent(BuildComponentType.InProcNodeProvider) as NodeProviderInProc; nodeProviderInProc.Dispose(); _buildManager.Dispose(); } } /// <summary> /// Verify that when a single request is submitted, we get a request assigned back out. /// </summary> [Fact(Skip = "https://github.com/Microsoft/msbuild/issues/515")] public void TestSimpleRequest() { CreateConfiguration(1, "foo.proj"); BuildRequest request = CreateBuildRequest(1, 1); BuildRequestBlocker blocker = new BuildRequestBlocker(request.ParentGlobalRequestId, new string[] { }, new BuildRequest[] { request }); List<ScheduleResponse> response = new List<ScheduleResponse>(_scheduler.ReportRequestBlocked(1, blocker)); Assert.Single(response); Assert.Equal(ScheduleActionType.ScheduleWithConfiguration, response[0].Action); Assert.Equal(request, response[0].BuildRequest); } /// <summary> /// Verify that when we submit a request and we already have results, we get the results back. /// </summary> [Fact(Skip = "https://github.com/Microsoft/msbuild/issues/515")] public void TestSimpleRequestWithCachedResultsSuccess() { CreateConfiguration(1, "foo.proj"); BuildRequest request = CreateBuildRequest(1, 1, new string[] { "foo" }); BuildResult result = CacheBuildResult(request, "foo", BuildResultUtilities.GetSuccessResult()); BuildRequestBlocker blocker = new BuildRequestBlocker(request.ParentGlobalRequestId, new string[] { }, new BuildRequest[] { request }); List<ScheduleResponse> response = new List<ScheduleResponse>(_scheduler.ReportRequestBlocked(1, blocker)); Assert.Equal(2, response.Count); // First response tells the parent of the results. Assert.Equal(ScheduleActionType.ReportResults, response[0].Action); Assert.True(ResultsCache_Tests.AreResultsIdentical(result, response[0].Unblocker.Result)); // Second response tells the parent to continue. Assert.Equal(ScheduleActionType.ResumeExecution, response[1].Action); Assert.Null(response[1].Unblocker.Result); } /// <summary> /// Verify that when we submit a request with failing results, we get the results back. /// </summary> [Fact(Skip = "https://github.com/Microsoft/msbuild/issues/515")] public void TestSimpleRequestWithCachedResultsFail() { CreateConfiguration(1, "foo.proj"); BuildRequest request = CreateBuildRequest(1, 1, new string[] { "foo" }); BuildResult result = CacheBuildResult(request, "foo", BuildResultUtilities.GetStopWithErrorResult()); BuildRequestBlocker blocker = new BuildRequestBlocker(request.ParentGlobalRequestId, new string[] { }, new BuildRequest[] { request }); List<ScheduleResponse> response = new List<ScheduleResponse>(_scheduler.ReportRequestBlocked(1, blocker)); Assert.Equal(2, response.Count); // First response tells the parent of the results. Assert.Equal(ScheduleActionType.ReportResults, response[0].Action); Assert.True(ResultsCache_Tests.AreResultsIdentical(result, response[0].Unblocker.Result)); // Second response tells the parent to continue. Assert.Equal(ScheduleActionType.ResumeExecution, response[1].Action); Assert.Null(response[1].Unblocker.Result); } /// <summary> /// Verify that when we submit a child request with results cached, we get those results back. /// </summary> [Fact(Skip = "https://github.com/Microsoft/msbuild/issues/515")] public void TestChildRequest() { CreateConfiguration(1, "foo.proj"); BuildRequest request = CreateBuildRequest(1, 1, new string[] { "foo" }); BuildRequestBlocker blocker = new BuildRequestBlocker(-1, new string[] { }, new BuildRequest[] { request }); List<ScheduleResponse> response = new List<ScheduleResponse>(_scheduler.ReportRequestBlocked(1, blocker)); CreateConfiguration(2, "bar.proj"); BuildRequest childRequest = CreateBuildRequest(2, 2, new string[] { "foo" }, request); BuildResult childResult = CacheBuildResult(childRequest, "foo", BuildResultUtilities.GetSuccessResult()); blocker = new BuildRequestBlocker(0, new string[] { "foo" }, new BuildRequest[] { childRequest }); response = new List<ScheduleResponse>(_scheduler.ReportRequestBlocked(1, blocker)); Assert.Equal(2, response.Count); // The first response will be to report the results back to the node. Assert.Equal(ScheduleActionType.ReportResults, response[0].Action); Assert.True(ResultsCache_Tests.AreResultsIdentical(childResult, response[0].Unblocker.Result)); // The second response will be to continue building the original request. Assert.Equal(ScheduleActionType.ResumeExecution, response[1].Action); Assert.Null(response[1].Unblocker.Result); } /// <summary> /// Verify that when multiple requests are submitted, the first one in is the first one out. /// </summary> [Fact(Skip = "https://github.com/Microsoft/msbuild/issues/515")] public void TestMultipleRequests() { CreateConfiguration(1, "foo.proj"); BuildRequest request1 = CreateBuildRequest(1, 1, new string[] { "foo" }); BuildRequest request2 = CreateBuildRequest(2, 1, new string[] { "bar" }); BuildRequestBlocker blocker = new BuildRequestBlocker(request1.ParentGlobalRequestId, new string[] { }, new BuildRequest[] { request1, request2 }); List<ScheduleResponse> response = new List<ScheduleResponse>(_scheduler.ReportRequestBlocked(1, blocker)); Assert.Single(response); Assert.Equal(ScheduleActionType.ScheduleWithConfiguration, response[0].Action); Assert.Equal(request1, response[0].BuildRequest); } /// <summary> /// Verify that when multiple requests are submitted with results cached, we get the results back. /// </summary> [Fact(Skip = "https://github.com/Microsoft/msbuild/issues/515")] public void TestMultipleRequestsWithSomeResults() { CreateConfiguration(1, "foo.proj"); BuildRequest request1 = CreateBuildRequest(1, 1, new string[] { "foo" }); CreateConfiguration(2, "bar.proj"); BuildRequest request2 = CreateBuildRequest(2, 2, new string[] { "bar" }); BuildResult result2 = CacheBuildResult(request2, "bar", BuildResultUtilities.GetSuccessResult()); BuildRequestBlocker blocker = new BuildRequestBlocker(request1.ParentGlobalRequestId, new string[] { }, new BuildRequest[] { request1, request2 }); List<ScheduleResponse> response = new List<ScheduleResponse>(_scheduler.ReportRequestBlocked(1, blocker)); Assert.Equal(2, response.Count); Assert.Equal(ScheduleActionType.ReportResults, response[0].Action); Assert.True(ResultsCache_Tests.AreResultsIdentical(result2, response[0].Unblocker.Result)); Assert.Equal(ScheduleActionType.ScheduleWithConfiguration, response[1].Action); Assert.Equal(request1, response[1].BuildRequest); } /// <summary> /// Verify that when multiple requests are submitted with results cached, we get the results back. /// </summary> [Fact(Skip = "https://github.com/Microsoft/msbuild/issues/515")] public void TestMultipleRequestsWithAllResults() { CreateConfiguration(1, "foo.proj"); BuildRequest request1 = CreateBuildRequest(1, 1, new string[] { "foo" }); BuildResult result1 = CacheBuildResult(request1, "foo", BuildResultUtilities.GetSuccessResult()); CreateConfiguration(2, "bar.proj"); BuildRequest request2 = CreateBuildRequest(2, 2, new string[] { "bar" }); BuildResult result2 = CacheBuildResult(request2, "bar", BuildResultUtilities.GetSuccessResult()); BuildRequestBlocker blocker = new BuildRequestBlocker(request1.ParentGlobalRequestId, new string[] { }, new BuildRequest[] { request1, request2 }); List<ScheduleResponse> response = new List<ScheduleResponse>(_scheduler.ReportRequestBlocked(1, blocker)); Assert.Equal(3, response.Count); // First two are the results which were cached. Assert.Equal(ScheduleActionType.ReportResults, response[0].Action); Assert.True(ResultsCache_Tests.AreResultsIdentical(result1, response[0].Unblocker.Result)); Assert.Equal(ScheduleActionType.ReportResults, response[1].Action); Assert.True(ResultsCache_Tests.AreResultsIdentical(result2, response[1].Unblocker.Result)); // Last response is to continue the parent. Assert.Equal(ScheduleActionType.ResumeExecution, response[2].Action); Assert.Equal(request1.ParentGlobalRequestId, response[2].Unblocker.BlockedRequestId); Assert.Null(response[2].Unblocker.Result); } /// <summary> /// Verify that if the affinity of one of the requests is out-of-proc, we create an out-of-proc node (but only one) /// even if the max node count = 1. /// </summary> [Fact(Skip = "https://github.com/Microsoft/msbuild/issues/515")] public void TestOutOfProcNodeCreatedWhenAffinityIsOutOfProc() { CreateConfiguration(1, "foo.proj"); BuildRequest request1 = CreateBuildRequest(1, 1, new string[] { "foo" }, NodeAffinity.OutOfProc, _defaultParentRequest); BuildRequest request2 = CreateBuildRequest(2, 1, new string[] { "bar" }, NodeAffinity.OutOfProc, _defaultParentRequest); BuildRequestBlocker blocker = new BuildRequestBlocker(request1.ParentGlobalRequestId, new string[] { }, new BuildRequest[] { request1, request2 }); List<ScheduleResponse> response = new List<ScheduleResponse>(_scheduler.ReportRequestBlocked(1, blocker)); // Parent request is blocked by the fact that both child requests require the out-of-proc node that doesn't // exist yet. Assert.Single(response); Assert.Equal(ScheduleActionType.CreateNode, response[0].Action); Assert.Equal(NodeAffinity.OutOfProc, response[0].RequiredNodeType); Assert.Equal(1, response[0].NumberOfNodesToCreate); } /// <summary> /// Verify that if the affinity of our requests is out-of-proc, that many out-of-proc nodes will /// be made (assuming it does not exceed MaxNodeCount) /// </summary> [Fact(Skip = "https://github.com/Microsoft/msbuild/issues/515")] public void TestOutOfProcNodesCreatedWhenAffinityIsOutOfProc() { _host.BuildParameters.MaxNodeCount = 4; CreateConfiguration(1, "foo.proj"); BuildRequest request1 = CreateBuildRequest(1, 1, new string[] { "foo" }, NodeAffinity.OutOfProc, _defaultParentRequest); BuildRequest request2 = CreateBuildRequest(2, 1, new string[] { "bar" }, NodeAffinity.OutOfProc, _defaultParentRequest); BuildRequestBlocker blocker = new BuildRequestBlocker(request1.ParentGlobalRequestId, new string[] { }, new BuildRequest[] { request1, request2 }); List<ScheduleResponse> response = new List<ScheduleResponse>(_scheduler.ReportRequestBlocked(1, blocker)); // Parent request is blocked by the fact that both child requests require the out-of-proc node that doesn't // exist yet. Assert.Single(response); Assert.Equal(ScheduleActionType.CreateNode, response[0].Action); Assert.Equal(NodeAffinity.OutOfProc, response[0].RequiredNodeType); Assert.Equal(2, response[0].NumberOfNodesToCreate); } /// <summary> /// Verify that if we have multiple requests and the max node count to fulfill them, /// we still won't create any new nodes if they're all for the same configuration -- /// they'd end up all being assigned to the same node. /// </summary> [Fact(Skip = "https://github.com/Microsoft/msbuild/issues/515")] public void TestNoNewNodesCreatedForMultipleRequestsWithSameConfiguration() { _host.BuildParameters.MaxNodeCount = 3; CreateConfiguration(1, "foo.proj"); BuildRequest request1 = CreateBuildRequest(1, 1, new string[] { "foo" }); BuildRequest request2 = CreateBuildRequest(2, 1, new string[] { "bar" }); BuildRequest request3 = CreateBuildRequest(3, 1, new string[] { "baz" }); BuildRequest request4 = CreateBuildRequest(4, 1, new string[] { "qux" }); BuildRequestBlocker blocker = new BuildRequestBlocker(request1.ParentGlobalRequestId, new string[] { }, new BuildRequest[] { request1, request2, request3, request4 }); List<ScheduleResponse> response = new List<ScheduleResponse>(_scheduler.ReportRequestBlocked(1, blocker)); Assert.Single(response); Assert.Equal(ScheduleActionType.ScheduleWithConfiguration, response[0].Action); Assert.Equal(request1, response[0].BuildRequest); } /// <summary> /// Verify that if the affinity of our requests is "any", we will not create more than /// MaxNodeCount nodes (1 IP node + MaxNodeCount - 1 OOP nodes) /// </summary> [Fact(Skip = "https://github.com/Microsoft/msbuild/issues/515")] public void TestMaxNodeCountNotExceededWithRequestsOfAffinityAny() { _host.BuildParameters.MaxNodeCount = 3; CreateConfiguration(1, "foo.proj"); CreateConfiguration(2, "bar.proj"); CreateConfiguration(3, "baz.proj"); CreateConfiguration(4, "quz.proj"); BuildRequest request1 = CreateBuildRequest(1, 1, new string[] { "foo" }); BuildRequest request2 = CreateBuildRequest(2, 2, new string[] { "bar" }); BuildRequest request3 = CreateBuildRequest(3, 3, new string[] { "baz" }); BuildRequest request4 = CreateBuildRequest(4, 4, new string[] { "qux" }); BuildRequestBlocker blocker = new BuildRequestBlocker(request1.ParentGlobalRequestId, new string[] { }, new BuildRequest[] { request1, request2, request3, request4 }); List<ScheduleResponse> response = new List<ScheduleResponse>(_scheduler.ReportRequestBlocked(1, blocker)); Assert.Equal(2, response.Count); Assert.Equal(ScheduleActionType.ScheduleWithConfiguration, response[0].Action); Assert.Equal(request1, response[0].BuildRequest); Assert.Equal(ScheduleActionType.CreateNode, response[1].Action); Assert.Equal(NodeAffinity.OutOfProc, response[1].RequiredNodeType); Assert.Equal(2, response[1].NumberOfNodesToCreate); } /// <summary> /// Verify that if we get 2 Any and 2 inproc requests, in that order, we will only create 2 nodes, since the initial inproc /// node will service an Any request instead of an inproc request, leaving only one non-inproc request for the second round /// of node creation. /// </summary> [Fact(Skip = "https://github.com/Microsoft/msbuild/issues/515")] public void VerifyRequestOrderingDoesNotAffectNodeCreationCountWithInProcAndAnyRequests() { // Since we're creating our own BuildManager, we need to make sure that the default // one has properly relinquished the inproc node NodeProviderInProc nodeProviderInProc = ((IBuildComponentHost)BuildManager.DefaultBuildManager).GetComponent(BuildComponentType.InProcNodeProvider) as NodeProviderInProc; nodeProviderInProc?.Dispose(); _host = new MockHost(); _host.BuildParameters.MaxNodeCount = 3; _scheduler = new Scheduler(); _scheduler.InitializeComponent(_host); _logger = new MockLogger(); _parameters = new BuildParameters(); _parameters.Loggers = new ILogger[] { _logger }; _parameters.ShutdownInProcNodeOnBuildFinish = true; _buildManager = new BuildManager(); CreateConfiguration(99, "parent.proj"); _defaultParentRequest = CreateBuildRequest(99, 99, new string[] { }, null); CreateConfiguration(1, "foo.proj"); BuildRequest request1 = CreateBuildRequest(1, 1, new string[] { "foo" }, NodeAffinity.Any, _defaultParentRequest); BuildRequest request2 = CreateBuildRequest(2, 1, new string[] { "bar" }, NodeAffinity.InProc, _defaultParentRequest); BuildRequest request3 = CreateBuildRequest(3, 1, new string[] { "bar" }, NodeAffinity.InProc, _defaultParentRequest); List<ScheduleResponse> response = new List<ScheduleResponse>(_scheduler.ReportRequestBlocked(1, new BuildRequestBlocker(-1, new string[] { }, new BuildRequest[] { _defaultParentRequest, request1, request2, request3 }))); Assert.Single(response); Assert.Equal(ScheduleActionType.CreateNode, response[0].Action); Assert.Equal(NodeAffinity.InProc, response[0].RequiredNodeType); Assert.Equal(1, response[0].NumberOfNodesToCreate); List<NodeInfo> nodeInfos = new List<NodeInfo>(new NodeInfo[] { new NodeInfo(1, NodeProviderType.InProc) }); List<ScheduleResponse> moreResponses = new List<ScheduleResponse>(_scheduler.ReportNodesCreated(nodeInfos)); Assert.Equal(2, moreResponses.Count); Assert.Equal(ScheduleActionType.ScheduleWithConfiguration, moreResponses[0].Action); Assert.Equal(ScheduleActionType.CreateNode, moreResponses[1].Action); Assert.Equal(NodeAffinity.OutOfProc, moreResponses[1].RequiredNodeType); Assert.Equal(1, moreResponses[1].NumberOfNodesToCreate); } /// <summary> /// Verify that if the affinity of our requests is out-of-proc, we will create as many as /// MaxNodeCount out-of-proc nodes /// </summary> [Fact(Skip = "https://github.com/Microsoft/msbuild/issues/515")] public void TestMaxNodeCountOOPNodesCreatedForOOPAffinitizedRequests() { _host.BuildParameters.MaxNodeCount = 3; CreateConfiguration(1, "foo.proj"); CreateConfiguration(2, "bar.proj"); CreateConfiguration(3, "baz.proj"); CreateConfiguration(4, "quz.proj"); BuildRequest request1 = CreateBuildRequest(1, 1, new string[] { "foo" }, NodeAffinity.OutOfProc, _defaultParentRequest); BuildRequest request2 = CreateBuildRequest(2, 2, new string[] { "bar" }, NodeAffinity.OutOfProc, _defaultParentRequest); BuildRequest request3 = CreateBuildRequest(3, 3, new string[] { "baz" }, NodeAffinity.OutOfProc, _defaultParentRequest); BuildRequest request4 = CreateBuildRequest(4, 4, new string[] { "qux" }, NodeAffinity.OutOfProc, _defaultParentRequest); BuildRequestBlocker blocker = new BuildRequestBlocker(request1.ParentGlobalRequestId, new string[] { }, new BuildRequest[] { request1, request2, request3, request4 }); List<ScheduleResponse> response = new List<ScheduleResponse>(_scheduler.ReportRequestBlocked(1, blocker)); // Parent request is blocked by the fact that both child requests require the out-of-proc node that doesn't // exist yet. Assert.Single(response); Assert.Equal(ScheduleActionType.CreateNode, response[0].Action); Assert.Equal(NodeAffinity.OutOfProc, response[0].RequiredNodeType); Assert.Equal(3, response[0].NumberOfNodesToCreate); } /// <summary> /// Verify that if only some of our requests are explicitly affinitized to out-of-proc, and that number /// is less than MaxNodeCount, that we only create MaxNodeCount - 1 OOP nodes (for a total of MaxNodeCount /// nodes, when the inproc node is included) /// </summary> [Fact(Skip = "https://github.com/Microsoft/msbuild/issues/515")] public void TestMaxNodeCountNodesNotExceededWithSomeOOPRequests1() { _host.BuildParameters.MaxNodeCount = 3; CreateConfiguration(1, "foo.proj"); CreateConfiguration(2, "bar.proj"); CreateConfiguration(3, "baz.proj"); CreateConfiguration(4, "quz.proj"); BuildRequest request1 = CreateBuildRequest(1, 1, new string[] { "foo" }, NodeAffinity.OutOfProc, _defaultParentRequest); BuildRequest request2 = CreateBuildRequest(2, 2, new string[] { "bar" }); BuildRequest request3 = CreateBuildRequest(3, 3, new string[] { "baz" }); BuildRequest request4 = CreateBuildRequest(4, 4, new string[] { "qux" }); BuildRequestBlocker blocker = new BuildRequestBlocker(request1.ParentGlobalRequestId, new string[] { }, new BuildRequest[] { request1, request2, request3, request4 }); List<ScheduleResponse> response = new List<ScheduleResponse>(_scheduler.ReportRequestBlocked(1, blocker)); Assert.Equal(2, response.Count); Assert.Equal(ScheduleActionType.ScheduleWithConfiguration, response[0].Action); Assert.Equal(request2, response[0].BuildRequest); Assert.Equal(ScheduleActionType.CreateNode, response[1].Action); Assert.Equal(NodeAffinity.OutOfProc, response[1].RequiredNodeType); Assert.Equal(2, response[1].NumberOfNodesToCreate); } /// <summary> /// Verify that if only some of our requests are explicitly affinitized to out-of-proc, and that number /// is less than MaxNodeCount, that we only create MaxNodeCount - 1 OOP nodes (for a total of MaxNodeCount /// nodes, when the inproc node is included) /// </summary> [Fact(Skip = "https://github.com/Microsoft/msbuild/issues/515")] public void TestMaxNodeCountNodesNotExceededWithSomeOOPRequests2() { _host.BuildParameters.MaxNodeCount = 3; CreateConfiguration(1, "foo.proj"); CreateConfiguration(2, "bar.proj"); CreateConfiguration(3, "baz.proj"); CreateConfiguration(4, "quz.proj"); BuildRequest request1 = CreateBuildRequest(1, 1, new string[] { "foo" }, NodeAffinity.OutOfProc, _defaultParentRequest); BuildRequest request2 = CreateBuildRequest(2, 2, new string[] { "bar" }, NodeAffinity.OutOfProc, _defaultParentRequest); BuildRequest request3 = CreateBuildRequest(3, 3, new string[] { "baz" }); BuildRequest request4 = CreateBuildRequest(4, 4, new string[] { "qux" }); BuildRequestBlocker blocker = new BuildRequestBlocker(request1.ParentGlobalRequestId, new string[] { }, new BuildRequest[] { request1, request2, request3, request4 }); List<ScheduleResponse> response = new List<ScheduleResponse>(_scheduler.ReportRequestBlocked(1, blocker)); Assert.Equal(2, response.Count); Assert.Equal(ScheduleActionType.ScheduleWithConfiguration, response[0].Action); Assert.Equal(request3, response[0].BuildRequest); Assert.Equal(ScheduleActionType.CreateNode, response[1].Action); Assert.Equal(NodeAffinity.OutOfProc, response[1].RequiredNodeType); Assert.Equal(2, response[1].NumberOfNodesToCreate); } /// <summary> /// Make sure that traversal projects are marked with an affinity of "InProc", which means that /// even if multiple are available, we should still only have the single inproc node. /// </summary> [Fact(Skip = "https://github.com/Microsoft/msbuild/issues/515")] public void TestTraversalAffinityIsInProc() { _host.BuildParameters.MaxNodeCount = 3; CreateConfiguration(1, "dirs.proj"); CreateConfiguration(2, "abc.metaproj"); BuildRequest request1 = CreateBuildRequest(1, 1, new string[] { "foo" }, _defaultParentRequest); BuildRequest request2 = CreateBuildRequest(2, 2, new string[] { "bar" }, _defaultParentRequest); BuildRequestBlocker blocker = new BuildRequestBlocker(request1.ParentGlobalRequestId, new string[] { }, new BuildRequest[] { request1, request2 }); List<ScheduleResponse> response = new List<ScheduleResponse>(_scheduler.ReportRequestBlocked(1, blocker)); // There will be no request to create a new node, because both of the above requests are traversals, // which have an affinity of "inproc", and the inproc node already exists. Assert.Single(response); Assert.Equal(ScheduleActionType.ScheduleWithConfiguration, response[0].Action); Assert.Equal(request1, response[0].BuildRequest); } /// <summary> /// With something approximating the BuildManager's build loop, make sure that we don't end up /// trying to create more nodes than we can actually support. /// </summary> [Fact(Skip = "https://github.com/Microsoft/msbuild/issues/515")] public void VerifyNoOverCreationOfNodesWithBuildLoop() { // Since we're creating our own BuildManager, we need to make sure that the default // one has properly relinquished the inproc node NodeProviderInProc nodeProviderInProc = ((IBuildComponentHost)BuildManager.DefaultBuildManager).GetComponent(BuildComponentType.InProcNodeProvider) as NodeProviderInProc; nodeProviderInProc?.Dispose(); _host = new MockHost(); _host.BuildParameters.MaxNodeCount = 3; _scheduler = new Scheduler(); _scheduler.InitializeComponent(_host); _parameters = new BuildParameters(); _parameters.ShutdownInProcNodeOnBuildFinish = true; _buildManager = new BuildManager(); CreateConfiguration(99, "parent.proj"); _defaultParentRequest = CreateBuildRequest(99, 99, new string[] { }, null); CreateConfiguration(1, "foo.proj"); BuildRequest request1 = CreateBuildRequest(1, 1, new string[] { "foo" }, NodeAffinity.OutOfProc, _defaultParentRequest); CreateConfiguration(2, "foo2.proj"); BuildRequest request2 = CreateBuildRequest(2, 2, new string[] { "bar" }, NodeAffinity.OutOfProc, _defaultParentRequest); CreateConfiguration(3, "foo3.proj"); BuildRequest request3 = CreateBuildRequest(3, 3, new string[] { "bar" }, NodeAffinity.InProc, _defaultParentRequest); List<ScheduleResponse> responses = new List<ScheduleResponse>(_scheduler.ReportRequestBlocked(1, new BuildRequestBlocker(-1, new string[] { }, new BuildRequest[] { _defaultParentRequest, request1, request2, request3 }))); int nextNodeId = 1; bool inProcNodeExists = false; MockPerformSchedulingActions(responses, ref nextNodeId, ref inProcNodeExists); Assert.Equal(4, nextNodeId); // 3 nodes } /// <summary> /// Verify that if we get two requests but one of them is a failure, we only get the failure result back. /// </summary> [Fact(Skip = "https://github.com/Microsoft/msbuild/issues/515")] public void TestTwoRequestsWithFirstFailure() { CreateConfiguration(1, "foo.proj"); BuildRequest request1 = CreateBuildRequest(1, 1, new string[] { "foo" }); BuildResult result1 = CacheBuildResult(request1, "foo", BuildResultUtilities.GetStopWithErrorResult()); BuildRequest request2 = CreateBuildRequest(2, 1, new string[] { "bar" }); BuildRequestBlocker blocker = new BuildRequestBlocker(request1.ParentGlobalRequestId, new string[] { }, new BuildRequest[] { request1, request2 }); List<ScheduleResponse> response = new List<ScheduleResponse>(_scheduler.ReportRequestBlocked(1, blocker)); Assert.Equal(2, response.Count); Assert.True(ResultsCache_Tests.AreResultsIdentical(result1, response[0].Unblocker.Result)); Assert.Equal(ScheduleActionType.ScheduleWithConfiguration, response[1].Action); } /// <summary> /// Verify that if we get two requests but one of them is a failure, we only get the failure result back. /// </summary> [Fact(Skip = "https://github.com/Microsoft/msbuild/issues/515")] public void TestTwoRequestsWithSecondFailure() { CreateConfiguration(1, "foo.proj"); BuildRequest request1 = CreateBuildRequest(1, 1, new string[] { "foo" }); BuildRequest request2 = CreateBuildRequest(2, 1, new string[] { "bar" }); BuildResult result2 = CacheBuildResult(request2, "bar", BuildResultUtilities.GetStopWithErrorResult()); BuildRequestBlocker blocker = new BuildRequestBlocker(request1.ParentGlobalRequestId, new string[] { }, new BuildRequest[] { request1, request2 }); List<ScheduleResponse> response = new List<ScheduleResponse>(_scheduler.ReportRequestBlocked(1, blocker)); Assert.Equal(2, response.Count); Assert.True(ResultsCache_Tests.AreResultsIdentical(result2, response[0].Unblocker.Result)); Assert.Equal(ScheduleActionType.ScheduleWithConfiguration, response[1].Action); } /// <summary> /// Verify that if we get three requests but one of them is a failure, we only get the failure result back. /// </summary> [Fact(Skip = "https://github.com/Microsoft/msbuild/issues/515")] public void TestThreeRequestsWithOneFailure() { CreateConfiguration(1, "foo.proj"); BuildRequest request1 = CreateBuildRequest(1, 1, new string[] { "foo" }); BuildRequest request2 = CreateBuildRequest(2, 1, new string[] { "bar" }); BuildResult result2 = CacheBuildResult(request2, "bar", BuildResultUtilities.GetStopWithErrorResult()); BuildRequest request3 = CreateBuildRequest(3, 1, new string[] { "baz" }); BuildRequestBlocker blocker = new BuildRequestBlocker(request1.ParentGlobalRequestId, new string[] { }, new BuildRequest[] { request1, request2, request3 }); List<ScheduleResponse> response = new List<ScheduleResponse>(_scheduler.ReportRequestBlocked(1, blocker)); Assert.Equal(2, response.Count); Assert.True(ResultsCache_Tests.AreResultsIdentical(result2, response[0].Unblocker.Result)); Assert.Equal(ScheduleActionType.ScheduleWithConfiguration, response[1].Action); } /// <summary> /// Verify that providing a result to the only outstanding request results in build complete. /// </summary> [Fact(Skip = "https://github.com/Microsoft/msbuild/issues/515")] public void TestResult() { CreateConfiguration(1, "foo.proj"); BuildRequest request = CreateBuildRequest(1, 1); BuildRequestBlocker blocker = new BuildRequestBlocker(request.ParentGlobalRequestId, new string[] { }, new BuildRequest[] { request }); List<ScheduleResponse> response = new List<ScheduleResponse>(_scheduler.ReportRequestBlocked(1, blocker)); BuildResult result = CreateBuildResult(request, "foo", BuildResultUtilities.GetSuccessResult()); response = new List<ScheduleResponse>(_scheduler.ReportResult(1, result)); Assert.Equal(2, response.Count); // First response is reporting the results for this request to the parent Assert.Equal(ScheduleActionType.ReportResults, response[0].Action); // Second response is continuing execution of the parent Assert.Equal(ScheduleActionType.ResumeExecution, response[1].Action); Assert.Equal(request.ParentGlobalRequestId, response[1].Unblocker.BlockedRequestId); } /// <summary> /// Tests that the detailed summary setting causes the summary to be produced. /// </summary> [Fact(Skip = "https://github.com/Microsoft/msbuild/issues/515")] public void TestDetailedSummary() { string contents = ObjectModelHelpers.CleanupFileContents(@" <Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'> <Target Name='test'> <Message Text='[success]'/> </Target> </Project> "); _parameters.DetailedSummary = true; Project project = new Project(new XmlTextReader(new StringReader(contents))); BuildRequestData data = new BuildRequestData(project.CreateProjectInstance(), new string[] { "test" }); BuildResult result = _buildManager.Build(_parameters, data); Assert.Equal(BuildResultCode.Success, result.OverallResult); _logger.AssertLogContains("[success]"); // Verify the existence of the first line of the header. StringReader reader = new StringReader(ResourceUtilities.GetResourceString("BuildHierarchyHeader")); _logger.AssertLogContains(reader.ReadLine()); } /// <summary> /// Creates a configuration and stores it in the cache. /// </summary> private void CreateConfiguration(int configId, string file) { BuildRequestData data = new BuildRequestData(file, new Dictionary<string, string>(), "4.0", new string[] { }, null); BuildRequestConfiguration config = new BuildRequestConfiguration(configId, data, "4.0"); config.ProjectInitialTargets = new List<string>(); config.ProjectDefaultTargets = new List<string>(); (_host.GetComponent(BuildComponentType.ConfigCache) as IConfigCache).AddConfiguration(config); } /// <summary> /// Creates and caches a built result. /// </summary> private BuildResult CacheBuildResult(BuildRequest request, string target, WorkUnitResult workUnitResult) { BuildResult result = CreateBuildResult(request, target, workUnitResult); IResultsCache resultsCache = _host.GetComponent(BuildComponentType.ResultsCache) as IResultsCache; resultsCache.AddResult(result); return result; } /// <summary> /// Creates a build result for a request /// </summary> private BuildResult CreateBuildResult(BuildRequest request, string target, WorkUnitResult workUnitResult) { BuildResult result = new BuildResult(request); result.AddResultsForTarget(target, new TargetResult(new TaskItem[] { }, workUnitResult)); return result; } /// <summary> /// Creates a build request. /// </summary> private BuildRequest CreateBuildRequest(int nodeRequestId, int configId) { return CreateBuildRequest(nodeRequestId, configId, new string[] { }); } /// <summary> /// Creates a build request. /// </summary> private BuildRequest CreateBuildRequest(int nodeRequestId, int configId, string[] targets) { return CreateBuildRequest(nodeRequestId, configId, targets, _defaultParentRequest); } /// <summary> /// Creates a build request. /// </summary> private BuildRequest CreateBuildRequest(int nodeRequestId, int configId, string[] targets, BuildRequest parentRequest) { return CreateBuildRequest(nodeRequestId, configId, targets, NodeAffinity.Any, parentRequest); } /// <summary> /// Creates a build request. /// </summary> private BuildRequest CreateBuildRequest(int nodeRequestId, int configId, string[] targets, NodeAffinity nodeAffinity, BuildRequest parentRequest) { HostServices hostServices = null; if (nodeAffinity != NodeAffinity.Any) { hostServices = new HostServices(); hostServices.SetNodeAffinity(String.Empty, nodeAffinity); } BuildRequest request = new BuildRequest(1 /* submissionId */, nodeRequestId, configId, targets, hostServices, BuildEventContext.Invalid, parentRequest); return request; } /// <summary> /// Method that fakes the actions done by BuildManager.PerformSchedulingActions /// </summary> private void MockPerformSchedulingActions(IEnumerable<ScheduleResponse> responses, ref int nodeId, ref bool inProcNodeExists) { List<NodeInfo> nodeInfos = new List<NodeInfo>(); foreach (ScheduleResponse response in responses) { if (response.Action == ScheduleActionType.CreateNode) { NodeProviderType nodeType; if (response.RequiredNodeType == NodeAffinity.InProc || (response.RequiredNodeType == NodeAffinity.Any && !inProcNodeExists)) { nodeType = NodeProviderType.InProc; inProcNodeExists = true; } else { nodeType = NodeProviderType.OutOfProc; } for (int i = 0; i < response.NumberOfNodesToCreate; i++) { nodeInfos.Add(new NodeInfo(nodeId, nodeType)); nodeId++; } } } if (nodeInfos.Count > 0) { List<ScheduleResponse> moreResponses = new List<ScheduleResponse>(_scheduler.ReportNodesCreated(nodeInfos)); MockPerformSchedulingActions(moreResponses, ref nodeId, ref inProcNodeExists); } } } }
/* * @(#)Configuration.java 1.11 2000/08/16 * */ /* Configuration files associate a property name with a value. The format is that of a Java .properties file.*/ using System; using System.Runtime.InteropServices; namespace Comzept.Genesis.Tidy { /// <summary> /// Read configuration file and manage configuration properties. /// /// (c) 1998-2000 (W3C) MIT, INRIA, Keio University /// See Tidy.java for the copyright notice. /// Derived from <a href="http://www.w3.org/People/Raggett/tidy"> /// HTML Tidy Release 4 Aug 2000</a> /// /// </summary> /// <author> Dave Raggett dsr@w3.org /// </author> /// <author> Andy Quick ac.quick@sympatico.ca (translation to Java) /// </author> /// <version> 1.0, 1999/05/22 /// </version> /// <version> 1.0.1, 1999/05/29 /// </version> /// <version> 1.1, 1999/06/18 Java Bean /// </version> /// <version> 1.2, 1999/07/10 Tidy Release 7 Jul 1999 /// </version> /// <version> 1.3, 1999/07/30 Tidy Release 26 Jul 1999 /// </version> /// <version> 1.4, 1999/09/04 DOM support /// </version> /// <version> 1.5, 1999/10/23 Tidy Release 27 Sep 1999 /// </version> /// <version> 1.6, 1999/11/01 Tidy Release 22 Oct 1999 /// </version> /// <version> 1.7, 1999/12/06 Tidy Release 30 Nov 1999 /// </version> /// <version> 1.8, 2000/01/22 Tidy Release 13 Jan 2000 /// </version> /// <version> 1.9, 2000/06/03 Tidy Release 30 Apr 2000 /// </version> /// <version> 1.10, 2000/07/22 Tidy Release 8 Jul 2000 /// </version> /// <version> 1.11, 2000/08/16 Tidy Release 4 Aug 2000 /// </version> [Serializable] public class Configuration { /// <summary> /// Character encoding /// </summary> public const int RAW = 0; /// <summary> /// Character encoding /// </summary> public const int ASCII = 1; /// <summary> /// Character encoding /// </summary> public const int LATIN1 = 2; /// <summary> /// Character encoding /// </summary> public const int UTF8 = 3; /// <summary> /// Character encoding /// </summary> public const int ISO2022 = 4; /// <summary> /// Character encoding /// </summary> public const int MACROMAN = 5; /// <summary> /// Mode controlling treatment of doctype /// </summary> public const int DOCTYPE_OMIT = 0; /// <summary> /// Mode controlling treatment of doctype /// </summary> public const int DOCTYPE_AUTO = 1; /// <summary> /// Mode controlling treatment of doctype /// </summary> public const int DOCTYPE_STRICT = 2; /// <summary> /// Mode controlling treatment of doctype /// </summary> public const int DOCTYPE_LOOSE = 3; /// <summary> /// Mode controlling treatment of doctype /// </summary> public const int DOCTYPE_USER = 4; /// <summary> /// default indentation /// </summary> protected internal int spaces = 2; /* */ /// <summary> /// default wrap margin /// </summary> protected internal int wraplen = 68; /* */ /// <summary> /// Default encoding is ASCII. /// </summary> protected internal int CharEncoding = ASCII; /// <summary> /// Default tab size (4). /// </summary> protected internal int tabsize = 4; /// <summary> /// see doctype property /// </summary> protected internal int docTypeMode = DOCTYPE_AUTO; /* see doctype property */ /// <summary> /// default text for alt attribute /// </summary> protected internal System.String altText = null; /* default text for alt attribute */ /// <summary> /// style sheet for slides /// </summary> protected internal System.String slidestyle = null; /* style sheet for slides */ /// <summary> /// user specified doctype /// </summary> protected internal System.String docTypeStr = null; /* user specified doctype */ /// <summary> /// file name to write errors to /// </summary> protected internal System.String errfile = null; /* file name to write errors to */ /// <summary> /// if true then output tidied markup /// </summary> protected internal bool writeback = false; /* if true then output tidied markup */ /// <summary> /// if true normal output is suppressed /// </summary> protected internal bool OnlyErrors = false; /* if true normal output is suppressed */ /// <summary> /// however errors are always shown /// </summary> protected internal bool ShowWarnings = true; /* however errors are always shown */ /// <summary> /// no 'Parsing X', guessed DTD or summary /// </summary> protected internal bool Quiet = false; /* no 'Parsing X', guessed DTD or summary */ /// <summary> /// indent content of appropriate tags /// </summary> protected internal bool IndentContent = false; /* indent content of appropriate tags */ /// <summary> /// does text/block level content effect indentation /// </summary> protected internal bool SmartIndent = false; /* does text/block level content effect indentation */ /// <summary> /// suppress optional end tags /// </summary> protected internal bool HideEndTags = false; /* suppress optional end tags */ /// <summary> /// treat input as XML /// </summary> protected internal bool XmlTags = false; /* treat input as XML */ /// <summary> /// create output as XML /// </summary> protected internal bool XmlOut = false; /* create output as XML */ /// <summary> /// output extensible HTML /// </summary> protected internal bool xHTML = false; /* output extensible HTML */ /// <summary> /// add &lt;?xml?&gt; for XML docs /// </summary> protected internal bool XmlPi = false; /* add <?xml?> for XML docs */ /// <summary> /// avoid mapping values &gt; 127 to entities /// </summary> protected internal bool RawOut = false; /* avoid mapping values > 127 to entities */ /// <summary> /// output tags in upper not lower case /// </summary> protected internal bool UpperCaseTags = false; /* output tags in upper not lower case */ /// <summary> /// output attributes in upper not lower case /// </summary> protected internal bool UpperCaseAttrs = false; /* output attributes in upper not lower case */ /// <summary> /// remove presentational clutter /// </summary> protected internal bool MakeClean = false; /* remove presentational clutter */ /// <summary> /// replace i by em and b by strong /// </summary> protected internal bool LogicalEmphasis = false; /* replace i by em and b by strong */ /// <summary> /// discard presentation tags /// </summary> protected internal bool DropFontTags = false; /* discard presentation tags */ /// <summary> /// discard empty p elements /// </summary> protected internal bool DropEmptyParas = true; /* discard empty p elements */ /// <summary> /// fix comments with adjacent hyphens /// </summary> protected internal bool FixComments = true; /* fix comments with adjacent hyphens */ /// <summary> /// o/p newline before &lt;br/&gt; or not? /// </summary> protected internal bool BreakBeforeBR = false; /* o/p newline before <br/> or not? */ /// <summary> /// create slides on each h2 element /// </summary> protected internal bool BurstSlides = false; /* create slides on each h2 element */ /// <summary> /// use numeric entities /// </summary> protected internal bool NumEntities = false; /* use numeric entities */ /// <summary> /// output " marks as &amp;quot; /// </summary> protected internal bool QuoteMarks = false; /* output " marks as &quot; */ /// <summary> /// output non-breaking space as entity /// </summary> protected internal bool QuoteNbsp = true; /* output non-breaking space as entity */ /// <summary> /// output naked ampersand as &amp;amp; /// </summary> protected internal bool QuoteAmpersand = true; /* output naked ampersand as &amp; */ /// <summary> /// wrap within attribute values /// </summary> protected internal bool WrapAttVals = false; /* wrap within attribute values */ /// <summary> /// wrap within JavaScript string literals /// </summary> protected internal bool WrapScriptlets = false; /* wrap within JavaScript string literals */ /// <summary> /// wrap within <![ ... ]> section tags /// </summary> protected internal bool WrapSection = true; /* wrap within <![ ... ]> section tags */ /// <summary> /// wrap within ASP pseudo elements /// </summary> protected internal bool WrapAsp = true; /* wrap within ASP pseudo elements */ /// <summary> /// wrap within JSTE pseudo elements /// </summary> protected internal bool WrapJste = true; /* wrap within JSTE pseudo elements */ /// <summary> /// wrap within PHP pseudo elements /// </summary> protected internal bool WrapPhp = true; /* wrap within PHP pseudo elements */ /// <summary> /// fix URLs by replacing \ with / /// </summary> protected internal bool FixBackslash = true; /* fix URLs by replacing \ with / */ protected internal bool IndentAttributes = false; /* newline+indent before each attribute */ /// <summary> /// if set to yes PIs must end with ?&gt; /// </summary> protected internal bool XmlPIs = false; /* if set to yes PIs must end with ?> */ /// <summary> /// if set to yes adds xml:space attr as needed /// </summary> protected internal bool XmlSpace = false; /* if set to yes adds xml:space attr as needed */ /// <summary> /// if yes text at body is wrapped in &lt;p&gt;'s /// </summary> protected internal bool EncloseBodyText = false; /* if yes text at body is wrapped in <p>'s */ /// <summary> /// if yes text in blocks is wrapped in &lt;p&gt;'s /// </summary> protected internal bool EncloseBlockText = false; /* if yes text in blocks is wrapped in <p>'s */ /// <summary> /// if yes last modied time is preserved /// </summary> protected internal bool KeepFileTimes = true; /* if yes last modied time is preserved */ /// <summary> /// draconian cleaning for Word2000 /// </summary> protected internal bool Word2000 = false; /* draconian cleaning for Word2000 */ /// <summary> /// add meta element indicating tidied doc /// </summary> protected internal bool TidyMark = true; /* add meta element indicating tidied doc */ /// <summary> /// if true format error output for GNU Emacs /// </summary> protected internal bool Emacs = false; /* if true format error output for GNU Emacs */ /// <summary> /// if true attributes may use newlines /// </summary> protected internal bool LiteralAttribs = false; /* if true attributes may use newlines */ /// <summary> /// TagTable associated with this Configuration. /// </summary> protected internal TagTable tt; /* TagTable associated with this Configuration */ [NonSerialized] private System.Collections.Specialized.NameValueCollection _properties = new System.Collections.Specialized.NameValueCollection(); /// <summary> /// Create a config instance. /// </summary> public Configuration() { } /// <summary> /// Add a property. /// </summary> /// <param name="p"></param> public virtual void AddProps(System.Collections.Specialized.NameValueCollection p) { System.Collections.IEnumerator enum_Renamed = p.Keys.GetEnumerator(); //UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'" while (enum_Renamed.MoveNext()) { //UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'" System.String key = (System.String) enum_Renamed.Current; System.String value_Renamed = p.Get(key); _properties[(System.String) key] = (System.String) value_Renamed; } parseProps(); } /// <summary> /// Parse a configuration file. /// </summary> /// <param name="filename"></param> public virtual void ParseFile(System.String filename) { try { new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read); _properties = new System.Collections.Specialized.NameValueCollection(System.Configuration.ConfigurationSettings.AppSettings); } catch (System.IO.IOException e) { System.Console.Error.WriteLine(filename + e.ToString()); return ; } parseProps(); } private void parseProps() { System.String value_Renamed; value_Renamed = _properties.Get("indent-spaces"); if (value_Renamed != null) spaces = parseInt(value_Renamed, "indent-spaces"); value_Renamed = _properties.Get("wrap"); if (value_Renamed != null) wraplen = parseInt(value_Renamed, "wrap"); value_Renamed = _properties.Get("wrap-attributes"); if (value_Renamed != null) WrapAttVals = parseBool(value_Renamed, "wrap-attributes"); value_Renamed = _properties.Get("wrap-script-literals"); if (value_Renamed != null) WrapScriptlets = parseBool(value_Renamed, "wrap-script-literals"); value_Renamed = _properties.Get("wrap-sections"); if (value_Renamed != null) WrapSection = parseBool(value_Renamed, "wrap-sections"); value_Renamed = _properties.Get("wrap-asp"); if (value_Renamed != null) WrapAsp = parseBool(value_Renamed, "wrap-asp"); value_Renamed = _properties.Get("wrap-jste"); if (value_Renamed != null) WrapJste = parseBool(value_Renamed, "wrap-jste"); value_Renamed = _properties.Get("wrap-php"); if (value_Renamed != null) WrapPhp = parseBool(value_Renamed, "wrap-php"); value_Renamed = _properties.Get("literal-attributes"); if (value_Renamed != null) LiteralAttribs = parseBool(value_Renamed, "literal-attributes"); value_Renamed = _properties.Get("tab-size"); if (value_Renamed != null) tabsize = parseInt(value_Renamed, "tab-size"); value_Renamed = _properties.Get("markup"); if (value_Renamed != null) OnlyErrors = parseInvBool(value_Renamed, "markup"); value_Renamed = _properties.Get("quiet"); if (value_Renamed != null) Quiet = parseBool(value_Renamed, "quiet"); value_Renamed = _properties.Get("tidy-mark"); if (value_Renamed != null) TidyMark = parseBool(value_Renamed, "tidy-mark"); value_Renamed = _properties.Get("indent"); if (value_Renamed != null) IndentContent = parseIndent(value_Renamed, "indent"); value_Renamed = _properties.Get("indent-attributes"); if (value_Renamed != null) IndentAttributes = parseBool(value_Renamed, "ident-attributes"); value_Renamed = _properties.Get("hide-endtags"); if (value_Renamed != null) HideEndTags = parseBool(value_Renamed, "hide-endtags"); value_Renamed = _properties.Get("input-xml"); if (value_Renamed != null) XmlTags = parseBool(value_Renamed, "input-xml"); value_Renamed = _properties.Get("output-xml"); if (value_Renamed != null) XmlOut = parseBool(value_Renamed, "output-xml"); value_Renamed = _properties.Get("output-xhtml"); if (value_Renamed != null) xHTML = parseBool(value_Renamed, "output-xhtml"); value_Renamed = _properties.Get("add-xml-pi"); if (value_Renamed != null) XmlPi = parseBool(value_Renamed, "add-xml-pi"); value_Renamed = _properties.Get("add-xml-decl"); if (value_Renamed != null) XmlPi = parseBool(value_Renamed, "add-xml-decl"); value_Renamed = _properties.Get("assume-xml-procins"); if (value_Renamed != null) XmlPIs = parseBool(value_Renamed, "assume-xml-procins"); value_Renamed = _properties.Get("raw"); if (value_Renamed != null) RawOut = parseBool(value_Renamed, "raw"); value_Renamed = _properties.Get("uppercase-tags"); if (value_Renamed != null) UpperCaseTags = parseBool(value_Renamed, "uppercase-tags"); value_Renamed = _properties.Get("uppercase-attributes"); if (value_Renamed != null) UpperCaseAttrs = parseBool(value_Renamed, "uppercase-attributes"); value_Renamed = _properties.Get("clean"); if (value_Renamed != null) MakeClean = parseBool(value_Renamed, "clean"); value_Renamed = _properties.Get("logical-emphasis"); if (value_Renamed != null) LogicalEmphasis = parseBool(value_Renamed, "logical-emphasis"); value_Renamed = _properties.Get("word-2000"); if (value_Renamed != null) Word2000 = parseBool(value_Renamed, "word-2000"); value_Renamed = _properties.Get("drop-empty-paras"); if (value_Renamed != null) DropEmptyParas = parseBool(value_Renamed, "drop-empty-paras"); value_Renamed = _properties.Get("drop-font-tags"); if (value_Renamed != null) DropFontTags = parseBool(value_Renamed, "drop-font-tags"); value_Renamed = _properties.Get("enclose-text"); if (value_Renamed != null) EncloseBodyText = parseBool(value_Renamed, "enclose-text"); value_Renamed = _properties.Get("enclose-block-text"); if (value_Renamed != null) EncloseBlockText = parseBool(value_Renamed, "enclose-block-text"); value_Renamed = _properties.Get("alt-text"); if (value_Renamed != null) altText = value_Renamed; value_Renamed = _properties.Get("add-xml-space"); if (value_Renamed != null) XmlSpace = parseBool(value_Renamed, "add-xml-space"); value_Renamed = _properties.Get("fix-bad-comments"); if (value_Renamed != null) FixComments = parseBool(value_Renamed, "fix-bad-comments"); value_Renamed = _properties.Get("split"); if (value_Renamed != null) BurstSlides = parseBool(value_Renamed, "split"); value_Renamed = _properties.Get("break-before-br"); if (value_Renamed != null) BreakBeforeBR = parseBool(value_Renamed, "break-before-br"); value_Renamed = _properties.Get("numeric-entities"); if (value_Renamed != null) NumEntities = parseBool(value_Renamed, "numeric-entities"); value_Renamed = _properties.Get("quote-marks"); if (value_Renamed != null) QuoteMarks = parseBool(value_Renamed, "quote-marks"); value_Renamed = _properties.Get("quote-nbsp"); if (value_Renamed != null) QuoteNbsp = parseBool(value_Renamed, "quote-nbsp"); value_Renamed = _properties.Get("quote-ampersand"); if (value_Renamed != null) QuoteAmpersand = parseBool(value_Renamed, "quote-ampersand"); value_Renamed = _properties.Get("write-back"); if (value_Renamed != null) writeback = parseBool(value_Renamed, "write-back"); value_Renamed = _properties.Get("keep-time"); if (value_Renamed != null) KeepFileTimes = parseBool(value_Renamed, "keep-time"); value_Renamed = _properties.Get("show-warnings"); if (value_Renamed != null) ShowWarnings = parseBool(value_Renamed, "show-warnings"); value_Renamed = _properties.Get("error-file"); if (value_Renamed != null) errfile = parseName(value_Renamed, "error-file"); value_Renamed = _properties.Get("slide-style"); if (value_Renamed != null) slidestyle = parseName(value_Renamed, "slide-style"); value_Renamed = _properties.Get("new-inline-tags"); if (value_Renamed != null) parseInlineTagNames(value_Renamed, "new-inline-tags"); value_Renamed = _properties.Get("new-blocklevel-tags"); if (value_Renamed != null) parseBlockTagNames(value_Renamed, "new-blocklevel-tags"); value_Renamed = _properties.Get("new-empty-tags"); if (value_Renamed != null) parseEmptyTagNames(value_Renamed, "new-empty-tags"); value_Renamed = _properties.Get("new-pre-tags"); if (value_Renamed != null) parsePreTagNames(value_Renamed, "new-pre-tags"); value_Renamed = _properties.Get("char-encoding"); if (value_Renamed != null) CharEncoding = parseCharEncoding(value_Renamed, "char-encoding"); value_Renamed = _properties.Get("doctype"); if (value_Renamed != null) docTypeStr = ParseDocType(value_Renamed, "doctype"); value_Renamed = _properties.Get("fix-backslash"); if (value_Renamed != null) FixBackslash = parseBool(value_Renamed, "fix-backslash"); value_Renamed = _properties.Get("gnu-emacs"); if (value_Renamed != null) Emacs = parseBool(value_Renamed, "gnu-emacs"); } /// <summary> /// Ensure that config is self consistent. /// </summary> public virtual void Adjust() { if (EncloseBlockText) EncloseBodyText = true; /* avoid the need to set IndentContent when SmartIndent is set */ if (SmartIndent) IndentContent = true; /* disable wrapping */ if (wraplen == 0) wraplen = 0x7FFFFFFF; /* Word 2000 needs o:p to be declared as inline */ if (Word2000) { tt.DefineInlineTag("o:p"); } /* XHTML is written in lower case */ if (xHTML) { XmlOut = true; UpperCaseTags = false; UpperCaseAttrs = false; } /* if XML in, then XML out */ if (XmlTags) { XmlOut = true; XmlPIs = true; } /* XML requires end tags */ if (XmlOut) { QuoteAmpersand = true; HideEndTags = false; } } private static int parseInt(System.String s, System.String option) { int i = 0; try { i = System.Int32.Parse(s); } catch (System.FormatException) { Report.badArgument(option); i = - 1; } return i; } private static bool parseBool(System.String s, System.String option) { bool b = false; if (s != null && s.Length > 0) { char c = s[0]; if ((c == 't') || (c == 'T') || (c == 'Y') || (c == 'y') || (c == '1')) b = true; else if ((c == 'f') || (c == 'F') || (c == 'N') || (c == 'n') || (c == '0')) b = false; else Report.badArgument(option); } return b; } private static bool parseInvBool(System.String s, System.String option) { bool b = false; if (s != null && s.Length > 0) { char c = s[0]; if ((c == 't') || (c == 'T') || (c == 'Y') || (c == 'y')) b = true; else if ((c == 'f') || (c == 'F') || (c == 'N') || (c == 'n')) b = false; else Report.badArgument(option); } return !b; } private static System.String parseName(System.String s, System.String option) { SupportClass.Tokenizer t = new SupportClass.Tokenizer(s); System.String rs = null; if (t.Count >= 1) rs = t.NextToken(); else Report.badArgument(option); return rs; } private static int parseCharEncoding(System.String s, System.String option) { int result = ASCII; if (Lexer.wstrcasecmp(s, "ascii") == 0) result = ASCII; else if (Lexer.wstrcasecmp(s, "latin1") == 0) result = LATIN1; else if (Lexer.wstrcasecmp(s, "raw") == 0) result = RAW; else if (Lexer.wstrcasecmp(s, "utf8") == 0) result = UTF8; else if (Lexer.wstrcasecmp(s, "iso2022") == 0) result = ISO2022; else if (Lexer.wstrcasecmp(s, "mac") == 0) result = MACROMAN; else Report.badArgument(option); return result; } /* slight hack to avoid changes to pprint.c */ private bool parseIndent(System.String s, System.String option) { bool b = IndentContent; if (Lexer.wstrcasecmp(s, "yes") == 0) { b = true; SmartIndent = false; } else if (Lexer.wstrcasecmp(s, "true") == 0) { b = true; SmartIndent = false; } else if (Lexer.wstrcasecmp(s, "no") == 0) { b = false; SmartIndent = false; } else if (Lexer.wstrcasecmp(s, "false") == 0) { b = false; SmartIndent = false; } else if (Lexer.wstrcasecmp(s, "auto") == 0) { b = true; SmartIndent = true; } else Report.badArgument(option); return b; } private void parseInlineTagNames(System.String s, System.String option) { SupportClass.Tokenizer t = new SupportClass.Tokenizer(s, " \t\n\r,"); while (t.HasMoreTokens()) { tt.DefineInlineTag(t.NextToken()); } } private void parseBlockTagNames(System.String s, System.String option) { SupportClass.Tokenizer t = new SupportClass.Tokenizer(s, " \t\n\r,"); while (t.HasMoreTokens()) { tt.DefineBlockTag(t.NextToken()); } } private void parseEmptyTagNames(System.String s, System.String option) { SupportClass.Tokenizer t = new SupportClass.Tokenizer(s, " \t\n\r,"); while (t.HasMoreTokens()) { tt.DefineEmptyTag(t.NextToken()); } } private void parsePreTagNames(System.String s, System.String option) { SupportClass.Tokenizer t = new SupportClass.Tokenizer(s, " \t\n\r,"); while (t.HasMoreTokens()) { tt.DefinePreTag(t.NextToken()); } } /// <summary> /// doctype: omit | auto | strict | loose | &lt;fpi&gt;, where the fpi is a string similar to "-//ACME//DTD HTML 3.14159//EN". /// </summary> /// <param name="s"></param> /// <param name="option"></param> /// <returns></returns> protected internal virtual System.String ParseDocType(System.String s, System.String option) { s = s.Trim(); /* "-//ACME//DTD HTML 3.14159//EN" or similar */ if (s.StartsWith("\"")) { docTypeMode = DOCTYPE_USER; return s; } /* read first word */ System.String word = ""; SupportClass.Tokenizer t = new SupportClass.Tokenizer(s, " \t\n\r,"); if (t.HasMoreTokens()) word = t.NextToken(); if (Lexer.wstrcasecmp(word, "omit") == 0) docTypeMode = DOCTYPE_OMIT; else if (Lexer.wstrcasecmp(word, "strict") == 0) docTypeMode = DOCTYPE_STRICT; else if (Lexer.wstrcasecmp(word, "loose") == 0 || Lexer.wstrcasecmp(word, "transitional") == 0) docTypeMode = DOCTYPE_LOOSE; else if (Lexer.wstrcasecmp(word, "auto") == 0) docTypeMode = DOCTYPE_AUTO; else { docTypeMode = DOCTYPE_AUTO; Report.badArgument(option); } return null; } } }
// // CollectionViewObservableTest.cs // // Author: // Antonius Riha <antoniusriha@gmail.com> // // Copyright (c) 2012 Antonius Riha // // 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 NUnit.Framework; using CollectionTransforms; using System.Collections.ObjectModel; using System.ComponentModel; namespace DevLab.Tests { [TestFixture()] public class CollectionViewObservableTest { [Test()] public void TestCtor () { model = new ObservableCollection<NotifySong> (DataGenerator.GetSampleNotifyItems ()); obj = new CollectionView<NotifySong> (model); var index = 0; foreach (NotifySong item in obj) { Assert.AreEqual (model [index], item); index++; } // Assert.IsTrue (obj.CanObserve); Assert.Fail (); } [Test()] public void TestCanSort () { TestCtor (); // sort desc collection is empty, therefore must not can sort Assert.IsFalse (obj.CanSort); // set invalid sort desc obj.SortDescriptions.Add (new SortDescription ()); Assert.IsFalse (obj.CanSort); // remove invalid sort desc and set valid sort desc obj.SortDescriptions.RemoveAt (0); obj.SortDescriptions.Add (new SortDescription ("Title", ListSortDirection.Ascending)); Assert.IsTrue (obj.CanSort); // add another valid sort desc obj.SortDescriptions.Add (new SortDescription ("Artist", ListSortDirection.Descending)); Assert.IsTrue (obj.CanSort); } [Test()] public void TestCanFilter () { TestCtor (); // filter not set, hence must not can filter Assert.IsFalse (obj.CanFilter); // set filter obj.Filter = (song) => { if (song.Artist.Contains ("Schubert")) return false; return true; }; Assert.IsTrue (obj.CanFilter); } [Test()] public void TestSort () { TestCtor (); // Add 2 sort descs SetupSortDesc (); /* * when this test was written, the sample data was: * new NotifySong("Franz Schubert", "Die Kraehe"), new NotifySong("The Beatles", "Help"), new NotifySong("GGGG", "Abcd"), new NotifySong("Franz Schubert", "Meeres Stille") * * therfore according to the sort rules above, the data should now look like this: new NotifySong("Franz Schubert", "Meeres Stille"), new NotifySong("Franz Schubert", "Die Kraehe"), new NotifySong("GGGG", "Abcd"), new NotifySong("The Beatles", "Help") * */ NotifySong [] songs = { new NotifySong("Franz Schubert", "Meeres Stille"), new NotifySong("Franz Schubert", "Die Kraehe"), new NotifySong("GGGG", "Abcd"), new NotifySong("The Beatles", "Help") }; var i = 0; foreach (NotifySong item in obj) { // System.Console.WriteLine ("Original: " + songs [i]); // System.Console.WriteLine ("CollectionView: " + item); Assert.AreEqual (songs [i].Artist, item.Artist); Assert.AreEqual (songs [i].Title, item.Title); i++; } } [Test()] public void TestFilter () { TestCtor (); SetupFilter (); foreach (NotifySong item in obj) { // System.Console.WriteLine (item); Assert.IsFalse (item.Artist.Contains ("Schubert")); } } [Test ()] public void TestAdd () { TestCtor (); // setup filter and sort desc SetupFilter (); SetupSortDesc (); // add songs and validate obj afterwards var song1 = new NotifySong ("Franz Schubert", "Abends unter der Linde"); model.Add (song1); var song2 = new NotifySong ("Kuuuuu", "onoonono"); model.Insert (1, song2); /* * when this test was written, the sample data was: * new NotifySong("Franz Schubert", "Die Kraehe"), new NotifySong("The Beatles", "Help"), new NotifySong("GGGG", "Abcd"), new NotifySong("Franz Schubert", "Meeres Stille") * * therfore according to the sort rules above, the data after the 2 insert * actions should now look like this: new NotifySong("GGGG", "Abcd"), new NotifySong ("Kuuuuu", "onoonono"), new NotifySong("The Beatles", "Help") * */ NotifySong [] songs = { new NotifySong("GGGG", "Abcd"), new NotifySong ("Kuuuuu", "onoonono"), new NotifySong("The Beatles", "Help") }; var i = 0; foreach (NotifySong item in obj) { // System.Console.WriteLine ("Original: " + songs [i]); // System.Console.WriteLine ("CollectionView: " + item); Assert.AreEqual (songs [i].Artist, item.Artist); Assert.AreEqual (songs [i].Title, item.Title); i++; } } [Test()] public void TestRemove () { TestCtor (); // setup filter and sort desc SetupFilter (); SetupSortDesc (); model.RemoveAt (2); /* * when this test was written, the sample data was: * new NotifySong("Franz Schubert", "Die Kraehe"), new NotifySong("The Beatles", "Help"), new NotifySong("GGGG", "Abcd"), new NotifySong("Franz Schubert", "Meeres Stille") * * therfore according to the sort rules above, the data after the remove * action should now look like this: new NotifySong("The Beatles", "Help") * */ NotifySong [] songs = { new NotifySong("The Beatles", "Help") }; var i = 0; foreach (NotifySong item in obj) { // System.Console.WriteLine ("Original: " + songs [i]); // System.Console.WriteLine ("CollectionView: " + item); Assert.AreEqual (songs [i].Artist, item.Artist); Assert.AreEqual (songs [i].Title, item.Title); i++; } } [Test()] public void TestReplace () { TestCtor (); // setup filter and sort desc SetupFilter (); SetupSortDesc (); var song1 = new NotifySong ("OOOOO", "aaaaaaa"); model [2] = song1; model [3] = null; /* * when this test was written, the sample data was: * new NotifySong("Franz Schubert", "Die Kraehe"), new NotifySong("The Beatles", "Help"), new NotifySong("GGGG", "Abcd"), new NotifySong("Franz Schubert", "Meeres Stille") * * therfore according to the sort rules above, the data after the replace * actions should now look like this: null, new NotifySong("OOOOO", "aaaaaaa"), new NotifySong("The Beatles", "Help") * */ NotifySong [] songs = { null, new NotifySong("OOOOO", "aaaaaaa"), new NotifySong("The Beatles", "Help") }; var i = 0; foreach (NotifySong item in obj) { System.Console.WriteLine ("Original: " + songs [i]); System.Console.WriteLine ("CollectionView: " + item); if (songs [i] == null) { Assert.AreEqual (songs [i], item); } else { Assert.AreEqual (songs [i].Artist, item.Artist); Assert.AreEqual (songs [i].Title, item.Title); } i++; } } [Test()] public void TestMove () { TestCtor (); // setup filter SetupFilter (); model.Move (1, 2); /* * when this test was written, the sample data was: * new NotifySong("Franz Schubert", "Die Kraehe"), new NotifySong("The Beatles", "Help"), new NotifySong("GGGG", "Abcd"), new NotifySong("Franz Schubert", "Meeres Stille") * * therfore the data after the move action should now look like this: new NotifySong("GGGG", "Abcd"), new NotifySong("The Beatles", "Help") * */ NotifySong [] songs = { new NotifySong("GGGG", "Abcd"), new NotifySong("The Beatles", "Help") }; var i = 0; foreach (NotifySong item in obj) { // System.Console.WriteLine ("Original: " + songs [i]); // System.Console.WriteLine ("CollectionView: " + item); Assert.AreEqual (songs [i].Artist, item.Artist); Assert.AreEqual (songs [i].Title, item.Title); i++; } } void SetupFilter () { obj.Filter = (song) => { if (song == null) return true; if (song.Artist.Contains ("Schubert")) return false; return true; }; } void SetupSortDesc () { obj.SortDescriptions.Add (new SortDescription ("Artist", ListSortDirection.Ascending)); obj.SortDescriptions.Add (new SortDescription ("Title", ListSortDirection.Descending)); } CollectionView<NotifySong> obj; ObservableCollection<NotifySong> model; } }
// 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Implementation.Outlining; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Projection; using Microsoft.VisualStudio.Text.Tagging; using Moq; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Tagging { public class AsynchronousTaggerTests : TestBase { /// <summary> /// This hits a special codepath in the product that is optimized for more than 100 spans. /// I'm leaving this test here because it covers that code path (as shown by code coverage) /// </summary> [WpfFact] [WorkItem(530368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530368")] public async Task LargeNumberOfSpans() { using (var workspace = await TestWorkspace.CreateCSharpAsync(@"class Program { void M() { int z = 0; z = z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z; } }")) { Callback tagProducer = (span, cancellationToken) => { return new List<ITagSpan<TestTag>>() { new TagSpan<TestTag>(span, new TestTag()) }; }; var asyncListener = new TaggerOperationListener(); WpfTestCase.RequireWpfFact($"{nameof(AsynchronousTaggerTests)}.{nameof(LargeNumberOfSpans)} creates asynchronous taggers"); var notificationService = workspace.GetService<IForegroundNotificationService>(); var eventSource = CreateEventSource(); var taggerProvider = new TestTaggerProvider( tagProducer, eventSource, workspace, asyncListener, notificationService); var document = workspace.Documents.First(); var textBuffer = document.TextBuffer; var snapshot = textBuffer.CurrentSnapshot; var tagger = taggerProvider.CreateTagger<TestTag>(textBuffer); using (IDisposable disposable = (IDisposable)tagger) { var spans = Enumerable.Range(0, 101).Select(i => new Span(i * 4, 1)); var snapshotSpans = new NormalizedSnapshotSpanCollection(snapshot, spans); eventSource.SendUpdateEvent(); await asyncListener.CreateWaitTask(); var tags = tagger.GetTags(snapshotSpans); Assert.Equal(1, tags.Count()); } } } [WpfFact] public async Task TestSynchronousOutlining() { using (var workspace = await TestWorkspace.CreateCSharpAsync("class Program {\r\n\r\n}")) { WpfTestCase.RequireWpfFact($"{nameof(AsynchronousTaggerTests)}.{nameof(TestSynchronousOutlining)} creates asynchronous taggers"); var tagProvider = new OutliningTaggerProvider( workspace.GetService<IForegroundNotificationService>(), workspace.GetService<ITextEditorFactoryService>(), workspace.GetService<IEditorOptionsFactoryService>(), workspace.GetService<IProjectionBufferFactoryService>(), workspace.ExportProvider.GetExports<IAsynchronousOperationListener, FeatureMetadata>()); var document = workspace.Documents.First(); var textBuffer = document.TextBuffer; var tagger = tagProvider.CreateTagger<IOutliningRegionTag>(textBuffer); using (var disposable = (IDisposable)tagger) { // The very first all to get tags should return the single outlining span. var tags = tagger.GetAllTags(new NormalizedSnapshotSpanCollection(textBuffer.CurrentSnapshot.GetFullSpan()), CancellationToken.None); Assert.Equal(1, tags.Count()); } } } private static TestTaggerEventSource CreateEventSource() { return new TestTaggerEventSource(); } private sealed class TaggerOperationListener : AsynchronousOperationListener { } private sealed class TestTag : TextMarkerTag { public TestTag() : base("Test") { } } private delegate List<ITagSpan<TestTag>> Callback(SnapshotSpan span, CancellationToken cancellationToken); private sealed class TestTaggerProvider : AsynchronousTaggerProvider<TestTag> { private readonly Callback _callback; private readonly ITaggerEventSource _eventSource; private readonly Workspace _workspace; private readonly bool _disableCancellation; public TestTaggerProvider( Callback callback, ITaggerEventSource eventSource, Workspace workspace, IAsynchronousOperationListener asyncListener, IForegroundNotificationService notificationService, bool disableCancellation = false) : base(asyncListener, notificationService) { _callback = callback; _eventSource = eventSource; _workspace = workspace; _disableCancellation = disableCancellation; } protected override ITaggerEventSource CreateEventSource(ITextView textViewOpt, ITextBuffer subjectBuffer) { return _eventSource; } protected override Task ProduceTagsAsync(TaggerContext<TestTag> context, DocumentSnapshotSpan snapshotSpan, int? caretPosition) { var tags = _callback(snapshotSpan.SnapshotSpan, context.CancellationToken); if (tags != null) { foreach (var tag in tags) { context.AddTag(tag); } } return SpecializedTasks.EmptyTask; } } private sealed class TestTaggerEventSource : AbstractTaggerEventSource { public TestTaggerEventSource() : base(delay: TaggerDelay.NearImmediate) { } public void SendUpdateEvent() { this.RaiseChanged(); } public override void Connect() { } public override void Disconnect() { } } } }
// ---------------------------------------------------------------------------------- // // 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 AutoMapper; using Microsoft.Azure.Commands.Network.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using Microsoft.Azure.Commands.ResourceManager.Common.Tags; using Microsoft.Azure.Management.Network; using System.Collections; using System.Collections.Generic; using System.Management.Automation; using MNM = Microsoft.Azure.Management.Network.Models; namespace Microsoft.Azure.Commands.Network { [Cmdlet(VerbsCommon.New, "AzureRmApplicationGateway", SupportsShouldProcess = true), OutputType(typeof(PSApplicationGateway))] public class NewAzureApplicationGatewayCommand : ApplicationGatewayBaseCmdlet { [Alias("ResourceName")] [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource name.")] [ValidateNotNullOrEmpty] public virtual string Name { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group name.")] [ResourceGroupCompleter] [ValidateNotNullOrEmpty] public virtual string ResourceGroupName { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "location.")] [LocationCompleter("Microsoft.Network/applicationGateways")] [ValidateNotNullOrEmpty] public virtual string Location { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The SKU of application gateway")] [ValidateNotNullOrEmpty] public virtual PSApplicationGatewaySku Sku { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The SSL policy of application gateway")] public virtual PSApplicationGatewaySslPolicy SslPolicy { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of IPConfiguration (subnet)")] [ValidateNotNullOrEmpty] public List<PSApplicationGatewayIPConfiguration> GatewayIPConfigurations { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of ssl certificates")] public List<PSApplicationGatewaySslCertificate> SslCertificates { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of authentication certificates")] public List<PSApplicationGatewayAuthenticationCertificate> AuthenticationCertificates { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of frontend IP config")] public List<PSApplicationGatewayFrontendIPConfiguration> FrontendIPConfigurations { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of frontend port")] public List<PSApplicationGatewayFrontendPort> FrontendPorts { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of probe")] public List<PSApplicationGatewayProbe> Probes { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of backend address pool")] public List<PSApplicationGatewayBackendAddressPool> BackendAddressPools { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of backend http settings")] public List<PSApplicationGatewayBackendHttpSettings> BackendHttpSettingsCollection { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of http listener")] public List<PSApplicationGatewayHttpListener> HttpListeners { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of UrlPathMap")] public List<PSApplicationGatewayUrlPathMap> UrlPathMaps { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of request routing rule")] public List<PSApplicationGatewayRequestRoutingRule> RequestRoutingRules { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of redirect configuration")] public List<PSApplicationGatewayRedirectConfiguration> RedirectConfigurations { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Firewall configuration")] public virtual PSApplicationGatewayWebApplicationFirewallConfiguration WebApplicationFirewallConfiguration { get; set; } [Parameter( Mandatory = false, HelpMessage = " Whether HTTP2 is enabled.")] public SwitchParameter EnableHttp2 { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "A hashtable which represents resource tags.")] public Hashtable Tag { get; set; } [Parameter( Mandatory = false, HelpMessage = "Do not ask for confirmation if you want to overrite a resource")] public SwitchParameter Force { get; set; } [Parameter(Mandatory = false, HelpMessage = "Run cmdlet in the background")] public SwitchParameter AsJob { get; set; } public override void ExecuteCmdlet() { base.ExecuteCmdlet(); WriteWarning("The output object type of this cmdlet will be modified in a future release."); var present = this.IsApplicationGatewayPresent(this.ResourceGroupName, this.Name); ConfirmAction( Force.IsPresent, string.Format(Microsoft.Azure.Commands.Network.Properties.Resources.OverwritingResource, Name), Microsoft.Azure.Commands.Network.Properties.Resources.OverwritingResourceMessage, Name, () => { var applicationGateway = CreateApplicationGateway(); WriteObject(applicationGateway); }, () => present); } private PSApplicationGateway CreateApplicationGateway() { var applicationGateway = new PSApplicationGateway(); applicationGateway.Name = this.Name; applicationGateway.ResourceGroupName = this.ResourceGroupName; applicationGateway.Location = this.Location; applicationGateway.Sku = this.Sku; if (this.SslPolicy != null) { applicationGateway.SslPolicy = new PSApplicationGatewaySslPolicy(); applicationGateway.SslPolicy = this.SslPolicy; } if (this.GatewayIPConfigurations != null) { applicationGateway.GatewayIPConfigurations = this.GatewayIPConfigurations; } if (this.SslCertificates != null) { applicationGateway.SslCertificates = this.SslCertificates; } if (this.AuthenticationCertificates != null) { applicationGateway.AuthenticationCertificates = this.AuthenticationCertificates; } if (this.FrontendIPConfigurations != null) { applicationGateway.FrontendIPConfigurations = this.FrontendIPConfigurations; } if (this.FrontendPorts != null) { applicationGateway.FrontendPorts = this.FrontendPorts; } if (this.Probes != null) { applicationGateway.Probes = this.Probes; } if (this.BackendAddressPools != null) { applicationGateway.BackendAddressPools = this.BackendAddressPools; } if (this.BackendHttpSettingsCollection != null) { applicationGateway.BackendHttpSettingsCollection = this.BackendHttpSettingsCollection; } if (this.HttpListeners != null) { applicationGateway.HttpListeners = this.HttpListeners; } if (this.UrlPathMaps != null) { applicationGateway.UrlPathMaps = this.UrlPathMaps; } if (this.RequestRoutingRules != null) { applicationGateway.RequestRoutingRules = this.RequestRoutingRules; } if (this.RedirectConfigurations != null) { applicationGateway.RedirectConfigurations = this.RedirectConfigurations; } if (this.WebApplicationFirewallConfiguration != null) { applicationGateway.WebApplicationFirewallConfiguration = this.WebApplicationFirewallConfiguration; } if (this.EnableHttp2.IsPresent) { applicationGateway.EnableHttp2 = true; } // Normalize the IDs ApplicationGatewayChildResourceHelper.NormalizeChildResourcesId(applicationGateway); // Map to the sdk object var appGwModel = NetworkResourceManagerProfile.Mapper.Map<MNM.ApplicationGateway>(applicationGateway); appGwModel.Tags = TagsConversionHelper.CreateTagDictionary(this.Tag, validate: true); // Execute the Create ApplicationGateway call this.ApplicationGatewayClient.CreateOrUpdate(this.ResourceGroupName, this.Name, appGwModel); var getApplicationGateway = this.GetApplicationGateway(this.ResourceGroupName, this.Name); return getApplicationGateway; } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using NUnit.Framework; using Palaso.IO; namespace Palaso.Tests { [TestFixture] public class SFMReaderTest { [Test] public void ReadNextText_MultilineInitialTextStateFollowedByMedialTag_Null() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "text first\ntext \\tag")); SFMReader test = new SFMReader(stream); Assert.AreEqual(string.Empty, test.ReadNextText()); } [Test] public void ReadNextText_MultilineInitialTextStateFollowedByInitialTagThenText_2ndLineText() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "text first\n\\tag more text")); SFMReader test = new SFMReader(stream); Assert.AreEqual("more text", test.ReadNextText()); } [Test] public void ReadNextText_MultilineInitialTextState_Null() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "text first\nmore text")); SFMReader test = new SFMReader(stream); Assert.AreEqual("text first\nmore text", test.ReadInitialText()); Assert.IsNull(test.ReadNextText()); } [Test] public void ReadNextText_MultilineInitialTextStateFollowedByTagOnly_Empty() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "text first\n\\tag")); SFMReader test = new SFMReader(stream); Assert.AreEqual(string.Empty, test.ReadNextText()); } [Test] public void ReadNextText_MultilineInitialTextStateFollowedByEmpty_Null() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "text first\n")); SFMReader test = new SFMReader(stream); Assert.AreEqual("text first\n", test.ReadInitialText()); Assert.IsNull(test.ReadNextText()); } // Multiline tag state [Test] public void ReadNextText_MultilineTagStateFollowedByMedialTag_1stPartOf2ndLineText() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\tag\ntext \\tag more text")); SFMReader test = new SFMReader(stream); Assert.AreEqual("text ", test.ReadNextText()); Assert.AreEqual("more text", test.ReadNextText()); } [Test] public void ReadNextText_MultilineTagStateFollowedByTextOnly_2ndLineText() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\tag\nmore text")); SFMReader test = new SFMReader(stream); Assert.AreEqual("more text", test.ReadNextText()); } [Test] public void ReadNextText_MultilineTagStateFollowedByTagOnly_Empty() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\tag\n\\tag")); SFMReader test = new SFMReader(stream); Assert.AreEqual(string.Empty, test.ReadNextText()); } [Test] public void ReadNextText_MultilineTagStateFollowedByEmpty_Null() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\tag\n")); SFMReader test = new SFMReader(stream); Assert.AreEqual(string.Empty, test.ReadNextText()); } // Multiline Text state [Test] public void ReadNextText_MultilineTextStateFollowedByMedialTag_1stLineTextAnd2ndLineBeginningText() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\tag text first\ntext \\tag more text")); SFMReader test = new SFMReader(stream); Assert.AreEqual("text first\ntext ", test.ReadNextText()); Assert.AreEqual("more text", test.ReadNextText()); } [Test] public void ReadNextText_MultilineTextStateFollowedByInitialTag_1stLineTextThen2ndLineText() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\tag text first\n\\tag more text")); SFMReader test = new SFMReader(stream); Assert.AreEqual("text first\n", test.ReadNextText()); Assert.AreEqual("more text", test.ReadNextText()); } [Test] public void ReadNextText_MultilineTextStateFollowedByTextOnly_1stAnd2ndLineText() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\tag text first\nmore text")); SFMReader test = new SFMReader(stream); Assert.AreEqual("text first\nmore text", test.ReadNextText()); } [Test] public void ReadNextText_MultilineTextStateFollowedByTagOnly_1stLineText() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\tag text first\n\\tag")); SFMReader test = new SFMReader(stream); Assert.AreEqual("text first\n", test.ReadNextText()); } [Test] public void ReadNextText_MultilineTextStateFollowedByEmpty_1stAnd2ndLineText() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\tag text first\n")); SFMReader test = new SFMReader(stream); Assert.AreEqual("text first\n", test.ReadNextText()); } // Multiline Next Text, Empty state [Test] public void ReadNextText_MultilineEmptyFollowedByEmpty_Null() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\tag\n\n")); SFMReader test = new SFMReader(stream); Assert.AreEqual("\n", test.ReadNextText()); } [Test] public void ReadNextText_MultilineEmptyFollowedByTextOnly_2ndLine() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\tag\n\ntext")); SFMReader test = new SFMReader(stream); Assert.AreEqual("\ntext", test.ReadNextText()); } [Test] public void ReadNextText_MultilineEmptyFollowedByTag_Empty() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\tag\n\n\\tag")); SFMReader test = new SFMReader(stream); Assert.AreEqual("\n", test.ReadNextText()); } //---- [Test] public void ReadNextText_TextOnly_Null() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( @"text first")); SFMReader test = new SFMReader(stream); Assert.IsNull(test.ReadNextText()); } [Test] public void ReadNextText_TagOnly_Empty() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( @"\one")); SFMReader test = new SFMReader(stream); string token = test.ReadNextText(); Assert.AreEqual("", token); } [Test] public void ReadNextText_InitialText() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( @"text first\bf text")); SFMReader test = new SFMReader(stream); string token = test.ReadNextText(); Assert.AreEqual("text", token); } [Test] public void ReadNextText_MedialText() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( @"\one text first\bf")); SFMReader test = new SFMReader(stream); string token = test.ReadNextText(); Assert.AreEqual("text first", token); } [Test] public void ReadNextText_TagLast_Empty() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( @"\one text first\two")); SFMReader test = new SFMReader(stream); test.ReadNextText(); string token = test.ReadNextText(); Assert.AreEqual(string.Empty, token); } [Test] public void ReadNextText_TextLast_Null() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( @"\one text first")); SFMReader test = new SFMReader(stream); test.ReadNextText(); string token = test.ReadNextText(); Assert.IsNull(token); } [Test] public void ReadNextText_NoText_Null() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( @"")); SFMReader test = new SFMReader(stream); string token = test.ReadNextText(); Assert.IsNull(token); } [Test] public void ReadNextText_TwoTagsInARow_Empty() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( @"\tag1\tag2")); SFMReader test = new SFMReader(stream); string token = test.ReadNextText(); Assert.AreEqual(string.Empty, token); } [Test] public void ReadInitialText_InitialText() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( @"text first\bf")); SFMReader test = new SFMReader(stream); string token = test.ReadInitialText(); Assert.AreEqual("text first", token); } [Test] public void ReadInitialText_NoInitialText_Empty() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( @"\bf some text")); SFMReader test = new SFMReader(stream); string token = test.ReadInitialText(); Assert.AreEqual(string.Empty, token); } [Test] public void ReadInitialText_TagOnly_Empty() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( @"\bf")); SFMReader test = new SFMReader(stream); string token = test.ReadInitialText(); Assert.AreEqual(string.Empty, token); } [Test] public void ReadInitialText_TextOnly() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( @"some text")); SFMReader test = new SFMReader(stream); string token = test.ReadInitialText(); Assert.AreEqual("some text", token); } [Test] public void ReadInitialText_Empty() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( @"")); SFMReader test = new SFMReader(stream); string token = test.ReadInitialText(); Assert.AreEqual("", token); } // Initial Text, mulitiline [Test] public void ReadInitialText_MultiLineEmptyFollowedByEmpty_Empty() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\n\n")); SFMReader test = new SFMReader(stream); string token = test.ReadInitialText(); Assert.AreEqual("\n\n", token); } [Test] public void ReadInitialText_MultiLineEmptyFollowedByText() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\ntext")); SFMReader test = new SFMReader(stream); string token = test.ReadInitialText(); Assert.AreEqual("\ntext", token); } [Test] public void ReadInitialText_MultiLineEmptyFollowedByTag_Empty() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\n\\tag")); SFMReader test = new SFMReader(stream); string token = test.ReadInitialText(); Assert.AreEqual("\n", token); } [Test] public void ReadInitialText_MultiLineEmptyFollowedByTextAndTag_2ndLineBeginningText() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\ntext \\tag")); SFMReader test = new SFMReader(stream); string token = test.ReadInitialText(); Assert.AreEqual("\ntext ", token); } [Test] public void ReadInitialText_MultiLineTextFollowedByEmpty_1stLine() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "text\n")); SFMReader test = new SFMReader(stream); string token = test.ReadInitialText(); Assert.AreEqual("text\n", token); } [Test] public void ReadInitialText_MultiLineTextFollowedByText_2Lines() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "text\nmore text")); SFMReader test = new SFMReader(stream); string token = test.ReadInitialText(); Assert.AreEqual("text\nmore text", token); } [Test] public void ReadInitialText_MultiLineTextFollowedByTag_1stLine() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "text\n\\tag")); SFMReader test = new SFMReader(stream); string token = test.ReadInitialText(); Assert.AreEqual("text\n", token); } [Test] public void ReadInitialText_MultiLineTextFollowedByTextAndTag_1stLineAndBeginning2ndLine() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "text\nmore text\\tag")); SFMReader test = new SFMReader(stream); string token = test.ReadInitialText(); Assert.AreEqual("text\nmore text", token); } [Test] public void ReadInitialText_MultiLineTagFollowedByEmpty_Empty() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\tag\n")); SFMReader test = new SFMReader(stream); string token = test.ReadInitialText(); Assert.AreEqual(string.Empty, token); } [Test] public void ReadInitialText_MultiLineTagFollowedByText_Empty() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\tag\ntext")); SFMReader test = new SFMReader(stream); string token = test.ReadInitialText(); Assert.AreEqual(string.Empty, token); } [Test] public void ReadNextTag_MedialTag() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( @"\tag text first\bf more text")); SFMReader test = new SFMReader(stream); test.ReadNextTag(); string token = test.ReadNextTag(); Assert.AreEqual("bf", token); } [Test] public void ReadNextTag_InitialText_FirstTag() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( @"text first\bf")); SFMReader test = new SFMReader(stream); string token = test.ReadNextTag(); Assert.AreEqual("bf", token); } [Test] public void ReadNextTag_InitialTag() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( @"\bf some text")); SFMReader test = new SFMReader(stream); string token = test.ReadNextTag(); Assert.AreEqual("bf", token); } [Test] public void ReadNextTag_FinalTag() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( @"\tag text first\bf")); SFMReader test = new SFMReader(stream); test.ReadNextTag(); string token = test.ReadNextTag(); Assert.AreEqual("bf", token); } [Test] public void ReadNextTag_AfterFinalText_Null() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( @"\bf text")); SFMReader test = new SFMReader(stream); test.ReadNextTag(); string token = test.ReadNextTag(); Assert.IsNull(token); } [Test] public void ReadNextTag_TagOnly() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( @"\bf")); SFMReader test = new SFMReader(stream); string token = test.ReadNextTag(); Assert.AreEqual("bf", token); } [Test] public void ReadNextTag_TextOnly_Null() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( @"text first\bf")); SFMReader test = new SFMReader(stream); string token = test.ReadNextTag(); Assert.AreEqual("bf", token); } [Test] public void ReadNextTag_EmptyTag() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( @"\ some text")); SFMReader test = new SFMReader(stream); string token = test.ReadNextTag(); Assert.AreEqual(string.Empty, token); } // Next tag, multiline, from empty [Test] public void ReadNextTag_MultilineEmptyFollowedByEmpty_Null() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\ntext")); SFMReader test = new SFMReader(stream); string token = test.ReadNextTag(); Assert.IsNull(token); } [Test] public void ReadNextTag_MultilineEmptyFollowedByText_Null() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\ntext")); SFMReader test = new SFMReader(stream); string token = test.ReadNextTag(); Assert.IsNull(token); } [Test] public void ReadNextTag_MultilineEmptyFollowedByTextThenTag_Tag() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\ntext\\tag")); SFMReader test = new SFMReader(stream); string token = test.ReadNextTag(); Assert.AreEqual("tag", token); } [Test] public void ReadNextTag_MultilineEmptyFollowedByTagOnly() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\n\\tag")); SFMReader test = new SFMReader(stream); string token = test.ReadNextTag(); Assert.AreEqual("tag", token); } [Test] public void ReadNextTag_MultilineEmptyFollowedByTagThenText() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\n\\tag text")); SFMReader test = new SFMReader(stream); string token = test.ReadNextTag(); Assert.AreEqual("tag", token); } // Multiline Initial Text [Test] public void ReadNextTag_MultilineInitialTextFollowedByEmpty() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "initial text\n")); SFMReader test = new SFMReader(stream); string token = test.ReadNextTag(); Assert.IsNull(token); } [Test] public void ReadNextTag_MultilineInitialTextFollowedByText() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "initial text\nsome text")); SFMReader test = new SFMReader(stream); string token = test.ReadNextTag(); Assert.IsNull(token); } [Test] public void ReadNextTag_MultilineInitialTextFollowedByTextThenTag() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "initial text\ntext\\tag")); SFMReader test = new SFMReader(stream); string token = test.ReadNextTag(); Assert.AreEqual("tag", token); } [Test] public void ReadNextTag_MultilineInitialTextFollowedByTagOnly() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "initial text\n\\tag")); SFMReader test = new SFMReader(stream); string token = test.ReadNextTag(); Assert.AreEqual("tag", token); } // Multiline text mode [Test] public void ReadNextTag_MultilineTextModeFollowedByEmpty_Null() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\tag initial text\n")); SFMReader test = new SFMReader(stream); test.ReadNextTag(); string token = test.ReadNextTag(); Assert.IsNull(token); } [Test] public void ReadNextTag_MultilineTextModeFollowedByTextOnly_Null() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\tag initial text\ntext")); SFMReader test = new SFMReader(stream); test.ReadNextTag(); string token = test.ReadNextTag(); Assert.IsNull(token); } [Test] public void ReadNextTag_MultilineTextModeFollowedByTextThenTag_2ndLineTag() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\taginitial text\ntext\\tag2")); SFMReader test = new SFMReader(stream); test.ReadNextTag(); string token = test.ReadNextTag(); Assert.AreEqual("tag2", token); } [Test] public void ReadNextTag_MultilineTextModeFollowedByTagOnly_2ndLineTag() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\taginitial text\n\\tag2")); SFMReader test = new SFMReader(stream); test.ReadNextTag(); string token = test.ReadNextTag(); Assert.AreEqual("tag2", token); } [Test] public void ReadNextTag_MultilineTagModeFollowedByEmpty_Null() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\taginitial\n")); SFMReader test = new SFMReader(stream); test.ReadNextTag(); string token = test.ReadNextTag(); Assert.IsNull(token); } [Test] public void ReadNextTag_MultilineTagModeFollowedByTextOnly_Null() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\taginitial\nsome text")); SFMReader test = new SFMReader(stream); test.ReadNextTag(); string token = test.ReadNextTag(); Assert.IsNull(token); } [Test] public void ReadNextTag_MultilineTagModeFollowedByTextThenTag_2ndLineTag() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\taginitial\nsome text\\tag")); SFMReader test = new SFMReader(stream); test.ReadNextTag(); string token = test.ReadNextTag(); Assert.AreEqual("tag", token); } [Test] public void ReadNextTag_MultilineTagModeFollowedByTagOnly_2ndLineTag() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\taginitial\n\\tag")); SFMReader test = new SFMReader(stream); test.ReadNextTag(); string token = test.ReadNextTag(); Assert.AreEqual("tag", token); } [Test] public void ReadNextTag_TwoTagsInARow() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( @"\tag1\tag2")); SFMReader test = new SFMReader(stream); Assert.AreEqual("tag1", test.ReadNextTag()); Assert.AreEqual("tag2", test.ReadNextTag()); } [Test] public void ReadNextTagThenReadNextText() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( @"\tag1 text")); SFMReader test = new SFMReader(stream); test.ReadNextTag(); Assert.AreEqual("text", test.ReadNextText()); } [Test] public void ReadInitialThenReadNextTag() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( @"text \tag1")); SFMReader test = new SFMReader(stream); test.ReadInitialText(); Assert.AreEqual("tag1", test.ReadNextTag()); } [Test] public void ReadNextTextThenReadNextTag() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( @"\tag1 some text\tag2")); SFMReader test = new SFMReader(stream); test.ReadNextText(); Assert.AreEqual("tag2", test.ReadNextTag()); } [Test] public void ReadNextTextThenReadInitialText_Throw() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes(@"\tag1 some text\tag2")); SFMReader test = new SFMReader(stream); test.ReadNextText(); Assert.Throws<InvalidOperationException>( () => test.ReadInitialText()); } [Test] public void ReadNextTagThenReadInitialText_Throw() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes(@"\tag1 some text\tag2")); SFMReader test = new SFMReader(stream); test.ReadNextTag(); Assert.Throws<InvalidOperationException>( () => test.ReadInitialText()); } [Test] public void UsfmMode_TagTerminiatedByAsterisk() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( @"\tag1*some text")); SFMReader test = new SFMReader(stream); test.Mode = SFMReader.ParseMode.Usfm; Assert.AreEqual("tag1*", test.ReadNextTag()); Assert.AreEqual("some text", test.ReadNextText()); } [Test] public void DefaultMode_TagTerminiatedByAsterisk() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( @"\tag1*some text")); SFMReader test = new SFMReader(stream); Assert.AreEqual("tag1*some", test.ReadNextTag()); Assert.AreEqual("text", test.ReadNextText()); } [Test] public void Mode_InitializedToDefault() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( @"\tag text first\bf")); SFMReader test = new SFMReader(stream); Assert.AreEqual(SFMReader.ParseMode.Default, test.Mode); } [Test] public void ShoeboxMode_TagsWithoutNewline_TreatedAsText() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( @"\tag text first\bf")); SFMReader test = new SFMReader(stream); test.Mode = SFMReader.ParseMode.Shoebox; Assert.AreEqual("text first\\bf", test.ReadNextText()); string token = test.ReadNextTag(); Assert.IsNull(token); } [Test] public void Offset_BeforeAnyTextIsRead_0() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\tag text more text")); SFMReader test = new SFMReader(stream); Assert.AreEqual(0, test.Offset); } [Test] public void Offset_After3LetterTagThenSpace_5() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\tag ")); SFMReader test = new SFMReader(stream); test.ReadNextTag(); Assert.AreEqual(5, test.Offset); } [Test] public void Offset_After3LetterTagAnd4LetterWord_9() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\tag text")); SFMReader test = new SFMReader(stream); test.ReadNextTag(); test.ReadNextText(); Assert.AreEqual(9, test.Offset); } [Test] public void Offset_After3LetterTagAnd4LetterWordAnd4LetterTag_14() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\tag text\\tag2")); SFMReader test = new SFMReader(stream); test.ReadNextTag(); test.ReadNextText(); test.ReadNextTag(); Assert.AreEqual(14, test.Offset); } [Test] public void Offset_After3LetterTagAnd4LetterWordASpaceThen4LetterTag_15() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\tag text \\tag2")); SFMReader test = new SFMReader(stream); test.ReadNextTag(); test.ReadNextText(); test.ReadNextTag(); Assert.AreEqual(15, test.Offset); } [Test] public void Offset_After5CharactersOfInitialText_5() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "hello")); SFMReader test = new SFMReader(stream); test.ReadInitialText(); Assert.AreEqual(5, test.Offset); } [Test] public void Offset_After3LetterTag2SpacesAnd4LetterWord_10() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\tag text")); SFMReader test = new SFMReader(stream); test.ReadNextTag(); test.ReadNextText(); Assert.AreEqual(10, test.Offset); } [Test] public void Offset_After3LetterTag4LetterWordAndASpace_10() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\tag text ")); SFMReader test = new SFMReader(stream); test.ReadNextTag(); test.ReadNextText(); Assert.AreEqual(10, test.Offset); } [Test] public void Offset_After3LetterTagAfterEOF_4() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\tag")); SFMReader test = new SFMReader(stream); test.ReadNextTag(); test.ReadNextText(); Assert.AreEqual(4, test.Offset); } [Test] public void Offset_ShoeboxModeAfter4LetterTagWithStarAfterEOF_5() { Stream stream = new MemoryStream(Encoding.ASCII.GetBytes( "\\tag*")); SFMReader test = new SFMReader(stream); test.Mode = SFMReader.ParseMode.Shoebox; test.ReadNextTag(); test.ReadNextText(); Assert.AreEqual(5, test.Offset); } } }
// 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.Azure.AcceptanceTestsHeadExceptions { using Fixtures.Azure; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; /// <summary> /// Test Infrastructure for AutoRest /// </summary> public partial class AutoRestHeadExceptionTestService : ServiceClient<AutoRestHeadExceptionTestService>, IAutoRestHeadExceptionTestService, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.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> /// Credentials needed for the client to connect to 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> /// 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 IHeadExceptionOperations. /// </summary> public virtual IHeadExceptionOperations HeadException { get; private set; } /// <summary> /// Initializes a new instance of the AutoRestHeadExceptionTestService class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestHeadExceptionTestService(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestHeadExceptionTestService 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 AutoRestHeadExceptionTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestHeadExceptionTestService 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="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestHeadExceptionTestService(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestHeadExceptionTestService 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="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestHeadExceptionTestService(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestHeadExceptionTestService class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestHeadExceptionTestService(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestHeadExceptionTestService class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to 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> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestHeadExceptionTestService(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestHeadExceptionTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestHeadExceptionTestService(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestHeadExceptionTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to 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> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestHeadExceptionTestService(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { HeadException = new HeadExceptionOperations(this); BaseUri = new System.Uri("http://localhost"); AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
using System; using System.Collections; using System.Xml.Serialization; namespace Data.Scans { /// <summary> /// A scan point is a single point in a scan. It might have /// more than one Shot (perhaps because several shots are being /// taken per shot to improve S:N. The shots are stored in two /// groups to facilitate switched scans. A scan point also has some /// analog channel readings associated with it. The scan point keeps /// a record of the scan parameter. /// </summary> [Serializable] public class ScanPoint : MarshalByRefObject { private double scanParameter; private ArrayList onShots = new ArrayList(); private ArrayList offShots = new ArrayList(); private ArrayList analogs = new ArrayList(); public Shot AverageOnShot { get { return AverageShots(onShots); } } public Shot AverageOffShot { get { return AverageShots(offShots); } } private Shot AverageShots(ArrayList shots) { if (shots.Count == 1) return (Shot)shots[0]; Shot temp = new Shot(); foreach (Shot s in shots) temp += s; return temp/shots.Count; } public double IntegrateOn(int index, double startTime, double endTime) { return Integrate(onShots, index, startTime, endTime); } public double IntegrateOff(int index, double startTime, double endTime) { return Integrate(offShots, index, startTime, endTime); } public double AbsIntegrateOn(int index, double startTime, double endTime) { return AbsValIntegrate(onShots, index, startTime, endTime); } public double AbsIntegrateOff(int index, double startTime, double endTime) { return AbsValIntegrate(offShots, index, startTime, endTime); } public double VarianceOn(int index, double startTime, double endTime) { return Variance(onShots, index, startTime, endTime); } public double FractionOfShotNoiseOn(int index, double startTime, double endTime) { return FractionOfShotNoise(onShots, index, startTime, endTime); } public double FractionOfShotNoiseNormedOn(int[] index, double startTime0, double endTime0, double startTime1, double endTime1) { return FractionOfShotNoiseNormed(onShots, index, startTime0, endTime0,startTime1,endTime1); } private double Integrate(ArrayList shots, int index, double startTime, double endTime) { double temp = 0; foreach (Shot s in shots) temp += s.Integrate(index, startTime, endTime); return temp/shots.Count; } private double AbsValIntegrate(ArrayList shots, int index, double startTime, double endTime) { double temp = 0; foreach (Shot s in shots) temp += s.AbsValIntegrate(index, startTime, endTime); return temp / shots.Count; } private double IntegrateNormed(ArrayList shots, int[] index, double startTime0, double endTime0, double startTime1, double endTime1) { double temp = 0; foreach (Shot s in shots) temp += s.Integrate(index[0], startTime0, endTime0) / s.Integrate(index[1], startTime1, endTime1); return temp / shots.Count; } private double Variance(ArrayList shots, int index, double startTime, double endTime) { double tempMn = 0; double tempx2 = 0; double vari = 0; double n = shots.Count; if (n==1) { return vari; } else { foreach (Shot s in shots) tempMn += s.Integrate(index, startTime, endTime); foreach (Shot s in shots) tempx2 += Math.Pow(s.Integrate(index, startTime, endTime),2); return vari = (n / (n - 1)) * ((tempx2 / n) - Math.Pow((tempMn / n), 2)); } } private double VarianceNormed(ArrayList shots, int[] index, double startTime0, double endTime0, double startTime1, double endTime1) { double tempMn = 0; double tempx2 = 0; double vari = 0; double n = shots.Count; if (n == 1) { return vari; } else { foreach (Shot s in shots) tempMn += s.Integrate(index[0], startTime0, endTime0) / s.Integrate(index[1], startTime1, endTime1); foreach (Shot s in shots) tempx2 += Math.Pow(s.Integrate(index[0], startTime0, endTime0) / s.Integrate(index[1], startTime1, endTime1), 2); return vari = (n / (n - 1)) * ((tempx2 / n) - Math.Pow((tempMn / n), 2)); } } private double Calibration(ArrayList shots, int index) { Shot s = (Shot)shots[0]; return s.Calibration(index); } private double FractionOfShotNoise(ArrayList shots, int index, double startTime, double endTime) { return Math.Pow(Variance(shots, index, startTime, endTime)/(Integrate(shots, index, startTime, endTime)*Calibration(shots, index)),0.5); } private double FractionOfShotNoiseNormed(ArrayList shots, int[] index, double startTime0, double endTime0, double startTime1, double endTime1) { double fracNoiseTN = Math.Pow(VarianceNormed(shots, index, startTime0, endTime0, startTime1, endTime1),0.5) / IntegrateNormed(shots, index, startTime0, endTime0, startTime1, endTime1); double fracNoiseT2 = Calibration(shots, index[0]) / Integrate(shots, index[0], startTime0, endTime0); double fracNoiseN2 = Calibration(shots, index[1]) / Integrate(shots, index[1], startTime1, endTime1); return fracNoiseTN / Math.Pow(fracNoiseT2 + fracNoiseN2, 0.5); } public double MeanOn(int index) { return Mean(onShots, index); } public double MeanOff(int index) { return Mean(offShots, index); } private double Mean(ArrayList shots, int index) { double temp = 0; foreach (Shot s in shots) temp += s.Mean(index); return temp / shots.Count; } public static ScanPoint operator +(ScanPoint p1, ScanPoint p2) { if (p1.OnShots.Count == p2.OnShots.Count && p1.OffShots.Count == p2.OffShots.Count && p1.Analogs.Count == p2.Analogs.Count) { ScanPoint temp = new ScanPoint(); temp.ScanParameter = p1.ScanParameter; for (int i = 0 ; i < p1.OnShots.Count ; i++) temp.OnShots.Add((Shot)p1.OnShots[i] + (Shot)p2.OnShots[i]); for (int i = 0 ; i < p1.OffShots.Count ; i++) temp.OffShots.Add((Shot)p1.OffShots[i] + (Shot)p2.OffShots[i]); for (int i = 0 ; i < p1.Analogs.Count ; i++) temp.Analogs.Add((double)p1.Analogs[i] + (double)p2.Analogs[i]); return temp; } else { if (p1.OnShots.Count == 0) return p2; if (p2.OnShots.Count == 0) return p1; return null; } } public static ScanPoint operator /(ScanPoint p, int n) { ScanPoint temp = new ScanPoint(); temp.ScanParameter = p.ScanParameter; foreach (Shot s in p.OnShots) temp.OnShots.Add(s/n); foreach (Shot s in p.OffShots) temp.OffShots.Add(s/n); foreach (double a in p.Analogs) temp.Analogs.Add(a/n); return temp; } public double ScanParameter { get { return scanParameter; } set { scanParameter = value; } } [XmlArray] [XmlArrayItem(Type = typeof(Shot))] public ArrayList OnShots { get { return onShots; } } [XmlArray] [XmlArrayItem(Type = typeof(Shot))] public ArrayList OffShots { get { return offShots; } } [XmlArray] [XmlArrayItem(Type = typeof(double))] public ArrayList Analogs { get { return analogs; } } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using DiscUtils.Streams; namespace DiscUtils.Udf { internal class FileContentBuffer : IBuffer { private readonly uint _blockSize; private readonly UdfContext _context; private List<CookedExtent> _extents; private readonly FileEntry _fileEntry; private readonly Partition _partition; public FileContentBuffer(UdfContext context, Partition partition, FileEntry fileEntry, uint blockSize) { _context = context; _partition = partition; _fileEntry = fileEntry; _blockSize = blockSize; LoadExtents(); } public bool CanRead { get { return true; } } public bool CanWrite { get { return false; } } public long Capacity { get { return (long)_fileEntry.InformationLength; } } public IEnumerable<StreamExtent> Extents { get { throw new NotImplementedException(); } } public int Read(long pos, byte[] buffer, int offset, int count) { if (_fileEntry.InformationControlBlock.AllocationType == AllocationType.Embedded) { byte[] srcBuffer = _fileEntry.AllocationDescriptors; if (pos > srcBuffer.Length) { return 0; } int toCopy = (int)Math.Min(srcBuffer.Length - pos, count); Array.Copy(srcBuffer, (int)pos, buffer, offset, toCopy); return toCopy; } return ReadFromExtents(pos, buffer, offset, count); } public void Write(long pos, byte[] buffer, int offset, int count) { throw new NotImplementedException(); } public void Clear(long pos, int count) { throw new NotSupportedException(); } public void Flush() {} public void SetCapacity(long value) { throw new NotImplementedException(); } public IEnumerable<StreamExtent> GetExtentsInRange(long start, long count) { throw new NotImplementedException(); } private void LoadExtents() { _extents = new List<CookedExtent>(); byte[] activeBuffer = _fileEntry.AllocationDescriptors; AllocationType allocType = _fileEntry.InformationControlBlock.AllocationType; if (allocType == AllocationType.ShortDescriptors) { long filePos = 0; int i = 0; while (i < activeBuffer.Length) { ShortAllocationDescriptor sad = EndianUtilities.ToStruct<ShortAllocationDescriptor>(activeBuffer, i); if (sad.ExtentLength == 0) { break; } if (sad.Flags != ShortAllocationFlags.RecordedAndAllocated) { throw new NotImplementedException( "Extents that are not 'recorded and allocated' not implemented"); } CookedExtent newExtent = new CookedExtent { FileContentOffset = filePos, Partition = int.MaxValue, StartPos = sad.ExtentLocation * (long)_blockSize, Length = sad.ExtentLength }; _extents.Add(newExtent); filePos += sad.ExtentLength; i += sad.Size; } } else if (allocType == AllocationType.Embedded) { // do nothing } else if (allocType == AllocationType.LongDescriptors) { long filePos = 0; int i = 0; while (i < activeBuffer.Length) { LongAllocationDescriptor lad = EndianUtilities.ToStruct<LongAllocationDescriptor>(activeBuffer, i); if (lad.ExtentLength == 0) { break; } CookedExtent newExtent = new CookedExtent { FileContentOffset = filePos, Partition = lad.ExtentLocation.Partition, StartPos = lad.ExtentLocation.LogicalBlock * (long)_blockSize, Length = lad.ExtentLength }; _extents.Add(newExtent); filePos += lad.ExtentLength; i += lad.Size; } } else { throw new NotImplementedException("Allocation Type: " + _fileEntry.InformationControlBlock.AllocationType); } } private int ReadFromExtents(long pos, byte[] buffer, int offset, int count) { int totalToRead = (int)Math.Min(Capacity - pos, count); int totalRead = 0; while (totalRead < totalToRead) { CookedExtent extent = FindExtent(pos + totalRead); long extentOffset = pos + totalRead - extent.FileContentOffset; int toRead = (int)Math.Min(totalToRead - totalRead, extent.Length - extentOffset); Partition part; if (extent.Partition != int.MaxValue) { part = _context.LogicalPartitions[extent.Partition]; } else { part = _partition; } int numRead = part.Content.Read(extent.StartPos + extentOffset, buffer, offset + totalRead, toRead); if (numRead == 0) { return totalRead; } totalRead += numRead; } return totalRead; } private CookedExtent FindExtent(long pos) { foreach (CookedExtent extent in _extents) { if (extent.FileContentOffset + extent.Length > pos) { return extent; } } return null; } private class CookedExtent { public long FileContentOffset; public long Length; public int Partition; public long StartPos; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Aurora.Areas.HelpPage.ModelDescriptions; using Aurora.Areas.HelpPage.Models; namespace Aurora.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// 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.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.Win32.SafeHandles; using System.Diagnostics; namespace System.Net.Sockets { internal partial class SafeCloseSocket : #if DEBUG DebugSafeHandleMinusOneIsInvalid #else SafeHandleMinusOneIsInvalid #endif { private int _receiveTimeout = -1; private int _sendTimeout = -1; private bool _nonBlocking; private bool _underlyingHandleNonBlocking; private SocketAsyncContext _asyncContext; private TrackedSocketOptions _trackedOptions; internal bool LastConnectFailed { get; set; } internal bool DualMode { get; set; } internal bool ExposedHandleOrUntrackedConfiguration { get; private set; } public void RegisterConnectResult(SocketError error) { switch (error) { case SocketError.Success: case SocketError.WouldBlock: break; default: LastConnectFailed = true; break; } } public void TransferTrackedState(SafeCloseSocket target) { target._trackedOptions = _trackedOptions; target.LastConnectFailed = LastConnectFailed; target.DualMode = DualMode; target.ExposedHandleOrUntrackedConfiguration = ExposedHandleOrUntrackedConfiguration; } public void SetExposed() => ExposedHandleOrUntrackedConfiguration = true; public bool IsTrackedOption(TrackedSocketOptions option) => (_trackedOptions & option) != 0; public void TrackOption(SocketOptionLevel level, SocketOptionName name) { // As long as only these options are set, we can support Connect{Async}(IPAddress[], ...). switch (level) { case SocketOptionLevel.Tcp: switch (name) { case SocketOptionName.NoDelay: _trackedOptions |= TrackedSocketOptions.NoDelay; return; } break; case SocketOptionLevel.IP: switch (name) { case SocketOptionName.DontFragment: _trackedOptions |= TrackedSocketOptions.DontFragment; return; case SocketOptionName.IpTimeToLive: _trackedOptions |= TrackedSocketOptions.Ttl; return; } break; case SocketOptionLevel.IPv6: switch (name) { case SocketOptionName.IPv6Only: _trackedOptions |= TrackedSocketOptions.DualMode; return; case SocketOptionName.IpTimeToLive: _trackedOptions |= TrackedSocketOptions.Ttl; return; } break; case SocketOptionLevel.Socket: switch (name) { case SocketOptionName.Broadcast: _trackedOptions |= TrackedSocketOptions.EnableBroadcast; return; case SocketOptionName.Linger: _trackedOptions |= TrackedSocketOptions.LingerState; return; case SocketOptionName.ReceiveBuffer: _trackedOptions |= TrackedSocketOptions.ReceiveBufferSize; return; case SocketOptionName.ReceiveTimeout: _trackedOptions |= TrackedSocketOptions.ReceiveTimeout; return; case SocketOptionName.SendBuffer: _trackedOptions |= TrackedSocketOptions.SendBufferSize; return; case SocketOptionName.SendTimeout: _trackedOptions |= TrackedSocketOptions.SendTimeout; return; } break; } // For any other settings, we need to track that they were used so that we can error out // if a Connect{Async}(IPAddress[],...) attempt is made. ExposedHandleOrUntrackedConfiguration = true; } public SocketAsyncContext AsyncContext { get { if (Volatile.Read(ref _asyncContext) == null) { Interlocked.CompareExchange(ref _asyncContext, new SocketAsyncContext(this), null); } return _asyncContext; } } // This will set the underlying OS handle to be nonblocking, for whatever reason -- // performing an async operation or using a timeout will cause this to happen. // Once the OS handle is nonblocking, it never transitions back to blocking. private void SetHandleNonBlocking() { // We don't care about synchronization because this is idempotent if (!_underlyingHandleNonBlocking) { AsyncContext.SetNonBlocking(); _underlyingHandleNonBlocking = true; } } public bool IsNonBlocking { get { return _nonBlocking; } set { _nonBlocking = value; // // If transitioning to non-blocking, we need to set the native socket to non-blocking mode. // If we ever transition back to blocking, we keep the native socket in non-blocking mode, and emulate // blocking. This avoids problems with switching to native blocking while there are pending async // operations. // if (value) { SetHandleNonBlocking(); } } } public int ReceiveTimeout { get { return _receiveTimeout; } set { Debug.Assert(value == -1 || value > 0, $"Unexpected value: {value}"); // We always implement timeouts using nonblocking I/O and AsyncContext, // to avoid issues when switching from blocking I/O to nonblocking. if (value != -1) { SetHandleNonBlocking(); } _receiveTimeout = value; } } public int SendTimeout { get { return _sendTimeout; } set { Debug.Assert(value == -1 || value > 0, $"Unexpected value: {value}"); // We always implement timeouts using nonblocking I/O and AsyncContext, // to avoid issues when switching from blocking I/O to nonblocking. if (value != -1) { SetHandleNonBlocking(); } _sendTimeout = value; } } public bool IsDisconnected { get; private set; } = false; public void SetToDisconnected() { IsDisconnected = true; } public static unsafe SafeCloseSocket CreateSocket(IntPtr fileDescriptor) { return CreateSocket(InnerSafeCloseSocket.CreateSocket(fileDescriptor)); } public static unsafe SocketError CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, out SafeCloseSocket socket) { SocketError errorCode; socket = CreateSocket(InnerSafeCloseSocket.CreateSocket(addressFamily, socketType, protocolType, out errorCode)); return errorCode; } public static unsafe SocketError Accept(SafeCloseSocket socketHandle, byte[] socketAddress, ref int socketAddressSize, out SafeCloseSocket socket) { SocketError errorCode; socket = CreateSocket(InnerSafeCloseSocket.Accept(socketHandle, socketAddress, ref socketAddressSize, out errorCode)); return errorCode; } private void InnerReleaseHandle() { if (_asyncContext != null) { _asyncContext.Close(); } } internal sealed partial class InnerSafeCloseSocket : SafeHandleMinusOneIsInvalid { private unsafe SocketError InnerReleaseHandle() { int errorCode; // If _blockable was set in BlockingRelease, it's safe to block here, which means // we can honor the linger options set on the socket. It also means closesocket() might return WSAEWOULDBLOCK, in which // case we need to do some recovery. if (_blockable) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle} Following 'blockable' branch."); errorCode = Interop.Sys.Close(handle); if (errorCode == -1) { errorCode = (int)Interop.Sys.GetLastError(); } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, close()#1:{errorCode}"); #if DEBUG _closeSocketHandle = handle; _closeSocketResult = SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode); #endif // If it's not EWOULDBLOCK, there's no more recourse - we either succeeded or failed. if (errorCode != (int)Interop.Error.EWOULDBLOCK) { return SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode); } // The socket must be non-blocking with a linger timeout set. // We have to set the socket to blocking. errorCode = Interop.Sys.Fcntl.DangerousSetIsNonBlocking(handle, 0); if (errorCode == 0) { // The socket successfully made blocking; retry the close(). errorCode = Interop.Sys.Close(handle); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, close()#2:{errorCode}"); #if DEBUG _closeSocketHandle = handle; _closeSocketResult = SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode); #endif return SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode); } // The socket could not be made blocking; fall through to the regular abortive close. } // By default or if CloseAsIs() path failed, set linger timeout to zero to get an abortive close (RST). var linger = new Interop.Sys.LingerOption { OnOff = 1, Seconds = 0 }; errorCode = (int)Interop.Sys.SetLingerOption(handle, &linger); #if DEBUG _closeSocketLinger = SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode); #endif if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, setsockopt():{errorCode}"); if (errorCode != 0 && errorCode != (int)Interop.Error.EINVAL && errorCode != (int)Interop.Error.ENOPROTOOPT) { // Too dangerous to try closesocket() - it might block! return SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode); } errorCode = Interop.Sys.Close(handle); #if DEBUG _closeSocketHandle = handle; _closeSocketResult = SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode); #endif if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, close#3():{(errorCode == -1 ? (int)Interop.Sys.GetLastError() : errorCode)}"); return SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode); } public static InnerSafeCloseSocket CreateSocket(IntPtr fileDescriptor) { var res = new InnerSafeCloseSocket(); res.SetHandle(fileDescriptor); return res; } public static unsafe InnerSafeCloseSocket CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, out SocketError errorCode) { IntPtr fd; Interop.Error error = Interop.Sys.Socket(addressFamily, socketType, protocolType, &fd); if (error == Interop.Error.SUCCESS) { Debug.Assert(fd != (IntPtr)(-1), "fd should not be -1"); errorCode = SocketError.Success; // The socket was created successfully; enable IPV6_V6ONLY by default for AF_INET6 sockets. if (addressFamily == AddressFamily.InterNetworkV6) { int on = 1; error = Interop.Sys.SetSockOpt(fd, SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, (byte*)&on, sizeof(int)); if (error != Interop.Error.SUCCESS) { Interop.Sys.Close(fd); fd = (IntPtr)(-1); errorCode = SocketPal.GetSocketErrorForErrorCode(error); } } } else { Debug.Assert(fd == (IntPtr)(-1), $"Unexpected fd: {fd}"); errorCode = SocketPal.GetSocketErrorForErrorCode(error); } var res = new InnerSafeCloseSocket(); res.SetHandle(fd); return res; } public static unsafe InnerSafeCloseSocket Accept(SafeCloseSocket socketHandle, byte[] socketAddress, ref int socketAddressLen, out SocketError errorCode) { IntPtr acceptedFd; if (!socketHandle.IsNonBlocking) { errorCode = socketHandle.AsyncContext.Accept(socketAddress, ref socketAddressLen, -1, out acceptedFd); } else { bool completed = SocketPal.TryCompleteAccept(socketHandle, socketAddress, ref socketAddressLen, out acceptedFd, out errorCode); if (!completed) { errorCode = SocketError.WouldBlock; } } var res = new InnerSafeCloseSocket(); res.SetHandle(acceptedFd); return res; } } } /// <summary>Flags that correspond to exposed options on Socket.</summary> [Flags] internal enum TrackedSocketOptions : short { DontFragment = 0x1, DualMode = 0x2, EnableBroadcast = 0x4, LingerState = 0x8, NoDelay = 0x10, ReceiveBufferSize = 0x20, ReceiveTimeout = 0x40, SendBufferSize = 0x80, SendTimeout = 0x100, Ttl = 0x200, } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Text; using Nwc.XmlRpc; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Region.Framework.Interfaces; using OpenSim.Services.Interfaces; namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")] public class XmlRpcGroupsServicesConnectorModule : ISharedRegionModule, IGroupsServicesConnector { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public const GroupPowers m_DefaultEveryonePowers = GroupPowers.AllowSetHome | GroupPowers.Accountable | GroupPowers.JoinChat | GroupPowers.AllowVoiceChat | GroupPowers.ReceiveNotices | GroupPowers.StartProposal | GroupPowers.VoteOnProposal; private bool m_connectorEnabled = false; private string m_groupsServerURI = string.Empty; private bool m_disableKeepAlive = false; private string m_groupReadKey = string.Empty; private string m_groupWriteKey = string.Empty; private IUserAccountService m_accountService = null; private ExpiringCache<string, XmlRpcResponse> m_memoryCache; private int m_cacheTimeout = 30; // Used to track which agents are have dropped from a group chat session // Should be reset per agent, on logon // TODO: move this to Flotsam XmlRpc Service // SessionID, List<AgentID> private Dictionary<UUID, List<UUID>> m_groupsAgentsDroppedFromChatSession = new Dictionary<UUID, List<UUID>>(); private Dictionary<UUID, List<UUID>> m_groupsAgentsInvitedToChatSession = new Dictionary<UUID, List<UUID>>(); #region IRegionModuleBase Members public string Name { get { return "XmlRpcGroupsServicesConnector"; } } // this module is not intended to be replaced, but there should only be 1 of them. public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource config) { IConfig groupsConfig = config.Configs["Groups"]; if (groupsConfig == null) { // Do not run this module by default. return; } else { // if groups aren't enabled, we're not needed. // if we're not specified as the connector to use, then we're not wanted if ((groupsConfig.GetBoolean("Enabled", false) == false) || (groupsConfig.GetString("ServicesConnectorModule", "Default") != Name)) { m_connectorEnabled = false; return; } m_log.InfoFormat("[XMLRPC-GROUPS-CONNECTOR]: Initializing {0}", this.Name); m_groupsServerURI = groupsConfig.GetString("GroupsServerURI", string.Empty); if ((m_groupsServerURI == null) || (m_groupsServerURI == string.Empty)) { m_log.ErrorFormat("Please specify a valid URL for GroupsServerURI in OpenSim.ini, [Groups]"); m_connectorEnabled = false; return; } m_disableKeepAlive = groupsConfig.GetBoolean("XmlRpcDisableKeepAlive", false); m_groupReadKey = groupsConfig.GetString("XmlRpcServiceReadKey", string.Empty); m_groupWriteKey = groupsConfig.GetString("XmlRpcServiceWriteKey", string.Empty); m_cacheTimeout = groupsConfig.GetInt("GroupsCacheTimeout", 30); if (m_cacheTimeout == 0) { m_log.WarnFormat("[XMLRPC-GROUPS-CONNECTOR]: Groups Cache Disabled."); } else { m_log.InfoFormat("[XMLRPC-GROUPS-CONNECTOR]: Groups Cache Timeout set to {0}.", m_cacheTimeout); } // If we got all the config options we need, lets start'er'up m_memoryCache = new ExpiringCache<string, XmlRpcResponse>(); m_connectorEnabled = true; } } public void Close() { m_log.InfoFormat("[XMLRPC-GROUPS-CONNECTOR]: Closing {0}", this.Name); } public void AddRegion(OpenSim.Region.Framework.Scenes.Scene scene) { if (m_connectorEnabled) { if (m_accountService == null) { m_accountService = scene.UserAccountService; } scene.RegisterModuleInterface<IGroupsServicesConnector>(this); } } public void RemoveRegion(OpenSim.Region.Framework.Scenes.Scene scene) { if (scene.RequestModuleInterface<IGroupsServicesConnector>() == this) { scene.UnregisterModuleInterface<IGroupsServicesConnector>(this); } } public void RegionLoaded(OpenSim.Region.Framework.Scenes.Scene scene) { // TODO: May want to consider listenning for Agent Connections so we can pre-cache group info // scene.EventManager.OnNewClient += OnNewClient; } #endregion #region ISharedRegionModule Members public void PostInitialise() { // NoOp } #endregion #region IGroupsServicesConnector Members /// <summary> /// Create a Group, including Everyone and Owners Role, place FounderID in both groups, select Owner as selected role, and newly created group as agent's active role. /// </summary> public UUID CreateGroup(UUID requestingAgentID, string name, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish, UUID founderID) { UUID GroupID = UUID.Random(); UUID OwnerRoleID = UUID.Random(); Hashtable param = new Hashtable(); param["GroupID"] = GroupID.ToString(); param["Name"] = name; param["Charter"] = charter; param["ShowInList"] = showInList == true ? 1 : 0; param["InsigniaID"] = insigniaID.ToString(); param["MembershipFee"] = 0; param["OpenEnrollment"] = openEnrollment == true ? 1 : 0; param["AllowPublish"] = allowPublish == true ? 1 : 0; param["MaturePublish"] = maturePublish == true ? 1 : 0; param["FounderID"] = founderID.ToString(); param["EveryonePowers"] = ((ulong)m_DefaultEveryonePowers).ToString(); param["OwnerRoleID"] = OwnerRoleID.ToString(); // Would this be cleaner as (GroupPowers)ulong.MaxValue; GroupPowers OwnerPowers = GroupPowers.Accountable | GroupPowers.AllowEditLand | GroupPowers.AllowFly | GroupPowers.AllowLandmark | GroupPowers.AllowRez | GroupPowers.AllowSetHome | GroupPowers.AllowVoiceChat | GroupPowers.AssignMember | GroupPowers.AssignMemberLimited | GroupPowers.ChangeActions | GroupPowers.ChangeIdentity | GroupPowers.ChangeMedia | GroupPowers.ChangeOptions | GroupPowers.CreateRole | GroupPowers.DeedObject | GroupPowers.DeleteRole | GroupPowers.Eject | GroupPowers.FindPlaces | GroupPowers.Invite | GroupPowers.JoinChat | GroupPowers.LandChangeIdentity | GroupPowers.LandDeed | GroupPowers.LandDivideJoin | GroupPowers.LandEdit | GroupPowers.LandEjectAndFreeze | GroupPowers.LandGardening | GroupPowers.LandManageAllowed | GroupPowers.LandManageBanned | GroupPowers.LandManagePasses | GroupPowers.LandOptions | GroupPowers.LandRelease | GroupPowers.LandSetSale | GroupPowers.ModerateChat | GroupPowers.ObjectManipulate | GroupPowers.ObjectSetForSale | GroupPowers.ReceiveNotices | GroupPowers.RemoveMember | GroupPowers.ReturnGroupOwned | GroupPowers.ReturnGroupSet | GroupPowers.ReturnNonGroup | GroupPowers.RoleProperties | GroupPowers.SendNotices | GroupPowers.SetLandingPoint | GroupPowers.StartProposal | GroupPowers.VoteOnProposal; param["OwnersPowers"] = ((ulong)OwnerPowers).ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.createGroup", param); if (respData.Contains("error")) { // UUID is not nullable return UUID.Zero; } return UUID.Parse((string)respData["GroupID"]); } public void UpdateGroup(UUID requestingAgentID, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish) { Hashtable param = new Hashtable(); param["GroupID"] = groupID.ToString(); param["Charter"] = charter; param["ShowInList"] = showInList == true ? 1 : 0; param["InsigniaID"] = insigniaID.ToString(); param["MembershipFee"] = membershipFee; param["OpenEnrollment"] = openEnrollment == true ? 1 : 0; param["AllowPublish"] = allowPublish == true ? 1 : 0; param["MaturePublish"] = maturePublish == true ? 1 : 0; XmlRpcCall(requestingAgentID, "groups.updateGroup", param); } public void AddGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers) { Hashtable param = new Hashtable(); param["GroupID"] = groupID.ToString(); param["RoleID"] = roleID.ToString(); param["Name"] = name; param["Description"] = description; param["Title"] = title; param["Powers"] = powers.ToString(); XmlRpcCall(requestingAgentID, "groups.addRoleToGroup", param); } public void RemoveGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID) { Hashtable param = new Hashtable(); param["GroupID"] = groupID.ToString(); param["RoleID"] = roleID.ToString(); XmlRpcCall(requestingAgentID, "groups.removeRoleFromGroup", param); } public void UpdateGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers) { Hashtable param = new Hashtable(); param["GroupID"] = groupID.ToString(); param["RoleID"] = roleID.ToString(); if (name != null) { param["Name"] = name; } if (description != null) { param["Description"] = description; } if (title != null) { param["Title"] = title; } param["Powers"] = powers.ToString(); XmlRpcCall(requestingAgentID, "groups.updateGroupRole", param); } public GroupRecord GetGroupRecord(UUID requestingAgentID, UUID GroupID, string GroupName) { Hashtable param = new Hashtable(); if (GroupID != UUID.Zero) { param["GroupID"] = GroupID.ToString(); } if ((GroupName != null) && (GroupName != string.Empty)) { param["Name"] = GroupName.ToString(); } Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroup", param); if (respData.Contains("error")) { return null; } return GroupProfileHashtableToGroupRecord(respData); } public GroupProfileData GetMemberGroupProfile(UUID requestingAgentID, UUID GroupID, UUID AgentID) { Hashtable param = new Hashtable(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroup", param); if (respData.Contains("error")) { // GroupProfileData is not nullable return new GroupProfileData(); } GroupMembershipData MemberInfo = GetAgentGroupMembership(requestingAgentID, AgentID, GroupID); GroupProfileData MemberGroupProfile = GroupProfileHashtableToGroupProfileData(respData); MemberGroupProfile.MemberTitle = MemberInfo.GroupTitle; MemberGroupProfile.PowersMask = MemberInfo.GroupPowers; return MemberGroupProfile; } public void SetAgentActiveGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); XmlRpcCall(requestingAgentID, "groups.setAgentActiveGroup", param); } public void SetAgentActiveGroupRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); param["SelectedRoleID"] = RoleID.ToString(); XmlRpcCall(requestingAgentID, "groups.setAgentGroupInfo", param); } public void SetAgentGroupInfo(UUID requestingAgentID, UUID AgentID, UUID GroupID, bool AcceptNotices, bool ListInProfile) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); param["AcceptNotices"] = AcceptNotices ? "1" : "0"; param["ListInProfile"] = ListInProfile ? "1" : "0"; XmlRpcCall(requestingAgentID, "groups.setAgentGroupInfo", param); } public void AddAgentToGroupInvite(UUID requestingAgentID, UUID inviteID, UUID groupID, UUID roleID, UUID agentID) { Hashtable param = new Hashtable(); param["InviteID"] = inviteID.ToString(); param["AgentID"] = agentID.ToString(); param["RoleID"] = roleID.ToString(); param["GroupID"] = groupID.ToString(); XmlRpcCall(requestingAgentID, "groups.addAgentToGroupInvite", param); } public GroupInviteInfo GetAgentToGroupInvite(UUID requestingAgentID, UUID inviteID) { Hashtable param = new Hashtable(); param["InviteID"] = inviteID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentToGroupInvite", param); if (respData.Contains("error")) { return null; } GroupInviteInfo inviteInfo = new GroupInviteInfo(); inviteInfo.InviteID = inviteID; inviteInfo.GroupID = UUID.Parse((string)respData["GroupID"]); inviteInfo.RoleID = UUID.Parse((string)respData["RoleID"]); inviteInfo.AgentID = UUID.Parse((string)respData["AgentID"]); return inviteInfo; } public void RemoveAgentToGroupInvite(UUID requestingAgentID, UUID inviteID) { Hashtable param = new Hashtable(); param["InviteID"] = inviteID.ToString(); XmlRpcCall(requestingAgentID, "groups.removeAgentToGroupInvite", param); } public void AddAgentToGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); param["RoleID"] = RoleID.ToString(); XmlRpcCall(requestingAgentID, "groups.addAgentToGroup", param); } public void RemoveAgentFromGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); XmlRpcCall(requestingAgentID, "groups.removeAgentFromGroup", param); } public void AddAgentToGroupRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); param["RoleID"] = RoleID.ToString(); XmlRpcCall(requestingAgentID, "groups.addAgentToGroupRole", param); } public void RemoveAgentFromGroupRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); param["RoleID"] = RoleID.ToString(); XmlRpcCall(requestingAgentID, "groups.removeAgentFromGroupRole", param); } public List<DirGroupsReplyData> FindGroups(UUID requestingAgentID, string search) { Hashtable param = new Hashtable(); param["Search"] = search; Hashtable respData = XmlRpcCall(requestingAgentID, "groups.findGroups", param); List<DirGroupsReplyData> findings = new List<DirGroupsReplyData>(); if (!respData.Contains("error")) { Hashtable results = (Hashtable)respData["results"]; foreach (Hashtable groupFind in results.Values) { DirGroupsReplyData data = new DirGroupsReplyData(); data.groupID = new UUID((string)groupFind["GroupID"]); ; data.groupName = (string)groupFind["Name"]; data.members = int.Parse((string)groupFind["Members"]); // data.searchOrder = order; findings.Add(data); } } return findings; } public GroupMembershipData GetAgentGroupMembership(UUID requestingAgentID, UUID AgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentGroupMembership", param); if (respData.Contains("error")) { return null; } GroupMembershipData data = HashTableToGroupMembershipData(respData); return data; } public GroupMembershipData GetAgentActiveMembership(UUID requestingAgentID, UUID AgentID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentActiveMembership", param); if (respData.Contains("error")) { return null; } return HashTableToGroupMembershipData(respData); } public List<GroupMembershipData> GetAgentGroupMemberships(UUID requestingAgentID, UUID AgentID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentGroupMemberships", param); List<GroupMembershipData> memberships = new List<GroupMembershipData>(); if (!respData.Contains("error")) { foreach (object membership in respData.Values) { memberships.Add(HashTableToGroupMembershipData((Hashtable)membership)); } } return memberships; } public List<GroupRolesData> GetAgentGroupRoles(UUID requestingAgentID, UUID AgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentRoles", param); List<GroupRolesData> Roles = new List<GroupRolesData>(); if (respData.Contains("error")) { return Roles; } foreach (Hashtable role in respData.Values) { GroupRolesData data = new GroupRolesData(); data.RoleID = new UUID((string)role["RoleID"]); data.Name = (string)role["Name"]; data.Description = (string)role["Description"]; data.Powers = ulong.Parse((string)role["Powers"]); data.Title = (string)role["Title"]; Roles.Add(data); } return Roles; } public List<GroupRolesData> GetGroupRoles(UUID requestingAgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupRoles", param); List<GroupRolesData> Roles = new List<GroupRolesData>(); if (respData.Contains("error")) { return Roles; } foreach (Hashtable role in respData.Values) { GroupRolesData data = new GroupRolesData(); data.Description = (string)role["Description"]; data.Members = int.Parse((string)role["Members"]); data.Name = (string)role["Name"]; data.Powers = ulong.Parse((string)role["Powers"]); data.RoleID = new UUID((string)role["RoleID"]); data.Title = (string)role["Title"]; Roles.Add(data); } return Roles; } public List<GroupMembersData> GetGroupMembers(UUID requestingAgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupMembers", param); List<GroupMembersData> members = new List<GroupMembersData>(); if (respData.Contains("error")) { return members; } foreach (Hashtable membership in respData.Values) { GroupMembersData data = new GroupMembersData(); data.AcceptNotices = ((string)membership["AcceptNotices"]) == "1"; data.AgentID = new UUID((string)membership["AgentID"]); data.Contribution = int.Parse((string)membership["Contribution"]); data.IsOwner = ((string)membership["IsOwner"]) == "1"; data.ListInProfile = ((string)membership["ListInProfile"]) == "1"; data.AgentPowers = ulong.Parse((string)membership["AgentPowers"]); data.Title = (string)membership["Title"]; members.Add(data); } return members; } public List<GroupRoleMembersData> GetGroupRoleMembers(UUID requestingAgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupRoleMembers", param); List<GroupRoleMembersData> members = new List<GroupRoleMembersData>(); if (!respData.Contains("error")) { foreach (Hashtable membership in respData.Values) { GroupRoleMembersData data = new GroupRoleMembersData(); data.MemberID = new UUID((string)membership["AgentID"]); data.RoleID = new UUID((string)membership["RoleID"]); members.Add(data); } } return members; } public List<GroupNoticeData> GetGroupNotices(UUID requestingAgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupNotices", param); List<GroupNoticeData> values = new List<GroupNoticeData>(); if (!respData.Contains("error")) { foreach (Hashtable value in respData.Values) { GroupNoticeData data = new GroupNoticeData(); data.NoticeID = UUID.Parse((string)value["NoticeID"]); data.Timestamp = uint.Parse((string)value["Timestamp"]); data.FromName = (string)value["FromName"]; data.Subject = (string)value["Subject"]; data.HasAttachment = false; data.AssetType = 0; values.Add(data); } } return values; } public GroupNoticeInfo GetGroupNotice(UUID requestingAgentID, UUID noticeID) { Hashtable param = new Hashtable(); param["NoticeID"] = noticeID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupNotice", param); if (respData.Contains("error")) { return null; } GroupNoticeInfo data = new GroupNoticeInfo(); data.GroupID = UUID.Parse((string)respData["GroupID"]); data.Message = (string)respData["Message"]; data.BinaryBucket = Utils.HexStringToBytes((string)respData["BinaryBucket"], true); data.noticeData.NoticeID = UUID.Parse((string)respData["NoticeID"]); data.noticeData.Timestamp = uint.Parse((string)respData["Timestamp"]); data.noticeData.FromName = (string)respData["FromName"]; data.noticeData.Subject = (string)respData["Subject"]; data.noticeData.HasAttachment = false; data.noticeData.AssetType = 0; if (data.Message == null) { data.Message = string.Empty; } return data; } public void AddGroupNotice(UUID requestingAgentID, UUID groupID, UUID noticeID, string fromName, string subject, string message, byte[] binaryBucket) { string binBucket = OpenMetaverse.Utils.BytesToHexString(binaryBucket, ""); Hashtable param = new Hashtable(); param["GroupID"] = groupID.ToString(); param["NoticeID"] = noticeID.ToString(); param["FromName"] = fromName; param["Subject"] = subject; param["Message"] = message; param["BinaryBucket"] = binBucket; param["TimeStamp"] = ((uint)Util.UnixTimeSinceEpoch()).ToString(); XmlRpcCall(requestingAgentID, "groups.addGroupNotice", param); } #endregion #region GroupSessionTracking public void ResetAgentGroupChatSessions(UUID agentID) { foreach (List<UUID> agentList in m_groupsAgentsDroppedFromChatSession.Values) { agentList.Remove(agentID); } } public bool hasAgentBeenInvitedToGroupChatSession(UUID agentID, UUID groupID) { // If we're tracking this group, and we can find them in the tracking, then they've been invited return m_groupsAgentsInvitedToChatSession.ContainsKey(groupID) && m_groupsAgentsInvitedToChatSession[groupID].Contains(agentID); } public bool hasAgentDroppedGroupChatSession(UUID agentID, UUID groupID) { // If we're tracking drops for this group, // and we find them, well... then they've dropped return m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID) && m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID); } public void AgentDroppedFromGroupChatSession(UUID agentID, UUID groupID) { if (m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID)) { // If not in dropped list, add if (!m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID)) { m_groupsAgentsDroppedFromChatSession[groupID].Add(agentID); } } } public void AgentInvitedToGroupChatSession(UUID agentID, UUID groupID) { // Add Session Status if it doesn't exist for this session CreateGroupChatSessionTracking(groupID); // If nessesary, remove from dropped list if (m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID)) { m_groupsAgentsDroppedFromChatSession[groupID].Remove(agentID); } } private void CreateGroupChatSessionTracking(UUID groupID) { if (!m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID)) { m_groupsAgentsDroppedFromChatSession.Add(groupID, new List<UUID>()); m_groupsAgentsInvitedToChatSession.Add(groupID, new List<UUID>()); } } #endregion #region XmlRpcHashtableMarshalling private GroupProfileData GroupProfileHashtableToGroupProfileData(Hashtable groupProfile) { GroupProfileData group = new GroupProfileData(); group.GroupID = UUID.Parse((string)groupProfile["GroupID"]); group.Name = (string)groupProfile["Name"]; if (groupProfile["Charter"] != null) { group.Charter = (string)groupProfile["Charter"]; } group.ShowInList = ((string)groupProfile["ShowInList"]) == "1"; group.InsigniaID = UUID.Parse((string)groupProfile["InsigniaID"]); group.MembershipFee = int.Parse((string)groupProfile["MembershipFee"]); group.OpenEnrollment = ((string)groupProfile["OpenEnrollment"]) == "1"; group.AllowPublish = ((string)groupProfile["AllowPublish"]) == "1"; group.MaturePublish = ((string)groupProfile["MaturePublish"]) == "1"; group.FounderID = UUID.Parse((string)groupProfile["FounderID"]); group.OwnerRole = UUID.Parse((string)groupProfile["OwnerRoleID"]); group.GroupMembershipCount = int.Parse((string)groupProfile["GroupMembershipCount"]); group.GroupRolesCount = int.Parse((string)groupProfile["GroupRolesCount"]); return group; } private GroupRecord GroupProfileHashtableToGroupRecord(Hashtable groupProfile) { GroupRecord group = new GroupRecord(); group.GroupID = UUID.Parse((string)groupProfile["GroupID"]); group.GroupName = groupProfile["Name"].ToString(); if (groupProfile["Charter"] != null) { group.Charter = (string)groupProfile["Charter"]; } group.ShowInList = ((string)groupProfile["ShowInList"]) == "1"; group.GroupPicture = UUID.Parse((string)groupProfile["InsigniaID"]); group.MembershipFee = int.Parse((string)groupProfile["MembershipFee"]); group.OpenEnrollment = ((string)groupProfile["OpenEnrollment"]) == "1"; group.AllowPublish = ((string)groupProfile["AllowPublish"]) == "1"; group.MaturePublish = ((string)groupProfile["MaturePublish"]) == "1"; group.FounderID = UUID.Parse((string)groupProfile["FounderID"]); group.OwnerRoleID = UUID.Parse((string)groupProfile["OwnerRoleID"]); return group; } private static GroupMembershipData HashTableToGroupMembershipData(Hashtable respData) { GroupMembershipData data = new GroupMembershipData(); data.AcceptNotices = ((string)respData["AcceptNotices"] == "1"); data.Contribution = int.Parse((string)respData["Contribution"]); data.ListInProfile = ((string)respData["ListInProfile"] == "1"); data.ActiveRole = new UUID((string)respData["SelectedRoleID"]); data.GroupTitle = (string)respData["Title"]; data.GroupPowers = ulong.Parse((string)respData["GroupPowers"]); // Is this group the agent's active group data.GroupID = new UUID((string)respData["GroupID"]); UUID ActiveGroup = new UUID((string)respData["ActiveGroupID"]); data.Active = data.GroupID.Equals(ActiveGroup); data.AllowPublish = ((string)respData["AllowPublish"] == "1"); if (respData["Charter"] != null) { data.Charter = (string)respData["Charter"]; } data.FounderID = new UUID((string)respData["FounderID"]); data.GroupID = new UUID((string)respData["GroupID"]); data.GroupName = (string)respData["GroupName"]; data.GroupPicture = new UUID((string)respData["InsigniaID"]); data.MaturePublish = ((string)respData["MaturePublish"] == "1"); data.MembershipFee = int.Parse((string)respData["MembershipFee"]); data.OpenEnrollment = ((string)respData["OpenEnrollment"] == "1"); data.ShowInList = ((string)respData["ShowInList"] == "1"); return data; } #endregion /// <summary> /// Encapsulate the XmlRpc call to standardize security and error handling. /// </summary> private Hashtable XmlRpcCall(UUID requestingAgentID, string function, Hashtable param) { XmlRpcResponse resp = null; string CacheKey = null; // Only bother with the cache if it isn't disabled. if (m_cacheTimeout > 0) { if (!function.StartsWith("groups.get")) { // Any and all updates cause the cache to clear m_memoryCache.Clear(); } else { StringBuilder sb = new StringBuilder(requestingAgentID + function); foreach (object key in param.Keys) { if (param[key] != null) { sb.AppendFormat(",{0}:{1}", key.ToString(), param[key].ToString()); } } CacheKey = sb.ToString(); m_memoryCache.TryGetValue(CacheKey, out resp); } } if (resp == null) { string UserService; UUID SessionID; GetClientGroupRequestID(requestingAgentID, out UserService, out SessionID); param.Add("RequestingAgentID", requestingAgentID.ToString()); param.Add("RequestingAgentUserService", UserService); param.Add("RequestingSessionID", SessionID.ToString()); param.Add("ReadKey", m_groupReadKey); param.Add("WriteKey", m_groupWriteKey); IList parameters = new ArrayList(); parameters.Add(param); ConfigurableKeepAliveXmlRpcRequest req; req = new ConfigurableKeepAliveXmlRpcRequest(function, parameters, m_disableKeepAlive); try { resp = req.Send(m_groupsServerURI, 10000); if ((m_cacheTimeout > 0) && (CacheKey != null)) { m_memoryCache.AddOrUpdate(CacheKey, resp, TimeSpan.FromSeconds(m_cacheTimeout)); } } catch (Exception e) { m_log.ErrorFormat( "[XMLRPC-GROUPS-CONNECTOR]: An error has occured while attempting to access the XmlRpcGroups server method {0} at {1}", function, m_groupsServerURI); m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: {0}{1}", e.Message, e.StackTrace); foreach (string ResponseLine in req.RequestResponse.Split(new string[] { Environment.NewLine }, StringSplitOptions.None)) { m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: {0} ", ResponseLine); } foreach (string key in param.Keys) { m_log.WarnFormat("[XMLRPC-GROUPS-CONNECTOR]: {0} :: {1}", key, param[key].ToString()); } Hashtable respData = new Hashtable(); respData.Add("error", e.ToString()); return respData; } } if (resp.Value is Hashtable) { Hashtable respData = (Hashtable)resp.Value; if (respData.Contains("error") && !respData.Contains("succeed")) { LogRespDataToConsoleError(respData); } return respData; } m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: The XmlRpc server returned a {1} instead of a hashtable for {0}", function, resp.Value.GetType().ToString()); if (resp.Value is ArrayList) { ArrayList al = (ArrayList)resp.Value; m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: Contains {0} elements", al.Count); foreach (object o in al) { m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: {0} :: {1}", o.GetType().ToString(), o.ToString()); } } else { m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: Function returned: {0}", resp.Value.ToString()); } Hashtable error = new Hashtable(); error.Add("error", "invalid return value"); return error; } private void LogRespDataToConsoleError(Hashtable respData) { m_log.Error("[XMLRPC-GROUPS-CONNECTOR]: Error:"); foreach (string key in respData.Keys) { m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: Key: {0}", key); string[] lines = respData[key].ToString().Split(new char[] { '\n' }); foreach (string line in lines) { m_log.ErrorFormat("[XMLRPC-GROUPS-CONNECTOR]: {0}", line); } } } /// <summary> /// Group Request Tokens are an attempt to allow the groups service to authenticate /// requests. /// TODO: This broke after the big grid refactor, either find a better way, or discard this /// </summary> /// <param name="client"></param> /// <returns></returns> private void GetClientGroupRequestID(UUID AgentID, out string UserServiceURL, out UUID SessionID) { UserServiceURL = ""; SessionID = UUID.Zero; // Need to rework this based on changes to User Services /* UserAccount userAccount = m_accountService.GetUserAccount(UUID.Zero,AgentID); if (userAccount == null) { // This should be impossible. If I've been passed a reference to a client // that client should be registered with the UserService. So something // is horribly wrong somewhere. m_log.WarnFormat("[GROUPS]: Could not find a UserServiceURL for {0}", AgentID); } else if (userProfile is ForeignUserProfileData) { // They aren't from around here ForeignUserProfileData fupd = (ForeignUserProfileData)userProfile; UserServiceURL = fupd.UserServerURI; SessionID = fupd.CurrentAgent.SessionID; } else { // They're a local user, use this: UserServiceURL = m_commManager.NetworkServersInfo.UserURL; SessionID = userProfile.CurrentAgent.SessionID; } */ } } } namespace Nwc.XmlRpc { using System; using System.Collections; using System.IO; using System.Xml; using System.Net; using System.Text; using System.Reflection; /// <summary>Class supporting the request side of an XML-RPC transaction.</summary> public class ConfigurableKeepAliveXmlRpcRequest : XmlRpcRequest { private Encoding _encoding = new ASCIIEncoding(); private XmlRpcRequestSerializer _serializer = new XmlRpcRequestSerializer(); private XmlRpcResponseDeserializer _deserializer = new XmlRpcResponseDeserializer(); private bool _disableKeepAlive = true; public string RequestResponse = String.Empty; /// <summary>Instantiate an <c>XmlRpcRequest</c> for a specified method and parameters.</summary> /// <param name="methodName"><c>String</c> designating the <i>object.method</i> on the server the request /// should be directed to.</param> /// <param name="parameters"><c>ArrayList</c> of XML-RPC type parameters to invoke the request with.</param> public ConfigurableKeepAliveXmlRpcRequest(String methodName, IList parameters, bool disableKeepAlive) { MethodName = methodName; _params = parameters; _disableKeepAlive = disableKeepAlive; } /// <summary>Send the request to the server.</summary> /// <param name="url"><c>String</c> The url of the XML-RPC server.</param> /// <returns><c>XmlRpcResponse</c> The response generated.</returns> public XmlRpcResponse Send(String url) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); if (request == null) throw new XmlRpcException(XmlRpcErrorCodes.TRANSPORT_ERROR, XmlRpcErrorCodes.TRANSPORT_ERROR_MSG + ": Could not create request with " + url); request.Method = "POST"; request.ContentType = "text/xml"; request.AllowWriteStreamBuffering = true; request.KeepAlive = !_disableKeepAlive; Stream stream = request.GetRequestStream(); XmlTextWriter xml = new XmlTextWriter(stream, _encoding); _serializer.Serialize(xml, this); xml.Flush(); xml.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader input = new StreamReader(response.GetResponseStream()); string inputXml = input.ReadToEnd(); XmlRpcResponse resp; try { resp = (XmlRpcResponse)_deserializer.Deserialize(inputXml); } catch (Exception e) { RequestResponse = inputXml; throw e; } input.Close(); response.Close(); return resp; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #region Using directives using System.Collections; using System; using System.Collections.Generic; using System.Globalization; using System.Management.Automation; #endregion namespace Microsoft.Management.Infrastructure.CimCmdlets { /// <summary> /// Containing all necessary information originated from /// the parameters of <see cref="InvokeCimMethodCommand"/> /// </summary> internal class CimSetCimInstanceContext : XOperationContextBase { /// <summary> /// <para> /// Constructor /// </para> /// </summary> /// <param name="theNamespace"></param> /// <param name="theCollection"></param> /// <param name="theProxy"></param> internal CimSetCimInstanceContext(string theNamespace, IDictionary theProperty, CimSessionProxy theProxy, string theParameterSetName, bool passThru) { this.proxy = theProxy; this.property = theProperty; this.nameSpace = theNamespace; this.parameterSetName = theParameterSetName; this.passThru = passThru; } /// <summary> /// <para>property value</para> /// </summary> internal IDictionary Property { get { return this.property; } } private IDictionary property; /// <summary> /// <para>parameter set name</para> /// </summary> internal string ParameterSetName { get { return this.parameterSetName; } } private string parameterSetName; /// <summary> /// <para>PassThru value</para> /// </summary> internal bool PassThru { get { return this.passThru; } } private bool passThru; } /// <summary> /// <para> /// Implements operations of set-ciminstance cmdlet. /// </para> /// </summary> internal sealed class CimSetCimInstance : CimGetInstance { /// <summary> /// <para> /// Constructor /// </para> /// </summary> public CimSetCimInstance() : base() { } /// <summary> /// <para> /// Base on parametersetName to set ciminstances /// </para> /// </summary> /// <param name="cmdlet"><see cref="SetCimInstanceCommand"/> object.</param> public void SetCimInstance(SetCimInstanceCommand cmdlet) { IEnumerable<string> computerNames = ConstValue.GetComputerNames( GetComputerName(cmdlet)); List<CimSessionProxy> proxys = new List<CimSessionProxy>(); switch (cmdlet.ParameterSetName) { case CimBaseCommand.CimInstanceComputerSet: foreach (string computerName in computerNames) { // create CimSessionProxySetCimInstance object internally proxys.Add(CreateSessionProxy(computerName, cmdlet.CimInstance, cmdlet, cmdlet.PassThru)); } break; case CimBaseCommand.CimInstanceSessionSet: foreach (CimSession session in GetCimSession(cmdlet)) { // create CimSessionProxySetCimInstance object internally proxys.Add(CreateSessionProxy(session, cmdlet, cmdlet.PassThru)); } break; default: break; } switch (cmdlet.ParameterSetName) { case CimBaseCommand.CimInstanceComputerSet: case CimBaseCommand.CimInstanceSessionSet: string nameSpace = ConstValue.GetNamespace(GetCimInstanceParameter(cmdlet).CimSystemProperties.Namespace); string target = cmdlet.CimInstance.ToString(); foreach (CimSessionProxy proxy in proxys) { if (!cmdlet.ShouldProcess(target, action)) { return; } Exception exception = null; CimInstance instance = cmdlet.CimInstance; // For CimInstance parameter sets, Property is an optional parameter if (cmdlet.Property != null) { if (!SetProperty(cmdlet.Property, ref instance, ref exception)) { cmdlet.ThrowTerminatingError(exception, action); return; } } proxy.ModifyInstanceAsync(nameSpace, instance); } break; case CimBaseCommand.QueryComputerSet: case CimBaseCommand.QuerySessionSet: GetCimInstanceInternal(cmdlet); break; default: break; } } /// <summary> /// <para> /// Set <see cref="CimInstance"/> with properties specified in cmdlet /// </para> /// </summary> /// <param name="cimInstance"></param> public void SetCimInstance(CimInstance cimInstance, CimSetCimInstanceContext context, CmdletOperationBase cmdlet) { DebugHelper.WriteLog("CimSetCimInstance::SetCimInstance", 4); if (!cmdlet.ShouldProcess(cimInstance.ToString(), action)) { return; } Exception exception = null; if (!SetProperty(context.Property, ref cimInstance, ref exception)) { cmdlet.ThrowTerminatingError(exception, action); return; } CimSessionProxy proxy = CreateCimSessionProxy(context.Proxy, context.PassThru); proxy.ModifyInstanceAsync(cimInstance.CimSystemProperties.Namespace, cimInstance); } #region private members /// <summary> /// <para> /// Set the properties value to be modified to the given /// <see cref="CimInstance"/> /// </para> /// </summary> /// <param name="properties"></param> /// <param name="cimInstance"></param> /// <param name="terminationMessage"></param> /// <returns></returns> private bool SetProperty(IDictionary properties, ref CimInstance cimInstance, ref Exception exception) { DebugHelper.WriteLogEx(); if (properties.Count == 0) { // simply ignore if empty properties was provided return true; } IDictionaryEnumerator enumerator = properties.GetEnumerator(); while (enumerator.MoveNext()) { object value = GetBaseObject(enumerator.Value); string key = enumerator.Key.ToString(); DebugHelper.WriteLog("Input property name '{0}' with value '{1}'", 1, key, value); try { CimProperty property = cimInstance.CimInstanceProperties[key]; // modify existing property value if found if (property != null) { if ((property.Flags & CimFlags.ReadOnly) == CimFlags.ReadOnly) { // can not modify ReadOnly property exception = new CimException(string.Format(CultureInfo.CurrentUICulture, Strings.CouldNotModifyReadonlyProperty, key, cimInstance)); return false; } // allow modify the key property value as long as it is not readonly, // then the modified ciminstance is stand for a different CimInstance DebugHelper.WriteLog("Set property name '{0}' has old value '{1}'", 4, key, property.Value); property.Value = value; } else // For dynamic instance, it is valid to add a new property { CimProperty newProperty; if( value == null ) { newProperty = CimProperty.Create( key, value, CimType.String, CimFlags.Property); } else { CimType referenceType = CimType.Unknown; object referenceObject = GetReferenceOrReferenceArrayObject(value, ref referenceType); if (referenceObject != null) { newProperty = CimProperty.Create( key, referenceObject, referenceType, CimFlags.Property); } else { newProperty = CimProperty.Create( key, value, CimFlags.Property); } } try { cimInstance.CimInstanceProperties.Add(newProperty); } catch (CimException e) { if (e.NativeErrorCode == NativeErrorCode.Failed) { string errorMessage = string.Format(CultureInfo.CurrentUICulture, Strings.UnableToAddPropertyToInstance, newProperty.Name, cimInstance); exception = new CimException(errorMessage, e); } else { exception = e; } return false; } DebugHelper.WriteLog("Add non-key property name '{0}' with value '{1}'.", 3, key, value); } } catch (Exception e) { DebugHelper.WriteLog("Exception {0}", 4, e); exception = e; return false; } } return true; } #endregion #region const strings /// <summary> /// Action. /// </summary> private const string action = @"Set-CimInstance"; #endregion } }
//---------------------------------------------------------------------------- // // <copyright file="Vector3D.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // // Description: 3D vector implementation. // // See spec at http://avalon/medialayer/Specifications/Avalon3D%20API%20Spec.mht // // History: // 06/02/2003 : t-gregr - Created // //--------------------------------------------------------------------------- using MS.Internal; using System; using System.Windows; using System.Windows.Media.Media3D; namespace System.Windows.Media.Media3D { /// <summary> /// Vector3D - 3D vector representation. /// </summary> public partial struct Vector3D { //----------------------------------------------------- // // Constructors // //----------------------------------------------------- #region Constructors /// <summary> /// Constructor that sets vector's initial values. /// </summary> /// <param name="x">Value of the X coordinate of the new vector. /// <param name="y">Value of the Y coordinate of the new vector. /// <param name="z">Value of the Z coordinate of the new vector. public Vector3D(double x, double y, double z) { _x = x; _y = y; _z = z; } #endregion Constructors //------------------------------------------------------ // // Public Methods // //----------------------------------------------------- #region Public Methods /// <summary> /// Length of the vector. /// </summary> public double Length { get { return Math.Sqrt(_x * _x + _y * _y + _z * _z); } } /// <summary> /// Length of the vector squared. /// </summary> public double LengthSquared { get { return _x * _x + _y * _y + _z * _z; } } /// <summary> /// Updates the vector to maintain its direction, but to have a length /// of 1. Equivalent to dividing the vector by its Length. /// Returns NaN if length is zero. /// </summary> public void Normalize() { // Computation of length can overflow easily because it // first computes squared length, so we first divide by // the largest coefficient. double m = Math.Abs(_x); double absy = Math.Abs(_y); double absz = Math.Abs(_z); if (absy > m) { m = absy; } if (absz > m) { m = absz; } _x /= m; _y /= m; _z /= m; double length = Math.Sqrt(_x * _x + _y * _y + _z * _z); this /= length; } /// <summary> /// Computes the angle between two vectors. /// </summary> /// <param name="vector1">First vector. /// <param name="vector2">Second vector. /// <returns> /// Returns the angle required to rotate vector1 into vector2 in degrees. /// This will return a value between [0, 180] degrees. /// (Note that this is slightly different from the Vector member /// function of the same name. Signed angles do not extend to 3D.) /// </returns> public static double AngleBetween(Vector3D vector1, Vector3D vector2) { vector1.Normalize(); vector2.Normalize(); double ratio = DotProduct(vector1, vector2); // The "straight forward" method of acos(u.v) has large precision // issues when the dot product is near +/-1. This is due to the // steep slope of the acos function as we approach +/- 1. Slight // precision errors in the dot product calculation cause large // variation in the output value. // // | | // \__ | // ---___ | // ---___ | // ---_|_ // | ---___ // | ---___ // | ---__ // | \ // | | // -|-------------------+-------------------|- // -1 0 1 // // acos(x) // // To avoid this we use an alternative method which finds the // angle bisector by (u-v)/2: // // _> // u _- \ (u-v)/2 // _- __-v // _=__-- // .=-----------> // v // // Because u and v and unit vectors, (u-v)/2 forms a right angle // with the angle bisector. The hypotenuse is 1, therefore // 2*asin(|u-v|/2) gives us the angle between u and v. // // The largest possible value of |u-v| occurs with perpendicular // vectors and is sqrt(2)/2 which is well away from extreme slope // at +/-1. // // (See Windows OS Bug #1706299 for details) double theta; if (ratio < 0) { theta = Math.PI - 2.0 * Math.Asin((-vector1 - vector2).Length / 2.0); } else { theta = 2.0 * Math.Asin((vector1 - vector2).Length / 2.0); } return M3DUtil.RadiansToDegrees(theta); } /// <summary> /// Operator -Vector (unary negation). /// </summary> /// <param name="vector">Vector being negated. /// <returns>Negation of the given vector.</returns> public static Vector3D operator -(Vector3D vector) { return new Vector3D(-vector._x, -vector._y, -vector._z); } /// <summary> /// Negates the values of X, Y, and Z on this Vector3D /// </summary> public void Negate() { _x = -_x; _y = -_y; _z = -_z; } /// <summary> /// Vector addition. /// </summary> /// <param name="vector1">First vector being added. /// <param name="vector2">Second vector being added. /// <returns>Result of addition.</returns> public static Vector3D operator +(Vector3D vector1, Vector3D vector2) { return new Vector3D(vector1._x + vector2._x, vector1._y + vector2._y, vector1._z + vector2._z); } /// <summary> /// Vector addition. /// </summary> /// <param name="vector1">First vector being added. /// <param name="vector2">Second vector being added. /// <returns>Result of addition.</returns> public static Vector3D Add(Vector3D vector1, Vector3D vector2) { return new Vector3D(vector1._x + vector2._x, vector1._y + vector2._y, vector1._z + vector2._z); } /// <summary> /// Vector subtraction. /// </summary> /// <param name="vector1">Vector that is subtracted from. /// <param name="vector2">Vector being subtracted. /// <returns>Result of subtraction.</returns> public static Vector3D operator -(Vector3D vector1, Vector3D vector2) { return new Vector3D(vector1._x - vector2._x, vector1._y - vector2._y, vector1._z - vector2._z); } /// <summary> /// Vector subtraction. /// </summary> /// <param name="vector1">Vector that is subtracted from. /// <param name="vector2">Vector being subtracted. /// <returns>Result of subtraction.</returns> public static Vector3D Subtract(Vector3D vector1, Vector3D vector2) { return new Vector3D(vector1._x - vector2._x, vector1._y - vector2._y, vector1._z - vector2._z); } /// <summary> /// Vector3D + Point3D addition. /// </summary> /// <param name="vector">Vector by which we offset the point. /// <param name="point">Point being offset by the given vector. /// <returns>Result of addition.</returns> public static Point3D operator +(Vector3D vector, Point3D point) { return new Point3D(vector._x + point._x, vector._y + point._y, vector._z + point._z); } /// <summary> /// Vector3D + Point3D addition. /// </summary> /// <param name="vector">Vector by which we offset the point. /// <param name="point">Point being offset by the given vector. /// <returns>Result of addition.</returns> public static Point3D Add(Vector3D vector, Point3D point) { return new Point3D(vector._x + point._x, vector._y + point._y, vector._z + point._z); } /// <summary> /// Vector3D - Point3D subtraction. /// </summary> /// <param name="vector">Vector by which we offset the point. /// <param name="point">Point being offset by the given vector. /// <returns>Result of subtraction.</returns> public static Point3D operator -(Vector3D vector, Point3D point) { return new Point3D(vector._x - point._x, vector._y - point._y, vector._z - point._z); } /// <summary> /// Vector3D - Point3D subtraction. /// </summary> /// <param name="vector">Vector by which we offset the point. /// <param name="point">Point being offset by the given vector. /// <returns>Result of subtraction.</returns> public static Point3D Subtract(Vector3D vector, Point3D point) { return new Point3D(vector._x - point._x, vector._y - point._y, vector._z - point._z); } /// <summary> /// Scalar multiplication. /// </summary> /// <param name="vector">Vector being multiplied. /// <param name="scalar">Scalar value by which the vector is multiplied. /// <returns>Result of multiplication.</returns> public static Vector3D operator *(Vector3D vector, double scalar) { return new Vector3D(vector._x * scalar, vector._y * scalar, vector._z * scalar); } /// <summary> /// Scalar multiplication. /// </summary> /// <param name="vector">Vector being multiplied. /// <param name="scalar">Scalar value by which the vector is multiplied. /// <returns>Result of multiplication.</returns> public static Vector3D Multiply(Vector3D vector, double scalar) { return new Vector3D(vector._x * scalar, vector._y * scalar, vector._z * scalar); } /// <summary> /// Scalar multiplication. /// </summary> /// <param name="scalar">Scalar value by which the vector is multiplied /// <param name="vector">Vector being multiplied. /// <returns>Result of multiplication.</returns> public static Vector3D operator *(double scalar, Vector3D vector) { return new Vector3D(vector._x * scalar, vector._y * scalar, vector._z * scalar); } /// <summary> /// Scalar multiplication. /// </summary> /// <param name="scalar">Scalar value by which the vector is multiplied /// <param name="vector">Vector being multiplied. /// <returns>Result of multiplication.</returns> public static Vector3D Multiply(double scalar, Vector3D vector) { return new Vector3D(vector._x * scalar, vector._y * scalar, vector._z * scalar); } /// <summary> /// Scalar division. /// </summary> /// <param name="vector">Vector being divided. /// <param name="scalar">Scalar value by which we divide the vector. /// <returns>Result of division.</returns> public static Vector3D operator /(Vector3D vector, double scalar) { return vector * (1.0 / scalar); } /// <summary> /// Scalar division. /// </summary> /// <param name="vector">Vector being divided. /// <param name="scalar">Scalar value by which we divide the vector. /// <returns>Result of division.</returns> public static Vector3D Divide(Vector3D vector, double scalar) { return vector * (1.0 / scalar); } /// <summary> /// Vector3D * Matrix3D multiplication /// </summary> /// <param name="vector">Vector being tranformed. /// <param name="matrix">Transformation matrix applied to the vector. /// <returns>Result of multiplication.</returns> public static Vector3D operator *(Vector3D vector, Matrix3D matrix) { return matrix.Transform(vector); } /// <summary> /// Vector3D * Matrix3D multiplication /// </summary> /// <param name="vector">Vector being tranformed. /// <param name="matrix">Transformation matrix applied to the vector. /// <returns>Result of multiplication.</returns> public static Vector3D Multiply(Vector3D vector, Matrix3D matrix) { return matrix.Transform(vector); } /// <summary> /// Vector dot product. /// </summary> /// <param name="vector1">First vector. /// <param name="vector2">Second vector. /// <returns>Dot product of two vectors.</returns> public static double DotProduct(Vector3D vector1, Vector3D vector2) { return DotProduct(ref vector1, ref vector2); } /// <summary> /// Faster internal version of DotProduct that avoids copies /// /// vector1 and vector2 to a passed by ref for perf and ARE NOT MODIFIED /// </summary> internal static double DotProduct(ref Vector3D vector1, ref Vector3D vector2) { return vector1._x * vector2._x + vector1._y * vector2._y + vector1._z * vector2._z; } /// <summary> /// Vector cross product. /// </summary> /// <param name="vector1">First vector. /// <param name="vector2">Second vector. /// <returns>Cross product of two vectors.</returns> public static Vector3D CrossProduct(Vector3D vector1, Vector3D vector2) { Vector3D result; CrossProduct(ref vector1, ref vector2, out result); return result; } /// <summary> /// Faster internal version of CrossProduct that avoids copies /// /// vector1 and vector2 to a passed by ref for perf and ARE NOT MODIFIED /// </summary> internal static void CrossProduct(ref Vector3D vector1, ref Vector3D vector2, out Vector3D result) { result._x = vector1._y * vector2._z - vector1._z * vector2._y; result._y = vector1._z * vector2._x - vector1._x * vector2._z; result._z = vector1._x * vector2._y - vector1._y * vector2._x; } /// <summary> /// Vector3D to Point3D conversion. /// </summary> /// <param name="vector">Vector being converted. /// <returns>Point representing the given vector.</returns> public static explicit operator Point3D(Vector3D vector) { return new Point3D(vector._x, vector._y, vector._z); } /// <summary> /// Explicit conversion to Size3D. Note that since Size3D cannot contain negative values, /// the resulting size will contains the absolute values of X, Y, and Z. /// </summary> /// <param name="vector">The vector to convert to a size. /// <returns>A size equal to this vector.</returns> public static explicit operator Size3D(Vector3D vector) { return new Size3D(Math.Abs(vector._x), Math.Abs(vector._y), Math.Abs(vector._z)); } #endregion Public Methods } } // File provided for Reference Use Only by Microsoft Corporation (c) 2007. // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------------------- // // <copyright file="Vector3D.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // // Description: 3D vector implementation. // // See spec at http://avalon/medialayer/Specifications/Avalon3D%20API%20Spec.mht // // History: // 06/02/2003 : t-gregr - Created // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.Media3D; using System; using System.Windows; using System.Windows.Media.Media3D; namespace System.Windows.Media.Media3D { /// <summary> /// Vector3D - 3D vector representation. /// </summary> public partial struct Vector3D { //----------------------------------------------------- // // Constructors // //----------------------------------------------------- #region Constructors /// <summary> /// Constructor that sets vector's initial values. /// </summary> /// <param name="x">Value of the X coordinate of the new vector. /// <param name="y">Value of the Y coordinate of the new vector. /// <param name="z">Value of the Z coordinate of the new vector. public Vector3D(double x, double y, double z) { _x = x; _y = y; _z = z; } #endregion Constructors //------------------------------------------------------ // // Public Methods // //----------------------------------------------------- #region Public Methods /// <summary> /// Length of the vector. /// </summary> public double Length { get { return Math.Sqrt(_x * _x + _y * _y + _z * _z); } } /// <summary> /// Length of the vector squared. /// </summary> public double LengthSquared { get { return _x * _x + _y * _y + _z * _z; } } /// <summary> /// Updates the vector to maintain its direction, but to have a length /// of 1. Equivalent to dividing the vector by its Length. /// Returns NaN if length is zero. /// </summary> public void Normalize() { // Computation of length can overflow easily because it // first computes squared length, so we first divide by // the largest coefficient. double m = Math.Abs(_x); double absy = Math.Abs(_y); double absz = Math.Abs(_z); if (absy > m) { m = absy; } if (absz > m) { m = absz; } _x /= m; _y /= m; _z /= m; double length = Math.Sqrt(_x * _x + _y * _y + _z * _z); this /= length; } /// <summary> /// Computes the angle between two vectors. /// </summary> /// <param name="vector1">First vector. /// <param name="vector2">Second vector. /// <returns> /// Returns the angle required to rotate vector1 into vector2 in degrees. /// This will return a value between [0, 180] degrees. /// (Note that this is slightly different from the Vector member /// function of the same name. Signed angles do not extend to 3D.) /// </returns> public static double AngleBetween(Vector3D vector1, Vector3D vector2) { vector1.Normalize(); vector2.Normalize(); double ratio = DotProduct(vector1, vector2); // The "straight forward" method of acos(u.v) has large precision // issues when the dot product is near +/-1. This is due to the // steep slope of the acos function as we approach +/- 1. Slight // precision errors in the dot product calculation cause large // variation in the output value. // // | | // \__ | // ---___ | // ---___ | // ---_|_ // | ---___ // | ---___ // | ---__ // | \ // | | // -|-------------------+-------------------|- // -1 0 1 // // acos(x) // // To avoid this we use an alternative method which finds the // angle bisector by (u-v)/2: // // _> // u _- \ (u-v)/2 // _- __-v // _=__-- // .=-----------> // v // // Because u and v and unit vectors, (u-v)/2 forms a right angle // with the angle bisector. The hypotenuse is 1, therefore // 2*asin(|u-v|/2) gives us the angle between u and v. // // The largest possible value of |u-v| occurs with perpendicular // vectors and is sqrt(2)/2 which is well away from extreme slope // at +/-1. // // (See Windows OS Bug #1706299 for details) double theta; if (ratio < 0) { theta = Math.PI - 2.0 * Math.Asin((-vector1 - vector2).Length / 2.0); } else { theta = 2.0 * Math.Asin((vector1 - vector2).Length / 2.0); } return M3DUtil.RadiansToDegrees(theta); } /// <summary> /// Operator -Vector (unary negation). /// </summary> /// <param name="vector">Vector being negated. /// <returns>Negation of the given vector.</returns> public static Vector3D operator -(Vector3D vector) { return new Vector3D(-vector._x, -vector._y, -vector._z); } /// <summary> /// Negates the values of X, Y, and Z on this Vector3D /// </summary> public void Negate() { _x = -_x; _y = -_y; _z = -_z; } /// <summary> /// Vector addition. /// </summary> /// <param name="vector1">First vector being added. /// <param name="vector2">Second vector being added. /// <returns>Result of addition.</returns> public static Vector3D operator +(Vector3D vector1, Vector3D vector2) { return new Vector3D(vector1._x + vector2._x, vector1._y + vector2._y, vector1._z + vector2._z); } /// <summary> /// Vector addition. /// </summary> /// <param name="vector1">First vector being added. /// <param name="vector2">Second vector being added. /// <returns>Result of addition.</returns> public static Vector3D Add(Vector3D vector1, Vector3D vector2) { return new Vector3D(vector1._x + vector2._x, vector1._y + vector2._y, vector1._z + vector2._z); } /// <summary> /// Vector subtraction. /// </summary> /// <param name="vector1">Vector that is subtracted from. /// <param name="vector2">Vector being subtracted. /// <returns>Result of subtraction.</returns> public static Vector3D operator -(Vector3D vector1, Vector3D vector2) { return new Vector3D(vector1._x - vector2._x, vector1._y - vector2._y, vector1._z - vector2._z); } /// <summary> /// Vector subtraction. /// </summary> /// <param name="vector1">Vector that is subtracted from. /// <param name="vector2">Vector being subtracted. /// <returns>Result of subtraction.</returns> public static Vector3D Subtract(Vector3D vector1, Vector3D vector2) { return new Vector3D(vector1._x - vector2._x, vector1._y - vector2._y, vector1._z - vector2._z); } /// <summary> /// Vector3D + Point3D addition. /// </summary> /// <param name="vector">Vector by which we offset the point. /// <param name="point">Point being offset by the given vector. /// <returns>Result of addition.</returns> public static Point3D operator +(Vector3D vector, Point3D point) { return new Point3D(vector._x + point._x, vector._y + point._y, vector._z + point._z); } /// <summary> /// Vector3D + Point3D addition. /// </summary> /// <param name="vector">Vector by which we offset the point. /// <param name="point">Point being offset by the given vector. /// <returns>Result of addition.</returns> public static Point3D Add(Vector3D vector, Point3D point) { return new Point3D(vector._x + point._x, vector._y + point._y, vector._z + point._z); } /// <summary> /// Vector3D - Point3D subtraction. /// </summary> /// <param name="vector">Vector by which we offset the point. /// <param name="point">Point being offset by the given vector. /// <returns>Result of subtraction.</returns> public static Point3D operator -(Vector3D vector, Point3D point) { return new Point3D(vector._x - point._x, vector._y - point._y, vector._z - point._z); } /// <summary> /// Vector3D - Point3D subtraction. /// </summary> /// <param name="vector">Vector by which we offset the point. /// <param name="point">Point being offset by the given vector. /// <returns>Result of subtraction.</returns> public static Point3D Subtract(Vector3D vector, Point3D point) { return new Point3D(vector._x - point._x, vector._y - point._y, vector._z - point._z); } /// <summary> /// Scalar multiplication. /// </summary> /// <param name="vector">Vector being multiplied. /// <param name="scalar">Scalar value by which the vector is multiplied. /// <returns>Result of multiplication.</returns> public static Vector3D operator *(Vector3D vector, double scalar) { return new Vector3D(vector._x * scalar, vector._y * scalar, vector._z * scalar); } /// <summary> /// Scalar multiplication. /// </summary> /// <param name="vector">Vector being multiplied. /// <param name="scalar">Scalar value by which the vector is multiplied. /// <returns>Result of multiplication.</returns> public static Vector3D Multiply(Vector3D vector, double scalar) { return new Vector3D(vector._x * scalar, vector._y * scalar, vector._z * scalar); } /// <summary> /// Scalar multiplication. /// </summary> /// <param name="scalar">Scalar value by which the vector is multiplied /// <param name="vector">Vector being multiplied. /// <returns>Result of multiplication.</returns> public static Vector3D operator *(double scalar, Vector3D vector) { return new Vector3D(vector._x * scalar, vector._y * scalar, vector._z * scalar); } /// <summary> /// Scalar multiplication. /// </summary> /// <param name="scalar">Scalar value by which the vector is multiplied /// <param name="vector">Vector being multiplied. /// <returns>Result of multiplication.</returns> public static Vector3D Multiply(double scalar, Vector3D vector) { return new Vector3D(vector._x * scalar, vector._y * scalar, vector._z * scalar); } /// <summary> /// Scalar division. /// </summary> /// <param name="vector">Vector being divided. /// <param name="scalar">Scalar value by which we divide the vector. /// <returns>Result of division.</returns> public static Vector3D operator /(Vector3D vector, double scalar) { return vector * (1.0 / scalar); } /// <summary> /// Scalar division. /// </summary> /// <param name="vector">Vector being divided. /// <param name="scalar">Scalar value by which we divide the vector. /// <returns>Result of division.</returns> public static Vector3D Divide(Vector3D vector, double scalar) { return vector * (1.0 / scalar); } /// <summary> /// Vector3D * Matrix3D multiplication /// </summary> /// <param name="vector">Vector being tranformed. /// <param name="matrix">Transformation matrix applied to the vector. /// <returns>Result of multiplication.</returns> public static Vector3D operator *(Vector3D vector, Matrix3D matrix) { return matrix.Transform(vector); } /// <summary> /// Vector3D * Matrix3D multiplication /// </summary> /// <param name="vector">Vector being tranformed. /// <param name="matrix">Transformation matrix applied to the vector. /// <returns>Result of multiplication.</returns> public static Vector3D Multiply(Vector3D vector, Matrix3D matrix) { return matrix.Transform(vector); } /// <summary> /// Vector dot product. /// </summary> /// <param name="vector1">First vector. /// <param name="vector2">Second vector. /// <returns>Dot product of two vectors.</returns> public static double DotProduct(Vector3D vector1, Vector3D vector2) { return DotProduct(ref vector1, ref vector2); } /// <summary> /// Faster internal version of DotProduct that avoids copies /// /// vector1 and vector2 to a passed by ref for perf and ARE NOT MODIFIED /// </summary> internal static double DotProduct(ref Vector3D vector1, ref Vector3D vector2) { return vector1._x * vector2._x + vector1._y * vector2._y + vector1._z * vector2._z; } /// <summary> /// Vector cross product. /// </summary> /// <param name="vector1">First vector. /// <param name="vector2">Second vector. /// <returns>Cross product of two vectors.</returns> public static Vector3D CrossProduct(Vector3D vector1, Vector3D vector2) { Vector3D result; CrossProduct(ref vector1, ref vector2, out result); return result; } /// <summary> /// Faster internal version of CrossProduct that avoids copies /// /// vector1 and vector2 to a passed by ref for perf and ARE NOT MODIFIED /// </summary> internal static void CrossProduct(ref Vector3D vector1, ref Vector3D vector2, out Vector3D result) { result._x = vector1._y * vector2._z - vector1._z * vector2._y; result._y = vector1._z * vector2._x - vector1._x * vector2._z; result._z = vector1._x * vector2._y - vector1._y * vector2._x; } /// <summary> /// Vector3D to Point3D conversion. /// </summary> /// <param name="vector">Vector being converted. /// <returns>Point representing the given vector.</returns> public static explicit operator Point3D(Vector3D vector) { return new Point3D(vector._x, vector._y, vector._z); } /// <summary> /// Explicit conversion to Size3D. Note that since Size3D cannot contain negative values, /// the resulting size will contains the absolute values of X, Y, and Z. /// </summary> /// <param name="vector">The vector to convert to a size. /// <returns>A size equal to this vector.</returns> public static explicit operator Size3D(Vector3D vector) { return new Size3D(Math.Abs(vector._x), Math.Abs(vector._y), Math.Abs(vector._z)); } #endregion Public Methods } } // File provided for Reference Use Only by Microsoft Corporation (c) 2007. // Copyright (c) Microsoft Corporation. All rights reserved.
// 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.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security.Permissions; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Imaging; using Microsoft.VisualStudio.Imaging.Interop; using Microsoft.VisualStudio.Shell.Interop; using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants; using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID; namespace Microsoft.VisualStudioTools.Project { internal abstract class ReferenceNode : HierarchyNode { internal delegate void CannotAddReferenceErrorMessage(); #region ctors /// <summary> /// constructor for the ReferenceNode /// </summary> protected ReferenceNode(ProjectNode root, ProjectElement element) : base(root, element) { this.ExcludeNodeFromScc = true; } /// <summary> /// constructor for the ReferenceNode /// </summary> internal ReferenceNode(ProjectNode root) : base(root) { this.ExcludeNodeFromScc = true; } #endregion #region overridden properties public override int MenuCommandId => VsMenus.IDM_VS_CTXT_REFERENCE; public override Guid ItemTypeGuid => Guid.Empty; public override string Url => string.Empty; public override string Caption => string.Empty; #endregion #region overridden methods protected override NodeProperties CreatePropertiesObject() { return new ReferenceNodeProperties(this); } /// <summary> /// Get an instance of the automation object for ReferenceNode /// </summary> /// <returns>An instance of Automation.OAReferenceItem type if succeeded</returns> public override object GetAutomationObject() { if (this.ProjectMgr == null || this.ProjectMgr.IsClosed) { return null; } return new Automation.OAReferenceItem(this.ProjectMgr.GetAutomationObject() as Automation.OAProject, this); } /// <summary> /// Disable inline editing of Caption of a ReferendeNode /// </summary> /// <returns>null</returns> public override string GetEditLabel() { return null; } protected override bool SupportsIconMonikers => true; protected override ImageMoniker GetIconMoniker(bool open) { return CanShowDefaultIcon() ? KnownMonikers.Reference : KnownMonikers.ReferenceWarning; } /// <summary> /// Not supported. /// </summary> internal override int ExcludeFromProject() { return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED; } public override void Remove(bool removeFromStorage) { var parent = this.Parent as ReferenceContainerNode; base.Remove(removeFromStorage); if (parent != null) { parent.FireChildRemoved(this); } } /// <summary> /// References node cannot be dragged. /// </summary> /// <returns>A stringbuilder.</returns> protected internal override string PrepareSelectedNodesForClipBoard() { return null; } internal override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result) { if (cmdGroup == VsMenus.guidStandardCommandSet2K) { if ((VsCommands2K)cmd == VsCommands2K.QUICKOBJECTSEARCH) { result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED; return VSConstants.S_OK; } } else { return (int)OleConstants.OLECMDERR_E_UNKNOWNGROUP; } return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result); } internal override int ExecCommandOnNode(Guid cmdGroup, uint cmd, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { if (cmdGroup == VsMenus.guidStandardCommandSet2K) { if ((VsCommands2K)cmd == VsCommands2K.QUICKOBJECTSEARCH) { return this.ShowObjectBrowser(); } } return base.ExecCommandOnNode(cmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut); } protected internal override void ShowDeleteMessage(IList<HierarchyNode> nodes, __VSDELETEITEMOPERATION action, out bool cancel, out bool useStandardDialog) { // Don't prompt if all the nodes are references useStandardDialog = !nodes.All(n => n is ReferenceNode); cancel = false; } #endregion #region methods /// <summary> /// Links a reference node to the project and hierarchy. /// </summary> public virtual void AddReference() { this.ProjectMgr.Site.GetUIThread().MustBeCalledFromUIThread(); var referencesFolder = this.ProjectMgr.GetReferenceContainer() as ReferenceContainerNode; Utilities.CheckNotNull(referencesFolder, "Could not find the References node"); CannotAddReferenceErrorMessage referenceErrorMessageHandler = null; if (!this.CanAddReference(out referenceErrorMessageHandler)) { if (referenceErrorMessageHandler != null) { referenceErrorMessageHandler.DynamicInvoke(new object[] { }); } return; } // Link the node to the project file. this.BindReferenceData(); // At this point force the item to be refreshed this.ItemNode.RefreshProperties(); referencesFolder.AddChild(this); return; } /// <summary> /// Refreshes a reference by re-resolving it and redrawing the icon. /// </summary> internal virtual void RefreshReference() { this.ResolveReference(); this.ProjectMgr.ReDrawNode(this, UIHierarchyElement.Icon); } /// <summary> /// Resolves references. /// </summary> protected virtual void ResolveReference() { } /// <summary> /// Validates that a reference can be added. /// </summary> /// <param name="errorHandler">A CannotAddReferenceErrorMessage delegate to show the error message.</param> /// <returns>true if the reference can be added.</returns> protected virtual bool CanAddReference(out CannotAddReferenceErrorMessage errorHandler) { // When this method is called this refererence has not yet been added to the hierarchy, only instantiated. errorHandler = null; if (this.IsAlreadyAdded()) { return false; } return true; } /// <summary> /// Checks if a reference is already added. The method parses all references and compares the Url. /// </summary> /// <returns>true if the assembly has already been added.</returns> protected virtual bool IsAlreadyAdded() { var referencesFolder = this.ProjectMgr.GetReferenceContainer() as ReferenceContainerNode; Utilities.CheckNotNull(referencesFolder, "Could not find the References node"); for (var n = referencesFolder.FirstChild; n != null; n = n.NextSibling) { var refererenceNode = n as ReferenceNode; if (null != refererenceNode) { // We check if the Url of the assemblies is the same. if (CommonUtils.IsSamePath(refererenceNode.Url, this.Url)) { return true; } } } return false; } /// <summary> /// Shows the Object Browser /// </summary> /// <returns></returns> protected virtual int ShowObjectBrowser() { if (!File.Exists(this.Url)) { return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED; } // Request unmanaged code permission in order to be able to create the unmanaged memory representing the guid. new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); var guid = VSConstants.guidCOMPLUSLibrary; var ptr = System.Runtime.InteropServices.Marshal.AllocCoTaskMem(guid.ToByteArray().Length); System.Runtime.InteropServices.Marshal.StructureToPtr(guid, ptr, false); var returnValue = VSConstants.S_OK; try { var objInfo = new VSOBJECTINFO[1]; objInfo[0].pguidLib = ptr; objInfo[0].pszLibName = this.Url; var objBrowser = this.ProjectMgr.Site.GetService(typeof(SVsObjBrowser)) as IVsObjBrowser; ErrorHandler.ThrowOnFailure(objBrowser.NavigateTo(objInfo, 0)); } catch (COMException e) { Trace.WriteLine("Exception" + e.ErrorCode); returnValue = e.ErrorCode; } finally { if (ptr != IntPtr.Zero) { System.Runtime.InteropServices.Marshal.FreeCoTaskMem(ptr); } } return returnValue; } internal override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation) { if (deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_RemoveFromProject) { return true; } return false; } protected abstract void BindReferenceData(); #endregion } }
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Threading; // Copyright (c) 2006 by Hugh Pyle, inguzaudio.com using DSPUtil; namespace DSPUtil { // Slower-than-fast convolvers for Samples // Slow (time-domain) convolver // Overlap-and-add method [Serializable] public class SlowConvolver : SoundObj, IConvolver { #region Instance members // A convolver for each channel TimeDomainConvolver[] _convolver; // Impulse length rounded up to power of two int _length; // Buffers for each channel of the two data inputs double[][] _impbuff; double[][] _databuff; // The convolver's output buffer (one for each channel) double[][] _outbuff; // A carry-forward buffer double[][] _copybuff; #endregion #region IConvolver impl // The impulse protected ISoundObj _impulse; protected int _impulseLength = DSPUtil.BUFSIZE; public virtual ISoundObj impulse { get { return _impulse; } set { // Note: it's OK to reset the impulse while running _impulse = value; _impulseLength = (_impulse == null) ? 0 : MathUtil.NextPowerOfTwo(_impulse.Iterations); // Read the impulse into a buffer, separating the channels for performance // Pad the impulse buffer to 2^n SoundBuffer buff = new SoundBuffer(_impulse); _impbuff = buff.ToDoubleArray(0, ImpulseLength); } } // De-convolution? Default is normal convolution. protected bool _deconvolve; public bool deconvolve { get { return false; } set { if (value) { throw new Exception("Time domain deconvolution not implemented."); } } } // Persist the convolution tail, and use it to feed the next convolution? Default no (null). // Set to a "name of this convolver" (e.g. the squeezebox MAC address it is destined for). // NOT IMPLEMENTED FOR TIME_DOMAIN CONVOLVER protected string _persistTail; protected string _persistFile; protected string _persistPath = Path.GetTempPath(); public string PersistPath { set { _persistPath = value; } } public string PersistTail { get { return _persistTail; } set { _persistTail = value; if (!String.IsNullOrEmpty(_persistTail)) { string filename = this.GetType() + "." + _persistTail; foreach (char c in System.IO.Path.GetInvalidFileNameChars()) { filename = filename.Replace(c, '_'); } _persistFile = Path.Combine(Path.GetTempPath(), filename + ".tail"); } } } /// <summary> /// This returns a bogus value. Tail persistence is not implemented in SlowConvolver. /// </summary> public bool IsPersistTail { get { return !String.IsNullOrEmpty(_persistTail); } } // Number of partitions -- zero for regular unpartitioned convolution public int partitions { get { return 0; } set { // ignore } } int ImpulseLength { get { // For now only iterate the impulse once if (_length == 0) { _length = MathUtil.NextPowerOfTwo(_impulse.Iterations); } return _length; } } #endregion // Gain, zero if not specified protected double _gain; public double gain { get { return _gain; } } public override int Iterations { get { return ((_impulse == null) ? 0 : _impulseLength) + _input.Iterations; } } /// <summary> /// Get an iterator for samples /// </summary> public override IEnumerator<ISample> Samples { get { if (_input == null) { yield break; } // Verify the input etc ushort nChannels = _input.NumChannels; // If the impulse is one channel, that's always OK; apply the same impulse to each input channel. // If the impulse has the same number of channels as the input, OK: apply each channel of impulse to the corresponding channel of input. // But otherwise, channels mismatch is not allowed (e.g. 2-channel impulse & 1-channel or 4-channel input) if ((_impulse.NumChannels > 1) && (_impulse.NumChannels != _input.NumChannels)) { throw new ArgumentException(String.Format("Impulse of {0} channels can't be used with an input of {1} channels.", _impulse.NumChannels, _input.NumChannels)); } // Allocate an array to hold the output buffers // (the buffers themselves are allocated by the convolver) _outbuff = new double[nChannels][]; // Allocate buffers for data & copyforward _databuff = new double[nChannels][]; _copybuff = new double[nChannels][]; for (int c = 0; c < nChannels; c++) { _databuff[c] = new double[ImpulseLength]; _copybuff[c] = new double[ImpulseLength]; } // Read the impulse into a buffer, separating the channels for performance // Pad the impulse buffer to 2^n // SoundBuffer buff = new SoundBuffer(_impulse); // _impbuff = buff.ToDoubleArray(0, ImpulseLength); // Create the convolvers, one per channel _convolver = new TimeDomainConvolver[nChannels]; for (int c = 0; c < nChannels; c++) { double[] imp = _impbuff[_impulse.NumChannels == 1 ? 0 : c]; _convolver[c] = new TimeDomainConvolver(imp, _deconvolve); } IEnumerator<ISample> inputSamples = _input.Samples; bool moreSamples = true; bool tail = false; while (moreSamples) // || tail) { // Read input, up to size of the impulse int x = 0; for (int j = 0; j < ImpulseLength; j++) { ISample s; if (moreSamples) { moreSamples = inputSamples.MoveNext(); } if (moreSamples) { s = inputSamples.Current; x = j; } else { s = new Sample(nChannels); // null data } for (ushort c = 0; c < nChannels; c++) { _databuff[c][j] = s[c]; } } tail = (!moreSamples && !tail); // Convolve input with the impulse for (int k = 0; k < nChannels; k++) { if (_outbuff[k] != null) { // Save the latter half of the output buffer for next time overlap-add for (int j = 0; j < ImpulseLength - 1; j++) { _copybuff[k][j] = _outbuff[k][j + ImpulseLength]; } } _outbuff[k] = _convolver[k].Convolve(_databuff[k], 1.0f); _gain = _convolver[k].Gain; } if (!tail) { x++; } // Yield the samples from convolver's output, added to any copy-buffer data for (int n = 0; n < x; n++) { ISample ret = nChannels == 2 ? new Sample2() : new Sample(nChannels) as ISample; for (int c = 0; c < nChannels; c++) { ret[c] = _copybuff[c][n] + _outbuff[c][n]; } yield return ret; } } } } } // Direct (and reasonably efficient) time domain convolver, expects equal-size 2^n inputs only, // See http://www.musicdsp.org/showone.php?id=65, // http://www.musicdsp.org/showone.php?id=66, // http://mathworld.wolfram.com/KaratsubaMultiplication.html [Serializable] class TimeDomainConvolver { double[] _impulse; double[] _buffer; double[] _output; double _gain; int _size; bool _deconvolve; // Util for convolution public TimeDomainConvolver(double[] impulse, bool deConvolve) { _impulse = impulse; _deconvolve = deConvolve; _size = _impulse.Length; if (!MathUtil.IsPowerOfTwo(_size)) { throw new ArgumentException("Convolve: input array size must be power of two"); } _buffer = new double[_size * 2]; _output = new double[_size * 2]; } public unsafe double[] Convolve(double[] data, double gain) { if (_size != data.Length) { throw new ArgumentException("Convolve: input arrays must be the same size"); } // arr_mul_knuth(_output, 0, _impulse, 0, data, 0, _buffer, 0, _size); fixed (double* o = _output, a = data, b = _impulse, tmp = _buffer) { mul_knuth(o, a, b, tmp, (uint)_size); } _gain = gain; if (_gain == 0) { // Gain not specified, calculate it from peak of in2 & output // and reduce further by 3dB double peak1 = 0; for (int j = 0; j < _impulse.Length; j++) { peak1 = Math.Max(peak1, Math.Abs(data[j])); } if (peak1 != 0) { double peak2 = 0; for (int j = 0; j < _output.Length; j++) { peak2 = Math.Max(peak2, Math.Abs(_output[j])); } if (!double.IsNaN(peak2)) { _gain = peak1 / peak2; } else { _gain = 1.0; } } } // Apply the specified gain // for (int j = 0; j < _output.Length; j++) // { // _output[j] *= _gain; // } return _output; } public double Gain { get { return _gain; } } // Array methods, safe private void arr_mul_brute(double[] r, uint ro, double[] a, uint ao, double[] b, uint bo, uint w) { for (uint i = 0; i < w + w; i++) r[ro + i] = 0; if (_deconvolve) { for (uint i = 0; i < w; i++) { for (uint j = 0; j < w; j++) r[ro + i + j] += a[ao + i] / b[bo + j]; } } else { for (uint i = 0; i < w; i++) { for (uint j = 0; j < w; j++) r[ro + i + j] += a[ao + i] * b[bo + j]; } } } private void arr_mul_knuth(double[] r, uint ro, double[] a, uint ao, double[] b, uint bo, double[] tmp, uint tmpo, uint w) { if (w < 25) { arr_mul_brute(r, ro, a, ao, b, bo, w); } else { uint m = w >> 1; for (uint i = 0; i < m; i++) { r[ro + i] = a[ao + m + i] - a[ao + i]; r[ro + i + m] = b[bo + i] - b[bo + m + i]; } arr_mul_knuth(tmp, tmpo, r, ro, r, ro + m, tmp, tmpo + w, m); arr_mul_knuth(r, ro, a, ao, b, bo, tmp, tmpo + w, m); arr_mul_knuth(r, ro + w, a, ao + m, b, bo + m, tmp, tmpo + w, m); for (uint i = 0; i < m; i++) { double bla = r[ro + m + i] + r[ro + w + i]; r[ro + m + i] = bla + r[ro + i] + tmp[tmpo + i]; r[ro + w + i] = bla + r[ro + w + m + i] + tmp[tmpo + m + i]; } } } // Pointer methods, unsafe, approx twice as fast as the safe methods private unsafe void mul_brute(double* r, double* a, double* b, uint w) { for (uint i = 0; i < w + w; i++) r[i] = 0; if (_deconvolve) { for (uint i = 0; i < w; i++) { for (uint j = 0; j < w; j++) r[i + j] += a[i] / b[j]; } } else { for (uint i = 0; i < w; i++) { for (uint j = 0; j < w; j++) r[i + j] += a[i] * b[j]; } } } // tmp must be of length 2*w private unsafe void mul_knuth(double* r, double* a, double* b, double* tmp, uint w) { if (w < 25) { mul_brute(r, a, b, w); } else { uint m = w >> 1; for (uint i = 0; i < m; i++) { r[i] = a[m + i] - a[i]; r[i + m] = b[i] - b[m + i]; } mul_knuth(tmp, r, r + m, tmp + w, m); mul_knuth(r, a, b, tmp + w, m); mul_knuth(r + w, a + m, b + m, tmp + w, m); for (uint i = 0; i < m; i++) { double bla = r[m + i] + r[w + i]; r[m + i] = bla + r[i] + tmp[i]; r[w + i] = bla + r[w + m + i] + tmp[m + i]; } } } } }
// 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.MirrorPolymorphic { using Microsoft.Rest; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// Some cool documentation. /// </summary> public partial class PolymorphicAnimalStore : ServiceClient<PolymorphicAnimalStore>, IPolymorphicAnimalStore { /// <summary> /// The base URI of the service. /// </summary> public System.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> /// Initializes a new instance of the PolymorphicAnimalStore class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public PolymorphicAnimalStore(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the PolymorphicAnimalStore 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> public PolymorphicAnimalStore(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the PolymorphicAnimalStore 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="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public PolymorphicAnimalStore(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the PolymorphicAnimalStore 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="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public PolymorphicAnimalStore(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// An optional partial-method to perform custom initialization. ///</summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { BaseUri = new System.Uri("https://management.azure.com/"); SerializationSettings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<Animal>("dtype")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<Animal>("dtype")); CustomInitialize(); } /// <summary> /// Product Types /// </summary> /// <remarks> /// The Products endpoint returns information about the Uber products offered /// at a given location. The response includes the display name and other /// details about each product, and lists the products in the proper display /// order. /// </remarks> /// <param name='animalCreateOrUpdateParameter'> /// An Animal /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Error2Exception"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<Animal>> CreateOrUpdatePolymorphicAnimalsWithHttpMessagesAsync(Animal animalCreateOrUpdateParameter = default(Animal), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("animalCreateOrUpdateParameter", animalCreateOrUpdateParameter); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdatePolymorphicAnimals", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "getpolymorphicAnimals").ToString(); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(animalCreateOrUpdateParameter != null) { _requestContent = SafeJsonConvert.SerializeObject(animalCreateOrUpdateParameter, SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Error2Exception(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error2 _errorBody = SafeJsonConvert.DeserializeObject<Error2>(_responseContent, DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<Animal>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Animal>(_responseContent, DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NBitcoin; using NBitcoin.Secp256k1; using WalletWasabi.Crypto; using WalletWasabi.Crypto.Groups; using WalletWasabi.Crypto.Randomness; using WalletWasabi.Crypto.ZeroKnowledge; using WalletWasabi.Crypto.ZeroKnowledge.LinearRelation; using WalletWasabi.Helpers; namespace WalletWasabi.WabiSabi.Crypto { /// <summary> /// Issues anonymous credentials using the coordinator's secret key. /// </summary> /// <remarks> /// CredentialIssuer is the coordinator's component used to issue anonymous credentials /// requested by a WabiSabi client. This means this component abstracts receives /// <see cref="RegistrationRequestMessage">RegistrationRequests</see>, validates the requested /// amounts are in the valid range, serial numbers are not duplicated nor reused, /// and finally issues the credentials using the coordinator's secret key (and also /// proving to the WabiSabi client that the credentials were issued with the right /// key). /// /// Note that this is a stateful component because it needs to keep track of the /// presented credentials' serial numbers in order to prevent credential reuse. /// Additionally it keeps also track of the `balance` in order to make sure it never /// issues credentials for more money than the total presented amount. All this means /// that the same instance has to be used for a given round (the coordinator needs to /// maintain only one instance of this class per round) /// /// About replay requests: a replay request is a <see cref="RegistrationRequestMessage">request</see> /// that has already been seen before. These kind of requests can be the result of misbehaving /// clients or simply clients using a retry communication mechanism. /// Reply requests are not handled by this component and they have to be handled by a different /// component. A good solution is to use a caching feature where the request fingerprint is /// used as a key, in this way using a standard solution it is possible to respond with the exact /// same valid credentials to the client without performance penalties. /// </remarks> public class CredentialIssuer { /// <summary> /// Initializes a new instance of the CredentialIssuer class. /// </summary> /// <param name="credentialIssuerSecretKey">The <see cref="CredentialIssuerSecretKey">coordinator's secret key</see> used to issue the credentials.</param> /// <param name="numberOfCredentials">The number of credentials that the protocol handles in each request/response.</param> /// <param name="randomNumberGenerator">The random number generator.</param> public CredentialIssuer(CredentialIssuerSecretKey credentialIssuerSecretKey, int numberOfCredentials, WasabiRandom randomNumberGenerator) { CredentialIssuerSecretKey = Guard.NotNull(nameof(credentialIssuerSecretKey), credentialIssuerSecretKey); NumberOfCredentials = Guard.InRangeAndNotNull(nameof(numberOfCredentials), numberOfCredentials, 1, 100); CredentialIssuerParameters = CredentialIssuerSecretKey.ComputeCredentialIssuerParameters(); RandomNumberGenerator = Guard.NotNull(nameof(randomNumberGenerator), randomNumberGenerator); } // Keeps track of the used serial numbers. This is part of // the double-spending prevention mechanism. private HashSet<GroupElement> SerialNumbers { get; } = new HashSet<GroupElement>(); // Canary test check to ensure credential balance is never negative private Money Balance { get; set; } = Money.Zero; private WasabiRandom RandomNumberGenerator { get; } private CredentialIssuerSecretKey CredentialIssuerSecretKey { get; } private CredentialIssuerParameters CredentialIssuerParameters { get; } /// <summary> /// Gets the number of credentials that have to be requested/presented /// This parameter is called `k` in the WabiSabi paper. /// </summary> public int NumberOfCredentials { get; } /// <summary> /// Process the <see cref="RegistrationRequestMessage">credentials registration requests</see> and /// issues the credentials. /// </summary> /// <param name="registrationRequest">The request containing the credentials presentations, credential requests and the proofs.</param> /// <returns>The <see cref="RegistrationResponseMessage">registration response</see> containing the requested credentials and the proofs.</returns> /// <exception cref="WabiSabiException">Error code: <see cref="WabiSabiErrorCode">WabiSabiErrorCode</see></exception> public RegistrationResponseMessage HandleRequest(RegistrationRequestMessage registrationRequest) { Guard.NotNull(nameof(registrationRequest), registrationRequest); var requested = registrationRequest.Requested ?? Enumerable.Empty<IssuanceRequest>(); var presented = registrationRequest.Presented ?? Enumerable.Empty<CredentialPresentation>(); var requestedCount = requested.Count(); if (requestedCount != NumberOfCredentials) { throw new WabiSabiException( WabiSabiErrorCode.InvalidNumberOfRequestedCredentials, $"{NumberOfCredentials} credential requests were expected but {requestedCount} were received."); } var presentedCount = presented.Count(); var requiredNumberOfPresentations = registrationRequest.IsNullRequest ? 0 : NumberOfCredentials; if (presentedCount != requiredNumberOfPresentations) { throw new WabiSabiException( WabiSabiErrorCode.InvalidNumberOfPresentedCredentials, $"{requiredNumberOfPresentations} credential presentations were expected but {presentedCount} were received."); } // Don't allow balance to go negative. In case this goes below zero // then there is a problem somewhere because this should not be possible. if (Balance + registrationRequest.DeltaAmount < Money.Zero) { throw new WabiSabiException(WabiSabiErrorCode.NegativeBalance); } // Check that the range proofs are of the appropriate bitwidth var rangeProofWidth = registrationRequest.IsNullRequest ? 0 : Constants.RangeProofWidth; var allRangeProofsAreCorrectSize = requested.All(x => x.BitCommitments.Count() == rangeProofWidth); if (!allRangeProofsAreCorrectSize) { throw new WabiSabiException(WabiSabiErrorCode.InvalidBitCommitment); } // Check all the serial numbers are unique. Note that this is checked separately from // ensuring that they haven't been used before, because even presenting a previously // unused credential more than once in the same request is still a double spend. if (registrationRequest.AreThereDuplicatedSerialNumbers) { throw new WabiSabiException(WabiSabiErrorCode.SerialNumberDuplicated); } var statements = new List<Statement>(); foreach (var presentation in presented) { // Calculate Z using coordinator secret. var z = presentation.ComputeZ(CredentialIssuerSecretKey); // Add the credential presentation to the statements to be verified. statements.Add(ProofSystem.ShowCredentialStatement(presentation, z, CredentialIssuerParameters)); // Check if the serial numbers have been used before. Note that // the serial numbers have not yet been verified at this point, but a // request with an invalid proof and a used serial number should also be // rejected. if (SerialNumbers.Contains(presentation.S)) { throw new WabiSabiException(WabiSabiErrorCode.SerialNumberAlreadyUsed, $"Serial number reused {presentation.S}"); } } foreach (var credentialRequest in requested) { statements.Add(registrationRequest.IsNullRequest ? ProofSystem.ZeroProofStatement(credentialRequest.Ma) : ProofSystem.RangeProofStatement(credentialRequest.Ma, credentialRequest.BitCommitments)); } // Balance proof if (!registrationRequest.IsNullRequest) { var sumCa = presented.Select(x => x.Ca).Sum(); var sumMa = requested.Select(x => x.Ma).Sum(); // A positive Delta_a means the requested credential amounts are larger // than the presented ones (i.e. input registration, and a negative // balance correspond to output registration). The equation requires a // commitment to 0, so the sum of the presented attributes and the // negated requested attributes are tweaked by delta_a. var absAmountDelta = new Scalar(registrationRequest.DeltaAmount.Abs()); var deltaA = registrationRequest.DeltaAmount < Money.Zero ? absAmountDelta.Negate() : absAmountDelta; var balanceTweak = deltaA * Generators.Gg; statements.Add(ProofSystem.BalanceProofStatement(balanceTweak + sumCa - sumMa)); } var transcript = BuildTransnscript(registrationRequest.IsNullRequest); // Verify all statements. var areProofsValid = ProofSystem.Verify(transcript, statements, registrationRequest.Proofs); if (!areProofsValid) { throw new WabiSabiException(WabiSabiErrorCode.CoordinatorReceivedInvalidProofs); } // Issue credentials. var credentials = requested.Select(x => IssueCredential(x.Ma, RandomNumberGenerator.GetScalar())).ToArray(); // Construct response. var proofs = ProofSystem.Prove(transcript, credentials.Select(x => x.Knowledge), RandomNumberGenerator); var macs = credentials.Select(x => x.Mac); var response = new RegistrationResponseMessage(macs, proofs); // Register the serial numbers to prevent credential reuse. foreach (var presentation in presented) { SerialNumbers.Add(presentation.S); } Balance += registrationRequest.DeltaAmount; return response; } private (MAC Mac, Knowledge Knowledge) IssueCredential(GroupElement ma, Scalar t) { var sk = CredentialIssuerSecretKey; var mac = MAC.ComputeMAC(sk, ma, t); var knowledge = ProofSystem.IssuerParametersKnowledge(mac, ma, sk); return (mac, knowledge); } private Transcript BuildTransnscript(bool isNullRequest) { var label = $"UnifiedRegistration/{NumberOfCredentials}/{isNullRequest}"; var encodedLabel = Encoding.UTF8.GetBytes(label); return new Transcript(encodedLabel); } } }
/* * The MIT License (MIT) * * Copyright (c) 2014 LeanIX GmbH * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using LeanIX.Api.Common; using LeanIX.Api.Models; namespace LeanIX.Api { public class ProcessesApi { private readonly ApiClient apiClient = ApiClient.GetInstance(); public ApiClient getClient() { return apiClient; } /// <summary> /// Read all Process /// </summary> /// <param name="relations">If set to true, all relations of the Fact Sheet are fetched as well. Fetching all relations can be slower. Default: false.</param> /// <param name="filter">Full-text filter</param> /// <returns></returns> public List<Process> getProcesses (bool relations, string filter) { // create path and map variables var path = "/processes".Replace("{format}","json"); // query params var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); string paramStr = null; if (relations != null){ paramStr = (relations != null && relations is DateTime) ? ((DateTime)(object)relations).ToString("u") : Convert.ToString(relations); queryParams.Add("relations", paramStr); } if (filter != null){ paramStr = (filter != null && filter is DateTime) ? ((DateTime)(object)filter).ToString("u") : Convert.ToString(filter); queryParams.Add("filter", paramStr); } try { var response = apiClient.invokeAPI(path, "GET", queryParams, null, headerParams); if(response != null){ return (List<Process>) ApiClient.deserialize(response, typeof(List<Process>)); } else { return null; } } catch (ApiException ex) { if(ex.ErrorCode == 404) { return null; } else { throw ex; } } } /// <summary> /// Create a new Process /// </summary> /// <param name="body">Message-Body</param> /// <returns></returns> public Process createProcess (Process body) { // create path and map variables var path = "/processes".Replace("{format}","json"); // query params var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); string paramStr = null; try { var response = apiClient.invokeAPI(path, "POST", queryParams, body, headerParams); if(response != null){ return (Process) ApiClient.deserialize(response, typeof(Process)); } else { return null; } } catch (ApiException ex) { if(ex.ErrorCode == 404) { return null; } else { throw ex; } } } /// <summary> /// Read a Process by a given ID /// </summary> /// <param name="ID">Unique ID</param> /// <param name="relations">If set to true, all relations of the Fact Sheet are fetched as well. Fetching all relations can be slower. Default: false.</param> /// <returns></returns> public Process getProcess (string ID, bool relations) { // create path and map variables var path = "/processes/{ID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())); // query params var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); // verify required params are set if (ID == null ) { throw new ApiException(400, "missing required params"); } string paramStr = null; if (relations != null){ paramStr = (relations != null && relations is DateTime) ? ((DateTime)(object)relations).ToString("u") : Convert.ToString(relations); queryParams.Add("relations", paramStr); } try { var response = apiClient.invokeAPI(path, "GET", queryParams, null, headerParams); if(response != null){ return (Process) ApiClient.deserialize(response, typeof(Process)); } else { return null; } } catch (ApiException ex) { if(ex.ErrorCode == 404) { return null; } else { throw ex; } } } /// <summary> /// Update a Process by a given ID /// </summary> /// <param name="ID">Unique ID</param> /// <param name="body">Message-Body</param> /// <returns></returns> public Process updateProcess (string ID, Process body) { // create path and map variables var path = "/processes/{ID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())); // query params var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); // verify required params are set if (ID == null ) { throw new ApiException(400, "missing required params"); } string paramStr = null; try { var response = apiClient.invokeAPI(path, "PUT", queryParams, body, headerParams); if(response != null){ return (Process) ApiClient.deserialize(response, typeof(Process)); } else { return null; } } catch (ApiException ex) { if(ex.ErrorCode == 404) { return null; } else { throw ex; } } } /// <summary> /// Delete a Process by a given ID /// </summary> /// <param name="ID">Unique ID</param> /// <returns></returns> public void deleteProcess (string ID) { // create path and map variables var path = "/processes/{ID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())); // query params var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); // verify required params are set if (ID == null ) { throw new ApiException(400, "missing required params"); } string paramStr = null; try { var response = apiClient.invokeAPI(path, "DELETE", queryParams, null, headerParams); if(response != null){ return ; } else { return ; } } catch (ApiException ex) { if(ex.ErrorCode == 404) { return ; } else { throw ex; } } } /// <summary> /// Read all of relation /// </summary> /// <param name="ID">Unique ID</param> /// <returns></returns> public List<ServiceHasProcess> getServiceHasProcesses (string ID) { // create path and map variables var path = "/processes/{ID}/serviceHasProcesses".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())); // query params var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); // verify required params are set if (ID == null ) { throw new ApiException(400, "missing required params"); } string paramStr = null; try { var response = apiClient.invokeAPI(path, "GET", queryParams, null, headerParams); if(response != null){ return (List<ServiceHasProcess>) ApiClient.deserialize(response, typeof(List<ServiceHasProcess>)); } else { return null; } } catch (ApiException ex) { if(ex.ErrorCode == 404) { return null; } else { throw ex; } } } /// <summary> /// Create a new relation /// </summary> /// <param name="ID">Unique ID</param> /// <param name="body">Message-Body</param> /// <returns></returns> public ServiceHasProcess createServiceHasProcess (string ID, Process body) { // create path and map variables var path = "/processes/{ID}/serviceHasProcesses".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())); // query params var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); // verify required params are set if (ID == null ) { throw new ApiException(400, "missing required params"); } string paramStr = null; try { var response = apiClient.invokeAPI(path, "POST", queryParams, body, headerParams); if(response != null){ return (ServiceHasProcess) ApiClient.deserialize(response, typeof(ServiceHasProcess)); } else { return null; } } catch (ApiException ex) { if(ex.ErrorCode == 404) { return null; } else { throw ex; } } } /// <summary> /// Read by relationID /// </summary> /// <param name="ID">Unique ID</param> /// <param name="relationID">Unique ID of the Relation</param> /// <returns></returns> public ServiceHasProcess getServiceHasProcess (string ID, string relationID) { // create path and map variables var path = "/processes/{ID}/serviceHasProcesses/{relationID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())).Replace("{" + "relationID" + "}", apiClient.escapeString(relationID.ToString())); // query params var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); // verify required params are set if (ID == null || relationID == null ) { throw new ApiException(400, "missing required params"); } string paramStr = null; try { var response = apiClient.invokeAPI(path, "GET", queryParams, null, headerParams); if(response != null){ return (ServiceHasProcess) ApiClient.deserialize(response, typeof(ServiceHasProcess)); } else { return null; } } catch (ApiException ex) { if(ex.ErrorCode == 404) { return null; } else { throw ex; } } } /// <summary> /// Update relation by a given relationID /// </summary> /// <param name="ID">Unique ID</param> /// <param name="relationID">Unique ID of the Relation</param> /// <param name="body">Message-Body</param> /// <returns></returns> public ServiceHasProcess updateServiceHasProcess (string ID, string relationID, Process body) { // create path and map variables var path = "/processes/{ID}/serviceHasProcesses/{relationID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())).Replace("{" + "relationID" + "}", apiClient.escapeString(relationID.ToString())); // query params var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); // verify required params are set if (ID == null || relationID == null ) { throw new ApiException(400, "missing required params"); } string paramStr = null; try { var response = apiClient.invokeAPI(path, "PUT", queryParams, body, headerParams); if(response != null){ return (ServiceHasProcess) ApiClient.deserialize(response, typeof(ServiceHasProcess)); } else { return null; } } catch (ApiException ex) { if(ex.ErrorCode == 404) { return null; } else { throw ex; } } } /// <summary> /// Delete relation by a given relationID /// </summary> /// <param name="ID">Unique ID</param> /// <param name="relationID">Unique ID of the Relation</param> /// <returns></returns> public void deleteServiceHasProcess (string ID, string relationID) { // create path and map variables var path = "/processes/{ID}/serviceHasProcesses/{relationID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())).Replace("{" + "relationID" + "}", apiClient.escapeString(relationID.ToString())); // query params var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(); // verify required params are set if (ID == null || relationID == null ) { throw new ApiException(400, "missing required params"); } string paramStr = null; try { var response = apiClient.invokeAPI(path, "DELETE", queryParams, null, headerParams); if(response != null){ return ; } else { return ; } } catch (ApiException ex) { if(ex.ErrorCode == 404) { return ; } else { throw ex; } } } } }
// // TabStrip.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 Gtk; using System; namespace MonoDevelop.Components.Docking { class TabStrip: Notebook { int currentTab = -1; bool ellipsized = true; HBox box = new HBox (); DockFrame frame; Label bottomFiller = new Label (); public TabStrip (DockFrame frame) { this.frame = frame; frame.ShadedContainer.Add (this); VBox vbox = new VBox (); box = new HBox (); vbox.PackStart (box, false, false, 0); vbox.PackStart (bottomFiller, false, false, 0); AppendPage (vbox, null); ShowBorder = false; ShowTabs = false; ShowAll (); bottomFiller.Hide (); BottomPadding = 3; } public int BottomPadding { get { return bottomFiller.HeightRequest; } set { bottomFiller.HeightRequest = value; bottomFiller.Visible = value > 0; } } public void AddTab (Gtk.Widget page, Gdk.Pixbuf icon, string label) { Tab tab = new Tab (); tab.SetLabel (page, icon, label); tab.ShowAll (); box.PackStart (tab, true, true, 0); if (currentTab == -1) CurrentTab = box.Children.Length - 1; else { tab.Active = false; page.Hide (); } tab.ButtonPressEvent += OnTabPress; } public void SetTabLabel (Gtk.Widget page, Gdk.Pixbuf icon, string label) { foreach (Tab tab in box.Children) { if (tab.Page == page) { tab.SetLabel (page, icon, label); UpdateEllipsize (Allocation); break; } } } public int TabCount { get { return box.Children.Length; } } public int CurrentTab { get { return currentTab; } set { if (currentTab == value) return; if (currentTab != -1) { Tab t = (Tab) box.Children [currentTab]; t.Page.Hide (); t.Active = false; } currentTab = value; if (currentTab != -1) { Tab t = (Tab) box.Children [currentTab]; t.Active = true; t.Page.Show (); } } } new public Gtk.Widget CurrentPage { get { if (currentTab != -1) { Tab t = (Tab) box.Children [currentTab]; return t.Page; } else return null; } set { if (value != null) { Gtk.Widget[] tabs = box.Children; for (int n = 0; n < tabs.Length; n++) { Tab tab = (Tab) tabs [n]; if (tab.Page == value) { CurrentTab = n; return; } } } CurrentTab = -1; } } public void Clear () { ellipsized = true; currentTab = -1; foreach (Widget w in box.Children) { box.Remove (w); w.Destroy (); } } void OnTabPress (object s, Gtk.ButtonPressEventArgs args) { CurrentTab = Array.IndexOf (box.Children, s); Tab t = (Tab) s; DockItem.SetFocus (t.Page); QueueDraw (); } protected override void OnSizeAllocated (Gdk.Rectangle allocation) { UpdateEllipsize (allocation); base.OnSizeAllocated (allocation); } void UpdateEllipsize (Gdk.Rectangle allocation) { int tsize = 0; foreach (Tab tab in box.Children) tsize += tab.LabelWidth; bool ellipsize = tsize > allocation.Width; if (ellipsize != ellipsized) { foreach (Tab tab in box.Children) { tab.SetEllipsize (ellipsize); Gtk.Box.BoxChild bc = (Gtk.Box.BoxChild) box [tab]; bc.Expand = bc.Fill = ellipsize; } ellipsized = ellipsize; } } public Gdk.Rectangle GetTabArea (int ntab) { Gtk.Widget[] tabs = box.Children; Tab tab = (Tab) tabs[ntab]; Gdk.Rectangle rect = GetTabArea (tab, ntab); int x, y; tab.GdkWindow.GetRootOrigin (out x, out y); rect.X += x; rect.Y += y; return rect; } protected override bool OnExposeEvent (Gdk.EventExpose evnt) { frame.ShadedContainer.DrawBackground (this); Gtk.Widget[] tabs = box.Children; for (int n=tabs.Length - 1; n>=0; n--) { Tab tab = (Tab) tabs [n]; if (n != currentTab) DrawTab (evnt, tab, n); } if (currentTab != -1) { Tab ctab = (Tab) tabs [currentTab]; // GdkWindow.DrawLine (Style.DarkGC (Gtk.StateType.Normal), Allocation.X, Allocation.Y, Allocation.Right, Allocation.Y); DrawTab (evnt, ctab, currentTab); } return base.OnExposeEvent (evnt); } public Gdk.Rectangle GetTabArea (Tab tab, int pos) { Gdk.Rectangle rect = tab.Allocation; int xdif = 0; if (pos > 0) xdif = 2; int reqh; // StateType st; if (tab.Active) { // st = StateType.Normal; reqh = tab.Allocation.Height; } else { reqh = tab.Allocation.Height - 3; // st = StateType.Active; } if (DockFrame.IsWindows) { rect.Height = reqh - 1; rect.Width--; if (pos > 0) { rect.X--; rect.Width++; } return rect; } else { rect.X -= xdif; rect.Width += xdif; rect.Height = reqh; return rect; } } void DrawTab (Gdk.EventExpose evnt, Tab tab, int pos) { Gdk.Rectangle rect = GetTabArea (tab, pos); StateType st; if (tab.Active) st = StateType.Normal; else st = StateType.Active; if (DockFrame.IsWindows) { GdkWindow.DrawRectangle (Style.DarkGC (Gtk.StateType.Normal), false, rect); rect.X++; rect.Width--; if (tab.Active) { GdkWindow.DrawRectangle (Style.LightGC (Gtk.StateType.Normal), true, rect); } else { using (Cairo.Context cr = Gdk.CairoHelper.Create (evnt.Window)) { cr.NewPath (); cr.MoveTo (rect.X, rect.Y); cr.RelLineTo (rect.Width, 0); cr.RelLineTo (0, rect.Height); cr.RelLineTo (-rect.Width, 0); cr.RelLineTo (0, -rect.Height); cr.ClosePath (); Cairo.Gradient pat = new Cairo.LinearGradient (rect.X, rect.Y, rect.X, rect.Y + rect.Height); Cairo.Color color1 = DockFrame.ToCairoColor (Style.Mid (Gtk.StateType.Normal)); pat.AddColorStop (0, color1); color1.R *= 1.2; color1.G *= 1.2; color1.B *= 1.2; pat.AddColorStop (1, color1); cr.Pattern = pat; cr.FillPreserve (); } } } else Gtk.Style.PaintExtension (Style, GdkWindow, st, ShadowType.Out, evnt.Area, this, "tab", rect.X, rect.Y, rect.Width, rect.Height, Gtk.PositionType.Top); } } class Tab: Gtk.EventBox { bool active; Gtk.Widget page; Gtk.Label labelWidget; int labelWidth; const int TopPadding = 2; const int BottomPadding = 4; const int TopPaddingActive = 3; const int BottomPaddingActive = 5; const int HorzPadding = 5; public Tab () { this.VisibleWindow = false; } public void SetLabel (Gtk.Widget page, Gdk.Pixbuf icon, string label) { Pango.EllipsizeMode oldMode = Pango.EllipsizeMode.End; this.page = page; if (Child != null) { if (labelWidget != null) oldMode = labelWidget.Ellipsize; Gtk.Widget oc = Child; Remove (oc); oc.Destroy (); } Gtk.HBox box = new HBox (); box.Spacing = 2; if (icon != null) box.PackStart (new Gtk.Image (icon), false, false, 0); if (!string.IsNullOrEmpty (label)) { labelWidget = new Gtk.Label (label); labelWidget.UseMarkup = true; box.PackStart (labelWidget, true, true, 0); } else { labelWidget = null; } Add (box); // Get the required size before setting the ellipsize property, since ellipsized labels // have a width request of 0 ShowAll (); labelWidth = SizeRequest ().Width; if (labelWidget != null) labelWidget.Ellipsize = oldMode; } public void SetEllipsize (bool elipsize) { if (labelWidget != null) { if (elipsize) labelWidget.Ellipsize = Pango.EllipsizeMode.End; else labelWidget.Ellipsize = Pango.EllipsizeMode.None; } } public int LabelWidth { get { return labelWidth; } } public bool Active { get { return active; } set { active = value; this.QueueResize (); QueueDraw (); } } public Widget Page { get { return page; } } protected override void OnSizeRequested (ref Gtk.Requisition req) { req = Child.SizeRequest (); req.Width += HorzPadding * 2; if (active) req.Height += TopPaddingActive + BottomPaddingActive; else req.Height += TopPadding + BottomPadding; } protected override void OnSizeAllocated (Gdk.Rectangle rect) { base.OnSizeAllocated (rect); rect.X += HorzPadding; rect.Width -= HorzPadding * 2; if (active) { rect.Y += TopPaddingActive; rect.Height = Child.SizeRequest ().Height; } else { rect.Y += TopPadding; rect.Height = Child.SizeRequest ().Height; } Child.SizeAllocate (rect); } } }
// 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.Reflection; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Collections.Tests { public static class QueueTests { [Fact] public static void Ctor_Empty() { const int DefaultCapactiy = 32; var queue = new Queue(); Assert.Equal(0, queue.Count); for (int i = 0; i <= DefaultCapactiy; i++) { queue.Enqueue(i); } Assert.Equal(DefaultCapactiy + 1, queue.Count); } [Theory] [InlineData(1)] [InlineData(32)] [InlineData(77)] public static void Ctor_Int(int capacity) { var queue = new Queue(capacity); for (int i = 0; i <= capacity; i++) { queue.Enqueue(i); } Assert.Equal(capacity + 1, queue.Count); } [Fact] public static void Ctor_Int_NegativeCapacity_ThrowsArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>("capacity", () => new Queue(-1)); // Capacity < 0 } [Theory] [InlineData(1, 2.0)] [InlineData(32, 1.0)] [InlineData(77, 5.0)] public static void Ctor_Int_Int(int capacity, float growFactor) { var queue = new Queue(capacity, growFactor); for (int i = 0; i <= capacity; i++) { queue.Enqueue(i); } Assert.Equal(capacity + 1, queue.Count); } [Fact] public static void Ctor_Int_Int_Invalid() { Assert.Throws<ArgumentOutOfRangeException>("capacity", () => new Queue(-1, 1)); // Capacity < 0 Assert.Throws<ArgumentOutOfRangeException>("growFactor", () => new Queue(1, (float)0.99)); // Grow factor < 1 Assert.Throws<ArgumentOutOfRangeException>("growFactor", () => new Queue(1, (float)10.01)); // Grow factor > 10 } [Fact] public static void Ctor_ICollection() { ArrayList arrList = Helpers.CreateIntArrayList(100); var queue = new Queue(arrList); Assert.Equal(arrList.Count, queue.Count); for (int i = 0; i < queue.Count; i++) { Assert.Equal(i, queue.Dequeue()); } } [Fact] public static void Ctor_ICollection_NullCollection_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("col", () => new Queue(null)); // Collection is null } [Fact] public static void DebuggerAttribute() { DebuggerAttributes.ValidateDebuggerDisplayReferences(new Queue()); var testQueue = new Queue(); testQueue.Enqueue("a"); testQueue.Enqueue(1); testQueue.Enqueue("b"); testQueue.Enqueue(2); DebuggerAttributes.ValidateDebuggerTypeProxyProperties(testQueue); bool threwNull = false; try { DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(Queue), null); } catch (TargetInvocationException ex) { threwNull = ex.InnerException is ArgumentNullException; } Assert.True(threwNull); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(32)] public static void Clear(int capacity) { var queue1 = new Queue(capacity); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { queue2.Enqueue(1); queue2.Clear(); Assert.Equal(0, queue2.Count); }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(32)] public static void Clear_Empty(int capacity) { var queue1 = new Queue(capacity); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { queue2.Clear(); Assert.Equal(0, queue2.Count); queue2.Clear(); Assert.Equal(0, queue2.Count); }); } [Fact] public static void Clone() { Queue queue1 = Helpers.CreateIntQueue(100); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { Queue clone = (Queue)queue2.Clone(); Assert.Equal(queue2.IsSynchronized, clone.IsSynchronized); Assert.Equal(queue2.Count, clone.Count); for (int i = 0; i < queue2.Count; i++) { Assert.True(clone.Contains(i)); } }); } [Fact] public static void Clone_IsShallowCopy() { var queue1 = new Queue(); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { queue2.Enqueue(new Foo(10)); Queue clone = (Queue)queue2.Clone(); var foo = (Foo)queue2.Dequeue(); foo.IntValue = 50; var fooClone = (Foo)clone.Dequeue(); Assert.Equal(50, fooClone.IntValue); }); } [Fact] public static void Clone_Empty() { var queue1 = new Queue(); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { Queue clone = (Queue)queue2.Clone(); Assert.Equal(0, clone.Count); // Can change the clone queue clone.Enqueue(500); Assert.Equal(500, clone.Dequeue()); }); } [Fact] public static void Clone_Clear() { Queue queue1 = Helpers.CreateIntQueue(100); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { queue2.Clear(); Queue clone = (Queue)queue2.Clone(); Assert.Equal(0, clone.Count); // Can change clone queue clone.Enqueue(500); Assert.Equal(500, clone.Dequeue()); }); } [Fact] public static void Clone_DequeueUntilEmpty() { Queue queue1 = Helpers.CreateIntQueue(100); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { for (int i = 0; i < 100; i++) { queue2.Dequeue(); } Queue clone = (Queue)queue2.Clone(); Assert.Equal(0, queue2.Count); // Can change clone the queue clone.Enqueue(500); Assert.Equal(500, clone.Dequeue()); }); } [Fact] public static void Clone_DequeueThenEnqueue() { var queue1 = new Queue(100); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { // Insert 50 items in the Queue for (int i = 0; i < 50; i++) { queue2.Enqueue(i); } // Insert and Remove 75 items in the Queue. This should wrap the queue // where there is 25 at the end of the array and 25 at the beginning for (int i = 0; i < 75; i++) { queue2.Enqueue(i + 50); queue2.Dequeue(); } Queue queClone = (Queue)queue2.Clone(); Assert.Equal(50, queClone.Count); Assert.Equal(75, queClone.Dequeue()); // Add an item to the Queue queClone.Enqueue(100); Assert.Equal(50, queClone.Count); Assert.Equal(76, queClone.Dequeue()); }); } [Fact] public static void Contains() { Queue queue1 = Helpers.CreateIntQueue(100); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { for (int i = 0; i < queue2.Count; i++) { Assert.True(queue2.Contains(i)); } queue2.Enqueue(null); Assert.True(queue2.Contains(null)); }); } [Fact] public static void Contains_NonExistentObject() { Queue queue1 = Helpers.CreateIntQueue(100); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { Assert.False(queue2.Contains(101)); Assert.False(queue2.Contains("hello world")); Assert.False(queue2.Contains(null)); queue2.Enqueue(null); Assert.False(queue2.Contains(-1)); // We have a null item in the list, so the algorithm may use a different branch }); } [Fact] public static void Contains_EmptyQueue() { var queue1 = new Queue(); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { Assert.False(queue2.Contains(101)); Assert.False(queue2.Contains("hello world")); Assert.False(queue2.Contains(null)); }); } [Theory] [InlineData(0, 0)] [InlineData(1, 0)] [InlineData(10, 0)] [InlineData(100, 0)] [InlineData(1000, 0)] [InlineData(1, 50)] [InlineData(10, 50)] [InlineData(100, 50)] [InlineData(1000, 50)] public static void CopyTo(int count, int index) { Queue queue1 = Helpers.CreateIntQueue(count); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { var array = new object[count + index]; queue2.CopyTo(array, index); Assert.Equal(count + index, array.Length); for (int i = index; i < index + count; i++) { Assert.Equal(queue2.Dequeue(), array[i]); } }); } [Fact] public static void CopyTo_DequeueThenEnqueue() { var queue1 = new Queue(100); // Insert 50 items in the Queue for (int i = 0; i < 50; i++) { queue1.Enqueue(i); } // Insert and Remove 75 items in the Queue. This should wrap the queue // where there is 25 at the end of the array and 25 at the beginning for (int i = 0; i < 75; i++) { queue1.Enqueue(i + 50); queue1.Dequeue(); } var array = new object[queue1.Count]; queue1.CopyTo(array, 0); Assert.Equal(queue1.Count, array.Length); for (int i = 0; i < queue1.Count; i++) { Assert.Equal(queue1.Dequeue(), array[i]); } } [Fact] public static void CopyTo_Invalid() { Queue queue1 = Helpers.CreateIntQueue(100); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { Assert.Throws<ArgumentNullException>("array", () => queue2.CopyTo(null, 0)); // Array is null Assert.Throws<ArgumentException>(() => queue2.CopyTo(new object[150, 150], 0)); // Array is multidimensional Assert.Throws<ArgumentOutOfRangeException>("index", () => queue2.CopyTo(new object[150], -1)); // Index < 0 Assert.Throws<ArgumentException>(null, () => queue2.CopyTo(new object[150], 51)); // Index + queue.Count > array.Length }); } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(100)] [InlineData(1000)] public static void Dequeue(int count) { Queue queue1 = Helpers.CreateIntQueue(count); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { for (int i = 1; i <= count; i++) { int obj = (int)queue2.Dequeue(); Assert.Equal(i - 1, obj); Assert.Equal(count - i, queue2.Count); } }); } [Fact] public static void Dequeue_EmptyQueue_ThrowsInvalidOperationException() { var queue1 = new Queue(); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { Assert.Throws<InvalidOperationException>(() => queue2.Dequeue()); // Queue is empty }); } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(100)] [InlineData(1000)] public static void Dequeue_UntilEmpty(int count) { Queue queue1 = Helpers.CreateIntQueue(count); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { for (int i = 0; i < count; i++) { queue2.Dequeue(); } Assert.Throws<InvalidOperationException>(() => queue2.Dequeue()); }); } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(100)] [InlineData(10000)] public static void Enqueue(int count) { var queue1 = new Queue(); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { for (int i = 1; i <= count; i++) { queue2.Enqueue(i); Assert.Equal(i, queue2.Count); } Assert.Equal(count, queue2.Count); }); } [Fact] public static void Enqueue_Null() { var queue1 = new Queue(); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { queue2.Enqueue(null); Assert.Equal(1, queue2.Count); }); } [Theory] [InlineData(0)] [InlineData(10)] [InlineData(100)] [InlineData(1000)] public static void GetEnumerator(int count) { var queue1 = Helpers.CreateIntQueue(count); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { Assert.NotSame(queue2.GetEnumerator(), queue2.GetEnumerator()); IEnumerator enumerator = queue2.GetEnumerator(); for (int i = 0; i < 2; i++) { int counter = 0; while (enumerator.MoveNext()) { Assert.Equal(counter, enumerator.Current); counter++; } Assert.Equal(count, counter); enumerator.Reset(); } }); } [Fact] public static void GetEnumerator_Invalid() { var queue1 = Helpers.CreateIntQueue(100); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { IEnumerator enumerator = queue2.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // If the underlying collection is modified, MoveNext and Reset throw, but Current doesn't enumerator.MoveNext(); object dequeued = queue2.Dequeue(); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); Assert.Equal(dequeued, enumerator.Current); // Current throws if the current index is < 0 or >= count enumerator = queue2.GetEnumerator(); while (enumerator.MoveNext()) ; Assert.False(enumerator.MoveNext()); Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Current throws after resetting enumerator = queue2.GetEnumerator(); Assert.True(enumerator.MoveNext()); Assert.True(enumerator.MoveNext()); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); }); } [Fact] public static void Peek() { string s1 = "hello"; string s2 = "world"; char c = '\0'; bool b = false; byte i8 = 0; short i16 = 0; int i32 = 0; long i64 = 0L; float f = (float)0.0; double d = 0.0; var queue1 = new Queue(); queue1.Enqueue(s1); queue1.Enqueue(s2); queue1.Enqueue(c); queue1.Enqueue(b); queue1.Enqueue(i8); queue1.Enqueue(i16); queue1.Enqueue(i32); queue1.Enqueue(i64); queue1.Enqueue(f); queue1.Enqueue(d); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { Assert.Same(s1, queue2.Peek()); queue2.Dequeue(); Assert.Same(s2, queue2.Peek()); queue2.Dequeue(); Assert.Equal(c, queue2.Peek()); queue2.Dequeue(); Assert.Equal(b, queue2.Peek()); queue2.Dequeue(); Assert.Equal(i8, queue2.Peek()); queue2.Dequeue(); Assert.Equal(i16, queue2.Peek()); queue2.Dequeue(); Assert.Equal(i32, queue2.Peek()); queue2.Dequeue(); Assert.Equal(i64, queue2.Peek()); queue2.Dequeue(); Assert.Equal(f, queue2.Peek()); queue2.Dequeue(); Assert.Equal(d, queue2.Peek()); queue2.Dequeue(); }); } [Fact] public static void Peek_EmptyQueue_ThrowsInvalidOperationException() { var queue1 = new Queue(); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { Assert.Throws<InvalidOperationException>(() => queue2.Peek()); // Queue is empty }); } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(100)] [InlineData(1000)] public static void ToArray(int count) { Queue queue1 = Helpers.CreateIntQueue(count); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { object[] arr = queue2.ToArray(); Assert.Equal(count, arr.Length); for (int i = 0; i < count; i++) { Assert.Equal(queue2.Dequeue(), arr[i]); } }); } [Fact] public static void ToArray_Wrapped() { var queue1 = new Queue(1); queue1.Enqueue(1); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { object[] arr = queue2.ToArray(); Assert.Equal(1, arr.Length); Assert.Equal(1, arr[0]); }); } [Fact] public static void ToArrayDiffentObjectTypes() { string s1 = "hello"; string s2 = "world"; char c = '\0'; bool b = false; byte i8 = 0; short i16 = 0; int i32 = 0; long i64 = 0L; float f = (float)0.0; double d = 0.0; var queue1 = new Queue(); queue1.Enqueue(s1); queue1.Enqueue(s2); queue1.Enqueue(c); queue1.Enqueue(b); queue1.Enqueue(i8); queue1.Enqueue(i16); queue1.Enqueue(i32); queue1.Enqueue(i64); queue1.Enqueue(f); queue1.Enqueue(d); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { object[] arr = queue2.ToArray(); Assert.Same(s1, arr[0]); Assert.Same(s2, arr[1]); Assert.Equal(c, arr[2]); Assert.Equal(b, arr[3]); Assert.Equal(i8, arr[4]); Assert.Equal(i16, arr[5]); Assert.Equal(i32, arr[6]); Assert.Equal(i64, arr[7]); Assert.Equal(f, arr[8]); Assert.Equal(d, arr[9]); }); } [Fact] public static void ToArray_EmptyQueue() { var queue1 = new Queue(); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { object[] arr = queue2.ToArray(); Assert.Equal(0, arr.Length); }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] [InlineData(1000)] public static void TrimToSize(int count) { Queue queue1 = Helpers.CreateIntQueue(count); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { queue2.TrimToSize(); Assert.Equal(count, queue2.Count); // Can change the queue after trimming queue2.Enqueue(100); Assert.Equal(count + 1, queue2.Count); if (count == 0) { Assert.Equal(100, queue2.Dequeue()); } else { Assert.Equal(0, queue2.Dequeue()); } }); } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(100)] [InlineData(1000)] public static void TrimToSize_DequeueAll(int count) { Queue queue1 = Helpers.CreateIntQueue(count); for (int i = 0; i < count; i++) { queue1.Dequeue(); } Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { queue2.TrimToSize(); Assert.Equal(0, queue2.Count); // Can change the queue after trimming queue2.Enqueue(1); Assert.Equal(1, queue2.Dequeue()); }); } [Fact] public static void TrimToSize_Wrapped() { var queue = new Queue(100); // Insert 50 items in the Queue for (int i = 0; i < 50; i++) { queue.Enqueue(i); } // Insert and Remove 75 items in the Queue. This should wrap the queue // where there is 25 at the end of the array and 25 at the beginning for (int i = 0; i < 75; i++) { queue.Enqueue(i + 50); queue.Dequeue(); } queue.TrimToSize(); Assert.Equal(50, queue.Count); Assert.Equal(75, queue.Dequeue()); queue.Enqueue(100); Assert.Equal(50, queue.Count); Assert.Equal(76, queue.Dequeue()); } private class Foo { public Foo(int intValue) { IntValue = intValue; } public int IntValue { get; set; } } } public class Queue_SyncRootTests { private const int NumberOfElements = 1000; private const int NumberOfWorkers = 1000; private Queue _queueDaughter; private Queue _queueGrandDaughter; [Fact] public void SyncRoot() { var queueMother = new Queue(); for (int i = 0; i < NumberOfElements; i++) { queueMother.Enqueue(i); } Assert.Equal(queueMother.SyncRoot.GetType(), typeof(object)); var queueSon = Queue.Synchronized(queueMother); _queueGrandDaughter = Queue.Synchronized(queueSon); _queueDaughter = Queue.Synchronized(queueMother); Assert.Equal(queueMother.SyncRoot, queueSon.SyncRoot); Assert.Equal(queueSon.SyncRoot, queueMother.SyncRoot); Assert.Equal(queueMother.SyncRoot, _queueGrandDaughter.SyncRoot); Assert.Equal(queueMother.SyncRoot, _queueDaughter.SyncRoot); Task[] workers = new Task[NumberOfWorkers]; Action action1 = SortElements; Action action2 = ReverseElements; for (int i = 0; i < NumberOfWorkers; i += 2) { workers[i] = Task.Run(action1); workers[i + 1] = Task.Run(action2); } Task.WaitAll(workers); } private void SortElements() { _queueGrandDaughter.Clear(); for (int i = 0; i < NumberOfElements; i++) { _queueGrandDaughter.Enqueue(i); } } private void ReverseElements() { _queueDaughter.Clear(); for (int i = 0; i < NumberOfElements; i++) { _queueDaughter.Enqueue(i); } } } public class Queue_SynchronizedTests { public Queue _queue; public int _threadsToUse = 8; public int _threadAge = 5; // 5000; public int _threadCount; [Fact] public static void Synchronized() { Queue queue = Helpers.CreateIntQueue(100); Queue syncQueue = Queue.Synchronized(queue); Assert.True(syncQueue.IsSynchronized); Assert.Equal(queue.Count, syncQueue.Count); for (int i = 0; i < queue.Count; i++) { Assert.True(syncQueue.Contains(i)); } } [Fact] public void SynchronizedEnqueue() { // Enqueue _queue = Queue.Synchronized(new Queue()); PerformTest(StartEnqueueThread, 40); // Dequeue Queue queue = Helpers.CreateIntQueue(_threadAge); _queue = Queue.Synchronized(queue); PerformTest(StartDequeueThread, 0); // Enqueue, dequeue _queue = Queue.Synchronized(new Queue()); PerformTest(StartEnqueueDequeueThread, 0); // Dequeue, enqueue queue = Helpers.CreateIntQueue(_threadAge); _queue = Queue.Synchronized(queue); PerformTest(StartDequeueEnqueueThread, _threadAge); } private void PerformTest(Action action, int expected) { var tasks = new Task[_threadsToUse]; for (int i = 0; i < _threadsToUse; i++) { tasks[i] = Task.Factory.StartNew(action, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); } _threadCount = _threadsToUse; Task.WaitAll(tasks); Assert.Equal(expected, _queue.Count); } [Fact] public static void Synchronized_NullQueue_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("queue", () => Queue.Synchronized(null)); // Queue is null } public void StartEnqueueThread() { int t_age = _threadAge; while (t_age > 0) { _queue.Enqueue(t_age); Interlocked.Decrement(ref t_age); } Interlocked.Decrement(ref _threadCount); } private void StartDequeueThread() { int t_age = _threadAge; while (t_age > 0) { try { _queue.Dequeue(); } catch { } Interlocked.Decrement(ref t_age); } Interlocked.Decrement(ref _threadCount); } private void StartEnqueueDequeueThread() { int t_age = _threadAge; while (t_age > 0) { _queue.Enqueue(2); _queue.Dequeue(); Interlocked.Decrement(ref t_age); } Interlocked.Decrement(ref _threadCount); } private void StartDequeueEnqueueThread() { int t_age = _threadAge; while (t_age > 0) { _queue.Dequeue(); _queue.Enqueue(2); Interlocked.Decrement(ref t_age); } Interlocked.Decrement(ref _threadCount); } } }
/* ** $Id: lopcodes.c,v 1.37.1.1 2007/12/27 13:02:25 roberto Exp $ ** See Copyright Notice in lua.h */ using System; using System.Collections.Generic; using System.Text; namespace SharpLua { using lu_byte = System.Byte; using Instruction = System.UInt32; public partial class Lua { /*=========================================================================== We assume that instructions are unsigned numbers. All instructions have an opcode in the first 6 bits. Instructions can have the following fields: `A' : 8 bits `B' : 9 bits `C' : 9 bits `Bx' : 18 bits (`B' and `C' together) `sBx' : signed Bx A signed argument is represented in excess K; that is, the number value is the unsigned value minus K. K is exactly the maximum value for that argument (so that -max is represented by 0, and +max is represented by 2*max), which is half the maximum for the corresponding unsigned argument. ===========================================================================*/ public enum OpMode { iABC, iABx, iAsBx }; /* basic instruction format */ /* ** size and position of opcode arguments. */ public const int SIZE_C = 9; public const int SIZE_B = 9; public const int SIZE_Bx = (SIZE_C + SIZE_B); public const int SIZE_A = 8; public const int SIZE_OP = 6; public const int POS_OP = 0; public const int POS_A = (POS_OP + SIZE_OP); public const int POS_C = (POS_A + SIZE_A); public const int POS_B = (POS_C + SIZE_C); public const int POS_Bx = POS_C; /* ** limits for opcode arguments. ** we use (signed) int to manipulate most arguments, ** so they must fit in LUAI_BITSINT-1 bits (-1 for sign) */ //#if SIZE_Bx < LUAI_BITSINT-1 public const int MAXARG_Bx = ((1 << SIZE_Bx) - 1); public const int MAXARG_sBx = (MAXARG_Bx >> 1); /* `sBx' is signed */ //#else //public const int MAXARG_Bx = System.Int32.MaxValue; //public const int MAXARG_sBx = System.Int32.MaxValue; //#endif public const uint MAXARG_A = (uint)((1 << (int)SIZE_A) - 1); public const uint MAXARG_B = (uint)((1 << (int)SIZE_B) - 1); public const uint MAXARG_C = (uint)((1 << (int)SIZE_C) - 1); /* creates a mask with `n' 1 bits at position `p' */ //public static int MASK1(int n, int p) { return ((~((~(Instruction)0) << n)) << p); } public static uint MASK1(int n, int p) { return (uint)((~((~0) << n)) << p); } /* creates a mask with `n' 0 bits at position `p' */ public static uint MASK0(int n, int p) { return (uint)(~MASK1(n, p)); } /* ** the following macros help to manipulate instructions */ public static OpCode GET_OPCODE(Instruction i) { return (OpCode)((i >> POS_OP) & MASK1(SIZE_OP, 0)); } public static OpCode GET_OPCODE(InstructionPtr i) { return GET_OPCODE(i[0]); } public static void SET_OPCODE(ref Instruction i, Instruction o) { i = (Instruction)(i & MASK0(SIZE_OP, POS_OP)) | ((o << POS_OP) & MASK1(SIZE_OP, POS_OP)); } public static void SET_OPCODE(ref Instruction i, OpCode opcode) { i = (Instruction)(i & MASK0(SIZE_OP, POS_OP)) | (((uint)opcode << POS_OP) & MASK1(SIZE_OP, POS_OP)); } public static void SET_OPCODE(InstructionPtr i, OpCode opcode) { SET_OPCODE(ref i.codes[i.pc], opcode); } public static int GETARG_A(Instruction i) { return (int)((i >> POS_A) & MASK1(SIZE_A, 0)); } public static int GETARG_A(InstructionPtr i) { return GETARG_A(i[0]); } public static void SETARG_A(InstructionPtr i, int u) { i[0] = (Instruction)((i[0] & MASK0(SIZE_A, POS_A)) | ((u << POS_A) & MASK1(SIZE_A, POS_A))); } public static int GETARG_B(Instruction i) { return (int)((i >> POS_B) & MASK1(SIZE_B, 0)); } public static int GETARG_B(InstructionPtr i) { return GETARG_B(i[0]); } public static void SETARG_B(InstructionPtr i, int b) { i[0] = (Instruction)((i[0] & MASK0(SIZE_B, POS_B)) | ((b << POS_B) & MASK1(SIZE_B, POS_B))); } public static int GETARG_C(Instruction i) { return (int)((i >> POS_C) & MASK1(SIZE_C, 0)); } public static int GETARG_C(InstructionPtr i) { return GETARG_C(i[0]); } public static void SETARG_C(InstructionPtr i, int b) { i[0] = (Instruction)((i[0] & MASK0(SIZE_C, POS_C)) | ((b << POS_C) & MASK1(SIZE_C, POS_C))); } public static int GETARG_Bx(Instruction i) { return (int)((i >> POS_Bx) & MASK1(SIZE_Bx, 0)); } public static int GETARG_Bx(InstructionPtr i) { return GETARG_Bx(i[0]); } public static void SETARG_Bx(InstructionPtr i, int b) { i[0] = (Instruction)((i[0] & MASK0(SIZE_Bx, POS_Bx)) | ((b << POS_Bx) & MASK1(SIZE_Bx, POS_Bx))); } public static int GETARG_sBx(Instruction i) { return (GETARG_Bx(i) - MAXARG_sBx); } public static int GETARG_sBx(InstructionPtr i) { return GETARG_sBx(i[0]); } public static void SETARG_sBx(InstructionPtr i, int b) { SETARG_Bx(i, b + MAXARG_sBx); } public static int CREATE_ABC(OpCode o, int a, int b, int c) { return (int)(((int)o << POS_OP) | (a << POS_A) | (b << POS_B) | (c << POS_C)); } public static int CREATE_ABx(OpCode o, int a, int bc) { int result = (int)(((int)o << POS_OP) | (a << POS_A) | (bc << POS_Bx)); return (int)(((int)o << POS_OP) | (a << POS_A) | (bc << POS_Bx)); } /* ** Macros to operate RK indices */ /* this bit 1 means constant (0 means register) */ public readonly static int BITRK = (1 << (SIZE_B - 1)); /* test whether value is a constant */ public static int ISK(int x) { return x & BITRK; } /* gets the index of the constant */ public static int INDEXK(int r) { return r & (~BITRK); } public static readonly int MAXINDEXRK = BITRK - 1; /* code a constant index as a RK value */ public static int RKASK(int x) { return x | BITRK; } /* ** invalid register that fits in 8 bits */ internal static readonly int NO_REG = (int)MAXARG_A; /* ** R(x) - register ** Kst(x) - constant (in constant table) ** RK(x) == if ISK(x) then Kst(INDEXK(x)) else R(x) */ /* ** grep "ORDER OP" if you change these enums */ public enum OpCode { /*---------------------------------------------------------------------- name args description ------------------------------------------------------------------------*/ OP_MOVE,/* A B R(A) := R(B) */ OP_LOADK,/* A Bx R(A) := Kst(Bx) */ OP_LOADBOOL,/* A B C R(A) := (Bool)B; if (C) pc++ */ OP_LOADNIL,/* A B R(A) := ... := R(B) := nil */ OP_GETUPVAL,/* A B R(A) := UpValue[B] */ OP_GETGLOBAL,/* A Bx R(A) := Gbl[Kst(Bx)] */ OP_GETTABLE,/* A B C R(A) := R(B)[RK(C)] */ OP_SETGLOBAL,/* A Bx Gbl[Kst(Bx)] := R(A) */ OP_SETUPVAL,/* A B UpValue[B] := R(A) */ OP_SETTABLE,/* A B C R(A)[RK(B)] := RK(C) */ OP_NEWTABLE,/* A B C R(A) := {} (size = B,C) */ OP_SELF,/* A B C R(A+1) := R(B); R(A) := R(B)[RK(C)] */ OP_ADD,/* A B C R(A) := RK(B) + RK(C) */ OP_SUB,/* A B C R(A) := RK(B) - RK(C) */ OP_MUL,/* A B C R(A) := RK(B) * RK(C) */ OP_DIV,/* A B C R(A) := RK(B) / RK(C) */ OP_MOD,/* A B C R(A) := RK(B) % RK(C) */ OP_POW,/* A B C R(A) := RK(B) ^ RK(C) */ OP_UNM,/* A B R(A) := -R(B) */ OP_NOT,/* A B R(A) := not R(B) */ OP_LEN,/* A B R(A) := length of R(B) */ OP_CONCAT,/* A B C R(A) := R(B).. ... ..R(C) */ OP_JMP,/* sBx pc+=sBx */ OP_EQ,/* A B C if ((RK(B) == RK(C)) ~= A) then pc++ */ OP_LT,/* A B C if ((RK(B) < RK(C)) ~= A) then pc++ */ OP_LE,/* A B C if ((RK(B) <= RK(C)) ~= A) then pc++ */ OP_TEST,/* A C if not (R(A) <=> C) then pc++ */ OP_TESTSET,/* A B C if (R(B) <=> C) then R(A) := R(B) else pc++ */ OP_CALL,/* A B C R(A), ... ,R(A+C-2) := R(A)(R(A+1), ... ,R(A+B-1)) */ OP_TAILCALL,/* A B C return R(A)(R(A+1), ... ,R(A+B-1)) */ OP_RETURN,/* A B return R(A), ... ,R(A+B-2) (see note) */ OP_FORLOOP,/* A sBx R(A)+=R(A+2); if R(A) <?= R(A+1) then { pc+=sBx; R(A+3)=R(A) }*/ OP_FORPREP,/* A sBx R(A)-=R(A+2); pc+=sBx */ OP_TFORLOOP,/* A C R(A+3), ... ,R(A+2+C) := R(A)(R(A+1), R(A+2)); if R(A+3) ~= nil then R(A+2)=R(A+3) else pc++ */ OP_SETLIST,/* A B C R(A)[(C-1)*FPF+i] := R(A+i), 1 <= i <= B */ OP_CLOSE,/* A close all variables in the stack up to (>=) R(A)*/ OP_CLOSURE,/* A Bx R(A) := closure(KPROTO[Bx], R(A), ... ,R(A+n)) */ OP_VARARG/* A B R(A), R(A+1), ..., R(A+B-1) = vararg */ , OP_BREAKPOINT, }; public const int NUM_OPCODES = (int)OpCode.OP_BREAKPOINT; /*=========================================================================== Notes: (*) In OP_CALL, if (B == 0) then B = top. C is the number of returns - 1, and can be 0: OP_CALL then sets `top' to last_result+1, so next open instruction (OP_CALL, OP_RETURN, OP_SETLIST) may use `top'. (*) In OP_VARARG, if (B == 0) then use actual number of varargs and set top (like in OP_CALL with C == 0). (*) In OP_RETURN, if (B == 0) then return up to `top' (*) In OP_SETLIST, if (B == 0) then B = `top'; if (C == 0) then next `instruction' is real C (*) For comparisons, A specifies what condition the test should accept (true or false). (*) All `skips' (pc++) assume that next instruction is a jump ===========================================================================*/ /* ** masks for instruction properties. The format is: ** bits 0-1: op mode ** bits 2-3: C arg mode ** bits 4-5: B arg mode ** bit 6: instruction set register A ** bit 7: operator is a test */ public enum OpArgMask { OpArgN, /* argument is not used */ OpArgU, /* argument is used */ OpArgR, /* argument is a register or a jump offset */ OpArgK /* argument is a constant or register/constant */ }; public static OpMode getOpMode(OpCode m) { return (OpMode)(luaP_opmodes[(int)m] & 3); } public static OpArgMask getBMode(OpCode m) { return (OpArgMask)((luaP_opmodes[(int)m] >> 4) & 3); } public static OpArgMask getCMode(OpCode m) { return (OpArgMask)((luaP_opmodes[(int)m] >> 2) & 3); } public static int testAMode(OpCode m) { return luaP_opmodes[(int)m] & (1 << 6); } public static int testTMode(OpCode m) { return luaP_opmodes[(int)m] & (1 << 7); } /* number of list items to accumulate before a SETLIST instruction */ public const int LFIELDS_PER_FLUSH = 50; /* ORDER OP */ public readonly static CharPtr[] luaP_opnames = { "MOVE", "LOADK", "LOADBOOL", "LOADNIL", "GETUPVAL", "GETGLOBAL", "GETTABLE", "SETGLOBAL", "SETUPVAL", "SETTABLE", "NEWTABLE", "SELF", "ADD", "SUB", "MUL", "DIV", "MOD", "POW", "UNM", "NOT", "LEN", "CONCAT", "JMP", "EQ", "LT", "LE", "TEST", "TESTSET", "CALL", "TAILCALL", "RETURN", "FORLOOP", "FORPREP", "TFORLOOP", "SETLIST", "CLOSE", "CLOSURE", "VARARG", "BREAKPOINT", }; private static lu_byte opmode(lu_byte t, lu_byte a, OpArgMask b, OpArgMask c, OpMode m) { return (lu_byte)(((t) << 7) | ((a) << 6) | (((lu_byte)b) << 4) | (((lu_byte)c) << 2) | ((lu_byte)m)); } public readonly static lu_byte[] luaP_opmodes = { /* T A B C mode opcode */ opmode(0, 1, OpArgMask.OpArgR, OpArgMask.OpArgN, OpMode.iABC) /* OP_MOVE */ ,opmode(0, 1, OpArgMask.OpArgK, OpArgMask.OpArgN, OpMode.iABx) /* OP_LOADK */ ,opmode(0, 1, OpArgMask.OpArgU, OpArgMask.OpArgU, OpMode.iABC) /* OP_LOADBOOL */ ,opmode(0, 1, OpArgMask.OpArgR, OpArgMask.OpArgN, OpMode.iABC) /* OP_LOADNIL */ ,opmode(0, 1, OpArgMask.OpArgU, OpArgMask.OpArgN, OpMode.iABC) /* OP_GETUPVAL */ ,opmode(0, 1, OpArgMask.OpArgK, OpArgMask.OpArgN, OpMode.iABx) /* OP_GETGLOBAL */ ,opmode(0, 1, OpArgMask.OpArgR, OpArgMask.OpArgK, OpMode.iABC) /* OP_GETTABLE */ ,opmode(0, 0, OpArgMask.OpArgK, OpArgMask.OpArgN, OpMode.iABx) /* OP_SETGLOBAL */ ,opmode(0, 0, OpArgMask.OpArgU, OpArgMask.OpArgN, OpMode.iABC) /* OP_SETUPVAL */ ,opmode(0, 0, OpArgMask.OpArgK, OpArgMask.OpArgK, OpMode.iABC) /* OP_SETTABLE */ ,opmode(0, 1, OpArgMask.OpArgU, OpArgMask.OpArgU, OpMode.iABC) /* OP_NEWTABLE */ ,opmode(0, 1, OpArgMask.OpArgR, OpArgMask.OpArgK, OpMode.iABC) /* OP_SELF */ ,opmode(0, 1, OpArgMask.OpArgK, OpArgMask.OpArgK, OpMode.iABC) /* OP_ADD */ ,opmode(0, 1, OpArgMask.OpArgK, OpArgMask.OpArgK, OpMode.iABC) /* OP_SUB */ ,opmode(0, 1, OpArgMask.OpArgK, OpArgMask.OpArgK, OpMode.iABC) /* OP_MUL */ ,opmode(0, 1, OpArgMask.OpArgK, OpArgMask.OpArgK, OpMode.iABC) /* OP_DIV */ ,opmode(0, 1, OpArgMask.OpArgK, OpArgMask.OpArgK, OpMode.iABC) /* OP_MOD */ ,opmode(0, 1, OpArgMask.OpArgK, OpArgMask.OpArgK, OpMode.iABC) /* OP_POW */ ,opmode(0, 1, OpArgMask.OpArgR, OpArgMask.OpArgN, OpMode.iABC) /* OP_UNM */ ,opmode(0, 1, OpArgMask.OpArgR, OpArgMask.OpArgN, OpMode.iABC) /* OP_NOT */ ,opmode(0, 1, OpArgMask.OpArgR, OpArgMask.OpArgN, OpMode.iABC) /* OP_LEN */ ,opmode(0, 1, OpArgMask.OpArgR, OpArgMask.OpArgR, OpMode.iABC) /* OP_CONCAT */ ,opmode(0, 0, OpArgMask.OpArgR, OpArgMask.OpArgN, OpMode.iAsBx) /* OP_JMP */ ,opmode(1, 0, OpArgMask.OpArgK, OpArgMask.OpArgK, OpMode.iABC) /* OP_EQ */ ,opmode(1, 0, OpArgMask.OpArgK, OpArgMask.OpArgK, OpMode.iABC) /* OP_LT */ ,opmode(1, 0, OpArgMask.OpArgK, OpArgMask.OpArgK, OpMode.iABC) /* OP_LE */ ,opmode(1, 1, OpArgMask.OpArgR, OpArgMask.OpArgU, OpMode.iABC) /* OP_TEST */ ,opmode(1, 1, OpArgMask.OpArgR, OpArgMask.OpArgU, OpMode.iABC) /* OP_TESTSET */ ,opmode(0, 1, OpArgMask.OpArgU, OpArgMask.OpArgU, OpMode.iABC) /* OP_CALL */ ,opmode(0, 1, OpArgMask.OpArgU, OpArgMask.OpArgU, OpMode.iABC) /* OP_TAILCALL */ ,opmode(0, 0, OpArgMask.OpArgU, OpArgMask.OpArgN, OpMode.iABC) /* OP_RETURN */ ,opmode(0, 1, OpArgMask.OpArgR, OpArgMask.OpArgN, OpMode.iAsBx) /* OP_FORLOOP */ ,opmode(0, 1, OpArgMask.OpArgR, OpArgMask.OpArgN, OpMode.iAsBx) /* OP_FORPREP */ ,opmode(1, 0, OpArgMask.OpArgN, OpArgMask.OpArgU, OpMode.iABC) /* OP_TFORLOOP */ ,opmode(0, 0, OpArgMask.OpArgU, OpArgMask.OpArgU, OpMode.iABC) /* OP_SETLIST */ ,opmode(0, 0, OpArgMask.OpArgN, OpArgMask.OpArgN, OpMode.iABC) /* OP_CLOSE */ ,opmode(0, 1, OpArgMask.OpArgU, OpArgMask.OpArgN, OpMode.iABx) /* OP_CLOSURE */ ,opmode(0, 1, OpArgMask.OpArgU, OpArgMask.OpArgN, OpMode.iABC) /* OP_VARARG */ ,opmode(0, 0, OpArgMask.OpArgN, OpArgMask.OpArgN, OpMode.iABC) /* OP_BREAKPOINT */ }; } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace SAEON.Observations.Data{ /// <summary> /// Strongly-typed collection for the VDataSource class. /// </summary> [Serializable] public partial class VDataSourceCollection : ReadOnlyList<VDataSource, VDataSourceCollection> { public VDataSourceCollection() {} } /// <summary> /// This is Read-only wrapper class for the vDataSource view. /// </summary> [Serializable] public partial class VDataSource : ReadOnlyRecord<VDataSource>, IReadOnlyRecord { #region Default Settings protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema Accessor 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("vDataSource", TableType.View, DataService.GetInstance("ObservationsDB")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema); colvarId.ColumnName = "ID"; colvarId.DataType = DbType.Guid; colvarId.MaxLength = 0; colvarId.AutoIncrement = false; colvarId.IsNullable = false; colvarId.IsPrimaryKey = false; colvarId.IsForeignKey = false; colvarId.IsReadOnly = false; schema.Columns.Add(colvarId); TableSchema.TableColumn colvarCode = new TableSchema.TableColumn(schema); colvarCode.ColumnName = "Code"; colvarCode.DataType = DbType.AnsiString; colvarCode.MaxLength = 50; colvarCode.AutoIncrement = false; colvarCode.IsNullable = false; colvarCode.IsPrimaryKey = false; colvarCode.IsForeignKey = false; colvarCode.IsReadOnly = false; schema.Columns.Add(colvarCode); TableSchema.TableColumn colvarName = new TableSchema.TableColumn(schema); colvarName.ColumnName = "Name"; colvarName.DataType = DbType.AnsiString; colvarName.MaxLength = 150; colvarName.AutoIncrement = false; colvarName.IsNullable = false; colvarName.IsPrimaryKey = false; colvarName.IsForeignKey = false; colvarName.IsReadOnly = false; schema.Columns.Add(colvarName); TableSchema.TableColumn colvarDescription = new TableSchema.TableColumn(schema); colvarDescription.ColumnName = "Description"; colvarDescription.DataType = DbType.AnsiString; colvarDescription.MaxLength = 5000; colvarDescription.AutoIncrement = false; colvarDescription.IsNullable = true; colvarDescription.IsPrimaryKey = false; colvarDescription.IsForeignKey = false; colvarDescription.IsReadOnly = false; schema.Columns.Add(colvarDescription); TableSchema.TableColumn colvarUrl = new TableSchema.TableColumn(schema); colvarUrl.ColumnName = "Url"; colvarUrl.DataType = DbType.AnsiString; colvarUrl.MaxLength = 250; colvarUrl.AutoIncrement = false; colvarUrl.IsNullable = true; colvarUrl.IsPrimaryKey = false; colvarUrl.IsForeignKey = false; colvarUrl.IsReadOnly = false; schema.Columns.Add(colvarUrl); TableSchema.TableColumn colvarDefaultNullValue = new TableSchema.TableColumn(schema); colvarDefaultNullValue.ColumnName = "DefaultNullValue"; colvarDefaultNullValue.DataType = DbType.Double; colvarDefaultNullValue.MaxLength = 0; colvarDefaultNullValue.AutoIncrement = false; colvarDefaultNullValue.IsNullable = true; colvarDefaultNullValue.IsPrimaryKey = false; colvarDefaultNullValue.IsForeignKey = false; colvarDefaultNullValue.IsReadOnly = false; schema.Columns.Add(colvarDefaultNullValue); TableSchema.TableColumn colvarErrorEstimate = new TableSchema.TableColumn(schema); colvarErrorEstimate.ColumnName = "ErrorEstimate"; colvarErrorEstimate.DataType = DbType.Double; colvarErrorEstimate.MaxLength = 0; colvarErrorEstimate.AutoIncrement = false; colvarErrorEstimate.IsNullable = true; colvarErrorEstimate.IsPrimaryKey = false; colvarErrorEstimate.IsForeignKey = false; colvarErrorEstimate.IsReadOnly = false; schema.Columns.Add(colvarErrorEstimate); TableSchema.TableColumn colvarUpdateFreq = new TableSchema.TableColumn(schema); colvarUpdateFreq.ColumnName = "UpdateFreq"; colvarUpdateFreq.DataType = DbType.Int32; colvarUpdateFreq.MaxLength = 0; colvarUpdateFreq.AutoIncrement = false; colvarUpdateFreq.IsNullable = false; colvarUpdateFreq.IsPrimaryKey = false; colvarUpdateFreq.IsForeignKey = false; colvarUpdateFreq.IsReadOnly = false; schema.Columns.Add(colvarUpdateFreq); TableSchema.TableColumn colvarStartDate = new TableSchema.TableColumn(schema); colvarStartDate.ColumnName = "StartDate"; colvarStartDate.DataType = DbType.Date; colvarStartDate.MaxLength = 0; colvarStartDate.AutoIncrement = false; colvarStartDate.IsNullable = true; colvarStartDate.IsPrimaryKey = false; colvarStartDate.IsForeignKey = false; colvarStartDate.IsReadOnly = false; schema.Columns.Add(colvarStartDate); TableSchema.TableColumn colvarEndDate = new TableSchema.TableColumn(schema); colvarEndDate.ColumnName = "EndDate"; colvarEndDate.DataType = DbType.Date; colvarEndDate.MaxLength = 0; colvarEndDate.AutoIncrement = false; colvarEndDate.IsNullable = true; colvarEndDate.IsPrimaryKey = false; colvarEndDate.IsForeignKey = false; colvarEndDate.IsReadOnly = false; schema.Columns.Add(colvarEndDate); TableSchema.TableColumn colvarLastUpdate = new TableSchema.TableColumn(schema); colvarLastUpdate.ColumnName = "LastUpdate"; colvarLastUpdate.DataType = DbType.DateTime; colvarLastUpdate.MaxLength = 0; colvarLastUpdate.AutoIncrement = false; colvarLastUpdate.IsNullable = false; colvarLastUpdate.IsPrimaryKey = false; colvarLastUpdate.IsForeignKey = false; colvarLastUpdate.IsReadOnly = false; schema.Columns.Add(colvarLastUpdate); TableSchema.TableColumn colvarDataSchemaID = new TableSchema.TableColumn(schema); colvarDataSchemaID.ColumnName = "DataSchemaID"; colvarDataSchemaID.DataType = DbType.Guid; colvarDataSchemaID.MaxLength = 0; colvarDataSchemaID.AutoIncrement = false; colvarDataSchemaID.IsNullable = true; colvarDataSchemaID.IsPrimaryKey = false; colvarDataSchemaID.IsForeignKey = false; colvarDataSchemaID.IsReadOnly = false; schema.Columns.Add(colvarDataSchemaID); TableSchema.TableColumn colvarUserId = new TableSchema.TableColumn(schema); colvarUserId.ColumnName = "UserId"; colvarUserId.DataType = DbType.Guid; colvarUserId.MaxLength = 0; colvarUserId.AutoIncrement = false; colvarUserId.IsNullable = false; colvarUserId.IsPrimaryKey = false; colvarUserId.IsForeignKey = false; colvarUserId.IsReadOnly = false; schema.Columns.Add(colvarUserId); TableSchema.TableColumn colvarAddedAt = new TableSchema.TableColumn(schema); colvarAddedAt.ColumnName = "AddedAt"; colvarAddedAt.DataType = DbType.DateTime; colvarAddedAt.MaxLength = 0; colvarAddedAt.AutoIncrement = false; colvarAddedAt.IsNullable = true; colvarAddedAt.IsPrimaryKey = false; colvarAddedAt.IsForeignKey = false; colvarAddedAt.IsReadOnly = false; schema.Columns.Add(colvarAddedAt); TableSchema.TableColumn colvarUpdatedAt = new TableSchema.TableColumn(schema); colvarUpdatedAt.ColumnName = "UpdatedAt"; colvarUpdatedAt.DataType = DbType.DateTime; colvarUpdatedAt.MaxLength = 0; colvarUpdatedAt.AutoIncrement = false; colvarUpdatedAt.IsNullable = true; colvarUpdatedAt.IsPrimaryKey = false; colvarUpdatedAt.IsForeignKey = false; colvarUpdatedAt.IsReadOnly = false; schema.Columns.Add(colvarUpdatedAt); TableSchema.TableColumn colvarRowVersion = new TableSchema.TableColumn(schema); colvarRowVersion.ColumnName = "RowVersion"; colvarRowVersion.DataType = DbType.Binary; colvarRowVersion.MaxLength = 0; colvarRowVersion.AutoIncrement = false; colvarRowVersion.IsNullable = false; colvarRowVersion.IsPrimaryKey = false; colvarRowVersion.IsForeignKey = false; colvarRowVersion.IsReadOnly = true; schema.Columns.Add(colvarRowVersion); TableSchema.TableColumn colvarDataSchemaName = new TableSchema.TableColumn(schema); colvarDataSchemaName.ColumnName = "DataSchemaName"; colvarDataSchemaName.DataType = DbType.AnsiString; colvarDataSchemaName.MaxLength = 100; colvarDataSchemaName.AutoIncrement = false; colvarDataSchemaName.IsNullable = true; colvarDataSchemaName.IsPrimaryKey = false; colvarDataSchemaName.IsForeignKey = false; colvarDataSchemaName.IsReadOnly = false; schema.Columns.Add(colvarDataSchemaName); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["ObservationsDB"].AddSchema("vDataSource",schema); } } #endregion #region Query Accessor public static Query CreateQuery() { return new Query(Schema); } #endregion #region .ctors public VDataSource() { SetSQLProps(); SetDefaults(); MarkNew(); } public VDataSource(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) { ForceDefaults(); } MarkNew(); } public VDataSource(object keyID) { SetSQLProps(); LoadByKey(keyID); } public VDataSource(string columnName, object columnValue) { SetSQLProps(); LoadByParam(columnName,columnValue); } #endregion #region Props [XmlAttribute("Id")] [Bindable(true)] public Guid Id { get { return GetColumnValue<Guid>("ID"); } set { SetColumnValue("ID", value); } } [XmlAttribute("Code")] [Bindable(true)] public string Code { get { return GetColumnValue<string>("Code"); } set { SetColumnValue("Code", value); } } [XmlAttribute("Name")] [Bindable(true)] public string Name { get { return GetColumnValue<string>("Name"); } set { SetColumnValue("Name", value); } } [XmlAttribute("Description")] [Bindable(true)] public string Description { get { return GetColumnValue<string>("Description"); } set { SetColumnValue("Description", value); } } [XmlAttribute("Url")] [Bindable(true)] public string Url { get { return GetColumnValue<string>("Url"); } set { SetColumnValue("Url", value); } } [XmlAttribute("DefaultNullValue")] [Bindable(true)] public double? DefaultNullValue { get { return GetColumnValue<double?>("DefaultNullValue"); } set { SetColumnValue("DefaultNullValue", value); } } [XmlAttribute("ErrorEstimate")] [Bindable(true)] public double? ErrorEstimate { get { return GetColumnValue<double?>("ErrorEstimate"); } set { SetColumnValue("ErrorEstimate", value); } } [XmlAttribute("UpdateFreq")] [Bindable(true)] public int UpdateFreq { get { return GetColumnValue<int>("UpdateFreq"); } set { SetColumnValue("UpdateFreq", value); } } [XmlAttribute("StartDate")] [Bindable(true)] public DateTime? StartDate { get { return GetColumnValue<DateTime?>("StartDate"); } set { SetColumnValue("StartDate", value); } } [XmlAttribute("EndDate")] [Bindable(true)] public DateTime? EndDate { get { return GetColumnValue<DateTime?>("EndDate"); } set { SetColumnValue("EndDate", value); } } [XmlAttribute("LastUpdate")] [Bindable(true)] public DateTime LastUpdate { get { return GetColumnValue<DateTime>("LastUpdate"); } set { SetColumnValue("LastUpdate", value); } } [XmlAttribute("DataSchemaID")] [Bindable(true)] public Guid? DataSchemaID { get { return GetColumnValue<Guid?>("DataSchemaID"); } set { SetColumnValue("DataSchemaID", value); } } [XmlAttribute("UserId")] [Bindable(true)] public Guid UserId { get { return GetColumnValue<Guid>("UserId"); } set { SetColumnValue("UserId", value); } } [XmlAttribute("AddedAt")] [Bindable(true)] public DateTime? AddedAt { get { return GetColumnValue<DateTime?>("AddedAt"); } set { SetColumnValue("AddedAt", value); } } [XmlAttribute("UpdatedAt")] [Bindable(true)] public DateTime? UpdatedAt { get { return GetColumnValue<DateTime?>("UpdatedAt"); } set { SetColumnValue("UpdatedAt", value); } } [XmlAttribute("RowVersion")] [Bindable(true)] public byte[] RowVersion { get { return GetColumnValue<byte[]>("RowVersion"); } set { SetColumnValue("RowVersion", value); } } [XmlAttribute("DataSchemaName")] [Bindable(true)] public string DataSchemaName { get { return GetColumnValue<string>("DataSchemaName"); } set { SetColumnValue("DataSchemaName", value); } } #endregion #region Columns Struct public struct Columns { public static string Id = @"ID"; public static string Code = @"Code"; public static string Name = @"Name"; public static string Description = @"Description"; public static string Url = @"Url"; public static string DefaultNullValue = @"DefaultNullValue"; public static string ErrorEstimate = @"ErrorEstimate"; public static string UpdateFreq = @"UpdateFreq"; public static string StartDate = @"StartDate"; public static string EndDate = @"EndDate"; public static string LastUpdate = @"LastUpdate"; public static string DataSchemaID = @"DataSchemaID"; public static string UserId = @"UserId"; public static string AddedAt = @"AddedAt"; public static string UpdatedAt = @"UpdatedAt"; public static string RowVersion = @"RowVersion"; public static string DataSchemaName = @"DataSchemaName"; } #endregion #region IAbstractRecord Members public new CT GetColumnValue<CT>(string columnName) { return base.GetColumnValue<CT>(columnName); } public object GetColumnValue(string columnName) { return base.GetColumnValue<object>(columnName); } #endregion } }
#region License /* * HttpBase.cs * * The MIT License * * Copyright (c) 2012-2014 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Text; using System.Threading; using WebSocketSharp.Net; namespace WebSocketSharp { internal abstract class HttpBase { #region Private Fields private NameValueCollection _headers; private const int _headersMaxLength = 8192; private Version _version; #endregion #region Internal Fields internal byte[] EntityBodyData; #endregion #region Protected Fields protected const string CrLf = "\r\n"; #endregion #region Protected Constructors protected HttpBase (Version version, NameValueCollection headers) { _version = version; _headers = headers; } #endregion #region Public Properties public string EntityBody { get { if (EntityBodyData == null || EntityBodyData.LongLength == 0) return String.Empty; Encoding enc = null; var contentType = _headers["Content-Type"]; if (contentType != null && contentType.Length > 0) enc = HttpUtility.GetEncoding (contentType); return (enc ?? Encoding.UTF8).GetString (EntityBodyData); } } public NameValueCollection Headers { get { return _headers; } } public Version ProtocolVersion { get { return _version; } } #endregion #region Private Methods private static byte[] readEntityBody (Stream stream, string length) { long len; if (!Int64.TryParse (length, out len)) throw new ArgumentException ("Cannot be parsed.", "length"); if (len < 0) throw new ArgumentOutOfRangeException ("length", "Less than zero."); return len > 1024 ? stream.ReadBytes (len, 1024) : len > 0 ? stream.ReadBytes ((int) len) : null; } private static string[] readHeaders (Stream stream, int maxLength) { var buff = new List<byte> (); var cnt = 0; Action<int> add = i => { buff.Add ((byte) i); cnt++; }; var read = false; while (cnt < maxLength) { if (stream.ReadByte ().EqualsWith ('\r', add) && stream.ReadByte ().EqualsWith ('\n', add) && stream.ReadByte ().EqualsWith ('\r', add) && stream.ReadByte ().EqualsWith ('\n', add)) { read = true; break; } } if (!read) throw new WebSocketException ("The length of header part is greater than the max length."); return Encoding.UTF8.GetString (buff.ToArray ()) .Replace (CrLf + " ", " ") .Replace (CrLf + "\t", " ") .Split (new[] { CrLf }, StringSplitOptions.RemoveEmptyEntries); } #endregion #region Protected Methods protected static T Read<T> (Stream stream, Func<string[], T> parser, int millisecondsTimeout) where T : HttpBase { var timeout = false; var timer = new Timer ( state => { timeout = true; stream.Close (); }, null, millisecondsTimeout, -1); T http = null; Exception exception = null; try { http = parser (readHeaders (stream, _headersMaxLength)); var contentLen = http.Headers["Content-Length"]; if (contentLen != null && contentLen.Length > 0) http.EntityBodyData = readEntityBody (stream, contentLen); } catch (Exception ex) { exception = ex; } finally { timer.Change (-1, -1); timer.Dispose (); } var msg = timeout ? "A timeout has occurred while reading an HTTP request/response." : exception != null ? "An exception has occurred while reading an HTTP request/response." : null; if (msg != null) throw new WebSocketException (msg, exception); return http; } #endregion #region Public Methods public byte[] ToByteArray () { return Encoding.UTF8.GetBytes (ToString ()); } #endregion } }
using System; using System.Collections.Specialized; using System.ComponentModel; using Android.Content; using Android.Content.Res; using Android.Graphics; using Android.Graphics.Drawables; using Android.OS; using Android.Runtime; using Android.Support.Design.Widget; using Android.Support.V4.App; using Android.Support.V4.View; using Android.Views; namespace Xamarin.Forms.Platform.Android.AppCompat { public class TabbedPageRenderer : VisualElementRenderer<TabbedPage>, TabLayout.IOnTabSelectedListener, ViewPager.IOnPageChangeListener, IManageFragments { Drawable _backgroundDrawable; bool _disposed; FragmentManager _fragmentManager; TabLayout _tabLayout; bool _useAnimations = true; FormsViewPager _viewPager; public TabbedPageRenderer() { AutoPackage = false; } FragmentManager FragmentManager => _fragmentManager ?? (_fragmentManager = ((FormsAppCompatActivity)Context).SupportFragmentManager); internal bool UseAnimations { get { return _useAnimations; } set { FormsViewPager pager = _viewPager; _useAnimations = value; if (pager != null) pager.EnableGesture = value; } } void IManageFragments.SetFragmentManager(FragmentManager childFragmentManager) { if (_fragmentManager == null) _fragmentManager = childFragmentManager; } void ViewPager.IOnPageChangeListener.OnPageScrolled(int position, float positionOffset, int positionOffsetPixels) { UpdateTabBarTranslation(position, positionOffset); } void ViewPager.IOnPageChangeListener.OnPageScrollStateChanged(int state) { } void ViewPager.IOnPageChangeListener.OnPageSelected(int position) { Element.CurrentPage = Element.Children[position]; } void TabLayout.IOnTabSelectedListener.OnTabReselected(TabLayout.Tab tab) { } void TabLayout.IOnTabSelectedListener.OnTabSelected(TabLayout.Tab tab) { if (Element == null) return; int selectedIndex = tab.Position; if (Element.Children.Count > selectedIndex && selectedIndex >= 0) Element.CurrentPage = Element.Children[selectedIndex]; } void TabLayout.IOnTabSelectedListener.OnTabUnselected(TabLayout.Tab tab) { } protected override void Dispose(bool disposing) { if (disposing && !_disposed) { _disposed = true; RemoveAllViews(); foreach (Page pageToRemove in Element.Children) { IVisualElementRenderer pageRenderer = Android.Platform.GetRenderer(pageToRemove); if (pageRenderer != null) { pageRenderer.ViewGroup.RemoveFromParent(); pageRenderer.Dispose(); } pageToRemove.ClearValue(Android.Platform.RendererProperty); } if (_viewPager != null) { _viewPager.Adapter.Dispose(); _viewPager.Dispose(); _viewPager = null; } if (_tabLayout != null) { _tabLayout.SetOnTabSelectedListener(null); _tabLayout.Dispose(); _tabLayout = null; } if (Element != null) Element.InternalChildren.CollectionChanged -= OnChildrenCollectionChanged; } base.Dispose(disposing); } protected override void OnAttachedToWindow() { base.OnAttachedToWindow(); Element.SendAppearing(); } protected override void OnDetachedFromWindow() { base.OnDetachedFromWindow(); Element.SendDisappearing(); } protected override void OnElementChanged(ElementChangedEventArgs<TabbedPage> e) { base.OnElementChanged(e); var activity = (FormsAppCompatActivity)Context; if (e.OldElement != null) e.OldElement.InternalChildren.CollectionChanged -= OnChildrenCollectionChanged; if (e.NewElement != null) { if (_tabLayout == null) { TabLayout tabs; if (FormsAppCompatActivity.TabLayoutResource > 0) { tabs = _tabLayout = activity.LayoutInflater.Inflate(FormsAppCompatActivity.TabLayoutResource, null).JavaCast<TabLayout>(); } else tabs = _tabLayout = new TabLayout(activity) { TabMode = TabLayout.ModeFixed, TabGravity = TabLayout.GravityFill }; FormsViewPager pager = _viewPager = new FormsViewPager(activity) { OverScrollMode = OverScrollMode.Never, EnableGesture = UseAnimations, LayoutParameters = new LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent), Adapter = new FormsFragmentPagerAdapter<Page>(e.NewElement, FragmentManager) { CountOverride = e.NewElement.Children.Count } }; pager.Id = FormsAppCompatActivity.GetUniqueId(); pager.AddOnPageChangeListener(this); tabs.SetupWithViewPager(pager); UpdateTabIcons(); tabs.SetOnTabSelectedListener(this); AddView(pager); AddView(tabs); } TabbedPage tabbedPage = e.NewElement; if (tabbedPage.CurrentPage != null) ScrollToCurrentPage(); UpdateIgnoreContainerAreas(); tabbedPage.InternalChildren.CollectionChanged += OnChildrenCollectionChanged; UpdateBarBackgroundColor(); UpdateBarTextColor(); } } protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (e.PropertyName == nameof(TabbedPage.CurrentPage)) ScrollToCurrentPage(); else if (e.PropertyName == NavigationPage.BarBackgroundColorProperty.PropertyName) UpdateBarBackgroundColor(); else if (e.PropertyName == NavigationPage.BarTextColorProperty.PropertyName) UpdateBarTextColor(); } protected override void OnLayout(bool changed, int l, int t, int r, int b) { TabLayout tabs = _tabLayout; FormsViewPager pager = _viewPager; Context context = Context; int width = r - l; int height = b - t; tabs.Measure(MeasureSpecFactory.MakeMeasureSpec(width, MeasureSpecMode.Exactly), MeasureSpecFactory.MakeMeasureSpec(height, MeasureSpecMode.AtMost)); var tabsHeight = 0; //MinimumHeight is only available on API 16+ if ((int)Build.VERSION.SdkInt >= 16) tabsHeight = Math.Min(height, Math.Max(tabs.MeasuredHeight, tabs.MinimumHeight)); else tabsHeight = Math.Min(height, tabs.MeasuredHeight); pager.Measure(MeasureSpecFactory.MakeMeasureSpec(width, MeasureSpecMode.AtMost), MeasureSpecFactory.MakeMeasureSpec(height, MeasureSpecMode.AtMost)); if (width > 0 && height > 0) { Element.ContainerArea = new Rectangle(0, context.FromPixels(tabsHeight), context.FromPixels(width), context.FromPixels(height - tabsHeight)); for (var i = 0; i < Element.InternalChildren.Count; i++) { var child = Element.InternalChildren[i] as VisualElement; if (child == null) continue; IVisualElementRenderer renderer = Android.Platform.GetRenderer(child); var navigationRenderer = renderer as NavigationPageRenderer; if (navigationRenderer != null) navigationRenderer.ContainerPadding = tabsHeight; } pager.Layout(0, 0, width, b); // We need to measure again to ensure that the tabs show up tabs.Measure(MeasureSpecFactory.MakeMeasureSpec(width, MeasureSpecMode.Exactly), MeasureSpecFactory.MakeMeasureSpec(tabsHeight, MeasureSpecMode.Exactly)); tabs.Layout(0, 0, width, tabsHeight); UpdateTabBarTranslation(pager.CurrentItem, 0); } base.OnLayout(changed, l, t, r, b); } void OnChildrenCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { FormsViewPager pager = _viewPager; TabLayout tabs = _tabLayout; ((FormsFragmentPagerAdapter<Page>)pager.Adapter).CountOverride = Element.Children.Count; pager.Adapter.NotifyDataSetChanged(); if (Element.Children.Count == 0) tabs.RemoveAllTabs(); else { tabs.SetupWithViewPager(pager); UpdateTabIcons(); tabs.SetOnTabSelectedListener(this); } UpdateIgnoreContainerAreas(); } void ScrollToCurrentPage() { _viewPager.SetCurrentItem(Element.Children.IndexOf(Element.CurrentPage), UseAnimations); } void UpdateIgnoreContainerAreas() { foreach (Page child in Element.Children) child.IgnoresContainerArea = child is NavigationPage; } void UpdateTabBarTranslation(int position, float offset) { TabLayout tabs = _tabLayout; if (position >= Element.InternalChildren.Count) return; var leftPage = (Page)Element.InternalChildren[position]; IVisualElementRenderer leftRenderer = Android.Platform.GetRenderer(leftPage); if (leftRenderer == null) return; if (offset <= 0 || position >= Element.InternalChildren.Count - 1) { var leftNavRenderer = leftRenderer as NavigationPageRenderer; if (leftNavRenderer != null) tabs.TranslationY = leftNavRenderer.GetNavBarHeight(); else tabs.TranslationY = 0; } else { var rightPage = (Page)Element.InternalChildren[position + 1]; IVisualElementRenderer rightRenderer = Android.Platform.GetRenderer(rightPage); var leftHeight = 0; var leftNavRenderer = leftRenderer as NavigationPageRenderer; if (leftNavRenderer != null) leftHeight = leftNavRenderer.GetNavBarHeight(); var rightHeight = 0; var rightNavRenderer = rightRenderer as NavigationPageRenderer; if (rightNavRenderer != null) rightHeight = rightNavRenderer.GetNavBarHeight(); tabs.TranslationY = leftHeight + (rightHeight - leftHeight) * offset; } } void UpdateTabIcons() { TabLayout tabs = _tabLayout; if (tabs.TabCount != Element.Children.Count) return; for (var i = 0; i < Element.Children.Count; i++) { Page child = Element.Children[i]; FileImageSource icon = child.Icon; if (string.IsNullOrEmpty(icon)) continue; TabLayout.Tab tab = tabs.GetTabAt(i); tab.SetIcon(ResourceManager.IdFromTitle(icon, ResourceManager.DrawableClass)); } } void UpdateBarBackgroundColor() { if (_disposed || _tabLayout == null) return; Color tintColor = Element.BarBackgroundColor; if (Forms.IsLollipopOrNewer) { if (tintColor.IsDefault) _tabLayout.BackgroundTintMode = null; else { _tabLayout.BackgroundTintMode = PorterDuff.Mode.Src; _tabLayout.BackgroundTintList = ColorStateList.ValueOf(tintColor.ToAndroid()); } } else { if (tintColor.IsDefault && _backgroundDrawable != null) _tabLayout.SetBackground(_backgroundDrawable); else if (!tintColor.IsDefault) { if (_backgroundDrawable == null) _backgroundDrawable = _tabLayout.Background; _tabLayout.SetBackgroundColor(tintColor.ToAndroid()); } } } void UpdateBarTextColor() { if (_disposed || _tabLayout == null) return; Color textColor = Element.BarTextColor; if (!textColor.IsDefault) _tabLayout.SetTabTextColors(textColor.ToAndroid().ToArgb(), textColor.ToAndroid().ToArgb()); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.SiteRecovery.Models; using Microsoft.Azure.Management.SiteRecoveryVault; namespace Microsoft.Azure.Management.SiteRecoveryVault { public static partial class VaultExtendedInfoOperationsExtensions { /// <summary> /// Get the vault extended info. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecoveryVault.IVaultExtendedInfoOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group containing the job /// collection. /// </param> /// <param name='resourceName'> /// Required. The name of the resource. /// </param> /// <param name='extendedInfoArgs'> /// Required. Create resource exnteded info input parameters. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse CreateExtendedInfo(this IVaultExtendedInfoOperations operations, string resourceGroupName, string resourceName, ResourceExtendedInformationArgs extendedInfoArgs, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IVaultExtendedInfoOperations)s).CreateExtendedInfoAsync(resourceGroupName, resourceName, extendedInfoArgs, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the vault extended info. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecoveryVault.IVaultExtendedInfoOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group containing the job /// collection. /// </param> /// <param name='resourceName'> /// Required. The name of the resource. /// </param> /// <param name='extendedInfoArgs'> /// Required. Create resource exnteded info input parameters. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> CreateExtendedInfoAsync(this IVaultExtendedInfoOperations operations, string resourceGroupName, string resourceName, ResourceExtendedInformationArgs extendedInfoArgs, CustomRequestHeaders customRequestHeaders) { return operations.CreateExtendedInfoAsync(resourceGroupName, resourceName, extendedInfoArgs, customRequestHeaders, CancellationToken.None); } /// <summary> /// Get the vault extended info. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecoveryVault.IVaultExtendedInfoOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group containing the job /// collection. /// </param> /// <param name='resourceName'> /// Required. The name of the resource. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the resource extended information object /// </returns> public static ResourceExtendedInformationResponse GetExtendedInfo(this IVaultExtendedInfoOperations operations, string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IVaultExtendedInfoOperations)s).GetExtendedInfoAsync(resourceGroupName, resourceName, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the vault extended info. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecoveryVault.IVaultExtendedInfoOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group containing the job /// collection. /// </param> /// <param name='resourceName'> /// Required. The name of the resource. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the resource extended information object /// </returns> public static Task<ResourceExtendedInformationResponse> GetExtendedInfoAsync(this IVaultExtendedInfoOperations operations, string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders) { return operations.GetExtendedInfoAsync(resourceGroupName, resourceName, customRequestHeaders, CancellationToken.None); } /// <summary> /// Get the vault extended info. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecoveryVault.IVaultExtendedInfoOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group containing the job /// collection. /// </param> /// <param name='resourceName'> /// Required. The name of the resource. /// </param> /// <param name='extendedInfoArgs'> /// Optional. Update resource exnteded info input parameters. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the resource extended information object /// </returns> public static ResourceExtendedInformationResponse UpdateExtendedInfo(this IVaultExtendedInfoOperations operations, string resourceGroupName, string resourceName, ResourceExtendedInformationArgs extendedInfoArgs, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IVaultExtendedInfoOperations)s).UpdateExtendedInfoAsync(resourceGroupName, resourceName, extendedInfoArgs, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the vault extended info. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecoveryVault.IVaultExtendedInfoOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group containing the job /// collection. /// </param> /// <param name='resourceName'> /// Required. The name of the resource. /// </param> /// <param name='extendedInfoArgs'> /// Optional. Update resource exnteded info input parameters. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the resource extended information object /// </returns> public static Task<ResourceExtendedInformationResponse> UpdateExtendedInfoAsync(this IVaultExtendedInfoOperations operations, string resourceGroupName, string resourceName, ResourceExtendedInformationArgs extendedInfoArgs, CustomRequestHeaders customRequestHeaders) { return operations.UpdateExtendedInfoAsync(resourceGroupName, resourceName, extendedInfoArgs, customRequestHeaders, CancellationToken.None); } /// <summary> /// Get the vault extended info. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecoveryVault.IVaultExtendedInfoOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group containing the job /// collection. /// </param> /// <param name='resourceName'> /// Required. The name of the resource. /// </param> /// <param name='parameters'> /// Required. Upload Vault Certificate input parameters. /// </param> /// <param name='certFriendlyName'> /// Required. Certificate friendly name /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the upload certificate response /// </returns> public static UploadCertificateResponse UploadCertificate(this IVaultExtendedInfoOperations operations, string resourceGroupName, string resourceName, CertificateArgs parameters, string certFriendlyName, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IVaultExtendedInfoOperations)s).UploadCertificateAsync(resourceGroupName, resourceName, parameters, certFriendlyName, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the vault extended info. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecoveryVault.IVaultExtendedInfoOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group containing the job /// collection. /// </param> /// <param name='resourceName'> /// Required. The name of the resource. /// </param> /// <param name='parameters'> /// Required. Upload Vault Certificate input parameters. /// </param> /// <param name='certFriendlyName'> /// Required. Certificate friendly name /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the upload certificate response /// </returns> public static Task<UploadCertificateResponse> UploadCertificateAsync(this IVaultExtendedInfoOperations operations, string resourceGroupName, string resourceName, CertificateArgs parameters, string certFriendlyName, CustomRequestHeaders customRequestHeaders) { return operations.UploadCertificateAsync(resourceGroupName, resourceName, parameters, certFriendlyName, customRequestHeaders, CancellationToken.None); } } }
#region License /* * HttpListenerPrefixCollection.cs * * This code is derived from System.Net.HttpListenerPrefixCollection.cs of Mono * (http://www.mono-project.com). * * The MIT License * * Copyright (c) 2005 Novell, Inc. (http://www.novell.com) * Copyright (c) 2012-2014 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Authors /* * Authors: * - Gonzalo Paniagua Javier <gonzalo@novell.com> */ #endregion using System; using System.Collections; using System.Collections.Generic; namespace WebSocketSharp.Net { /// <summary> /// Provides the collection used to store the URI prefixes for the <see cref="HttpListener"/>. /// </summary> /// <remarks> /// The <see cref="HttpListener"/> responds to the request which has a requested URI that /// the prefixes most closely match. /// </remarks> public class HttpListenerPrefixCollection : ICollection<string>, IEnumerable<string>, IEnumerable { #region Private Fields private HttpListener _listener; private List<string> _prefixes; #endregion #region Private Constructors private HttpListenerPrefixCollection () { _prefixes = new List<string> (); } #endregion #region Internal Constructors internal HttpListenerPrefixCollection (HttpListener listener) : this () { _listener = listener; } #endregion #region Public Properties /// <summary> /// Gets the number of prefixes contained in the <see cref="HttpListenerPrefixCollection"/>. /// </summary> /// <value> /// An <see cref="int"/> that represents the number of prefixes. /// </value> public int Count { get { return _prefixes.Count; } } /// <summary> /// Gets a value indicating whether the access to the <see cref="HttpListenerPrefixCollection"/> /// is read-only. /// </summary> /// <value> /// Always returns <c>false</c>. /// </value> public bool IsReadOnly { get { return false; } } /// <summary> /// Gets a value indicating whether the access to the <see cref="HttpListenerPrefixCollection"/> /// is synchronized. /// </summary> /// <value> /// Always returns <c>false</c>. /// </value> public bool IsSynchronized { get { return false; } } #endregion #region Public Methods /// <summary> /// Adds the specified <paramref name="uriPrefix"/> to /// the <see cref="HttpListenerPrefixCollection"/>. /// </summary> /// <param name="uriPrefix"> /// A <see cref="string"/> that represents the URI prefix to add. The prefix must be /// a well-formed URI prefix with http or https scheme, and must be terminated with /// a <c>"/"</c>. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="uriPrefix"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="uriPrefix"/> is invalid. /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="HttpListener"/> associated with /// this <see cref="HttpListenerPrefixCollection"/> is closed. /// </exception> public void Add (string uriPrefix) { _listener.CheckDisposed (); ListenerPrefix.CheckUriPrefix (uriPrefix); if (_prefixes.Contains (uriPrefix)) return; _prefixes.Add (uriPrefix); if (_listener.IsListening) EndPointManager.AddPrefix (uriPrefix, _listener); } /// <summary> /// Removes all URI prefixes from the <see cref="HttpListenerPrefixCollection"/>. /// </summary> /// <exception cref="ObjectDisposedException"> /// The <see cref="HttpListener"/> associated with /// this <see cref="HttpListenerPrefixCollection"/> is closed. /// </exception> public void Clear () { _listener.CheckDisposed (); _prefixes.Clear (); if (_listener.IsListening) EndPointManager.RemoveListener (_listener); } /// <summary> /// Returns a value indicating whether the <see cref="HttpListenerPrefixCollection"/> contains /// the specified <paramref name="uriPrefix"/>. /// </summary> /// <returns> /// <c>true</c> if the <see cref="HttpListenerPrefixCollection"/> contains /// <paramref name="uriPrefix"/>; otherwise, <c>false</c>. /// </returns> /// <param name="uriPrefix"> /// A <see cref="string"/> that represents the URI prefix to test. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="uriPrefix"/> is <see langword="null"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="HttpListener"/> associated with /// this <see cref="HttpListenerPrefixCollection"/> is closed. /// </exception> public bool Contains (string uriPrefix) { _listener.CheckDisposed (); if (uriPrefix == null) throw new ArgumentNullException ("uriPrefix"); return _prefixes.Contains (uriPrefix); } /// <summary> /// Copies the contents of the <see cref="HttpListenerPrefixCollection"/> to /// the specified <see cref="Array"/>. /// </summary> /// <param name="array"> /// An <see cref="Array"/> that receives the URI prefix strings in /// the <see cref="HttpListenerPrefixCollection"/>. /// </param> /// <param name="offset"> /// An <see cref="int"/> that represents the zero-based index in <paramref name="array"/> /// at which copying begins. /// </param> /// <exception cref="ObjectDisposedException"> /// The <see cref="HttpListener"/> associated with /// this <see cref="HttpListenerPrefixCollection"/> is closed. /// </exception> public void CopyTo (Array array, int offset) { _listener.CheckDisposed (); ((ICollection) _prefixes).CopyTo (array, offset); } /// <summary> /// Copies the contents of the <see cref="HttpListenerPrefixCollection"/> to /// the specified array of <see cref="string"/>. /// </summary> /// <param name="array"> /// An array of <see cref="string"/> that receives the URI prefix strings in /// the <see cref="HttpListenerPrefixCollection"/>. /// </param> /// <param name="offset"> /// An <see cref="int"/> that represents the zero-based index in <paramref name="array"/> /// at which copying begins. /// </param> /// <exception cref="ObjectDisposedException"> /// The <see cref="HttpListener"/> associated with /// this <see cref="HttpListenerPrefixCollection"/> is closed. /// </exception> public void CopyTo (string [] array, int offset) { _listener.CheckDisposed (); _prefixes.CopyTo (array, offset); } /// <summary> /// Gets the enumerator used to iterate through the <see cref="HttpListenerPrefixCollection"/>. /// </summary> /// <returns> /// An <see cref="T:System.Collections.Generic.IEnumerator{string}"/> instance used to iterate /// through the <see cref="HttpListenerPrefixCollection"/>. /// </returns> public IEnumerator<string> GetEnumerator () { return _prefixes.GetEnumerator (); } /// <summary> /// Removes the specified <paramref name="uriPrefix"/> from the list of prefixes in /// the <see cref="HttpListenerPrefixCollection"/>. /// </summary> /// <returns> /// <c>true</c> if <paramref name="uriPrefix"/> is successfully found and removed; /// otherwise, <c>false</c>. /// </returns> /// <param name="uriPrefix"> /// A <see cref="string"/> that represents the URI prefix to remove. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="uriPrefix"/> is <see langword="null"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="HttpListener"/> associated with /// this <see cref="HttpListenerPrefixCollection"/> is closed. /// </exception> public bool Remove (string uriPrefix) { _listener.CheckDisposed (); if (uriPrefix == null) throw new ArgumentNullException ("uriPrefix"); var result = _prefixes.Remove (uriPrefix); if (result && _listener.IsListening) EndPointManager.RemovePrefix (uriPrefix, _listener); return result; } #endregion #region Explicit Interface Implementation /// <summary> /// Gets the enumerator used to iterate through the <see cref="HttpListenerPrefixCollection"/>. /// </summary> /// <returns> /// An <see cref="IEnumerator"/> instance used to iterate through /// the <see cref="HttpListenerPrefixCollection"/>. /// </returns> IEnumerator IEnumerable.GetEnumerator () { return _prefixes.GetEnumerator (); } #endregion } }
//*********************************************************// // Copyright (c) Microsoft. All rights reserved. // // Apache 2.0 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.Diagnostics; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace Microsoft.VisualStudioTools.Project { // This class is No longer used by project system, retained for backwards for languages // which have already shipped this public type. #if SHAREDPROJECT_OLESERVICEPROVIDER public class OleServiceProvider : IOleServiceProvider, IDisposable { #region Public Types [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] public delegate object ServiceCreatorCallback(Type serviceType); #endregion #region Private Types private class ServiceData : IDisposable { private Type serviceType; private object instance; private ServiceCreatorCallback creator; private bool shouldDispose; public ServiceData(Type serviceType, object instance, ServiceCreatorCallback callback, bool shouldDispose) { Utilities.ArgumentNotNull("serviceType", serviceType); if ((null == instance) && (null == callback)) { throw new ArgumentNullException("instance"); } this.serviceType = serviceType; this.instance = instance; this.creator = callback; this.shouldDispose = shouldDispose; } public object ServiceInstance { get { if (null == instance) { Debug.Assert(serviceType != null); instance = creator(serviceType); } return instance; } } public Guid Guid { get { return serviceType.GUID; } } public void Dispose() { if ((shouldDispose) && (null != instance)) { IDisposable disp = instance as IDisposable; if (null != disp) { disp.Dispose(); } instance = null; } creator = null; GC.SuppressFinalize(this); } } #endregion #region fields private Dictionary<Guid, ServiceData> services = new Dictionary<Guid, ServiceData>(); private bool isDisposed; /// <summary> /// Defines an object that will be a mutex for this object for synchronizing thread calls. /// </summary> private static volatile object Mutex = new object(); #endregion #region ctors public OleServiceProvider() { } #endregion #region IOleServiceProvider Members public int QueryService(ref Guid guidService, ref Guid riid, out IntPtr ppvObject) { ppvObject = (IntPtr)0; int hr = VSConstants.S_OK; ServiceData serviceInstance = null; if (services != null && services.ContainsKey(guidService)) { serviceInstance = services[guidService]; } if (serviceInstance == null) { return VSConstants.E_NOINTERFACE; } // Now check to see if the user asked for an IID other than // IUnknown. If so, we must do another QI. // if (riid.Equals(NativeMethods.IID_IUnknown)) { object inst = serviceInstance.ServiceInstance; if (inst == null) { return VSConstants.E_NOINTERFACE; } ppvObject = Marshal.GetIUnknownForObject(serviceInstance.ServiceInstance); } else { IntPtr pUnk = IntPtr.Zero; try { pUnk = Marshal.GetIUnknownForObject(serviceInstance.ServiceInstance); hr = Marshal.QueryInterface(pUnk, ref riid, out ppvObject); } finally { if (pUnk != IntPtr.Zero) { Marshal.Release(pUnk); } } } return hr; } #endregion #region Dispose /// <summary> /// The IDispose interface Dispose method for disposing the object determinastically. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion /// <summary> /// Adds the given service to the service container. /// </summary> /// <param name="serviceType">The type of the service to add.</param> /// <param name="serviceInstance">An instance of the service.</param> /// <param name="shouldDisposeServiceInstance">true if the Dipose of the service provider is allowed to dispose the sevice instance.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "The services created here will be disposed in the Dispose method of this type.")] public void AddService(Type serviceType, object serviceInstance, bool shouldDisposeServiceInstance) { // Create the description of this service. Note that we don't do any validation // of the parameter here because the constructor of ServiceData will do it for us. ServiceData service = new ServiceData(serviceType, serviceInstance, null, shouldDisposeServiceInstance); // Now add the service desctription to the dictionary. AddService(service); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "The services created here will be disposed in the Dispose method of this type.")] public void AddService(Type serviceType, ServiceCreatorCallback callback, bool shouldDisposeServiceInstance) { // Create the description of this service. Note that we don't do any validation // of the parameter here because the constructor of ServiceData will do it for us. ServiceData service = new ServiceData(serviceType, null, callback, shouldDisposeServiceInstance); // Now add the service desctription to the dictionary. AddService(service); } private void AddService(ServiceData data) { // Make sure that the collection of services is created. if (null == services) { services = new Dictionary<Guid, ServiceData>(); } // Disallow the addition of duplicate services. if (services.ContainsKey(data.Guid)) { throw new InvalidOperationException(); } services.Add(data.Guid, data); } /// <devdoc> /// Removes the given service type from the service container. /// </devdoc> public void RemoveService(Type serviceType) { Utilities.ArgumentNotNull("serviceType", serviceType); if (services.ContainsKey(serviceType.GUID)) { services.Remove(serviceType.GUID); } } #region helper methods /// <summary> /// The method that does the cleanup. /// </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { // Everybody can go here. if (!this.isDisposed) { // Synchronize calls to the Dispose simulteniously. lock (Mutex) { if (disposing) { // Remove all our services if (services != null) { foreach (ServiceData data in services.Values) { data.Dispose(); } services.Clear(); services = null; } } this.isDisposed = true; } } } #endregion } #endif }
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 RockBands.Services.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; } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region StyleCop Suppression - generated code using System; using System.ComponentModel; using System.Windows; namespace Microsoft.Management.UI.Internal { /// <summary> /// Derives and extends GridViewColumn to add concepts such as column visibility.. /// </summary> [Localizability(LocalizationCategory.None)] partial class InnerListColumn { // // DataDescription dependency property // /// <summary> /// Identifies the DataDescription dependency property. /// </summary> public static readonly DependencyProperty DataDescriptionProperty = DependencyProperty.Register( "DataDescription", typeof(UIPropertyGroupDescription), typeof(InnerListColumn), new PropertyMetadata( null, DataDescriptionProperty_PropertyChanged) ); /// <summary> /// Gets or sets the data description. /// </summary> [Bindable(true)] [Category("Common Properties")] [Description("Gets or sets the data description.")] [Localizability(LocalizationCategory.None)] public UIPropertyGroupDescription DataDescription { get { return (UIPropertyGroupDescription) GetValue(DataDescriptionProperty); } set { SetValue(DataDescriptionProperty,value); } } static private void DataDescriptionProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { InnerListColumn obj = (InnerListColumn) o; obj.OnDataDescriptionChanged( new PropertyChangedEventArgs<UIPropertyGroupDescription>((UIPropertyGroupDescription)e.OldValue, (UIPropertyGroupDescription)e.NewValue) ); } /// <summary> /// Called when DataDescription property changes. /// </summary> protected virtual void OnDataDescriptionChanged(PropertyChangedEventArgs<UIPropertyGroupDescription> e) { OnDataDescriptionChangedImplementation(e); this.OnPropertyChanged(new PropertyChangedEventArgs("DataDescription")); } partial void OnDataDescriptionChangedImplementation(PropertyChangedEventArgs<UIPropertyGroupDescription> e); // // MinWidth dependency property // /// <summary> /// Identifies the MinWidth dependency property. /// </summary> public static readonly DependencyProperty MinWidthProperty = DependencyProperty.Register( "MinWidth", typeof(double), typeof(InnerListColumn), new PropertyMetadata( 20.0, MinWidthProperty_PropertyChanged), MinWidthProperty_ValidateProperty ); /// <summary> /// Gets or sets a value that dictates the minimum allowable width of the column. /// </summary> [Bindable(true)] [Category("Common Properties")] [Description("Gets or sets a value that dictates the minimum allowable width of the column.")] [Localizability(LocalizationCategory.None)] public double MinWidth { get { return (double) GetValue(MinWidthProperty); } set { SetValue(MinWidthProperty,value); } } static private void MinWidthProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { InnerListColumn obj = (InnerListColumn) o; obj.OnMinWidthChanged( new PropertyChangedEventArgs<double>((double)e.OldValue, (double)e.NewValue) ); } /// <summary> /// Called when MinWidth property changes. /// </summary> protected virtual void OnMinWidthChanged(PropertyChangedEventArgs<double> e) { OnMinWidthChangedImplementation(e); this.OnPropertyChanged(new PropertyChangedEventArgs("MinWidth")); } partial void OnMinWidthChangedImplementation(PropertyChangedEventArgs<double> e); static private bool MinWidthProperty_ValidateProperty(object value) { bool isValid = false; MinWidthProperty_ValidatePropertyImplementation((double) value, ref isValid); return isValid; } static partial void MinWidthProperty_ValidatePropertyImplementation(double value, ref bool isValid); // // Required dependency property // /// <summary> /// Identifies the Required dependency property. /// </summary> public static readonly DependencyProperty RequiredProperty = DependencyProperty.Register( "Required", typeof(bool), typeof(InnerListColumn), new PropertyMetadata( BooleanBoxes.FalseBox, RequiredProperty_PropertyChanged) ); /// <summary> /// Gets or sets a value indicating whether the column may not be removed. /// </summary> [Bindable(true)] [Category("Common Properties")] [Description("Gets or sets a value indicating whether the column may not be removed.")] [Localizability(LocalizationCategory.None)] public bool Required { get { return (bool) GetValue(RequiredProperty); } set { SetValue(RequiredProperty,BooleanBoxes.Box(value)); } } static private void RequiredProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { InnerListColumn obj = (InnerListColumn) o; obj.OnRequiredChanged( new PropertyChangedEventArgs<bool>((bool)e.OldValue, (bool)e.NewValue) ); } /// <summary> /// Called when Required property changes. /// </summary> protected virtual void OnRequiredChanged(PropertyChangedEventArgs<bool> e) { OnRequiredChangedImplementation(e); this.OnPropertyChanged(new PropertyChangedEventArgs("Required")); } partial void OnRequiredChangedImplementation(PropertyChangedEventArgs<bool> e); // // Visible dependency property // /// <summary> /// Identifies the Visible dependency property. /// </summary> public static readonly DependencyProperty VisibleProperty = DependencyProperty.Register( "Visible", typeof(bool), typeof(InnerListColumn), new PropertyMetadata( BooleanBoxes.TrueBox, VisibleProperty_PropertyChanged) ); /// <summary> /// Gets or sets a value indicating whether the columns we want to have available in the list. /// </summary> /// <remarks> /// Modifying the Visible property does not in itself make the column visible or not visible. This should always be kept in sync with the Columns property. /// </remarks> [Bindable(true)] [Category("Common Properties")] [Description("Gets or sets a value indicating whether the columns we want to have available in the list.")] [Localizability(LocalizationCategory.None)] public bool Visible { get { return (bool) GetValue(VisibleProperty); } set { SetValue(VisibleProperty,BooleanBoxes.Box(value)); } } static private void VisibleProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { InnerListColumn obj = (InnerListColumn) o; obj.OnVisibleChanged( new PropertyChangedEventArgs<bool>((bool)e.OldValue, (bool)e.NewValue) ); } /// <summary> /// Called when Visible property changes. /// </summary> protected virtual void OnVisibleChanged(PropertyChangedEventArgs<bool> e) { OnVisibleChangedImplementation(e); this.OnPropertyChanged(new PropertyChangedEventArgs("Visible")); } partial void OnVisibleChangedImplementation(PropertyChangedEventArgs<bool> e); } } #endregion
//--------------------------------------------------------------------- // <copyright file="CabPacker.cs" company="Microsoft Corporation"> // Copyright (c) 1999, Microsoft Corporation. All rights reserved. // </copyright> // <summary> // Part of the Deployment Tools Foundation project. // </summary> //--------------------------------------------------------------------- namespace Microsoft.PackageManagement.Archivers.Internal.Compression.Cab { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Runtime.InteropServices; #if !CORECLR using System.Security.Permissions; #endif using System.Text; internal class CabPacker : CabWorker { private const string TempStreamName = "%%TEMP%%"; private NativeMethods.FCI.Handle fciHandle; // These delegates need to be saved as member variables // so that they don't get GC'd. private NativeMethods.FCI.PFNALLOC fciAllocMemHandler; private NativeMethods.FCI.PFNFREE fciFreeMemHandler; private NativeMethods.FCI.PFNOPEN fciOpenStreamHandler; private NativeMethods.FCI.PFNREAD fciReadStreamHandler; private NativeMethods.FCI.PFNWRITE fciWriteStreamHandler; private NativeMethods.FCI.PFNCLOSE fciCloseStreamHandler; private NativeMethods.FCI.PFNSEEK fciSeekStreamHandler; private NativeMethods.FCI.PFNFILEPLACED fciFilePlacedHandler; private NativeMethods.FCI.PFNDELETE fciDeleteFileHandler; private NativeMethods.FCI.PFNGETTEMPFILE fciGetTempFileHandler; private NativeMethods.FCI.PFNGETNEXTCABINET fciGetNextCabinet; private NativeMethods.FCI.PFNSTATUS fciCreateStatus; private NativeMethods.FCI.PFNGETOPENINFO fciGetOpenInfo; private IPackStreamContext context; private FileAttributes fileAttributes; private DateTime fileLastWriteTime; private int maxCabBytes; private long totalFolderBytesProcessedInCurrentCab; private CompressionLevel compressionLevel; private bool dontUseTempFiles; private IList<Stream> tempStreams; public CabPacker(CabEngine cabEngine) : base(cabEngine) { this.fciAllocMemHandler = this.CabAllocMem; this.fciFreeMemHandler = this.CabFreeMem; this.fciOpenStreamHandler = this.CabOpenStreamEx; this.fciReadStreamHandler = this.CabReadStreamEx; this.fciWriteStreamHandler = this.CabWriteStreamEx; this.fciCloseStreamHandler = this.CabCloseStreamEx; this.fciSeekStreamHandler = this.CabSeekStreamEx; this.fciFilePlacedHandler = this.CabFilePlaced; this.fciDeleteFileHandler = this.CabDeleteFile; this.fciGetTempFileHandler = this.CabGetTempFile; this.fciGetNextCabinet = this.CabGetNextCabinet; this.fciCreateStatus = this.CabCreateStatus; this.fciGetOpenInfo = this.CabGetOpenInfo; this.tempStreams = new List<Stream>(); this.compressionLevel = CompressionLevel.Normal; } public bool UseTempFiles { get { return !this.dontUseTempFiles; } set { this.dontUseTempFiles = !value; } } public CompressionLevel CompressionLevel { get { return this.compressionLevel; } set { this.compressionLevel = value; } } [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] private void CreateFci(long maxArchiveSize) { NativeMethods.FCI.CCAB ccab = new NativeMethods.FCI.CCAB(); if (maxArchiveSize > 0 && maxArchiveSize < ccab.cb) { ccab.cb = Math.Max( NativeMethods.FCI.MIN_DISK, (int)maxArchiveSize); } object maxFolderSizeOption = this.context.GetOption( "maxFolderSize", null); if (maxFolderSizeOption != null) { long maxFolderSize = Convert.ToInt64( maxFolderSizeOption, CultureInfo.InvariantCulture); if (maxFolderSize > 0 && maxFolderSize < ccab.cbFolderThresh) { ccab.cbFolderThresh = (int)maxFolderSize; } } this.maxCabBytes = ccab.cb; ccab.szCab = this.context.GetArchiveName(0); if (ccab.szCab == null) { throw new FileNotFoundException( "Cabinet name not provided by stream context."); } ccab.setID = (short)new Random().Next( Int16.MinValue, Int16.MaxValue + 1); this.CabNumbers[ccab.szCab] = 0; this.currentArchiveName = ccab.szCab; this.totalArchives = 1; this.CabStream = null; this.Erf.Clear(); this.fciHandle = NativeMethods.FCI.Create( this.ErfHandle.AddrOfPinnedObject(), this.fciFilePlacedHandler, this.fciAllocMemHandler, this.fciFreeMemHandler, this.fciOpenStreamHandler, this.fciReadStreamHandler, this.fciWriteStreamHandler, this.fciCloseStreamHandler, this.fciSeekStreamHandler, this.fciDeleteFileHandler, this.fciGetTempFileHandler, ccab, IntPtr.Zero); this.CheckError(false); } [SuppressMessage("Microsoft.Security", "CA2106:SecureAsserts")] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] #if !CORECLR [SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)] #endif public void Pack( IPackStreamContext streamContext, IEnumerable<string> files, long maxArchiveSize) { if (streamContext == null) { throw new ArgumentNullException("streamContext"); } if (files == null) { throw new ArgumentNullException("files"); } lock (this) { try { this.context = streamContext; this.ResetProgressData(); this.CreateFci(maxArchiveSize); foreach (string file in files) { FileAttributes attributes; DateTime lastWriteTime; Stream fileStream = this.context.OpenFileReadStream( file, out attributes, out lastWriteTime); if (fileStream != null) { this.totalFileBytes += fileStream.Length; this.totalFiles++; this.context.CloseFileReadStream(file, fileStream); } } long uncompressedBytesInFolder = 0; this.currentFileNumber = -1; foreach (string file in files) { FileAttributes attributes; DateTime lastWriteTime; Stream fileStream = this.context.OpenFileReadStream( file, out attributes, out lastWriteTime); if (fileStream == null) { continue; } if (fileStream.Length >= (long)NativeMethods.FCI.MAX_FOLDER) { throw new NotSupportedException(String.Format( CultureInfo.InvariantCulture, "File {0} exceeds maximum file size " + "for cabinet format.", file)); } if (uncompressedBytesInFolder > 0) { // Automatically create a new folder if this file // won't fit in the current folder. bool nextFolder = uncompressedBytesInFolder + fileStream.Length >= (long)NativeMethods.FCI.MAX_FOLDER; // Otherwise ask the client if it wants to // move to the next folder. if (!nextFolder) { object nextFolderOption = streamContext.GetOption( "nextFolder", new object[] { file, this.currentFolderNumber }); nextFolder = Convert.ToBoolean( nextFolderOption, CultureInfo.InvariantCulture); } if (nextFolder) { this.FlushFolder(); uncompressedBytesInFolder = 0; } } if (this.currentFolderTotalBytes > 0) { this.currentFolderTotalBytes = 0; this.currentFolderNumber++; uncompressedBytesInFolder = 0; } this.currentFileName = file; this.currentFileNumber++; this.currentFileTotalBytes = fileStream.Length; this.currentFileBytesProcessed = 0; this.OnProgress(ArchiveProgressType.StartFile); uncompressedBytesInFolder += fileStream.Length; this.AddFile( file, fileStream, attributes, lastWriteTime, false, this.CompressionLevel); } this.FlushFolder(); this.FlushCabinet(); } finally { if (this.CabStream != null) { this.context.CloseArchiveWriteStream( this.currentArchiveNumber, this.currentArchiveName, this.CabStream); this.CabStream = null; } if (this.FileStream != null) { this.context.CloseFileReadStream( this.currentFileName, this.FileStream); this.FileStream = null; } this.context = null; if (this.fciHandle != null) { this.fciHandle.Dispose(); this.fciHandle = null; } } } } internal override int CabOpenStreamEx(string path, int openFlags, int shareMode, out int err, IntPtr pv) { if (this.CabNumbers.ContainsKey(path)) { Stream stream = this.CabStream; if (stream == null) { short cabNumber = this.CabNumbers[path]; this.currentFolderTotalBytes = 0; stream = this.context.OpenArchiveWriteStream(cabNumber, path, true, this.CabEngine); if (stream == null) { throw new FileNotFoundException( String.Format(CultureInfo.InvariantCulture, "Cabinet {0} not provided.", cabNumber)); } this.currentArchiveName = path; this.currentArchiveTotalBytes = Math.Min( this.totalFolderBytesProcessedInCurrentCab, this.maxCabBytes); this.currentArchiveBytesProcessed = 0; this.OnProgress(ArchiveProgressType.StartArchive); this.CabStream = stream; } path = CabWorker.CabStreamName; } else if (path == CabPacker.TempStreamName) { // Opening memory stream for a temp file. Stream stream = new MemoryStream(); this.tempStreams.Add(stream); int streamHandle = this.StreamHandles.AllocHandle(stream); err = 0; return streamHandle; } else if (path != CabWorker.CabStreamName) { // Opening a file on disk for a temp file. path = Path.Combine(Path.GetTempPath(), path); Stream stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite); this.tempStreams.Add(stream); stream = new DuplicateStream(stream); int streamHandle = this.StreamHandles.AllocHandle(stream); err = 0; return streamHandle; } return base.CabOpenStreamEx(path, openFlags, shareMode, out err, pv); } internal override int CabWriteStreamEx(int streamHandle, IntPtr memory, int cb, out int err, IntPtr pv) { int count = base.CabWriteStreamEx(streamHandle, memory, cb, out err, pv); if (count > 0 && err == 0) { Stream stream = this.StreamHandles[streamHandle]; if (DuplicateStream.OriginalStream(stream) == DuplicateStream.OriginalStream(this.CabStream)) { this.currentArchiveBytesProcessed += cb; if (this.currentArchiveBytesProcessed > this.currentArchiveTotalBytes) { this.currentArchiveBytesProcessed = this.currentArchiveTotalBytes; } } } return count; } internal override int CabCloseStreamEx(int streamHandle, out int err, IntPtr pv) { Stream stream = DuplicateStream.OriginalStream(this.StreamHandles[streamHandle]); if (stream == DuplicateStream.OriginalStream(this.FileStream)) { this.context.CloseFileReadStream(this.currentFileName, stream); this.FileStream = null; long remainder = this.currentFileTotalBytes - this.currentFileBytesProcessed; this.currentFileBytesProcessed += remainder; this.fileBytesProcessed += remainder; this.OnProgress(ArchiveProgressType.FinishFile); this.currentFileTotalBytes = 0; this.currentFileBytesProcessed = 0; this.currentFileName = null; } else if (stream == DuplicateStream.OriginalStream(this.CabStream)) { if (stream.CanWrite) { stream.Flush(); } this.currentArchiveBytesProcessed = this.currentArchiveTotalBytes; this.OnProgress(ArchiveProgressType.FinishArchive); this.currentArchiveNumber++; this.totalArchives++; this.context.CloseArchiveWriteStream( this.currentArchiveNumber, this.currentArchiveName, stream); this.currentArchiveName = this.NextCabinetName; this.currentArchiveBytesProcessed = this.currentArchiveTotalBytes = 0; this.totalFolderBytesProcessedInCurrentCab = 0; this.CabStream = null; } else // Must be a temp stream { #if CORECLR stream.Dispose(); #else stream.Close(); #endif this.tempStreams.Remove(stream); } return base.CabCloseStreamEx(streamHandle, out err, pv); } /// <summary> /// Disposes of resources allocated by the cabinet engine. /// </summary> /// <param name="disposing">If true, the method has been called directly or indirectly by a user's code, /// so managed and unmanaged resources will be disposed. If false, the method has been called by the /// runtime from inside the finalizer, and only unmanaged resources will be disposed.</param> [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] protected override void Dispose(bool disposing) { try { if (disposing) { if (this.fciHandle != null) { this.fciHandle.Dispose(); this.fciHandle = null; } } } finally { base.Dispose(disposing); } } private static NativeMethods.FCI.TCOMP GetCompressionType(CompressionLevel compLevel) { if (compLevel < CompressionLevel.Min) { return NativeMethods.FCI.TCOMP.TYPE_NONE; } else { if (compLevel > CompressionLevel.Max) { compLevel = CompressionLevel.Max; } int lzxWindowMax = ((int)NativeMethods.FCI.TCOMP.LZX_WINDOW_HI >> (int)NativeMethods.FCI.TCOMP.SHIFT_LZX_WINDOW) - ((int)NativeMethods.FCI.TCOMP.LZX_WINDOW_LO >> (int)NativeMethods.FCI.TCOMP.SHIFT_LZX_WINDOW); int lzxWindow = lzxWindowMax * (compLevel - CompressionLevel.Min) / (CompressionLevel.Max - CompressionLevel.Min); return (NativeMethods.FCI.TCOMP)((int)NativeMethods.FCI.TCOMP.TYPE_LZX | ((int)NativeMethods.FCI.TCOMP.LZX_WINDOW_LO + (lzxWindow << (int)NativeMethods.FCI.TCOMP.SHIFT_LZX_WINDOW))); } } [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] private void AddFile( string name, Stream stream, FileAttributes attributes, DateTime lastWriteTime, bool execute, CompressionLevel compLevel) { this.FileStream = stream; this.fileAttributes = attributes & (FileAttributes.Archive | FileAttributes.Hidden | FileAttributes.ReadOnly | FileAttributes.System); this.fileLastWriteTime = lastWriteTime; this.currentFileName = name; NativeMethods.FCI.TCOMP tcomp = CabPacker.GetCompressionType(compLevel); IntPtr namePtr = IntPtr.Zero; try { Encoding nameEncoding = Encoding.ASCII; if (Encoding.UTF8.GetByteCount(name) > name.Length) { nameEncoding = Encoding.UTF8; this.fileAttributes |= FileAttributes.Normal; // _A_NAME_IS_UTF } byte[] nameBytes = nameEncoding.GetBytes(name); namePtr = Marshal.AllocHGlobal(nameBytes.Length + 1); Marshal.Copy(nameBytes, 0, namePtr, nameBytes.Length); Marshal.WriteByte(namePtr, nameBytes.Length, 0); this.Erf.Clear(); var result = NativeMethods.FCI.AddFile( this.fciHandle, String.Empty, namePtr, execute, this.fciGetNextCabinet, this.fciCreateStatus, this.fciGetOpenInfo, tcomp); if (result == 0) { // Stop compiler from complaining this.CheckError(false); this.FileStream = null; this.currentFileName = null; return; } } finally { if (namePtr != IntPtr.Zero) { Marshal.FreeHGlobal(namePtr); } } this.CheckError(false); this.FileStream = null; this.currentFileName = null; } private void FlushFolder() { this.Erf.Clear(); var result = NativeMethods.FCI.FlushFolder(this.fciHandle, this.fciGetNextCabinet, this.fciCreateStatus); if (result == 0) { // Stop compiler from complaining this.CheckError(false); return; } this.CheckError(false); } private void FlushCabinet() { this.Erf.Clear(); var result = NativeMethods.FCI.FlushCabinet(this.fciHandle, false, this.fciGetNextCabinet, this.fciCreateStatus); if (result == 0) { // Stop compiler from complaining this.CheckError(false); return; } this.CheckError(false); } private int CabGetOpenInfo( string path, out short date, out short time, out short attribs, out int err, IntPtr pv) { CompressionEngine.DateTimeToDosDateAndTime(this.fileLastWriteTime, out date, out time); attribs = (short)this.fileAttributes; Stream stream = this.FileStream; this.FileStream = new DuplicateStream(stream); int streamHandle = this.StreamHandles.AllocHandle(stream); err = 0; return streamHandle; } private int CabFilePlaced( IntPtr pccab, string filePath, long fileSize, int continuation, IntPtr pv) { return 0; } private int CabGetNextCabinet(IntPtr pccab, uint prevCabSize, IntPtr pv) { NativeMethods.FCI.CCAB nextCcab = new NativeMethods.FCI.CCAB(); Marshal.PtrToStructure(pccab, nextCcab); nextCcab.szDisk = String.Empty; nextCcab.szCab = this.context.GetArchiveName(nextCcab.iCab); this.CabNumbers[nextCcab.szCab] = (short)nextCcab.iCab; this.NextCabinetName = nextCcab.szCab; Marshal.StructureToPtr(nextCcab, pccab, false); return 1; } private int CabCreateStatus(NativeMethods.FCI.STATUS typeStatus, uint cb1, uint cb2, IntPtr pv) { switch (typeStatus) { case NativeMethods.FCI.STATUS.FILE: if (cb2 > 0 && this.currentFileBytesProcessed < this.currentFileTotalBytes) { if (this.currentFileBytesProcessed + cb2 > this.currentFileTotalBytes) { cb2 = (uint)this.currentFileTotalBytes - (uint)this.currentFileBytesProcessed; } this.currentFileBytesProcessed += cb2; this.fileBytesProcessed += cb2; this.OnProgress(ArchiveProgressType.PartialFile); } break; case NativeMethods.FCI.STATUS.FOLDER: if (cb1 == 0) { this.currentFolderTotalBytes = cb2 - this.totalFolderBytesProcessedInCurrentCab; this.totalFolderBytesProcessedInCurrentCab = cb2; } else if (this.currentFolderTotalBytes == 0) { this.OnProgress(ArchiveProgressType.PartialArchive); } break; case NativeMethods.FCI.STATUS.CABINET: break; } return 0; } private int CabGetTempFile(IntPtr tempNamePtr, int tempNameSize, IntPtr pv) { string tempFileName; if (this.UseTempFiles) { tempFileName = Path.GetFileName(Path.GetTempFileName()); } else { tempFileName = CabPacker.TempStreamName; } byte[] tempNameBytes = Encoding.ASCII.GetBytes(tempFileName); if (tempNameBytes.Length >= tempNameSize) { return -1; } Marshal.Copy(tempNameBytes, 0, tempNamePtr, tempNameBytes.Length); Marshal.WriteByte(tempNamePtr, tempNameBytes.Length, 0); // null-terminator return 1; } private int CabDeleteFile(string path, out int err, IntPtr pv) { try { // Deleting a temp file - don't bother if it is only a memory stream. if (path != CabPacker.TempStreamName) { path = Path.Combine(Path.GetTempPath(), path); File.Delete(path); } } catch (IOException) { // Failure to delete a temp file is not fatal. } err = 0; return 1; } } }
// Jacqueline Kory Westlund // June 2016 // // The MIT License (MIT) // Copyright (c) 2016 Personal Robots Group // // 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 UnityEngine; using UnityEngine.SceneManagement; using System; using TouchScript.Gestures; using TouchScript.Gestures.TransformGestures; using TouchScript.Behaviors; using TouchScript.Hit; namespace opal { /// <summary> /// Manage gesture events and actions taken as a result of /// gestures (e.g., play sound, show highlight) /// </summary> public class GestureManager : MonoBehaviour { // allow touch? if false, doesn't react to touch events public bool allowTouch = true; // light for highlighting objects private GameObject highlight = null; // main camera private GameObject mainCam = null; // for logging stuff public event LogEventHandler logEvent; // track the most recently dragged game object so we can // check that it stays on the screen in the Update loop private GameObject mostRecentlyDraggedGO = null; // rectangle holds the camera boundaries so we don't have // to re-compute these every time we want to check whether // an object is still within the viewable area private Rect cameraRect; // DEMO VERSION public bool demo = false; private int demospeech = 0; // STORYBOOK VERSION public bool story = false; public int pagesInStory = 0; // Track the current page in the story. We always start at page 1. private int currentPage = 1; // SOCIAL STORIES VERSION public bool socialStories = true; /// <summary> /// Called on start, use to initialize stuff /// </summary> void Start () { // set up light this.highlight = GameObject.FindGameObjectWithTag(Constants.TAG_LIGHT); if(this.highlight != null) { this.LightOff(); Logger.Log("Got light: " + this.highlight.name); } else { Logger.LogError("ERROR: No light found"); } // if in story mode, we need the main camera if (this.story) { // find main camera this.mainCam = GameObject.Find("Main Camera"); if (this.mainCam != null) { Logger.Log ("Got main camera!"); this.mainCam.transform.position = new Vector3(0,0,-1); } else { Logger.LogError("ERROR: Couldn't find main camera!"); } } // get the camera boundaries so we don't have to re-compute these // every time we want to check whether an object is still within // the viewable area Vector3 bottomLeft = Camera.main.ScreenToWorldPoint(Vector3.zero); Vector3 topRight = Camera.main.ScreenToWorldPoint(new Vector3( Camera.main.pixelWidth, Camera.main.pixelHeight)); this.cameraRect = new Rect(bottomLeft.x, bottomLeft.y, topRight.x - bottomLeft.x, topRight.y - bottomLeft.y); } /// <summary> /// On enable, initialize stuff /// </summary> private void OnEnable () { // subscribe to gesture events GameObject[] gos = GameObject.FindGameObjectsWithTag(Constants.TAG_PLAY_OBJECT); foreach(GameObject go in gos) { AddAndSubscribeToGestures(go, true, false); } if (this.demo) { GameObject arrow = GameObject.FindGameObjectWithTag(Constants.TAG_BACK); if (arrow != null) AddAndSubscribeToGestures(arrow, false, false); // also subscribe for the sidekick GameObject sk = GameObject.FindGameObjectWithTag(Constants.TAG_SIDEKICK); // add a tap gesture component if one doesn't exist if (sk != null) { TapGesture tapg = sk.GetComponent<TapGesture>(); if(tapg == null) { tapg = sk.AddComponent<TapGesture>(); } // checking for null anyway in case adding the component didn't work if(tapg != null) { tapg.Tapped += tappedHandler; // subscribe to tap events Logger.Log(sk.name + " subscribed to tap events"); } } else { Logger.Log ("Gesture manager could not find sidekick!"); } } if (this.story) { // subscribe to gestures for next/previous arrows GameObject arrow = GameObject.FindGameObjectWithTag(Constants.TAG_BACK); if (arrow != null) AddAndSubscribeToGestures(arrow, false, false); GameObject arrow2 = GameObject.FindGameObjectWithTag(Constants.TAG_GO_NEXT); if (arrow2 != null) AddAndSubscribeToGestures(arrow2, false, false); } } /// <summary> /// On destroy, disable some stuff /// </summary> private void OnDestroy () { // unsubscribe from gesture events GameObject[] gos = GameObject.FindGameObjectsWithTag(Constants.TAG_PLAY_OBJECT); foreach(GameObject go in gos) { TapGesture tg = go.GetComponent<TapGesture>(); if(tg != null) { tg.Tapped -= tappedHandler; Logger.Log(go.name + " unsubscribed from tap events"); } TransformGesture trg = go.GetComponent<TransformGesture>(); if(trg != null) { trg.Transformed -= transformedHandler; trg.TransformCompleted -= transformCompleteHandler; trg.TransformStarted -= transformStartedHandler; Logger.Log(go.name + " unsubscribed from pan events"); } PressGesture prg = go.GetComponent<PressGesture>(); if(prg != null) { prg.Pressed -= pressedHandler; Logger.Log(go.name + " unsubscribed from press events"); } ReleaseGesture rg = go.GetComponent<ReleaseGesture>(); if(rg != null) { rg.Released -= releasedHandler; Logger.Log(go.name + " unsubscribed from release events"); } FlickGesture fg = go.GetComponent<FlickGesture>(); if(fg != null) { fg.Flicked -= flickHandler; Logger.Log (go.name + " unsubscribed from flick events"); } } //if (this.demo) //{ // also unsubscribe for the sidekick GameObject gob = GameObject.FindGameObjectWithTag(Constants.TAG_SIDEKICK); if (gob != null) { TapGesture tapg = gob.GetComponent<TapGesture>(); if(tapg != null) { tapg.Tapped -= tappedHandler; Logger.Log(gob.name + " unsubscribed from tap events"); } PressGesture prg = gob.GetComponent<PressGesture>(); if(prg != null) { prg.Pressed -= pressedHandler; Logger.Log(gob.name + " unsubscribed from press events"); } ReleaseGesture rg = gob.GetComponent<ReleaseGesture>(); if(rg != null) { rg.Released -= releasedHandler; Logger.Log(gob.name + " unsubscribed from release events"); } } //} } /// <summary> /// Update this instance. /// </summary> public void Update() { // Check whether the most recently moved game object is within the // screen boundaries -- if not, move it so it is. if (this.mostRecentlyDraggedGO != null) { // Send the highlight to the position of the dragged object so it // shows up in the right place. LightOn(1, this.mostRecentlyDraggedGO.transform.position); if (this.mostRecentlyDraggedGO.transform.position.x < this.cameraRect.xMin || this.mostRecentlyDraggedGO.transform.position.x > this.cameraRect.xMax || this.mostRecentlyDraggedGO.transform.position.y < this.cameraRect.yMin || this.mostRecentlyDraggedGO.transform.position.y > this.cameraRect.yMax) { // if the game object is not within the screen boundaries, move // it so that it is Logger.Log(this.mostRecentlyDraggedGO.name + " is going off screen! Keeping it on screen..."); this.mostRecentlyDraggedGO.transform.position = new Vector3( Mathf.Clamp(this.mostRecentlyDraggedGO.transform.position.x, this.cameraRect.xMin, this.cameraRect.xMax), Mathf.Clamp(this.mostRecentlyDraggedGO.transform.position.y, this.cameraRect.yMin, this.cameraRect.yMax), this.mostRecentlyDraggedGO.transform.position.z); } } } /// <summary> /// Subscribes a play object to all relevant gestures - tap, pan, /// press, release /// </summary> /// <param name="go">Game object</param> /// <param name="draggable">If set to <c>true</c> is a draggable object.</param> public void AddAndSubscribeToGestures (GameObject go, bool draggable, bool storypage) { // add a tap gesture component if one doesn't exist TapGesture tg = go.GetComponent<TapGesture>(); if(tg == null) { tg = go.AddComponent<TapGesture>(); } // checking for null anyway in case adding the component didn't work if(tg != null) { tg.Tapped += tappedHandler; // subscribe to tap events Logger.Log(go.name + " subscribed to tap events"); } // if this object is draggable, handle pan events if(draggable) { // add pan gesture component if one doesn't exist yet TransformGesture trg = go.GetComponent<TransformGesture>(); if(trg == null) { trg = go.AddComponent<TransformGesture>(); trg.Type = TransformGesture.TransformType.Translation; } if(trg != null) { trg.TransformStarted += transformStartedHandler; trg.Transformed += transformedHandler; trg.TransformCompleted += transformCompleteHandler; Logger.Log(go.name + " subscribed to drag events"); } // make sure we do have a transformer if we're draggable Transformer tr = go.GetComponent<Transformer>(); if (tr == null) { tr = go.AddComponent<Transformer>(); } } PressGesture prg = go.GetComponent<PressGesture>(); if(prg == null) { prg = go.AddComponent<PressGesture>(); } if(prg != null) { prg.Pressed += pressedHandler; Logger.Log(go.name + " subscribed to press events"); } ReleaseGesture rg = go.GetComponent<ReleaseGesture>(); if(rg == null) { rg = go.AddComponent<ReleaseGesture>(); } if(rg != null) { rg.Released += releasedHandler; Logger.Log(go.name + " subscribed to release events"); } // if this is a story page, handle swipe/flick events if (storypage) { // add flick gesture component if one doesn't exist yet FlickGesture fg = go.GetComponent<FlickGesture>(); if(fg == null) { fg = go.AddComponent<FlickGesture>(); } if(fg != null) { fg.Flicked += flickHandler; fg.AddFriendlyGesture(tg); fg.MinDistance = 0.4f; fg.FlickTime = 0.5f; fg.MovementThreshold = 0.1f; Logger.Log(go.name + " subscribed to flick events"); } } } #region gesture handlers /// <summary> /// Handle all tap events - log them and trigger actions in response /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">E.</param> private void tappedHandler (object sender, EventArgs e) { // get the gesture that was sent to us // this gesture will tell us what object was touched TapGesture gesture = sender as TapGesture; HitData hit = gesture.GetScreenPositionHitData(); // get info about where the hit object was located when the gesture was // recognized - i.e., where on the object (in screen dimensions) did // the tap occur? // want the info as a 2D point Logger.Log("TAP on " + gesture.gameObject.name + " at " + hit.Point); // fire event indicating that we received a message if(this.logEvent != null) { // only send subset of msg that is actual message this.logEvent(this, new LogEvent(LogEvent.EventType.Action, gesture.gameObject.name, "tap", hit.Point)); } // if this is a story, use arrows to go next/back in pages if(this.story && gesture.gameObject.tag.Contains(Constants.TAG_BACK)) { ChangePage(Constants.PREVIOUS); } else if (this.story && gesture.gameObject.tag.Contains(Constants.TAG_GO_NEXT)) { ChangePage(Constants.NEXT); } // if this is the demo app, and if the tap was on the back arrow, // go back to the demo intro scene else if(this.demo && gesture.gameObject.tag.Contains(Constants.TAG_BACK)) { SceneManager.LoadScene(Constants.SCENE_DEMO_INTRO); } // if this is a demo app, play sidekick animation if it is touched else if (this.demo && gesture.gameObject.tag.Contains(Constants.TAG_SIDEKICK)) { // tell the sidekick to animate if (Constants.DEMO_SIDEKICK_SPEECH[this.demospeech].Equals("")) { gesture.gameObject.GetComponent<Sidekick>().SidekickDo(Constants.ANIM_FLAP); } else { gesture.gameObject.GetComponent<Sidekick>().SidekickSay( Constants.DEMO_SIDEKICK_SPEECH[this.demospeech]); } this.demospeech = (this.demospeech + 1) % Constants.DEMO_SIDEKICK_SPEECH.Length; } // trigger sound on tap //Logger.Log("going to play a sound for " + gesture.gameObject.name); //if(this.allowTouch) PlaySoundAndPulse(gesture.gameObject); } /// <summary> /// Handle press events - log and turn on highlight /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">E.</param> private void pressedHandler (object sender, EventArgs e) { // get the gesture that was sent to us, which will tell us // which object was pressed PressGesture gesture = sender as PressGesture; HitData hit = gesture.GetScreenPositionHitData(); // get info about where the hit object was located when the gesture was // recognized - i.e., where on the object (in screen dimensions) did // the press occur? Logger.Log("PRESS on " + gesture.gameObject.name + " at " + hit.Point); // fire event to logger to log this action if(this.logEvent != null) { // if this is a social stories game, log additional info about // what object was pressed if (this.socialStories) { // log the press plus whether or not the pressed object was a YES or NO // button, or whether the object was a CORRECT or INCORRECT object this.logEvent(this, new LogEvent(LogEvent.EventType.Action, gesture.gameObject.name, "press", hit.Point, (gesture.gameObject.name.Contains("start_button") ? "START" : (gesture.gameObject.name.Contains("no_button") ? "NO" // If the game object doesn't have SavedProperties component, don't add // an additional message. Otherwise, log whether it was correct or not. : gesture.gameObject.GetComponent<SavedProperties>() == null ? "" : (gesture.gameObject.GetComponent<SavedProperties>().isCorrect ? "CORRECT" : (gesture.gameObject.GetComponent<SavedProperties>().isIncorrect ? "INCORRECT" : "")))))); } else { // log the press this.logEvent(this, new LogEvent(LogEvent.EventType.Action, gesture.gameObject.name, "press", hit.Point)); } } // move highlighting light and set active // don't highlight touches in a story if(this.allowTouch)// && !this.story) { // Center the light behind the pressed object, regardless of // where on the pressed object the touch was. LightOn(1, gesture.gameObject.transform.position); } // trigger sound on press if(this.allowTouch && gesture.gameObject.tag.Contains(Constants.TAG_PLAY_OBJECT)) { Logger.Log("going to play a sound for " + gesture.gameObject.name); PlaySoundAndPulse(gesture.gameObject); } } /// <summary> /// Handle released events - when object released, stop highlighting object /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">E.</param> private void releasedHandler (object sender, EventArgs e) { Logger.Log("PRESS COMPLETE"); if (this.allowTouch)// && !this.story) { LightOff(); } // fire event indicating that we received a message if(this.logEvent != null) { // only send subset of msg that is actual message this.logEvent(this, new LogEvent(LogEvent.EventType.Action, "", "release", null)); } } /// <summary> /// Handle all pan/drag events - log them, trigger actions in response /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">E.</param> private void transformStartedHandler (object sender, EventArgs e) { // get the gesture that was sent to us, which will tell us // which object was being dragged TransformGesture gesture = sender as TransformGesture; HitData hit = gesture.GetScreenPositionHitData(); // get info about where the hit object was located when the gesture was // recognized - i.e., where on the object (in screen dimensions) did // the drag occur? Logger.Log("DRAG STARTED on " + gesture.gameObject.name + " at " + hit.Point); // move this game object with the drag // note that hit2d.Point sets the z position to 0! does not keep // track what the z position actually was! so we adjust for this when // we check the allowed moves if(this.allowTouch) { // The transformer component moves object on drag events, but we // have to check that the object stays within the screen boundaries. // This happens in the Update loop; here we just save the most // recently dragged object. this.mostRecentlyDraggedGO = gesture.gameObject; // The transformer component moves the object. We just need to // send the light to the object's position - in particular, we // need the right z position so the light shows up in the right // plane. LightOn(1, new Vector3( gesture.gameObject.transform.position.x, gesture.gameObject.transform.position.y, gesture.gameObject.transform.position.z)); } // fire event indicating that we received a message if(this.logEvent != null) { // only send subset of msg that is actual message this.logEvent(this, new LogEvent(LogEvent.EventType.Action, gesture.gameObject.name, "pan", hit.Point)); } } /// <summary> /// Handle all pan/drag events - log them, trigger actions in response /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">E.</param> private void transformedHandler (object sender, EventArgs e) { // get the gesture that was sent to us, which will tell us // which object was being dragged TransformGesture gesture = sender as TransformGesture; HitData hit = gesture.GetScreenPositionHitData(); // get info about where the hit object was located when the gesture was // recognized - i.e., where on the object (in screen dimensions) did // the drag occur? Logger.Log("DRAG on " + gesture.gameObject.name + " at " + hit.Point); // fire event indicating that we received a message if(this.logEvent != null) { // only send subset of msg that is actual message // note that the hit.Point may not have the correct z position this.logEvent(this, new LogEvent(LogEvent.EventType.Action, gesture.gameObject.name, "pan", hit.Point)); } } /// <summary> /// Handle pan complete events - when drag is done, stop highlighting object /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">E.</param> private void transformCompleteHandler (object sender, EventArgs e) { Logger.Log("DRAG COMPLETE"); // Since we use the most recently dragged object's position in the // update loop to move the highlight around, we need to reset it // so we know not to keep the light on. this.mostRecentlyDraggedGO = null; LightOff(); // fire event indicating that an action occurred if(this.logEvent != null) { // only send relevant data this.logEvent(this, new LogEvent(LogEvent.EventType.Action, "", "pancomplete", null)); } } /// <summary> /// Handle flick events /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">E.</param> void flickHandler (object sender, EventArgs e) { // get the gesture that was sent to us, which will tell us // which object was flicked FlickGesture gesture = sender as FlickGesture; HitData hit = gesture.GetScreenPositionHitData(); // get info about where the hit object was located when the gesture was // recognized - i.e., where on the object (in screen dimensions) did // the flick occur? Logger.Log("FLICK on " + gesture.gameObject.name + " at " + hit.Point); // fire event to logger to log this action if(this.logEvent != null) { // log the flick this.logEvent(this, new LogEvent(LogEvent.EventType.Action, gesture.gameObject.name, "flick", hit.Point)); } if(this.allowTouch) { // if flick/swipe was to the right, advance page if (gesture.ScreenFlickVector.x < 0) { ChangePage(Constants.NEXT); } // if to the left, go back a page else if (gesture.ScreenFlickVector.x > 0) { ChangePage(Constants.PREVIOUS); } } // trigger sound on flick as feedback? //if(this.allowTouch && !gesture.gameObject.tag.Contains(Constants.TAG_SIDEKICK)) //{ // Logger.Log("going to play a sound for " + gesture.gameObject.name); // PlaySoundAndPulse(gesture.gameObject); //} } #endregion #region utilities /// <summary> /// Sets light object active in the specified position and with the specified scale /// </summary> /// <param name="posn">Posn.</param> public void LightOn (Vector3 posn) { LightOn(1, posn); } public void LightOn (int scaleBy, Vector3 posn) { if(this.highlight != null && this.highlight.GetComponent<Renderer>() != null) { this.highlight.GetComponent<Renderer>().enabled = true; this.highlight.transform.position = new Vector3(posn.x, posn.y, posn.z + 1); Vector3 sc = this.highlight.transform.localScale; sc.x *= scaleBy; this.highlight.transform.localScale = sc; } else { Logger.Log("Tried to turn light on ... but light is null!"); } } public void LightOn (Vector3 scale, Vector3 posn) { if(this.highlight != null && this.highlight.GetComponent<Renderer>() != null) { this.highlight.GetComponent<Renderer>().enabled = true; this.highlight.transform.position = new Vector3(posn.x, posn.y, posn.z + 1); this.highlight.transform.localScale = scale; } else { Logger.Log("Tried to turn light on ... but light is null!"); } } /// Deactivates light, returns to specified scale public void LightOff () { LightOff(1); } /// <summary> /// Deactivates light, returns to specified scale /// </summary> /// <param name="scaleBy">Scale by.</param> public void LightOff (int scaleBy) { if(this.highlight != null && this.highlight.GetComponent<Renderer>() != null) { Vector3 sc = this.highlight.transform.localScale; sc.x /= scaleBy; this.highlight.transform.localScale = sc; this.highlight.GetComponent<Renderer>().enabled = false; } else { Logger.Log("Tried to turn light off ... but light is null!"); } } /// <summary> /// Changes the page. /// </summary> /// <param name="next">If set to <c>true</c> next page, otherwise, previous page</param> public void ChangePage (bool next) { // if flick/swipe was to the right, advance page if (next) { if (this.mainCam != null) { Logger.Log ("swiping right..."); // don't go past end of story if (this.mainCam.transform.position.z < this.pagesInStory-1) { this.mainCam.transform.Translate(new Vector3(0,0,1)); this.currentPage++; GameObject.FindGameObjectWithTag( Constants.TAG_GO_NEXT).transform.Translate(new Vector3(0,0,1)); GameObject.FindGameObjectWithTag( Constants.TAG_BACK).transform.Translate(new Vector3(0,0,1)); } else // this is the end page, loop back to beginning of story { this.mainCam.transform.position = new Vector3(0,0,-1); this.currentPage = 1; GameObject tb = GameObject.FindGameObjectWithTag(Constants.TAG_BACK); GameObject tn = GameObject.FindGameObjectWithTag(Constants.TAG_GO_NEXT); tb.transform.position = new Vector3(tb.transform.position.x, tb.transform.position.y,0); tn.transform.position = new Vector3(tn.transform.position.x, tn.transform.position.y,0); } } else { Logger.Log ("no main cam! can't change page!"); } } else { if (this.mainCam != null) { Logger.Log("swiping left..."); // don't go before start of story if (this.mainCam.transform.position.z > -1) { this.mainCam.transform.Translate(new Vector3(0,0,-1)); this.currentPage--; GameObject.FindGameObjectWithTag( Constants.TAG_BACK).transform.Translate(new Vector3(0,0,-1)); GameObject.FindGameObjectWithTag( Constants.TAG_GO_NEXT).transform.Translate(new Vector3(0,0,-1)); } } else { Logger.Log ("no main cam! can't change page!"); } } } /// <summary> /// Go to the specified page in a storybook. /// </summary> /// <param name="page">Page.</param> public void GoToPage(int page) { Logger.Log("The current page is " + this.currentPage + " and we need to go to " + page + "."); if (page == this.currentPage) return; // If the page we need to get to is before the current page, go // back until we get there. while (page < this.currentPage) { Logger.Log("Going back to find the right page..."); this.ChangePage(Constants.PREVIOUS); } // If the page we need to get to is after the current page, go // forward until we get there. while (page > this.currentPage) { Logger.Log("Going forward to find the right page..."); this.ChangePage(Constants.NEXT); } } /// <summary> /// Plays the first sound attached to the object, if one exists /// </summary> /// <returns><c>true</c>, if sound was played, <c>false</c> otherwise.</returns> /// <param name="go">Game object with sound to play.</param> private bool PlaySound (GameObject go) { // play audio clip if this game object has a clip to play AudioSource auds = go.GetComponent<AudioSource>(); if(auds != null && auds.clip != null) { Logger.Log("playing clip for object " + go.name); // play the audio clip attached to the game object if(!go.GetComponent<AudioSource>().isPlaying) go.GetComponent<AudioSource>().Play(); return true; } else { Logger.Log("no sound found for " + go.name + "!"); return false; } } /// <summary> /// Plays the first sound attached to an object, if one exists, while /// also pulsing the object's size (to draw attention to it) /// </summary> /// <param name="go">Go.</param> private void PlaySoundAndPulse (GameObject go) { if(go != null) { // play a sound, if it exists and is not already playing // and also pulse size if(PlaySound(go) && (go.GetComponent<AudioSource>() != null) && !go.GetComponent<AudioSource>().isPlaying) go.GetComponent<GrowShrinkBehavior>().ScaleUpOnce(); } } #endregion } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure.Management.BackupServices; using Microsoft.Azure.Management.BackupServices.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.BackupServices { /// <summary> /// Definition of Workflow operation for the Azure Backup extension. /// </summary> internal partial class OperationStatus : IServiceOperations<BackupServicesManagementClient>, IOperationStatus { /// <summary> /// Initializes a new instance of the OperationStatus class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal OperationStatus(BackupServicesManagementClient client) { this._client = client; } private BackupServicesManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.BackupServices.BackupServicesManagementClient. /// </summary> public BackupServicesManagementClient Client { get { return this._client; } } /// <summary> /// Get the Operation Status. /// </summary> /// <param name='resourceGroupName'> /// Required. /// </param> /// <param name='resourceName'> /// Required. /// </param> /// <param name='operationId'> /// Required. OperationId. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The definition of a CSMOperationResult. /// </returns> public async Task<CSMOperationResult> CSMGetAsync(string resourceGroupName, string resourceName, string operationId, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } if (operationId == null) { throw new ArgumentNullException("operationId"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("resourceName", resourceName); tracingParameters.Add("operationId", operationId); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "CSMGetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Backup"; url = url + "/"; url = url + "BackupVault"; url = url + "/"; url = url + Uri.EscapeDataString(resourceName); url = url + "/operationResults/"; url = url + Uri.EscapeDataString(operationId); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-09-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept-Language", "en-us"); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result CSMOperationResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new CSMOperationResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken statusValue = responseDoc["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { string statusInstance = ((string)statusValue); result.Status = statusInstance; } JToken errorValue = responseDoc["error"]; if (errorValue != null && errorValue.Type != JTokenType.Null) { CSMOperationErrorInfo errorInstance = new CSMOperationErrorInfo(); result.Error = errorInstance; JToken codeValue = errorValue["code"]; if (codeValue != null && codeValue.Type != JTokenType.Null) { string codeInstance = ((string)codeValue); errorInstance.Code = codeInstance; } JToken messageValue = errorValue["message"]; if (messageValue != null && messageValue.Type != JTokenType.Null) { string messageInstance = ((string)messageValue); errorInstance.Message = messageInstance; } } JToken jobListArray = responseDoc["jobList"]; if (jobListArray != null && jobListArray.Type != JTokenType.Null) { foreach (JToken jobListValue in ((JArray)jobListArray)) { result.JobList.Add(((string)jobListValue)); } } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
namespace Humidifier.ElastiCache { using System.Collections.Generic; using ReplicationGroupTypes; public class ReplicationGroup : Humidifier.Resource { public static class Attributes { } public override string AWSTypeName { get { return @"AWS::ElastiCache::ReplicationGroup"; } } /// <summary> /// AtRestEncryptionEnabled /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-atrestencryptionenabled /// Required: False /// UpdateType: Immutable /// PrimitiveType: Boolean /// </summary> public dynamic AtRestEncryptionEnabled { get; set; } /// <summary> /// AuthToken /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-authtoken /// Required: False /// UpdateType: Conditional /// PrimitiveType: String /// </summary> public dynamic AuthToken { get; set; } /// <summary> /// AutoMinorVersionUpgrade /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-autominorversionupgrade /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic AutoMinorVersionUpgrade { get; set; } /// <summary> /// AutomaticFailoverEnabled /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-automaticfailoverenabled /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic AutomaticFailoverEnabled { get; set; } /// <summary> /// CacheNodeType /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-cachenodetype /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic CacheNodeType { get; set; } /// <summary> /// CacheParameterGroupName /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-cacheparametergroupname /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic CacheParameterGroupName { get; set; } /// <summary> /// CacheSecurityGroupNames /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-cachesecuritygroupnames /// Required: False /// UpdateType: Mutable /// Type: List /// PrimitiveItemType: String /// </summary> public dynamic CacheSecurityGroupNames { get; set; } /// <summary> /// CacheSubnetGroupName /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-cachesubnetgroupname /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic CacheSubnetGroupName { get; set; } /// <summary> /// Engine /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-engine /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic Engine { get; set; } /// <summary> /// EngineVersion /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-engineversion /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic EngineVersion { get; set; } /// <summary> /// KmsKeyId /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-kmskeyid /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic KmsKeyId { get; set; } /// <summary> /// NodeGroupConfiguration /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-nodegroupconfiguration /// Required: False /// UpdateType: Conditional /// Type: List /// ItemType: NodeGroupConfiguration /// </summary> public List<NodeGroupConfiguration> NodeGroupConfiguration { get; set; } /// <summary> /// NotificationTopicArn /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-notificationtopicarn /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic NotificationTopicArn { get; set; } /// <summary> /// NumCacheClusters /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-numcacheclusters /// Required: False /// UpdateType: Mutable /// PrimitiveType: Integer /// </summary> public dynamic NumCacheClusters { get; set; } /// <summary> /// NumNodeGroups /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-numnodegroups /// Required: False /// UpdateType: Conditional /// PrimitiveType: Integer /// </summary> public dynamic NumNodeGroups { get; set; } /// <summary> /// Port /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-port /// Required: False /// UpdateType: Immutable /// PrimitiveType: Integer /// </summary> public dynamic Port { get; set; } /// <summary> /// PreferredCacheClusterAZs /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-preferredcacheclusterazs /// Required: False /// UpdateType: Immutable /// Type: List /// PrimitiveItemType: String /// </summary> public dynamic PreferredCacheClusterAZs { get; set; } /// <summary> /// PreferredMaintenanceWindow /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-preferredmaintenancewindow /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic PreferredMaintenanceWindow { get; set; } /// <summary> /// PrimaryClusterId /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-primaryclusterid /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic PrimaryClusterId { get; set; } /// <summary> /// ReplicasPerNodeGroup /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-replicaspernodegroup /// Required: False /// UpdateType: Immutable /// PrimitiveType: Integer /// </summary> public dynamic ReplicasPerNodeGroup { get; set; } /// <summary> /// ReplicationGroupDescription /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-replicationgroupdescription /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic ReplicationGroupDescription { get; set; } /// <summary> /// ReplicationGroupId /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-replicationgroupid /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic ReplicationGroupId { get; set; } /// <summary> /// SecurityGroupIds /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-securitygroupids /// Required: False /// UpdateType: Mutable /// Type: List /// PrimitiveItemType: String /// </summary> public dynamic SecurityGroupIds { get; set; } /// <summary> /// SnapshotArns /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-snapshotarns /// Required: False /// UpdateType: Immutable /// Type: List /// PrimitiveItemType: String /// </summary> public dynamic SnapshotArns { get; set; } /// <summary> /// SnapshotName /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-snapshotname /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic SnapshotName { get; set; } /// <summary> /// SnapshotRetentionLimit /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-snapshotretentionlimit /// Required: False /// UpdateType: Mutable /// PrimitiveType: Integer /// </summary> public dynamic SnapshotRetentionLimit { get; set; } /// <summary> /// SnapshotWindow /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-snapshotwindow /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic SnapshotWindow { get; set; } /// <summary> /// SnapshottingClusterId /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-snapshottingclusterid /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic SnapshottingClusterId { get; set; } /// <summary> /// Tags /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-tags /// Required: False /// UpdateType: Mutable /// Type: List /// ItemType: Tag /// </summary> public List<Tag> Tags { get; set; } /// <summary> /// TransitEncryptionEnabled /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-transitencryptionenabled /// Required: False /// UpdateType: Immutable /// PrimitiveType: Boolean /// </summary> public dynamic TransitEncryptionEnabled { get; set; } } namespace ReplicationGroupTypes { public class NodeGroupConfiguration { /// <summary> /// NodeGroupId /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-replicationgroup-nodegroupconfiguration.html#cfn-elasticache-replicationgroup-nodegroupconfiguration-nodegroupid /// Required: False /// UpdateType: Conditional /// PrimitiveType: String /// </summary> public dynamic NodeGroupId { get; set; } /// <summary> /// PrimaryAvailabilityZone /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-replicationgroup-nodegroupconfiguration.html#cfn-elasticache-replicationgroup-nodegroupconfiguration-primaryavailabilityzone /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic PrimaryAvailabilityZone { get; set; } /// <summary> /// ReplicaAvailabilityZones /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-replicationgroup-nodegroupconfiguration.html#cfn-elasticache-replicationgroup-nodegroupconfiguration-replicaavailabilityzones /// Required: False /// UpdateType: Immutable /// Type: List /// PrimitiveItemType: String /// </summary> public dynamic ReplicaAvailabilityZones { get; set; } /// <summary> /// ReplicaCount /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-replicationgroup-nodegroupconfiguration.html#cfn-elasticache-replicationgroup-nodegroupconfiguration-replicacount /// Required: False /// UpdateType: Immutable /// PrimitiveType: Integer /// </summary> public dynamic ReplicaCount { get; set; } /// <summary> /// Slots /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-replicationgroup-nodegroupconfiguration.html#cfn-elasticache-replicationgroup-nodegroupconfiguration-slots /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic Slots { 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. using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Reflection; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices.WindowsRuntime; namespace System.Runtime.InteropServices { // Shared CCW Design (fyuan, 6/26/2013) // Normal CCW is implemented by constructing a native virtual function table with specific functions for each interface using MCG generated code. // For each CCW interface, there is a native class e.g. internal unsafe partial struct __vtable_Windows_ApplicationModel_Resources_Core__IResourceContext // Static field s_theCcwVtable constructs the virtual function table, whose address is stored in McgInterfaceData.CcwVtable field. // Each function within vtable is marked as [NativeCallable]. It has marsalling code and exception handling to set COM HRESULT. // During runtime __interface_ccw.Allocate allocates a small piece of native memory and constructs the real CCW callable by native code // Shared CCW is supported on generic interfaces, sharable across multiple instances of supported interfaces. // For example SharedCcw_IVector supports all IVector<T> CCW where T is a reference type using a single copy of code. // But to support individual element types, we need extra information about each element type and a thunk function to call real methods on interface instantiations. // Information about element type is encoded in McgGenericArgumentMarshalInfo struct per element type. McgInterfaceData has an added index MarshalIndex indexing into the table. // When constructing __inteface_ccw, an extra field m_pInterface is added to point back to McgInterfaceData, from which we can get McgGenericArgumentMarshalInfo. // Each CCW interface supported by shared CCW has a thunk function which is normally an instance of a generic function. The function is set use the SetThunk function generated by MCG // From a native CCW pointer, ComCallableObject.GetThunk functions returns target object, marshal index, and thunk function. // Shared CCW code can use marshal index to marshal objects between native and managed worlds, and use thunk function to invoke functions on corresponding managed code. // It also handles semantics of wrapper classes like ListToVectorAdapter for argument checking and exception -> HRESULT translation // Here is a example: // 1) SharedCCW_IVector supports IVector<T> where T is reference type // 2) Its thunk function is int IListThunk<T>(IList<T> list, IList_Oper oper, int index, ref object item). // 3) Thunk function handles 9 basic operations on IList<T>: GetCount, GetItem, IndexOf, SetItem, Insert, RemoveAt, Add, Clear, and ToReadOnly // 4) Functions in SharedCCW_IVector handles [NativeCallable] protocol, getting thunk information, marshalling, invoking thunk function, and exception handling. // 5) For a particular element type, say string, IListThunk<string> dispatches to basic operations on IList<string>. // 6) Due to generic code sharing, there is a real implementation of IListThunk<Canon> and IListThunk<string> just calls it with the right 'Generic Dictionary' /* Code generated by MCG for 4 shared CCW instances: IEnumerable<string> (IIterable), IIterator<T>, IList<T>(IVector), and IReadOnlyList<T>(IVectorView) SetThunk(35, AddrOfIntrinsics.AddrOf(Toolbox.IEnumerableThunk<string>)); SetThunk(36, AddrOfIntrinsics.AddrOf(Toolbox.IIteratorThunk<string>)); SetThunk(69, AddrOfIntrinsics.AddrOf(System.Runtime.InteropServices.Toolbox.IListThunk<string>)); SetThunk(70, AddrOfIntrinsics.AddrOf(System.Runtime.InteropServices.Toolbox.IReadOnlyListThunk<string>)); new McgGenericArgumentMarshalInfo() { // index: 2, 'string' => 'HSTRING $' ElementClassIndex = -1, ElementInterfaceIndex = s_McgTypeInfoIndex___com_HSTRING, VectorViewIndex = s_McgTypeInfoIndex___com_Windows_Foundation_Collections__IVectorView_A_string_V_, IteratorIndex = s_McgTypeInfoIndex___com_Windows_Foundation_Collections__IIterator_A_string_V_, }, new McgInterfaceData() { ... // index: 35, System.Collections.Generic.IEnumerable<string> MarshalIndex = 2, Flags = McgInterfaceFlags.isIInspectable | McgInterfaceFlags.useSharedCCW_IIterable, }, new McgInterfaceData() { ... // index: 36, Windows.Foundation.Collections.IIterator<string> MarshalIndex = 2, Flags = McgInterfaceFlags.isIInspectable | McgInterfaceFlags.useSharedCCW_IIterator, }, new McgInterfaceData() { ... // index: 69, System.Collections.Generic.IList<string> MarshalIndex = 2, Flags = McgInterfaceFlags.isIInspectable | McgInterfaceFlags.useSharedCCW_IVector, }, new McgInterfaceData() { ... // index: 70, System.Collections.Generic.IReadOnlyList<string> MarshalIndex = 2, Flags = McgInterfaceFlags.isIInspectable | McgInterfaceFlags.useSharedCCW_IVectorView, }, */ public static partial class Toolbox { // Basic operations on IList/IReadOnlyList to support IVector/IVectorView public enum IList_Oper { GetCount, GetItem, IndexOf, SetItem, Insert, RemoveAt, Add, Clear, ToReadOnly }; /// <summary> /// Static thunk function for calling methods on IList<T> /// </summary> public static int IListThunk<T>(IList<T> list, IList_Oper oper, int index, ref object item) where T : class { int result = 0; switch (oper) { case IList_Oper.GetCount: result = list.Count; break; case IList_Oper.GetItem: item = list[index]; break; case IList_Oper.IndexOf: result = list.IndexOf(InteropExtensions.UncheckedCast<T>(item)); break; case IList_Oper.SetItem: list[index] = InteropExtensions.UncheckedCast<T>(item); break; case IList_Oper.Insert: list.Insert(index, InteropExtensions.UncheckedCast<T>(item)); break; case IList_Oper.RemoveAt: list.RemoveAt(index); break; case IList_Oper.Add: list.Add(InteropExtensions.UncheckedCast<T>(item)); break; case IList_Oper.Clear: list.Clear(); break; case IList_Oper.ToReadOnly: { IReadOnlyList<T> view; // Note: This list is not really read-only - you could QI for a modifiable // list. We gain some perf by doing this. We believe this is acceptable. view = list as IReadOnlyList<T>; if (view == null) { view = new System.Collections.ObjectModel.ReadOnlyCollection<T>(list); } item = view; // return via item } break; default: Debug.Fail("IListThunk wrong oper"); break; } return result; } /// <summary> /// Static thunk function for calling methods on IList<T> /// </summary> public static object IListBlittableThunk<T>(IList<T> list, IList_Oper oper, ref int index, ref T item) where T : struct { object result = null; switch (oper) { case IList_Oper.GetCount: index = list.Count; break; case IList_Oper.GetItem: item = list[index]; break; case IList_Oper.IndexOf: index = list.IndexOf(item); break; case IList_Oper.SetItem: list[index] = item; break; case IList_Oper.Insert: list.Insert(index, item); break; case IList_Oper.RemoveAt: list.RemoveAt(index); break; case IList_Oper.Add: list.Add(item); break; case IList_Oper.Clear: list.Clear(); break; case IList_Oper.ToReadOnly: { // Note: This list is not really read-only - you could QI for a modifiable // list. We gain some perf by doing this. We believe this is acceptable. result = list as IReadOnlyList<T>; if (result == null) { result = new System.Collections.ObjectModel.ReadOnlyCollection<T>(list); } } break; default: Debug.Fail("IListBlittableThunk wrong oper"); break; } return result; } internal static bool EnsureIndexInt32(uint index, uint listCapacity, ref int hr) { // We use '<=' and not '<' becasue Int32.MaxValue == index would imply // that Size > Int32.MaxValue: if (((uint)System.Int32.MaxValue) <= index || index >= listCapacity) { hr = Interop.COM.E_BOUNDS; return false; } return true; } /// <summary> /// Static thunk function for calling methods on IReadOnlyList<T> /// </summary> public static int IReadOnlyListThunk<T>(IReadOnlyList<T> list, IList_Oper oper, int index, ref T item) where T : class { int result = 0; switch (oper) { case IList_Oper.GetCount: result = list.Count; break; case IList_Oper.GetItem: item = list[index]; break; case IList_Oper.IndexOf: { result = -1; index = list.Count; for (int i = 0; i < index; i++) { if (InteropExtensions.ComparerEquals<T>(item, list[i])) { result = i; break; } } } break; default: Debug.Fail("IReadOnlyListThunk wrong oper"); break; } return result; } /// <summary> /// Static thunk function for calling methods on IReadOnlyList<T> /// </summary> public static object IReadOnlyListBlittableThunk<T>(IReadOnlyList<T> list, IList_Oper oper, ref int index, ref T item) where T : struct { object result = null; switch (oper) { case IList_Oper.GetCount: index = list.Count; break; case IList_Oper.GetItem: item = list[index]; break; case IList_Oper.IndexOf: { index = -1; int count = list.Count; for (int i = 0; i < count; i++) { if (InteropExtensions.ComparerEquals<T>(item, list[i])) { index = i; break; } } } break; default: Debug.Fail("IReadOnlyListThunk wrong oper"); break; } return result; } } #if ENABLE_MIN_WINRT /// <summary> /// Shared CCW for IVector<T> over IList<T> where T is a reference type marshalled to COM interface /// </summary> internal unsafe struct SharedCcw_IVector { public System.IntPtr pfnQueryInterface; public System.IntPtr pfnAddRef; public System.IntPtr pfnRelease; public System.IntPtr pfnGetIids; public System.IntPtr pfnGetRuntimeClassName; public System.IntPtr pfnGetTrustLevel; public System.IntPtr pfnGetAt; public System.IntPtr pfnget_Size; public System.IntPtr pfnGetView; public System.IntPtr pfnIndexOf; public System.IntPtr pfnSetAt; public System.IntPtr pfnInsertAt; public System.IntPtr pfnRemoveAt; public System.IntPtr pfnAppend; public System.IntPtr pfnRemoveAtEnd; public System.IntPtr pfnClear; public System.IntPtr pfnGetMany; public System.IntPtr pfnReplaceAll; [PreInitialized] static SharedCcw_IVector s_theCcwVtable = new SharedCcw_IVector() { pfnQueryInterface = AddrOfIntrinsics.AddrOf<AddrOfQueryInterface>(__vtable_IUnknown.QueryInterface), pfnAddRef = AddrOfIntrinsics.AddrOf<AddrOfAddRef>(__vtable_IUnknown.AddRef), pfnRelease = AddrOfIntrinsics.AddrOf<AddrOfRelease>(__vtable_IUnknown.Release), pfnGetIids = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfGetIID>(__vtable_IInspectable.GetIIDs), pfnGetRuntimeClassName = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget3>(__vtable_IInspectable.GetRuntimeClassName), pfnGetTrustLevel = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget3>(__vtable_IInspectable.GetTrustLevel), pfnGetAt = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfGetSetInsertReplaceAll>(GetAt), pfnget_Size = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget3>(get_Size), pfnGetView = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget3>(GetView), pfnIndexOf = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfIndexOf>(IndexOf), pfnSetAt = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfGetSetInsertReplaceAll>(SetAt), pfnInsertAt = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfGetSetInsertReplaceAll>(InsertAt), pfnRemoveAt = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfRemoveAt>(RemoveAt), pfnAppend = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget3>(Append), pfnRemoveAtEnd = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget1>(RemoveAtEnd), pfnClear = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget1>(Clear), pfnGetMany = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfGetMany1>(GetMany), pfnReplaceAll = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfGetSetInsertReplaceAll>(ReplaceAll), }; public static System.IntPtr GetVtable() { return AddrOfIntrinsics.StaticFieldAddr(ref s_theCcwVtable); } [NativeCallable] internal static unsafe int GetAt(IntPtr pComThis, uint index, IntPtr pItem) { int hr = Interop.COM.S_OK; try { // Get Target Object object list = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); object item = null; CalliIntrinsics.Call<int>(thunk, list, Toolbox.IList_Oper.GetItem, (int)index, ref item); *((IntPtr*)pItem) = McgMarshal.ObjectToComInterface(item, interfaceType.GetElementInterfaceType()); } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); if (hrExcep is ArgumentOutOfRangeException) { hr = Interop.COM.E_BOUNDS; } } return hr; } [NativeCallable] internal static unsafe int get_Size(System.IntPtr pComThis, System.IntPtr pSize) { int hr = Interop.COM.S_OK; try { // Get Target Object object list = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); object dummy = null; *((uint*)pSize) = (uint)CalliIntrinsics.Call<int>(thunk, list, Toolbox.IList_Oper.GetCount, 0, ref dummy); } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } return hr; } [NativeCallable] static unsafe int GetView(System.IntPtr pComThis, System.IntPtr pView) { int hr = Interop.COM.S_OK; try { // Get Target Object object list = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); object view = null; CalliIntrinsics.Call<int>(thunk, list, Toolbox.IList_Oper.ToReadOnly, 0, ref view); *((IntPtr*)pView) = McgMarshal.ObjectToComInterface(view, interfaceType.GetVectorViewType()); } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } return hr; } [NativeCallable] internal static unsafe int IndexOf(System.IntPtr pComThis, System.IntPtr _value, System.IntPtr pIndex, System.IntPtr pFound) { int hr = Interop.COM.S_OK; try { // Get Target Object object list = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); object value = McgMarshal.ComInterfaceToObject(_value, interfaceType.GetElementInterfaceType(), interfaceType.GetElementClassType()); int index = CalliIntrinsics.Call<int>(thunk, list, Toolbox.IList_Oper.IndexOf, 0, ref value); if (index >= 0) { *((byte*)pFound) = 1; } else { *((byte*)pFound) = 0; index = 0; } *((int*)pIndex) = index; } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } return hr; } [NativeCallable] static unsafe int SetAt(System.IntPtr pComThis, uint index, IntPtr _value) { int hr = Interop.COM.S_OK; try { // Get Target Object object list = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); object value = null; uint listCount = (uint)CalliIntrinsics.Call<int>(thunk, list, Toolbox.IList_Oper.GetCount, 0, ref value); if (Toolbox.EnsureIndexInt32(index, listCount, ref hr)) { value = McgMarshal.ComInterfaceToObject(_value, interfaceType.GetElementInterfaceType(), interfaceType.GetElementClassType()); CalliIntrinsics.Call<int>(thunk, list, Toolbox.IList_Oper.SetItem, (int)index, ref value); } } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); if (hrExcep is ArgumentOutOfRangeException) { hr = Interop.COM.E_BOUNDS; } } return hr; } [NativeCallable] static unsafe int InsertAt(System.IntPtr pComThis, uint index, IntPtr _value) { int hr = Interop.COM.S_OK; try { // Get Target Object object list = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); object value = null; uint listCount = (uint)CalliIntrinsics.Call<int>(thunk, list, Toolbox.IList_Oper.GetCount, 0, ref value); // Inserting at an index one past the end of the list is equivalent to appending // so we need to ensure that we're within (0, count + 1). if (Toolbox.EnsureIndexInt32(index, listCount + 1, ref hr)) { value = McgMarshal.ComInterfaceToObject(_value, interfaceType.GetElementInterfaceType(), interfaceType.GetElementClassType()); CalliIntrinsics.Call<int>(thunk, list, Toolbox.IList_Oper.Insert, (int)index, ref value); } } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); if (hrExcep is ArgumentOutOfRangeException) { hr = Interop.COM.E_BOUNDS; } } return hr; } [NativeCallable] static unsafe int RemoveAt(System.IntPtr pComThis, uint index) { int hr = Interop.COM.S_OK; try { // Get Target Object object list = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); object dummy = null; uint listCount = (uint)CalliIntrinsics.Call<int>(thunk, list, Toolbox.IList_Oper.GetCount, 0, ref dummy); if (Toolbox.EnsureIndexInt32(index, listCount, ref hr)) { CalliIntrinsics.Call<int>(thunk, list, Toolbox.IList_Oper.RemoveAt, (int)index, ref dummy); } } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); if (hrExcep is ArgumentOutOfRangeException) { hr = Interop.COM.E_BOUNDS; } } return hr; } [NativeCallable] static unsafe int Append(System.IntPtr pComThis, IntPtr _value) { int hr = Interop.COM.S_OK; try { // Get Target Object object list = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); object value = McgMarshal.ComInterfaceToObject(_value, interfaceType.GetElementInterfaceType(), interfaceType.GetElementClassType()); CalliIntrinsics.Call<int>(thunk, list, Toolbox.IList_Oper.Add, 0, ref value); } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } return hr; } [NativeCallable] static unsafe int RemoveAtEnd(System.IntPtr pComThis) { int hr = Interop.COM.S_OK; try { // Get Target Object object list = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); object dummy = null; uint listCount = (uint)CalliIntrinsics.Call<int>(thunk, list, Toolbox.IList_Oper.GetCount, 0, ref dummy); if (listCount == 0) { hr = Interop.COM.E_BOUNDS; } else { CalliIntrinsics.Call<int>(thunk, list, Toolbox.IList_Oper.RemoveAt, (int)(listCount - 1), ref dummy); } } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); if (hrExcep is ArgumentOutOfRangeException) { hr = Interop.COM.E_BOUNDS; } } return hr; } [NativeCallable] static unsafe int Clear(System.IntPtr pComThis) { int hr = Interop.COM.S_OK; try { // Get Target Object object list = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); object dummy = null; CalliIntrinsics.Call<int>(thunk, list, Toolbox.IList_Oper.Clear, 0, ref dummy); } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } return hr; } [NativeCallable] internal static unsafe int GetMany(System.IntPtr pComThis, uint startIndex, uint len, System.IntPtr pDest, System.IntPtr pCount) { int hr = Interop.COM.S_OK; try { // Get Target Object object list = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); object value = null; uint listCount = (uint)CalliIntrinsics.Call<int>(thunk, list, Toolbox.IList_Oper.GetCount, 0, ref value); uint itemCount = 0; if ((startIndex != listCount) && Toolbox.EnsureIndexInt32(startIndex, listCount, ref hr)) { itemCount = System.Math.Min(len, listCount - startIndex); System.IntPtr* dst = (System.IntPtr*)pDest; // Convert to COM interfaces, without allocating array uint i = 0; while (i < itemCount) { CalliIntrinsics.Call<int>(thunk, list, Toolbox.IList_Oper.GetItem, (int)(i + startIndex), ref value); dst[i] = McgMarshal.ObjectToComInterface(value, interfaceType.GetElementInterfaceType()); i++; } // Fill the remaining with default value while (i < len) { dst[i++] = default(IntPtr); } } *((uint*)pCount) = itemCount; } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } return hr; } [NativeCallable] static unsafe int ReplaceAll(System.IntPtr pComThis, uint length, IntPtr pItems) { int hr = Interop.COM.S_OK; try { // Get Target Object object list = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); System.IntPtr* src = (System.IntPtr*)pItems; object value = null; CalliIntrinsics.Call<int>(thunk, list, Toolbox.IList_Oper.Clear, 0, ref value); for (uint i = 0; i < length; i++) { value = McgMarshal.ComInterfaceToObject(src[i], interfaceType.GetElementInterfaceType(), interfaceType.GetElementClassType()); CalliIntrinsics.Call<int>(thunk, list, Toolbox.IList_Oper.Add, 0, ref value); } } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } return hr; } } /// <summary> /// Shared CCW for IVector<T> over IList<T> where T is a blittable struct /// </summary> internal unsafe struct SharedCcw_IVector_Blittable { public System.IntPtr pfnQueryInterface; public System.IntPtr pfnAddRef; public System.IntPtr pfnRelease; public System.IntPtr pfnGetIids; public System.IntPtr pfnGetRuntimeClassName; public System.IntPtr pfnGetTrustLevel; public System.IntPtr pfnGetAt; public System.IntPtr pfnget_Size; public System.IntPtr pfnGetView; public System.IntPtr pfnIndexOf; public System.IntPtr pfnSetAt; public System.IntPtr pfnInsertAt; public System.IntPtr pfnRemoveAt; public System.IntPtr pfnAppend; public System.IntPtr pfnRemoveAtEnd; public System.IntPtr pfnClear; public System.IntPtr pfnGetMany; public System.IntPtr pfnReplaceAll; [PreInitialized] static SharedCcw_IVector_Blittable s_theCcwVtable = new SharedCcw_IVector_Blittable() { pfnQueryInterface = AddrOfIntrinsics.AddrOf<AddrOfQueryInterface>(__vtable_IUnknown.QueryInterface), pfnAddRef = AddrOfIntrinsics.AddrOf<AddrOfAddRef>(__vtable_IUnknown.AddRef), pfnRelease = AddrOfIntrinsics.AddrOf<AddrOfRelease>(__vtable_IUnknown.Release), pfnGetIids = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfGetIID>(__vtable_IInspectable.GetIIDs), pfnGetRuntimeClassName = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget3>(__vtable_IInspectable.GetRuntimeClassName), pfnGetTrustLevel = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget3>(__vtable_IInspectable.GetTrustLevel), pfnGetAt = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfGetSetInsertReplaceAll>(GetAt), pfnget_Size = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget3>(get_Size), pfnGetView = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget3>(GetView), pfnIndexOf = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfIndexOf>(IndexOf), pfnSetAt = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfGetSetInsertReplaceAll>(SetAt), pfnInsertAt = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfGetSetInsertReplaceAll>(InsertAt), pfnRemoveAt = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfRemoveAt>(RemoveAt), pfnAppend = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget3>(Append), pfnRemoveAtEnd = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget1>(RemoveAtEnd), pfnClear = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget1>(Clear), pfnGetMany = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfGetMany1>(GetMany), pfnReplaceAll = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfGetSetInsertReplaceAll>(ReplaceAll), }; public static System.IntPtr GetVtable() { return AddrOfIntrinsics.StaticFieldAddr(ref s_theCcwVtable); } [NativeCallable] internal static unsafe int GetAt(IntPtr pComThis, uint _index, IntPtr pItem) { int hr = Interop.COM.S_OK; try { // Get IList object object list = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); int index = (int)_index; CalliIntrinsics.Call<object>(thunk, list, Toolbox.IList_Oper.GetItem, ref index, pItem); } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); if (hrExcep is ArgumentOutOfRangeException) { hr = Interop.COM.E_BOUNDS; } } return hr; } [NativeCallable] internal static unsafe int get_Size(System.IntPtr pComThis, System.IntPtr pSize) { int hr = Interop.COM.S_OK; try { // Get IList object object list = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); int size = 0; CalliIntrinsics.Call<object>(thunk, list, Toolbox.IList_Oper.GetCount, ref size, default(IntPtr)); *((uint*)pSize) = (uint)size; } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } return hr; } [NativeCallable] static unsafe int GetView(System.IntPtr pComThis, System.IntPtr pView) { int hr = Interop.COM.S_OK; try { // Get IList object object list = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); int dummy = 0; object view = CalliIntrinsics.Call<object>(thunk, list, Toolbox.IList_Oper.ToReadOnly, ref dummy, default(IntPtr)); *((IntPtr*)pView) = McgMarshal.ObjectToComInterface(view, interfaceType.GetVectorViewType()); } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } return hr; } [NativeCallable] internal static unsafe int IndexOf(System.IntPtr pComThis, System.IntPtr _value, System.IntPtr pIndex, System.IntPtr pFound) { int hr = Interop.COM.S_OK; try { // Get IList object object list = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); int index = 0; CalliIntrinsics.Call<object>(thunk, list, Toolbox.IList_Oper.IndexOf, ref index, (IntPtr)(&_value)); if (index >= 0) { *((byte*)pFound) = 1; } else { *((byte*)pFound) = 0; index = 0; } *((int*)pIndex) = index; } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } return hr; } [NativeCallable] static unsafe int SetAt(System.IntPtr pComThis, uint _index, IntPtr _value) { int hr = Interop.COM.S_OK; try { // Get IList object object list = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); int index = (int)_index; CalliIntrinsics.Call<object>(thunk, list, Toolbox.IList_Oper.SetItem, ref index, (IntPtr)(&_value)); } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); if (hrExcep is ArgumentOutOfRangeException) { hr = Interop.COM.E_BOUNDS; } } return hr; } [NativeCallable] static unsafe int InsertAt(System.IntPtr pComThis, uint _index, IntPtr _value) { int hr = Interop.COM.S_OK; try { // Get IList object object list = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); int index = (int)_index; CalliIntrinsics.Call<object>(thunk, list, Toolbox.IList_Oper.Insert, ref index, (IntPtr)(&_value)); } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); if (hrExcep is ArgumentOutOfRangeException) { hr = Interop.COM.E_BOUNDS; } } return hr; } [NativeCallable] static unsafe int RemoveAt(System.IntPtr pComThis, uint _index) { int hr = Interop.COM.S_OK; try { // Get IList object object list = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); int index = (int)_index; CalliIntrinsics.Call<object>(thunk, list, Toolbox.IList_Oper.RemoveAt, ref index, default(IntPtr)); } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); if (hrExcep is ArgumentOutOfRangeException) { hr = Interop.COM.E_BOUNDS; } } return hr; } [NativeCallable] static unsafe int Append(System.IntPtr pComThis, IntPtr _value) { int hr = Interop.COM.S_OK; try { // Get IList object object list = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); int dummy = 0; CalliIntrinsics.Call<object>(thunk, list, Toolbox.IList_Oper.Add, ref dummy, (IntPtr)(&_value)); } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } return hr; } [NativeCallable] static unsafe int RemoveAtEnd(System.IntPtr pComThis) { int hr = Interop.COM.S_OK; try { // Get IList object object list = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); int index = 0; CalliIntrinsics.Call<object>(thunk, list, Toolbox.IList_Oper.GetCount, ref index, default(IntPtr)); if (index == 0) { hr = Interop.COM.E_BOUNDS; } else { index--; CalliIntrinsics.Call<object>(thunk, list, Toolbox.IList_Oper.RemoveAt, ref index, default(IntPtr)); } } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); if (hrExcep is ArgumentOutOfRangeException) { hr = Interop.COM.E_BOUNDS; } } return hr; } [NativeCallable] static unsafe int Clear(System.IntPtr pComThis) { int hr = Interop.COM.S_OK; try { // Get IList object object list = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); int dummy = 0; CalliIntrinsics.Call<object>(thunk, list, Toolbox.IList_Oper.Clear, ref dummy, default(IntPtr)); } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } return hr; } [NativeCallable] internal static unsafe int GetMany(System.IntPtr pComThis, uint startIndex, uint len, System.IntPtr pDest, System.IntPtr pCount) { int hr = Interop.COM.S_OK; try { // Get IList object object list = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); int listCount = 0; CalliIntrinsics.Call<object>(thunk, list, Toolbox.IList_Oper.GetCount, ref listCount, default(IntPtr)); uint itemCount = 0; if ((startIndex != listCount) && Toolbox.EnsureIndexInt32(startIndex, (uint)listCount, ref hr)) { itemCount = System.Math.Min(len, (uint)listCount - startIndex); // Convert to COM interfaces, without allocating array uint i = 0; int byteSize = interfaceType.GetByteSize(); while (i < itemCount) { int index = (int)(i + startIndex); CalliIntrinsics.Call<object>(thunk, list, Toolbox.IList_Oper.GetItem, ref index, pDest); pDest = (IntPtr)((byte*)pDest + byteSize); i++; } } *((uint*)pCount) = itemCount; } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } return hr; } [NativeCallable] static unsafe int ReplaceAll(System.IntPtr pComThis, uint length, IntPtr pItems) { int hr = Interop.COM.S_OK; try { // Get IList object object list = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); int dummy = 0; CalliIntrinsics.Call<object>(thunk, list, Toolbox.IList_Oper.Clear, ref dummy, default(IntPtr)); int byteSize = interfaceType.GetByteSize(); for (uint i = 0; i < length; i++) { CalliIntrinsics.Call<object>(thunk, list, Toolbox.IList_Oper.Add, ref dummy, pItems); pItems = (IntPtr)((byte*)pItems + byteSize); } } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } return hr; } } /// <summary> /// Shared CCW for IVectorView<T> over IReadOnlyList<T> where T is a reference type marshalled to COM interface /// </summary> internal unsafe struct SharedCcw_IVectorView { public System.IntPtr pfnQueryInterface; public System.IntPtr pfnAddRef; public System.IntPtr pfnRelease; public System.IntPtr pfnGetIids; public System.IntPtr pfnGetRuntimeClassName; public System.IntPtr pfnGetTrustLevel; public System.IntPtr pfnGetAt; public System.IntPtr pfnget_Size; public System.IntPtr pfnIndexOf; public System.IntPtr pfnGetMany; [PreInitialized] static SharedCcw_IVectorView s_theCcwVtable = new SharedCcw_IVectorView() { pfnQueryInterface = AddrOfIntrinsics.AddrOf<AddrOfQueryInterface>(__vtable_IUnknown.QueryInterface), pfnAddRef = AddrOfIntrinsics.AddrOf<AddrOfAddRef>(__vtable_IUnknown.AddRef), pfnRelease = AddrOfIntrinsics.AddrOf<AddrOfRelease>(__vtable_IUnknown.Release), pfnGetIids = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfGetIID>(__vtable_IInspectable.GetIIDs), pfnGetRuntimeClassName = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget3>(__vtable_IInspectable.GetRuntimeClassName), pfnGetTrustLevel = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget3>(__vtable_IInspectable.GetTrustLevel), // The 4 SharedCcw_IVectorView functions have exactly the same implementation as those in SharedCcw_IVector, just use them for free // The real difference is handled by IReadOnlyListThunk<T> pfnGetAt = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfGetSetInsertReplaceAll>(SharedCcw_IVector.GetAt), pfnget_Size = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget3>(SharedCcw_IVector.get_Size), pfnIndexOf = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfIndexOf>(SharedCcw_IVector.IndexOf), pfnGetMany = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfGetMany1>(SharedCcw_IVector.GetMany), }; public static System.IntPtr GetVtable() { return AddrOfIntrinsics.StaticFieldAddr(ref s_theCcwVtable); } } /// <summary> /// Shared CCW for IVectorView<T> over IReadOnlyList<T> where T is blittable /// </summary> internal unsafe struct SharedCcw_IVectorView_Blittable { public System.IntPtr pfnQueryInterface; public System.IntPtr pfnAddRef; public System.IntPtr pfnRelease; public System.IntPtr pfnGetIids; public System.IntPtr pfnGetRuntimeClassName; public System.IntPtr pfnGetTrustLevel; public System.IntPtr pfnGetAt; public System.IntPtr pfnget_Size; public System.IntPtr pfnIndexOf; public System.IntPtr pfnGetMany; [PreInitialized] static SharedCcw_IVectorView_Blittable s_theCcwVtable = new SharedCcw_IVectorView_Blittable() { pfnQueryInterface = AddrOfIntrinsics.AddrOf<AddrOfQueryInterface>(__vtable_IUnknown.QueryInterface), pfnAddRef = AddrOfIntrinsics.AddrOf<AddrOfAddRef>(__vtable_IUnknown.AddRef), pfnRelease = AddrOfIntrinsics.AddrOf<AddrOfRelease>(__vtable_IUnknown.Release), pfnGetIids = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfGetIID>(__vtable_IInspectable.GetIIDs), pfnGetRuntimeClassName = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget3>(__vtable_IInspectable.GetRuntimeClassName), pfnGetTrustLevel = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget3>(__vtable_IInspectable.GetTrustLevel), // The 4 SharedCcw_IVectorView_Blittable functions have exactly the same implementation as those in SharedCcw_IVector_Blittable, just use them for free // The real difference is handled by IReadOnlyListBlittableThunk<T> pfnGetAt = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfGetSetInsertReplaceAll>(SharedCcw_IVector_Blittable.GetAt), pfnget_Size = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget3>(SharedCcw_IVector_Blittable.get_Size), pfnIndexOf = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfIndexOf>(SharedCcw_IVector_Blittable.IndexOf), pfnGetMany = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfGetMany1>(SharedCcw_IVector_Blittable.GetMany), }; public static System.IntPtr GetVtable() { return AddrOfIntrinsics.StaticFieldAddr(ref s_theCcwVtable); } } /// <summary> /// Shared CCW for IIterable<T> over IEnumerable<T> where T is a reference type marshalled to COM interface /// </summary> internal unsafe struct SharedCcw_IIterable { public System.IntPtr pfnQueryInterface; public System.IntPtr pfnAddRef; public System.IntPtr pfnRelease; public System.IntPtr pfnGetIids; public System.IntPtr pfnGetRuntimeClassName; public System.IntPtr pfnGetTrustLevel; public System.IntPtr pfnFirst; [PreInitialized] static SharedCcw_IIterable s_theCcwVtable = new SharedCcw_IIterable() { pfnQueryInterface = AddrOfIntrinsics.AddrOf<AddrOfQueryInterface>(__vtable_IUnknown.QueryInterface), pfnAddRef = AddrOfIntrinsics.AddrOf<AddrOfAddRef>(__vtable_IUnknown.AddRef), pfnRelease = AddrOfIntrinsics.AddrOf<AddrOfRelease>(__vtable_IUnknown.Release), pfnGetIids = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfGetIID>(__vtable_IInspectable.GetIIDs), pfnGetRuntimeClassName = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget3>(__vtable_IInspectable.GetRuntimeClassName), pfnGetTrustLevel = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget3>(__vtable_IInspectable.GetTrustLevel), pfnFirst = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget3>(First), }; public static System.IntPtr GetVtable() { return AddrOfIntrinsics.StaticFieldAddr(ref s_theCcwVtable); } // Thunk function in \RH\src\tools\mcg\be\Templates\McgHelpers.cs due to dependency on EnumeratorToIteratorAdapter // public static object IEnumerableThunk<T>(System.Collections.Generic.IEnumerable<T> enumerable) // { // return new EnumeratorToIteratorAdapter<T>(enumerable.GetEnumerator()); // } [NativeCallable] static int First(System.IntPtr pComThis, System.IntPtr pResult) { int hr = Interop.COM.S_OK; try { // Get enumerable object enumerable = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; Debug.Assert((interfaceType.GetInterfaceFlags() & McgInterfaceFlags.useSharedCCW) != 0); IntPtr thunk = interfaceType.GetCcwVtableThunk(); // Create enumerator using thunk function object enumerator = CalliIntrinsics.Call<object>(thunk, enumerable); // Marshal to native iterator *((IntPtr*)pResult) = McgMarshal.ObjectToComInterface(enumerator, interfaceType.GetIteratorType()); } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } return hr; } } public static partial class Toolbox { public enum IIterator_Oper { get_Current, get_HasCurrent, MoveNext, GetMany }; } /// <summary> /// Shared CCW for IIterator<T> over IIterator<T> where T is a reference type marshalled to COM interface /// </summary> internal unsafe struct SharedCcw_IIterator { public System.IntPtr pfnQueryInterface; public System.IntPtr pfnAddRef; public System.IntPtr pfnRelease; public System.IntPtr pfnGetIids; public System.IntPtr pfnGetRuntimeClassName; public System.IntPtr pfnGetTrustLevel; public System.IntPtr pfnget_Current; public System.IntPtr pfnget_HasCurrent; public System.IntPtr pfnMoveNext; public System.IntPtr pfnGetMany; [PreInitialized] static SharedCcw_IIterator s_theCcwVtable = new SharedCcw_IIterator() { pfnQueryInterface = AddrOfIntrinsics.AddrOf<AddrOfQueryInterface>(__vtable_IUnknown.QueryInterface), pfnAddRef = AddrOfIntrinsics.AddrOf<AddrOfAddRef>(__vtable_IUnknown.AddRef), pfnRelease = AddrOfIntrinsics.AddrOf<AddrOfRelease>(__vtable_IUnknown.Release), pfnGetIids = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfGetIID>(__vtable_IInspectable.GetIIDs), pfnGetRuntimeClassName = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget3>(__vtable_IInspectable.GetRuntimeClassName), pfnGetTrustLevel = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget3>(__vtable_IInspectable.GetTrustLevel), pfnget_Current = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget3>(get_Current), pfnget_HasCurrent = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget3>(get_HasCurrent), pfnMoveNext = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget3>(MoveNext), pfnGetMany = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfGetMany2>(GetMany), }; public static System.IntPtr GetVtable() { return AddrOfIntrinsics.StaticFieldAddr(ref s_theCcwVtable); } [NativeCallable] static int get_Current(System.IntPtr pComThis, System.IntPtr pValue) { int hr = Interop.COM.S_OK; try { // Get iterator object iterator = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); object item = null; CalliIntrinsics.Call<int>(thunk, iterator, Toolbox.IIterator_Oper.get_Current, ref item, 0); *((IntPtr*)pValue) = McgMarshal.ObjectToComInterface(item, interfaceType.GetElementInterfaceType()); } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } return hr; } [NativeCallable] static int get_HasCurrent(System.IntPtr pComThis, System.IntPtr pValue) { int hr = Interop.COM.S_OK; try { // Get iterator object iterator = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); object item = null; *((byte*)pValue) = (byte)CalliIntrinsics.Call<int>(thunk, iterator, Toolbox.IIterator_Oper.get_HasCurrent, ref item, 0); } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } return hr; } [NativeCallable] static int MoveNext(System.IntPtr pComThis, System.IntPtr pValue) { int hr = Interop.COM.S_OK; try { // Get iterator object iterator = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); object item = null; *((byte*)pValue) = (byte)CalliIntrinsics.Call<int>(thunk, iterator, Toolbox.IIterator_Oper.MoveNext, ref item, 0); } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } return hr; } [NativeCallable] static int GetMany(System.IntPtr pComThis, uint len, System.IntPtr pDest, System.IntPtr pCount) { int hr = Interop.COM.S_OK; try { // Get iterator object iterator = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); object data = null; *((int*)pCount) = CalliIntrinsics.Call<int>(thunk, iterator, Toolbox.IIterator_Oper.GetMany, ref data, (int)len); System.IntPtr* dst = (System.IntPtr*)pDest; object[] src = data as object[]; for (uint i = 0; i < len; i++) { dst[i] = McgMarshal.ObjectToComInterface(src[i], interfaceType.GetElementInterfaceType()); } } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } return hr; } } /// <summary> /// Shared CCW for IIterator<T> over IIterator<T> where T is a blittable struct /// </summary> internal unsafe struct SharedCcw_IIterator_Blittable { public System.IntPtr pfnQueryInterface; public System.IntPtr pfnAddRef; public System.IntPtr pfnRelease; public System.IntPtr pfnGetIids; public System.IntPtr pfnGetRuntimeClassName; public System.IntPtr pfnGetTrustLevel; public System.IntPtr pfnget_Current; public System.IntPtr pfnget_HasCurrent; public System.IntPtr pfnMoveNext; public System.IntPtr pfnGetMany; [PreInitialized] static SharedCcw_IIterator_Blittable s_theCcwVtable = new SharedCcw_IIterator_Blittable() { pfnQueryInterface = AddrOfIntrinsics.AddrOf<AddrOfQueryInterface>(__vtable_IUnknown.QueryInterface), pfnAddRef = AddrOfIntrinsics.AddrOf<AddrOfAddRef>(__vtable_IUnknown.AddRef), pfnRelease = AddrOfIntrinsics.AddrOf<AddrOfRelease>(__vtable_IUnknown.Release), pfnGetIids = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfGetIID>(__vtable_IInspectable.GetIIDs), pfnGetRuntimeClassName = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget3>(__vtable_IInspectable.GetRuntimeClassName), pfnGetTrustLevel = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget3>(__vtable_IInspectable.GetTrustLevel), pfnget_Current = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget3>(get_Current), pfnget_HasCurrent = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget3>(get_HasCurrent), pfnMoveNext = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget3>(MoveNext), pfnGetMany = AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfGetMany2>(GetMany), }; public static System.IntPtr GetVtable() { return AddrOfIntrinsics.StaticFieldAddr(ref s_theCcwVtable); } // public static Array IIteratorBlittableThunk<T>(IIterator<T> it, IIterator_Oper oper, ref T data, ref int len) where T : struct [NativeCallable] static int get_Current(System.IntPtr pComThis, System.IntPtr pValue) { int hr = Interop.COM.S_OK; try { // Get iterator object iterator = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); int dummy = 0; CalliIntrinsics.Call<Array>(thunk, iterator, Toolbox.IIterator_Oper.get_Current, pValue, ref dummy); } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } return hr; } [NativeCallable] static int get_HasCurrent(System.IntPtr pComThis, System.IntPtr pValue) { int hr = Interop.COM.S_OK; try { // Get iterator object iterator = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); int has = 0; CalliIntrinsics.Call<Array>(thunk, iterator, Toolbox.IIterator_Oper.get_HasCurrent, default(IntPtr), ref has); *((byte*)pValue) = (byte)has; } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } return hr; } [NativeCallable] static int MoveNext(System.IntPtr pComThis, System.IntPtr pValue) { int hr = Interop.COM.S_OK; try { // Get iterator object iterator = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); int has = 0; CalliIntrinsics.Call<Array>(thunk, iterator, Toolbox.IIterator_Oper.MoveNext, default(IntPtr), ref has); *((byte*)pValue) = (byte)has; } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } return hr; } [NativeCallable] static int GetMany(System.IntPtr pComThis, uint len, System.IntPtr pDest, System.IntPtr pCount) { int hr = Interop.COM.S_OK; try { // Get iterator object iterator = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); int count = (int)len; Array data = CalliIntrinsics.Call<Array>(thunk, iterator, Toolbox.IIterator_Oper.GetMany, default(IntPtr), ref count); *((uint*)pCount) = (uint)count; PInvokeMarshal.CopyToNative(data, 0, pDest, count); } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } return hr; } } internal unsafe partial struct SharedCcw_AsyncOperationCompletedHandler { public System.IntPtr pfnQueryInterface; public System.IntPtr pfnAddRef; public System.IntPtr pfnRelease; public System.IntPtr pfnInvoke; [PreInitialized] static SharedCcw_AsyncOperationCompletedHandler s_theCcwVtable = new SharedCcw_AsyncOperationCompletedHandler() { pfnQueryInterface = AddrOfIntrinsics.AddrOf<AddrOfQueryInterface>(__vtable_IUnknown.QueryInterface), pfnAddRef = AddrOfIntrinsics.AddrOf<AddrOfAddRef>(__vtable_IUnknown.AddRef), pfnRelease = AddrOfIntrinsics.AddrOf<AddrOfRelease>(__vtable_IUnknown.Release), pfnInvoke = AddrOfIntrinsics.AddrOf<WinRTAddrOfIntrinsics.AddrOfTarget19>(Invoke), }; public static System.IntPtr GetVtable() { return AddrOfIntrinsics.StaticFieldAddr(ref s_theCcwVtable); } [NativeCallable] static int Invoke(System.IntPtr pComThis, System.IntPtr _asyncInfo, int asyncStatus) { int hr = Interop.COM.S_OK; try { // Get enumerable object handler = ComCallableObject.GetTarget(pComThis); // Get thunk RuntimeTypeHandle interfaceType = ((__interface_ccw*)pComThis)->InterfaceType; IntPtr thunk = interfaceType.GetCcwVtableThunk(); object asyncInfo = McgMarshal.ComInterfaceToObject(_asyncInfo, interfaceType.GetAsyncOperationType()); // Call handler.Invoke(asyncInfo, asyncStatus) CalliIntrinsics.Call<int>(thunk, handler, asyncInfo, asyncStatus); } catch (System.Exception hrExcep) { hr = McgMarshal.GetHRForExceptionWinRT(hrExcep); } return hr; } } #endif }
// 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.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.AddUsing { public partial class AddUsingTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestWhereExtension() { await TestAsync( @"using System ; using System . Collections . Generic ; class Program { static void Main ( string [ ] args ) { var q = args . [|Where|] } } ", @"using System ; using System . Collections . Generic ; using System . Linq ; class Program { static void Main ( string [ ] args ) { var q = args . Where } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestSelectExtension() { await TestAsync( @"using System ; using System . Collections . Generic ; class Program { static void Main ( string [ ] args ) { var q = args . [|Select|] } } ", @"using System ; using System . Collections . Generic ; using System . Linq ; class Program { static void Main ( string [ ] args ) { var q = args . Select } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestGroupByExtension() { await TestAsync( @"using System ; using System . Collections . Generic ; class Program { static void Main ( string [ ] args ) { var q = args . [|GroupBy|] } } ", @"using System ; using System . Collections . Generic ; using System . Linq ; class Program { static void Main ( string [ ] args ) { var q = args . GroupBy } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestJoinExtension() { await TestAsync( @"using System ; using System . Collections . Generic ; class Program { static void Main ( string [ ] args ) { var q = args . [|Join|] } } ", @"using System ; using System . Collections . Generic ; using System . Linq ; class Program { static void Main ( string [ ] args ) { var q = args . Join } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task RegressionFor8455() { await TestMissingAsync( @"class C { void M ( ) { int dim = ( int ) Math . [|Min|] ( ) ; } } "); } [WorkItem(772321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/772321")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestExtensionWithThePresenceOfTheSameNameNonExtensionMethod() { await TestAsync( @"namespace NS1 { class Program { void Main() { [|new C().Foo(4);|] } } class C { public void Foo(string y) { } } } namespace NS2 { static class CExt { public static void Foo(this NS1.C c, int x) { } } } ", @"using NS2; namespace NS1 { class Program { void Main() { new C().Foo(4); } } class C { public void Foo(string y) { } } } namespace NS2 { static class CExt { public static void Foo(this NS1.C c, int x) { } } } "); } [WorkItem(772321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/772321")] [WorkItem(920398, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/920398")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestExtensionWithThePresenceOfTheSameNameNonExtensionPrivateMethod() { await TestAsync( @"namespace NS1 { class Program { void Main() { [|new C().Foo(4);|] } } class C { private void Foo(int x) { } } } namespace NS2 { static class CExt { public static void Foo(this NS1.C c, int x) { } } } ", @"using NS2; namespace NS1 { class Program { void Main() { new C().Foo(4); } } class C { private void Foo(int x) { } } } namespace NS2 { static class CExt { public static void Foo(this NS1.C c, int x) { } } } "); } [WorkItem(772321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/772321")] [WorkItem(920398, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/920398")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestExtensionWithThePresenceOfTheSameNameExtensionPrivateMethod() { await TestAsync( @"using NS2; namespace NS1 { class Program { void Main() { [|new C().Foo(4);|] } } class C { } } namespace NS2 { static class CExt { private static void Foo(this NS1.C c, int x) { } } } namespace NS3 { static class CExt { public static void Foo(this NS1.C c, int x) { } } } ", @"using NS2; using NS3; namespace NS1 { class Program { void Main() { new C().Foo(4); } } class C { } } namespace NS2 { static class CExt { private static void Foo(this NS1.C c, int x) { } } } namespace NS3 { static class CExt { public static void Foo(this NS1.C c, int x) { } } } "); } [WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestAddUsingForAddExtentionMethod() { await TestAsync( @"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { [|1|] } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", @"using System ; using System . Collections ; using Ext ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { 1 } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", parseOptions: null); } [WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestAddUsingForAddExtentionMethod2() { await TestAsync( @"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { 1 , 2 , [|3|] } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", @"using System ; using System . Collections ; using Ext ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { 1 , 2 , 3 } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", parseOptions: null); } [WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestAddUsingForAddExtentionMethod3() { await TestAsync( @"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { 1 , [|2|] , 3 } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", @"using System ; using System . Collections ; using Ext ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { 1 , 2 , 3 } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", parseOptions: null); } [WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestAddUsingForAddExtentionMethod4() { await TestAsync( @"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } , [|{ 4 , 5 , 6 }|] , { 7 , 8 , 9 } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", @"using System ; using System . Collections ; using Ext ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", parseOptions: null); } [WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestAddUsingForAddExtentionMethod5() { await TestAsync( @"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } , { 4 , 5 , 6 } , [|{ 7 , 8 , 9 }|] } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", @"using System ; using System . Collections ; using Ext ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", parseOptions: null); } [WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestAddUsingForAddExtentionMethod6() { await TestAsync( @"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } , { ""Four"" , ""Five"" , ""Six"" } , [|{ '7' , '8' , '9' }|] } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", @"using System ; using System . Collections ; using Ext ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } , { ""Four"" , ""Five"" , ""Six"" } , { '7' , '8' , '9' } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", parseOptions: null); } [WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestAddUsingForAddExtentionMethod7() { await TestAsync( @"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } , [|{ ""Four"" , ""Five"" , ""Six"" }|] , { '7' , '8' , '9' } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", @"using System ; using System . Collections ; using Ext ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } , { ""Four"" , ""Five"" , ""Six"" } , { '7' , '8' , '9' } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", parseOptions: null); } [WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestAddUsingForAddExtentionMethod8() { await TestAsync( @"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { [|{ 1 , 2 , 3 }|] } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", @"using System ; using System . Collections ; using Ext ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", parseOptions: null); } [WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestAddUsingForAddExtentionMethod9() { await TestAsync( @"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { [|""This""|] } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", @"using System ; using System . Collections ; using Ext ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { ""This"" } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", parseOptions: null); } [WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestAddUsingForAddExtentionMethod10() { await TestAsync( @"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { [|{ 1 , 2 , 3 }|] , { ""Four"" , ""Five"" , ""Six"" } , { '7' , '8' , '9' } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } namespace Ext2 { static class Extensions { public static void Add ( this X x , object [ ] i ) { } } } ", @"using System ; using System . Collections ; using Ext ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } , { ""Four"" , ""Five"" , ""Six"" } , { '7' , '8' , '9' } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } namespace Ext2 { static class Extensions { public static void Add ( this X x , object [ ] i ) { } } } ", parseOptions: null); } [WorkItem(269, "https://github.com/dotnet/roslyn/issues/269")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestAddUsingForAddExtentionMethod11() { await TestAsync( @"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { [|{ 1 , 2 , 3 }|] , { ""Four"" , ""Five"" , ""Six"" } , { '7' , '8' , '9' } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } namespace Ext2 { static class Extensions { public static void Add ( this X x , object [ ] i ) { } } } ", @"using System ; using System . Collections ; using Ext2 ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } , { ""Four"" , ""Five"" , ""Six"" } , { '7' , '8' , '9' } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } namespace Ext2 { static class Extensions { public static void Add ( this X x , object [ ] i ) { } } } ", index: 1, parseOptions: null); } [WorkItem(3818, "https://github.com/dotnet/roslyn/issues/3818")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task InExtensionMethodUnderConditionalAccessExpression() { var initialText = @"<Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <Document FilePath = ""Program""> namespace Sample { class Program { static void Main(string[] args) { string myString = ""Sample""; var other = myString?[|.StringExtension()|].Substring(0); } } } </Document> <Document FilePath = ""Extensions""> namespace Sample.Extensions { public static class StringExtensions { public static string StringExtension(this string s) { return ""Ok""; } } } </Document> </Project> </Workspace>"; var expectedText = @"using Sample.Extensions; namespace Sample { class Program { static void Main(string[] args) { string myString = ""Sample""; var other = myString?.StringExtension().Substring(0); } } }"; await TestAsync(initialText, expectedText); } [WorkItem(3818, "https://github.com/dotnet/roslyn/issues/3818")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task InExtensionMethodUnderMultipleConditionalAccessExpressions() { var initialText = @"<Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <Document FilePath = ""Program""> public class C { public T F&lt;T&gt;(T x) { return F(new C())?.F(new C())?[|.Extn()|]; } } </Document> <Document FilePath = ""Extensions""> namespace Sample.Extensions { public static class Extensions { public static C Extn(this C obj) { return obj.F(new C()); } } } </Document> </Project> </Workspace>"; var expectedText = @"using Sample.Extensions; public class C { public T F<T>(T x) { return F(new C())?.F(new C())?.Extn(); } }"; await TestAsync(initialText, expectedText); } [WorkItem(3818, "https://github.com/dotnet/roslyn/issues/3818")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task InExtensionMethodUnderMultipleConditionalAccessExpressions2() { var initialText = @"<Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <Document FilePath = ""Program""> public class C { public T F&lt;T&gt;(T x) { return F(new C())?.F(new C())[|.Extn()|]?.F(newC()); } } </Document> <Document FilePath = ""Extensions""> namespace Sample.Extensions { public static class Extensions { public static C Extn(this C obj) { return obj.F(new C()); } } } </Document> </Project> </Workspace>"; var expectedText = @"using Sample.Extensions; public class C { public T F<T>(T x) { return F(new C())?.F(new C()).Extn()?.F(newC()); } }"; await TestAsync(initialText, expectedText); } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // CESchedulerPairTests.cs // Tests Ported from the TPL test bed // // Summary: // Implements the tests for the new scheduler ConcurrentExclusiveSchedulerPair // // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ using System; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using System.Security; using Xunit; using System.Diagnostics; namespace System.Threading.Tasks.Tests { public class TrackingTaskScheduler : TaskScheduler { public TrackingTaskScheduler(int maxConLevel) { //We need to set the value to 1 so that each time a scheduler is created, its tasks will start with one. _counter = 1; if (maxConLevel < 1 && maxConLevel != -1/*infinite*/) throw new ArgumentException("Maximum concurrency level should between 1 and int32.Maxvalue"); _maxConcurrencyLevel = maxConLevel; } protected override void QueueTask(Task task) { if (task == null) throw new ArgumentNullException("When requesting to QueueTask, the input task can not be null"); Task.Factory.StartNew(() => { lock (_lockObj) //Locking so that if multiple threads in threadpool does not incorrectly increment the counter. { //store the current value of the counter (This becomes the unique ID for this scheduler's Task) SchedulerID.Value = _counter; _counter++; } ExecuteTask(task); //Extracted out due to security attribute reason. }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); } private void ExecuteTask(Task task) { base.TryExecuteTask(task); } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { if (taskWasPreviouslyQueued) return false; return TryExecuteTask(task); } //public int SchedulerID //{ // get; // set; //} protected override IEnumerable<Task> GetScheduledTasks() { return null; } private object _lockObj = new object(); private int _counter = 1; //This is used to keep track of how many scheduler tasks were created public ThreadLocal<int> SchedulerID = new ThreadLocal<int>(); //This is the ID of the scheduler. /// <summary>The maximum concurrency level for the scheduler.</summary> private readonly int _maxConcurrencyLevel; public override int MaximumConcurrencyLevel { get { return _maxConcurrencyLevel; } } } public class CESchedulerPairTests { #region Test cases /// <summary> /// Test to ensure that ConcurrentExclusiveSchedulerPair can be created using user defined parameters /// and those parameters are respected when tasks are executed /// </summary> /// <remarks>maxItemsPerTask and which scheduler is used are verified in other testcases</remarks> [Theory] [InlineData("default")] [InlineData("scheduler")] [InlineData("maxconcurrent")] [InlineData("all")] public static void TestCreationOptions(string ctorType) { ConcurrentExclusiveSchedulerPair schedPair = null; //Need to define the default values since these values are passed to the verification methods TaskScheduler scheduler = TaskScheduler.Default; int maxConcurrentLevel = Environment.ProcessorCount; //Based on input args, use one of the ctor overloads switch (ctorType.ToLower()) { case "default": schedPair = new ConcurrentExclusiveSchedulerPair(); break; case "scheduler": schedPair = new ConcurrentExclusiveSchedulerPair(scheduler); break; case "maxconcurrent": maxConcurrentLevel = 2; schedPair = new ConcurrentExclusiveSchedulerPair(scheduler, maxConcurrentLevel); break; case "all": maxConcurrentLevel = int.MaxValue; schedPair = new ConcurrentExclusiveSchedulerPair(scheduler, -1/*MaxConcurrentLevel*/, -1/*MaxItemsPerTask*/); //-1 gets converted to Int32.MaxValue break; default: throw new NotImplementedException(string.Format("The option specified {0} to create the ConcurrentExclusiveSchedulerPair is invalid", ctorType)); } //Create the factories that use the exclusive scheduler and the concurrent scheduler. We test to ensure //that the ConcurrentExclusiveSchedulerPair created are valid by scheduling work on them. TaskFactory writers = new TaskFactory(schedPair.ExclusiveScheduler); TaskFactory readers = new TaskFactory(schedPair.ConcurrentScheduler); List<Task> taskList = new List<Task>(); //Store all tasks created, to enable wait until all of them are finished // Schedule some dummy work that should be run with as much parallelism as possible for (int i = 0; i < 50; i++) { //In the current design, when there are no more tasks to execute, the Task used by concurrentexclusive scheduler dies //by sleeping we simulate some non trivial work that takes time and causes the concurrentexclusive scheduler Task //to stay around for addition work. taskList.Add(readers.StartNew(() => { var sw = new SpinWait(); while (!sw.NextSpinWillYield) sw.SpinOnce() ; })); } // Schedule work where each item must be run when no other items are running for (int i = 0; i < 10; i++) taskList.Add(writers.StartNew(() => { var sw = new SpinWait(); while (!sw.NextSpinWillYield) sw.SpinOnce(); })); //Wait on the tasks to finish to ensure that the ConcurrentExclusiveSchedulerPair created can schedule and execute tasks without issues foreach (var item in taskList) { item.Wait(); } //verify that maxconcurrency was respected. if (ctorType == "maxconcurrent") { Assert.Equal(maxConcurrentLevel, schedPair.ConcurrentScheduler.MaximumConcurrencyLevel); } Assert.Equal(1, schedPair.ExclusiveScheduler.MaximumConcurrencyLevel); //verify that the schedulers have not completed Assert.False(schedPair.Completion.IsCompleted, "The schedulers should not have completed as a completion request was not issued."); //complete the scheduler and make sure it shuts down successfully schedPair.Complete(); schedPair.Completion.Wait(); //make sure no additional work may be scheduled foreach (var schedPairScheduler in new TaskScheduler[] { schedPair.ConcurrentScheduler, schedPair.ExclusiveScheduler }) { Exception caughtException = null; try { Task.Factory.StartNew(() => { }, CancellationToken.None, TaskCreationOptions.None, schedPairScheduler); } catch (Exception exc) { caughtException = exc; } Assert.True( caughtException is TaskSchedulerException && caughtException.InnerException is InvalidOperationException, "Queueing after completion should fail"); } } /// <summary> /// Test to verify that only up to maxItemsPerTask are executed by a single ConcurrentExclusiveScheduler Task /// </summary> /// <remarks>In ConcurrentExclusiveSchedulerPair, each tasks scheduled are run under an internal Task. The basic idea for the test /// is that each time ConcurrentExclusiveScheduler is called QueueTasK a counter (which acts as scheduler's Task id) is incremented. /// When a task executes, it observes the parent Task Id and if it matches the one its local cache, it increments its local counter (which tracks /// the items executed by a ConcurrentExclusiveScheduler Task). At any given time the Task's local counter cant exceed maxItemsPerTask</remarks> [Theory] [InlineData(4, 1, true)] [InlineData(1, 4, true)] [InlineData(4, 1, false)] [InlineData(1, 4, false)] public static void TestMaxItemsPerTask(int maxConcurrency, int maxItemsPerTask, bool completeBeforeTaskWait) { //Create a custom TaskScheduler with specified max concurrency (TrackingTaskScheduler is defined in Common\tools\CommonUtils\TPLTestSchedulers.cs) TrackingTaskScheduler scheduler = new TrackingTaskScheduler(maxConcurrency); //We need to use the custom scheduler to achieve the results. As a by-product, we test to ensure custom schedulers are supported ConcurrentExclusiveSchedulerPair schedPair = new ConcurrentExclusiveSchedulerPair(scheduler, maxConcurrency, maxItemsPerTask); TaskFactory readers = new TaskFactory(schedPair.ConcurrentScheduler); //get reader and writer schedulers TaskFactory writers = new TaskFactory(schedPair.ExclusiveScheduler); //These are threadlocals to ensure that no concurrency side effects occur ThreadLocal<int> itemsExecutedCount = new ThreadLocal<int>(); //Track the items executed by CEScheduler Task ThreadLocal<int> schedulerIDInsideTask = new ThreadLocal<int>(); //Used to store the Scheduler ID observed by a Task Executed by CEScheduler Task //Work done by both reader and writer tasks Action work = () => { //Get the id of the parent Task (which is the task created by the scheduler). Each task run by the scheduler task should //see the same SchedulerID value since they are run on the same thread int id = ((TrackingTaskScheduler)scheduler).SchedulerID.Value; if (id == schedulerIDInsideTask.Value) { //since ids match, this is one more Task being executed by the CEScheduler Task itemsExecutedCount.Value = ++itemsExecutedCount.Value; //This does not need to be thread safe since we are looking to ensure that only n number of tasks were executed and not the order //in which they were executed. Also asserting inside the thread is fine since we just want the test to be marked as failure Assert.True(itemsExecutedCount.Value <= maxItemsPerTask, string.Format("itemsExecutedCount={0} cant be greater than maxValue={1}. Parent TaskID={2}", itemsExecutedCount, maxItemsPerTask, id)); } else { //Since ids don't match, this is the first Task being executed in the CEScheduler Task schedulerIDInsideTask.Value = id; //cache the scheduler ID seen by the thread, so other tasks running in same thread can see this itemsExecutedCount.Value = 1; } //Give enough time for a Task to stay around, so that other tasks will be executed by the same CEScheduler Task //or else the CESchedulerTask will die and each Task might get executed by a different CEScheduler Task. This does not affect the //verifications, but its increases the chance of finding a bug if the maxItemPerTask is not respected new ManualResetEvent(false).WaitOne(1); }; List<Task> taskList = new List<Task>(); int maxConcurrentTasks = maxConcurrency * maxItemsPerTask * 5; int maxExclusiveTasks = maxConcurrency * maxItemsPerTask * 2; // Schedule Tasks in both concurrent and exclusive mode for (int i = 0; i < maxConcurrentTasks; i++) taskList.Add(readers.StartNew(work)); for (int i = 0; i < maxExclusiveTasks; i++) taskList.Add(writers.StartNew(work)); if (completeBeforeTaskWait) { schedPair.Complete(); schedPair.Completion.Wait(); Assert.True(taskList.TrueForAll(t => t.IsCompleted), "All tasks should have completed for scheduler to complete"); } //finally wait for all of the tasks, to ensure they all executed properly Task.WaitAll(taskList.ToArray()); if (!completeBeforeTaskWait) { schedPair.Complete(); schedPair.Completion.Wait(); Assert.True(taskList.TrueForAll(t => t.IsCompleted), "All tasks should have completed for scheduler to complete"); } } /// <summary> /// When user specifies a concurrency level above the level allowed by the task scheduler, the concurrency level should be set /// to the concurrencylevel specified in the taskscheduler. Also tests that the maxConcurrencyLevel specified was respected /// </summary> [Fact] public static void TestLowerConcurrencyLevel() { //a custom scheduler with maxConcurrencyLevel of one int customSchedulerConcurrency = 1; TrackingTaskScheduler scheduler = new TrackingTaskScheduler(customSchedulerConcurrency); // specify a maxConcurrencyLevel > TaskScheduler's maxconcurrencyLevel to ensure the pair takes the min of the two ConcurrentExclusiveSchedulerPair schedPair = new ConcurrentExclusiveSchedulerPair(scheduler, int.MaxValue); Assert.Equal(scheduler.MaximumConcurrencyLevel, schedPair.ConcurrentScheduler.MaximumConcurrencyLevel); //Now schedule a reader task that would block and verify that more reader tasks scheduled are not executed //(as long as the first task is blocked) TaskFactory readers = new TaskFactory(schedPair.ConcurrentScheduler); ManualResetEvent blockReaderTaskEvent = new ManualResetEvent(false); ManualResetEvent blockMainThreadEvent = new ManualResetEvent(false); //Add a reader tasks that would block readers.StartNew(() => { blockMainThreadEvent.Set(); blockReaderTaskEvent.WaitOne(); }); blockMainThreadEvent.WaitOne(); // wait for the blockedTask to start execution //Now add more reader tasks int maxConcurrentTasks = Environment.ProcessorCount; List<Task> taskList = new List<Task>(); for (int i = 0; i < maxConcurrentTasks; i++) taskList.Add(readers.StartNew(() => { })); //schedule some dummy reader tasks foreach (Task task in taskList) { bool wasTaskStarted = (task.Status != TaskStatus.Running) && (task.Status != TaskStatus.RanToCompletion); Assert.True(wasTaskStarted, string.Format("Additional reader tasks should not start when scheduler concurrency is {0} and a reader task is blocked", customSchedulerConcurrency)); } //finally unblock the blocjedTask and wait for all of the tasks, to ensure they all executed properly blockReaderTaskEvent.Set(); Task.WaitAll(taskList.ToArray()); } [Theory] [InlineData(true)] [InlineData(false)] public static void TestConcurrentBlockage(bool useReader) { ConcurrentExclusiveSchedulerPair schedPair = new ConcurrentExclusiveSchedulerPair(); TaskFactory readers = new TaskFactory(schedPair.ConcurrentScheduler); TaskFactory writers = new TaskFactory(schedPair.ExclusiveScheduler); ManualResetEvent blockExclusiveTaskEvent = new ManualResetEvent(false); ManualResetEvent blockMainThreadEvent = new ManualResetEvent(false); ManualResetEvent blockMre = new ManualResetEvent(false); //Schedule a concurrent task and ensure that it is executed, just for fun Task<bool> conTask = readers.StartNew<bool>(() => { new ManualResetEvent(false).WaitOne(10); ; return true; }); conTask.Wait(); Assert.True(conTask.Result, "The concurrenttask when executed successfully should have returned true"); //Now scehdule an exclusive task that is blocked(thereby preventing other concurrent tasks to finish) Task<bool> exclusiveTask = writers.StartNew<bool>(() => { blockMainThreadEvent.Set(); blockExclusiveTaskEvent.WaitOne(); return true; }); //With exclusive task in execution mode, schedule a number of concurrent tasks and ensure they are not executed blockMainThreadEvent.WaitOne(); List<Task> taskList = new List<Task>(); for (int i = 0; i < 20; i++) taskList.Add(readers.StartNew<bool>(() => { blockMre.WaitOne(10); return true; })); foreach (Task task in taskList) { bool wasTaskStarted = (task.Status != TaskStatus.Running) && (task.Status != TaskStatus.RanToCompletion); Assert.True(wasTaskStarted, "Concurrent tasks should not be executed when an exclusive task is getting executed"); } blockExclusiveTaskEvent.Set(); Task.WaitAll(taskList.ToArray()); } [Theory] [MemberData(nameof(ApiType))] public static void TestIntegration(string apiType, bool useReader) { Debug.WriteLine(string.Format(" Running apiType:{0} useReader:{1}", apiType, useReader)); int taskCount = Environment.ProcessorCount; //To get varying number of tasks as a function of cores ConcurrentExclusiveSchedulerPair schedPair = new ConcurrentExclusiveSchedulerPair(); CountdownEvent cde = new CountdownEvent(taskCount); //Used to track how many tasks were executed Action work = () => { cde.Signal(); }; //Work done by all APIs //Choose the right scheduler to use based on input parameter TaskScheduler scheduler = useReader ? schedPair.ConcurrentScheduler : schedPair.ExclusiveScheduler; SelectAPI2Target(apiType, taskCount, scheduler, work); cde.Wait(); //This will cause the test to block (and timeout) until all tasks are finished } /// <summary> /// Test to ensure that invalid parameters result in exceptions /// </summary> [Fact] public static void TestInvalidParameters() { Assert.Throws<ArgumentNullException>(() => new ConcurrentExclusiveSchedulerPair(null)); //TargetScheduler is null Assert.Throws<ArgumentOutOfRangeException>(() => new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, 0)); //maxConcurrencyLevel is invalid Assert.Throws<ArgumentOutOfRangeException>(() => new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, -2)); //maxConcurrencyLevel is invalid Assert.Throws<ArgumentOutOfRangeException>(() => new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, -1, 0)); //maxItemsPerTask is invalid Assert.Throws<ArgumentOutOfRangeException>(() => new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, -1, -2)); //maxItemsPerTask is invalid } /// <summary> /// Test to ensure completion task works successfully /// </summary> [Fact] public static void TestCompletionTask() { // Completion tasks is valid after initialization { var cesp = new ConcurrentExclusiveSchedulerPair(); Assert.True(cesp.Completion != null, "CompletionTask should never be null (after initialization)"); Assert.True(!cesp.Completion.IsCompleted, "CompletionTask should not have completed"); } // Completion task is valid after complete is called { var cesp = new ConcurrentExclusiveSchedulerPair(); cesp.Complete(); Assert.True(cesp.Completion != null, "CompletionTask should never be null (after complete)"); cesp.Completion.Wait(); } // Complete method may be called multiple times, and CompletionTask still completes { var cesp = new ConcurrentExclusiveSchedulerPair(); for (int i = 0; i < 20; i++) cesp.Complete(); // ensure multiple calls to Complete succeed Assert.True(cesp.Completion != null, "CompletionTask should never be null (after multiple completes)"); cesp.Completion.Wait(); } // Can create a bunch of schedulers, do work on them all, complete them all, and they all complete { var cesps = new ConcurrentExclusiveSchedulerPair[100]; for (int i = 0; i < cesps.Length; i++) { cesps[i] = new ConcurrentExclusiveSchedulerPair(); } for (int i = 0; i < cesps.Length; i++) { Action work = () => new ManualResetEvent(false).WaitOne(2); ; Task.Factory.StartNew(work, CancellationToken.None, TaskCreationOptions.None, cesps[i].ConcurrentScheduler); Task.Factory.StartNew(work, CancellationToken.None, TaskCreationOptions.None, cesps[i].ExclusiveScheduler); } for (int i = 0; i < cesps.Length; i++) { cesps[i].Complete(); cesps[i].Completion.Wait(); } } // Validate that CESP does not implement IDisposable Assert.Equal(null, new ConcurrentExclusiveSchedulerPair() as IDisposable); } /// <summary> /// Ensure that CESPs can be layered on other CESPs. /// </summary [Fact] public static void TestSchedulerNesting() { // Create a hierarchical set of scheduler pairs var cespParent = new ConcurrentExclusiveSchedulerPair(); var cespChild1 = new ConcurrentExclusiveSchedulerPair(cespParent.ConcurrentScheduler); var cespChild1Child1 = new ConcurrentExclusiveSchedulerPair(cespChild1.ConcurrentScheduler); var cespChild1Child2 = new ConcurrentExclusiveSchedulerPair(cespChild1.ExclusiveScheduler); var cespChild2 = new ConcurrentExclusiveSchedulerPair(cespParent.ExclusiveScheduler); var cespChild2Child1 = new ConcurrentExclusiveSchedulerPair(cespChild2.ConcurrentScheduler); var cespChild2Child2 = new ConcurrentExclusiveSchedulerPair(cespChild2.ExclusiveScheduler); // these are ordered such that we will complete the child schedulers before we complete their parents. That way // we don't complete a parent that's still in use. var cesps = new[] { cespChild1Child1, cespChild1Child2, cespChild1, cespChild2Child1, cespChild2Child2, cespChild2, cespParent, }; // Get the schedulers from all of the pairs List<TaskScheduler> schedulers = new List<TaskScheduler>(); foreach (var s in cesps) { schedulers.Add(s.ConcurrentScheduler); schedulers.Add(s.ExclusiveScheduler); } // Keep track of all created tasks var tasks = new List<Task>(); // Queue lots of work to each scheduler foreach (var scheduler in schedulers) { // Create a function that schedules and inlines recursively queued tasks Action<int> recursiveWork = null; recursiveWork = depth => { if (depth > 0) { Action work = () => { var sw = new SpinWait(); while (!sw.NextSpinWillYield) sw.SpinOnce(); recursiveWork(depth - 1); }; TaskFactory factory = new TaskFactory(scheduler); Debug.WriteLine(string.Format("Start tasks in scheduler {0}", scheduler.Id)); Task t1 = factory.StartNew(work); Task t2 = factory.StartNew(work); Task t3 = factory.StartNew(work); Task.WaitAll(t1, t2, t3); } }; for (int i = 0; i < 2; i++) { tasks.Add(Task.Factory.StartNew(() => recursiveWork(2), CancellationToken.None, TaskCreationOptions.None, scheduler)); } } // Wait for all tasks to complete, then complete the schedulers Task.WaitAll(tasks.ToArray()); foreach (var cesp in cesps) { cesp.Complete(); cesp.Completion.Wait(); } } /// <summary> /// Ensure that continuations and parent/children which hop between concurrent and exclusive work correctly. /// EH /// </summary> [Theory] [InlineData(true)] [InlineData(false)] public static void TestConcurrentExclusiveChain(bool syncContinuations) { var scheduler = new TrackingTaskScheduler(Environment.ProcessorCount); var cesp = new ConcurrentExclusiveSchedulerPair(scheduler); // continuations { var starter = new Task(() => { }); var t = starter; for (int i = 0; i < 10; i++) { t = t.ContinueWith(delegate { }, CancellationToken.None, syncContinuations ? TaskContinuationOptions.ExecuteSynchronously : TaskContinuationOptions.None, cesp.ConcurrentScheduler); t = t.ContinueWith(delegate { }, CancellationToken.None, syncContinuations ? TaskContinuationOptions.ExecuteSynchronously : TaskContinuationOptions.None, cesp.ExclusiveScheduler); } starter.Start(cesp.ExclusiveScheduler); t.Wait(); } // parent/child { var errorString = "hello faulty world"; var root = Task.Factory.StartNew(() => { Task.Factory.StartNew(() => { Task.Factory.StartNew(() => { Task.Factory.StartNew(() => { Task.Factory.StartNew(() => { Task.Factory.StartNew(() => { Task.Factory.StartNew(() => { throw new InvalidOperationException(errorString); }, CancellationToken.None, TaskCreationOptions.AttachedToParent, cesp.ExclusiveScheduler).Wait(); }, CancellationToken.None, TaskCreationOptions.AttachedToParent, cesp.ExclusiveScheduler); }, CancellationToken.None, TaskCreationOptions.AttachedToParent, cesp.ConcurrentScheduler); }, CancellationToken.None, TaskCreationOptions.AttachedToParent, cesp.ExclusiveScheduler); }, CancellationToken.None, TaskCreationOptions.AttachedToParent, cesp.ConcurrentScheduler); }, CancellationToken.None, TaskCreationOptions.AttachedToParent, cesp.ExclusiveScheduler); }, CancellationToken.None, TaskCreationOptions.None, cesp.ConcurrentScheduler); ((IAsyncResult)root).AsyncWaitHandle.WaitOne(); Assert.True(root.IsFaulted, "Root should have been faulted by child's error"); var ae = root.Exception.Flatten(); Assert.True(ae.InnerException is InvalidOperationException && ae.InnerException.Message == errorString, "Child's exception should have propagated to the root."); } } #endregion #region Helper Methods public static void SelectAPI2Target(string apiType, int taskCount, TaskScheduler scheduler, Action work) { switch (apiType) { case "StartNew": for (int i = 0; i < taskCount; i++) new TaskFactory(scheduler).StartNew(() => { work(); }); break; case "Start": for (int i = 0; i < taskCount; i++) new Task(() => { work(); }).Start(scheduler); break; case "ContinueWith": for (int i = 0; i < taskCount; i++) { new TaskFactory().StartNew(() => { }).ContinueWith((t) => { work(); }, scheduler); } break; case "FromAsync": for (int i = 0; i < taskCount; i++) { new TaskFactory(scheduler).FromAsync(Task.Factory.StartNew(() => { }), (iar) => { work(); }); } break; case "ContinueWhenAll": for (int i = 0; i < taskCount; i++) { new TaskFactory(scheduler).ContinueWhenAll(new Task[] { Task.Factory.StartNew(() => { }) }, (t) => { work(); }); } break; case "ContinueWhenAny": for (int i = 0; i < taskCount; i++) { new TaskFactory(scheduler).ContinueWhenAny(new Task[] { Task.Factory.StartNew(() => { }) }, (t) => { work(); }); } break; default: throw new ArgumentOutOfRangeException(string.Format("Api name specified {0} is invalid or is of incorrect case", apiType)); } } /// <summary> /// Used to provide parameters for the TestIntegration test /// </summary> public static IEnumerable<object[]> ApiType { get { List<object[]> values = new List<object[]>(); foreach (string apiType in new string[] { "StartNew", "Start", "ContinueWith", /* FromAsync: Not supported in .NET Native */ "ContinueWhenAll", "ContinueWhenAny" }) { foreach (bool useReader in new bool[] { true, false }) { values.Add(new object[] { apiType, useReader }); } } return values; } } #endregion } }
// ------------------------------------------------------------------------ // ======================================================================== // THIS CODE AND INFORMATION ARE GENERATED BY AUTOMATIC CODE GENERATOR // ======================================================================== // Template: ViewModel.tt // Version: 2.0 using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Windows; using System.Windows.Input; using Controls = WPAppStudio.Controls; using Entities = WPAppStudio.Entities; using EntitiesBase = WPAppStudio.Entities.Base; using IServices = WPAppStudio.Services.Interfaces; using IViewModels = WPAppStudio.ViewModel.Interfaces; using Localization = WPAppStudio.Localization; using Repositories = WPAppStudio.Repositories; using Services = WPAppStudio.Services; using ViewModelsBase = WPAppStudio.ViewModel.Base; using WPAppStudio; using WPAppStudio.Shared; namespace WPAppStudio.ViewModel { /// <summary> /// Implementation of BLOGPOSTS_Detail ViewModel. /// </summary> [CompilerGenerated] [GeneratedCode("Radarc", "4.0")] public partial class BLOGPOSTS_DetailViewModel : ViewModelsBase.VMBase, IViewModels.IBLOGPOSTS_DetailViewModel, ViewModelsBase.INavigable { private readonly Repositories.BLOGPOSTS_rssfeed _bLOGPOSTS_rssfeed; private readonly IServices.IDialogService _dialogService; private readonly IServices.INavigationService _navigationService; private readonly IServices.ISpeechService _speechService; private readonly IServices.IShareService _shareService; private readonly IServices.ILiveTileService _liveTileService; /// <summary> /// Initializes a new instance of the <see cref="BLOGPOSTS_DetailViewModel" /> class. /// </summary> /// <param name="bLOGPOSTS_rssfeed">The B L O G P O S T S_rssfeed.</param> /// <param name="dialogService">The Dialog Service.</param> /// <param name="navigationService">The Navigation Service.</param> /// <param name="speechService">The Speech Service.</param> /// <param name="shareService">The Share Service.</param> /// <param name="liveTileService">The Live Tile Service.</param> public BLOGPOSTS_DetailViewModel(Repositories.BLOGPOSTS_rssfeed bLOGPOSTS_rssfeed, IServices.IDialogService dialogService, IServices.INavigationService navigationService, IServices.ISpeechService speechService, IServices.IShareService shareService, IServices.ILiveTileService liveTileService) { _bLOGPOSTS_rssfeed = bLOGPOSTS_rssfeed; _dialogService = dialogService; _navigationService = navigationService; _speechService = speechService; _shareService = shareService; _liveTileService = liveTileService; } private EntitiesBase.RssSearchResult _currentRssSearchResult; /// <summary> /// CurrentRssSearchResult property. /// </summary> public EntitiesBase.RssSearchResult CurrentRssSearchResult { get { return _currentRssSearchResult; } set { SetProperty(ref _currentRssSearchResult, value); } } private bool _hasNextpanoramaBLOGPOSTS_Detail0; /// <summary> /// HasNextpanoramaBLOGPOSTS_Detail0 property. /// </summary> public bool HasNextpanoramaBLOGPOSTS_Detail0 { get { return _hasNextpanoramaBLOGPOSTS_Detail0; } set { SetProperty(ref _hasNextpanoramaBLOGPOSTS_Detail0, value); } } private bool _hasPreviouspanoramaBLOGPOSTS_Detail0; /// <summary> /// HasPreviouspanoramaBLOGPOSTS_Detail0 property. /// </summary> public bool HasPreviouspanoramaBLOGPOSTS_Detail0 { get { return _hasPreviouspanoramaBLOGPOSTS_Detail0; } set { SetProperty(ref _hasPreviouspanoramaBLOGPOSTS_Detail0, value); } } /// <summary> /// Delegate method for the TextToSpeechBLOGPOSTS_DetailStaticControlCommand command. /// </summary> public void TextToSpeechBLOGPOSTS_DetailStaticControlCommandDelegate() { _speechService.TextToSpeech(CurrentRssSearchResult.Title); } private ICommand _textToSpeechBLOGPOSTS_DetailStaticControlCommand; /// <summary> /// Gets the TextToSpeechBLOGPOSTS_DetailStaticControlCommand command. /// </summary> public ICommand TextToSpeechBLOGPOSTS_DetailStaticControlCommand { get { return _textToSpeechBLOGPOSTS_DetailStaticControlCommand = _textToSpeechBLOGPOSTS_DetailStaticControlCommand ?? new ViewModelsBase.DelegateCommand(TextToSpeechBLOGPOSTS_DetailStaticControlCommandDelegate); } } /// <summary> /// Delegate method for the ShareBLOGPOSTS_DetailStaticControlCommand command. /// </summary> public void ShareBLOGPOSTS_DetailStaticControlCommandDelegate() { _shareService.Share(CurrentRssSearchResult.Title, "", CurrentRssSearchResult.FeedUrl, CurrentRssSearchResult.ImageUrl); } private ICommand _shareBLOGPOSTS_DetailStaticControlCommand; /// <summary> /// Gets the ShareBLOGPOSTS_DetailStaticControlCommand command. /// </summary> public ICommand ShareBLOGPOSTS_DetailStaticControlCommand { get { return _shareBLOGPOSTS_DetailStaticControlCommand = _shareBLOGPOSTS_DetailStaticControlCommand ?? new ViewModelsBase.DelegateCommand(ShareBLOGPOSTS_DetailStaticControlCommandDelegate); } } /// <summary> /// Delegate method for the PinToStartBLOGPOSTS_DetailStaticControlCommand command. /// </summary> public void PinToStartBLOGPOSTS_DetailStaticControlCommandDelegate() { _liveTileService.PinToStart(typeof(IViewModels.IBLOGPOSTS_DetailViewModel), CreateTileInfoBLOGPOSTS_DetailStaticControl()); } private ICommand _pinToStartBLOGPOSTS_DetailStaticControlCommand; /// <summary> /// Gets the PinToStartBLOGPOSTS_DetailStaticControlCommand command. /// </summary> public ICommand PinToStartBLOGPOSTS_DetailStaticControlCommand { get { return _pinToStartBLOGPOSTS_DetailStaticControlCommand = _pinToStartBLOGPOSTS_DetailStaticControlCommand ?? new ViewModelsBase.DelegateCommand(PinToStartBLOGPOSTS_DetailStaticControlCommandDelegate); } } /// <summary> /// Delegate method for the GoToSourceBLOGPOSTS_DetailStaticControlCommand command. /// </summary> public void GoToSourceBLOGPOSTS_DetailStaticControlCommandDelegate() { _navigationService.NavigateTo(string.IsNullOrEmpty(CurrentRssSearchResult.FeedUrl) ? null : new Uri(CurrentRssSearchResult.FeedUrl)); } private ICommand _goToSourceBLOGPOSTS_DetailStaticControlCommand; /// <summary> /// Gets the GoToSourceBLOGPOSTS_DetailStaticControlCommand command. /// </summary> public ICommand GoToSourceBLOGPOSTS_DetailStaticControlCommand { get { return _goToSourceBLOGPOSTS_DetailStaticControlCommand = _goToSourceBLOGPOSTS_DetailStaticControlCommand ?? new ViewModelsBase.DelegateCommand(GoToSourceBLOGPOSTS_DetailStaticControlCommandDelegate); } } /// <summary> /// Delegate method for the NextpanoramaBLOGPOSTS_Detail0 command. /// </summary> public async void NextpanoramaBLOGPOSTS_Detail0Delegate() { LoadingCurrentRssSearchResult = true; var next = await _bLOGPOSTS_rssfeed.Next(CurrentRssSearchResult); if(next != null) CurrentRssSearchResult = next; RefreshHasPrevNext(); } private bool _loadingCurrentRssSearchResult; public bool LoadingCurrentRssSearchResult { get { return _loadingCurrentRssSearchResult; } set { SetProperty(ref _loadingCurrentRssSearchResult, value); } } private ICommand _nextpanoramaBLOGPOSTS_Detail0; /// <summary> /// Gets the NextpanoramaBLOGPOSTS_Detail0 command. /// </summary> public ICommand NextpanoramaBLOGPOSTS_Detail0 { get { return _nextpanoramaBLOGPOSTS_Detail0 = _nextpanoramaBLOGPOSTS_Detail0 ?? new ViewModelsBase.DelegateCommand(NextpanoramaBLOGPOSTS_Detail0Delegate); } } /// <summary> /// Delegate method for the PreviouspanoramaBLOGPOSTS_Detail0 command. /// </summary> public async void PreviouspanoramaBLOGPOSTS_Detail0Delegate() { LoadingCurrentRssSearchResult = true; var prev = await _bLOGPOSTS_rssfeed.Previous(CurrentRssSearchResult); if(prev != null) CurrentRssSearchResult = prev; RefreshHasPrevNext(); } private ICommand _previouspanoramaBLOGPOSTS_Detail0; /// <summary> /// Gets the PreviouspanoramaBLOGPOSTS_Detail0 command. /// </summary> public ICommand PreviouspanoramaBLOGPOSTS_Detail0 { get { return _previouspanoramaBLOGPOSTS_Detail0 = _previouspanoramaBLOGPOSTS_Detail0 ?? new ViewModelsBase.DelegateCommand(PreviouspanoramaBLOGPOSTS_Detail0Delegate); } } private async void RefreshHasPrevNext() { HasPreviouspanoramaBLOGPOSTS_Detail0 = await _bLOGPOSTS_rssfeed.HasPrevious(CurrentRssSearchResult); HasNextpanoramaBLOGPOSTS_Detail0 = await _bLOGPOSTS_rssfeed.HasNext(CurrentRssSearchResult); LoadingCurrentRssSearchResult = false; } public object NavigationContext { set { if (!(value is EntitiesBase.RssSearchResult)) { return; } CurrentRssSearchResult = value as EntitiesBase.RssSearchResult; RefreshHasPrevNext(); } } /// <summary> /// Initializes a <see cref="Services.TileInfo" /> object for the BLOGPOSTS_DetailStaticControl control. /// </summary> /// <returns>A <see cref="Services.TileInfo" /> object.</returns> public Services.TileInfo CreateTileInfoBLOGPOSTS_DetailStaticControl() { var tileInfo = new Services.TileInfo { CurrentId = CurrentRssSearchResult.Title, Title = CurrentRssSearchResult.Title, BackTitle = CurrentRssSearchResult.Title, BackContent = string.Empty, Count = 0, BackgroundImagePath = CurrentRssSearchResult.ImageUrl, BackBackgroundImagePath = CurrentRssSearchResult.ImageUrl, LogoPath = "Logo-1ea99746-061b-4dec-a7fe-1eee87957505.png" }; return tileInfo; } } }
using System; using System.Linq; using Eto.Drawing; using Eto.Forms; using swi = System.Windows.Input; using swm = System.Windows.Media; using sw = System.Windows; using sp = System.Printing; using swc = System.Windows.Controls; using swmi = System.Windows.Media.Imaging; using swd = System.Windows.Documents; using Eto.Wpf.Drawing; namespace Eto.Wpf { public static class WpfConversions { public const float WheelDelta = 120f; public static readonly sw.Size PositiveInfinitySize = new sw.Size(double.PositiveInfinity, double.PositiveInfinity); public static readonly sw.Size ZeroSize = new sw.Size(0, 0); public static swm.Color ToWpf(this Color value) { return swm.Color.FromArgb((byte)(value.A * byte.MaxValue), (byte)(value.R * byte.MaxValue), (byte)(value.G * byte.MaxValue), (byte)(value.B * byte.MaxValue)); } public static swm.Brush ToWpfBrush(this Color value, swm.Brush brush = null) { var solidBrush = brush as swm.SolidColorBrush; if (solidBrush == null || solidBrush.IsSealed) { solidBrush = new swm.SolidColorBrush(); } solidBrush.Color = value.ToWpf(); return solidBrush; } public static Color ToEto(this swm.Color value) { return new Color { A = value.A / 255f, R = value.R / 255f, G = value.G / 255f, B = value.B / 255f }; } public static Color ToEtoColor(this swm.Brush brush) { var solidBrush = brush as swm.SolidColorBrush; if (solidBrush != null) return solidBrush.Color.ToEto(); return Colors.Transparent; } public static Padding ToEto(this sw.Thickness value) { return new Padding((int)value.Left, (int)value.Top, (int)value.Right, (int)value.Bottom); } public static sw.Thickness ToWpf(this Padding value) { return new sw.Thickness(value.Left, value.Top, value.Right, value.Bottom); } public static Rectangle ToEto(this sw.Rect value) { if (value.IsEmpty) return Rectangle.Empty; return new Rectangle((int)value.X, (int)value.Y, (int)value.Width, (int)value.Height); } public static RectangleF ToEtoF(this sw.Rect value) { if (value.IsEmpty) return RectangleF.Empty; return new RectangleF((float)value.X, (float)value.Y, (float)value.Width, (float)value.Height); } public static sw.Rect ToWpf(this Rectangle value) { return new sw.Rect(value.X, value.Y, value.Width, value.Height); } public static sw.Int32Rect ToWpfInt32(this Rectangle value) { return new sw.Int32Rect(value.X, value.Y, value.Width, value.Height); } public static sw.Rect ToWpf(this RectangleF value) { return new sw.Rect(value.X, value.Y, value.Width, value.Height); } public static SizeF ToEto(this sw.Size value) { return new SizeF((float)value.Width, (float)value.Height); } public static Size ToEtoSize(this sw.Size value) { return new Size((int)(double.IsNaN(value.Width) ? -1 : value.Width), (int)(double.IsNaN(value.Height) ? -1 : value.Height)); } public static sw.Size ToWpf(this Size value) { return new sw.Size(value.Width == -1 ? double.NaN : value.Width, value.Height == -1 ? double.NaN : value.Height); } public static sw.Size ToWpf(this SizeF value) { return new sw.Size(value.Width, value.Height); } public static PointF ToEto(this sw.Point value) { return new PointF((float)value.X, (float)value.Y); } public static Point ToEtoPoint(this sw.Point value) { return new Point((int)value.X, (int)value.Y); } public static sw.Point ToWpf(this Point value) { return new sw.Point(value.X, value.Y); } public static sw.Point ToWpf(this PointF value) { return new sw.Point(value.X, value.Y); } public static KeyEventArgs ToEto(this swi.KeyEventArgs e, KeyEventType keyType) { var key = e.Key.ToEtoWithModifier(swi.Keyboard.Modifiers); return new KeyEventArgs(key, keyType) { Handled = e.Handled }; } public static MouseEventArgs ToEto(this swi.MouseButtonEventArgs e, sw.IInputElement control, swi.MouseButtonState buttonState = swi.MouseButtonState.Pressed) { var buttons = MouseButtons.None; if (e.ChangedButton == swi.MouseButton.Left && e.LeftButton == buttonState) buttons |= MouseButtons.Primary; if (e.ChangedButton == swi.MouseButton.Right && e.RightButton == buttonState) buttons |= MouseButtons.Alternate; if (e.ChangedButton == swi.MouseButton.Middle && e.MiddleButton == buttonState) buttons |= MouseButtons.Middle; var modifiers = swi.Keyboard.Modifiers.ToEto(); var location = e.GetPosition(control).ToEto(); return new MouseEventArgs(buttons, modifiers, location); } public static MouseEventArgs ToEto(this swi.MouseEventArgs e, sw.IInputElement control, swi.MouseButtonState buttonState = swi.MouseButtonState.Pressed) { var buttons = MouseButtons.None; if (e.LeftButton == buttonState) buttons |= MouseButtons.Primary; if (e.RightButton == buttonState) buttons |= MouseButtons.Alternate; if (e.MiddleButton == buttonState) buttons |= MouseButtons.Middle; var modifiers = swi.Keyboard.Modifiers.ToEto(); var location = e.GetPosition(control).ToEto(); return new MouseEventArgs(buttons, modifiers, location); } public static MouseEventArgs ToEto(this swi.MouseWheelEventArgs e, sw.IInputElement control, swi.MouseButtonState buttonState = swi.MouseButtonState.Pressed) { var buttons = MouseButtons.None; if (e.LeftButton == buttonState) buttons |= MouseButtons.Primary; if (e.RightButton == buttonState) buttons |= MouseButtons.Alternate; if (e.MiddleButton == buttonState) buttons |= MouseButtons.Middle; var modifiers = swi.Keyboard.Modifiers.ToEto(); var location = e.GetPosition(control).ToEto(); var delta = new SizeF(0, (float)e.Delta / WheelDelta); return new MouseEventArgs(buttons, modifiers, location, delta); } public static swm.BitmapScalingMode ToWpf(this ImageInterpolation value) { switch (value) { case ImageInterpolation.Default: return swm.BitmapScalingMode.Unspecified; case ImageInterpolation.None: return swm.BitmapScalingMode.NearestNeighbor; case ImageInterpolation.Low: return swm.BitmapScalingMode.LowQuality; case ImageInterpolation.Medium: return swm.BitmapScalingMode.HighQuality; case ImageInterpolation.High: return swm.BitmapScalingMode.HighQuality; default: throw new NotSupportedException(); } } public static ImageInterpolation ToEto(this swm.BitmapScalingMode value) { switch (value) { case swm.BitmapScalingMode.HighQuality: return ImageInterpolation.High; case swm.BitmapScalingMode.LowQuality: return ImageInterpolation.Low; case swm.BitmapScalingMode.NearestNeighbor: return ImageInterpolation.None; case swm.BitmapScalingMode.Unspecified: return ImageInterpolation.Default; default: throw new NotSupportedException(); } } public static sp.PageOrientation ToSP(this PageOrientation value) { switch (value) { case PageOrientation.Portrait: return sp.PageOrientation.Portrait; case PageOrientation.Landscape: return sp.PageOrientation.Landscape; default: throw new NotSupportedException(); } } public static PageOrientation ToEto(this sp.PageOrientation? value) { if (value == null) return PageOrientation.Portrait; switch (value.Value) { case sp.PageOrientation.Landscape: return PageOrientation.Landscape; case sp.PageOrientation.Portrait: return PageOrientation.Portrait; default: throw new NotSupportedException(); } } public static swc.PageRange ToPageRange(this Range<int> range) { return new swc.PageRange(range.Start, range.End); } public static Range<int> ToEto(this swc.PageRange range) { return new Range<int>(range.PageFrom, range.PageTo); } public static swc.PageRangeSelection ToSWC(this PrintSelection value) { switch (value) { case PrintSelection.AllPages: return swc.PageRangeSelection.AllPages; case PrintSelection.SelectedPages: return swc.PageRangeSelection.UserPages; default: throw new NotSupportedException(); } } public static PrintSelection ToEto(this swc.PageRangeSelection value) { switch (value) { case swc.PageRangeSelection.AllPages: return PrintSelection.AllPages; case swc.PageRangeSelection.UserPages: return PrintSelection.SelectedPages; default: throw new NotSupportedException(); } } public static Size GetSize(this sw.FrameworkElement element) { if (!double.IsNaN(element.ActualWidth) && !double.IsNaN(element.ActualHeight)) return new Size((int)element.ActualWidth, (int)element.ActualHeight); return new Size((int)(double.IsNaN(element.Width) ? -1 : element.Width), (int)(double.IsNaN(element.Height) ? -1 : element.Height)); } public static void SetSize(this sw.FrameworkElement element, Size size) { element.Width = size.Width == -1 ? double.NaN : size.Width; element.Height = size.Height == -1 ? double.NaN : size.Height; } public static void SetSize(this sw.FrameworkElement element, sw.Size size) { element.Width = size.Width; element.Height = size.Height; } public static FontStyle Convert(sw.FontStyle fontStyle, sw.FontWeight fontWeight) { var style = FontStyle.None; if (fontStyle == sw.FontStyles.Italic) style |= FontStyle.Italic; if (fontStyle == sw.FontStyles.Oblique) style |= FontStyle.Italic; if (fontWeight == sw.FontWeights.Bold) style |= FontStyle.Bold; return style; } public static FontDecoration Convert(sw.TextDecorationCollection decorations) { var decoration = FontDecoration.None; if (decorations != null) { if (sw.TextDecorations.Underline.All(decorations.Contains)) decoration |= FontDecoration.Underline; if (sw.TextDecorations.Strikethrough.All(decorations.Contains)) decoration |= FontDecoration.Strikethrough; } return decoration; } public static Bitmap ToEto(this swmi.BitmapSource bitmap) { return new Bitmap(new BitmapHandler(bitmap)); } public static swmi.BitmapSource ToWpf(this Image image, int? size = null) { if (image == null) return null; var imageHandler = image.Handler as IWpfImage; if (imageHandler != null) return imageHandler.GetImageClosestToSize(size); return image.ControlObject as swmi.BitmapSource; } public static swc.Image ToWpfImage(this Image image, int? size = null) { var source = image.ToWpf(size); if (source == null) return null; var swcImage = new swc.Image { Source = source }; if (size != null) { swcImage.MaxWidth = size.Value; swcImage.MaxHeight = size.Value; } return swcImage; } public static swm.Pen ToWpf(this Pen pen, bool clone = false) { var p = (swm.Pen)pen.ControlObject; if (clone) p = p.Clone(); return p; } public static swm.PenLineJoin ToWpf(this PenLineJoin value) { switch (value) { case PenLineJoin.Miter: return swm.PenLineJoin.Miter; case PenLineJoin.Bevel: return swm.PenLineJoin.Bevel; case PenLineJoin.Round: return swm.PenLineJoin.Round; default: throw new NotSupportedException(); } } public static PenLineJoin ToEto(this swm.PenLineJoin value) { switch (value) { case swm.PenLineJoin.Bevel: return PenLineJoin.Bevel; case swm.PenLineJoin.Miter: return PenLineJoin.Miter; case swm.PenLineJoin.Round: return PenLineJoin.Round; default: throw new NotSupportedException(); } } public static swm.PenLineCap ToWpf(this PenLineCap value) { switch (value) { case PenLineCap.Butt: return swm.PenLineCap.Flat; case PenLineCap.Round: return swm.PenLineCap.Round; case PenLineCap.Square: return swm.PenLineCap.Square; default: throw new NotSupportedException(); } } public static PenLineCap ToEto(this swm.PenLineCap value) { switch (value) { case swm.PenLineCap.Flat: return PenLineCap.Butt; case swm.PenLineCap.Round: return PenLineCap.Round; case swm.PenLineCap.Square: return PenLineCap.Square; default: throw new NotSupportedException(); } } public static swm.Brush ToWpf(this Brush brush, bool clone = false) { var b = (swm.Brush)brush.ControlObject; if (clone) b = b.Clone(); return b; } public static swm.Matrix ToWpf(this IMatrix matrix) { return (swm.Matrix)matrix.ControlObject; } public static swm.Transform ToWpfTransform(this IMatrix matrix) { return new swm.MatrixTransform(matrix.ToWpf()); } public static IMatrix ToEtoMatrix(this swm.Transform transform) { return new MatrixHandler(transform.Value); } public static swm.PathGeometry ToWpf(this IGraphicsPath path) { return (swm.PathGeometry)path.ControlObject; } public static swm.GradientSpreadMethod ToWpf(this GradientWrapMode wrap) { switch (wrap) { case GradientWrapMode.Reflect: return swm.GradientSpreadMethod.Reflect; case GradientWrapMode.Repeat: return swm.GradientSpreadMethod.Repeat; case GradientWrapMode.Pad: return swm.GradientSpreadMethod.Pad; default: throw new NotSupportedException(); } } public static GradientWrapMode ToEto(this swm.GradientSpreadMethod spread) { switch (spread) { case swm.GradientSpreadMethod.Reflect: return GradientWrapMode.Reflect; case swm.GradientSpreadMethod.Repeat: return GradientWrapMode.Repeat; case swm.GradientSpreadMethod.Pad: return GradientWrapMode.Pad; default: throw new NotSupportedException(); } } public static WindowStyle ToEto(this sw.WindowStyle style) { switch (style) { case sw.WindowStyle.None: return WindowStyle.None; case sw.WindowStyle.ThreeDBorderWindow: return WindowStyle.Default; default: throw new NotSupportedException(); } } public static sw.WindowStyle ToWpf(this WindowStyle style) { switch (style) { case WindowStyle.None: return sw.WindowStyle.None; case WindowStyle.Default: return sw.WindowStyle.ThreeDBorderWindow; default: throw new NotSupportedException(); } } public static CalendarMode ToEto(this swc.CalendarSelectionMode mode) { switch (mode) { case System.Windows.Controls.CalendarSelectionMode.SingleDate: return CalendarMode.Single; case System.Windows.Controls.CalendarSelectionMode.SingleRange: return CalendarMode.Range; case System.Windows.Controls.CalendarSelectionMode.MultipleRange: case System.Windows.Controls.CalendarSelectionMode.None: default: throw new NotSupportedException(); } } public static swc.CalendarSelectionMode ToWpf(this CalendarMode mode) { switch (mode) { case CalendarMode.Single: return swc.CalendarSelectionMode.SingleDate; case CalendarMode.Range: return swc.CalendarSelectionMode.SingleRange; default: throw new NotSupportedException(); } } public static TextAlignment ToEto(this sw.HorizontalAlignment align) { switch (align) { case sw.HorizontalAlignment.Left: return TextAlignment.Left; case sw.HorizontalAlignment.Right: return TextAlignment.Right; case sw.HorizontalAlignment.Center: return TextAlignment.Center; default: throw new NotSupportedException(); } } public static sw.HorizontalAlignment ToWpf(this TextAlignment align) { switch (align) { case TextAlignment.Center: return sw.HorizontalAlignment.Center; case TextAlignment.Left: return sw.HorizontalAlignment.Left; case TextAlignment.Right: return sw.HorizontalAlignment.Right; default: throw new NotSupportedException(); } } public static sw.TextAlignment ToWpfTextAlignment(this TextAlignment align) { switch (align) { case TextAlignment.Center: return sw.TextAlignment.Center; case TextAlignment.Left: return sw.TextAlignment.Left; case TextAlignment.Right: return sw.TextAlignment.Right; default: throw new NotSupportedException(); } } public static VerticalAlignment ToEto(this sw.VerticalAlignment align) { switch (align) { case sw.VerticalAlignment.Top: return VerticalAlignment.Top; case sw.VerticalAlignment.Bottom: return VerticalAlignment.Bottom; case sw.VerticalAlignment.Center: return VerticalAlignment.Center; case sw.VerticalAlignment.Stretch: return VerticalAlignment.Stretch; default: throw new NotSupportedException(); } } public static sw.VerticalAlignment ToWpf(this VerticalAlignment align) { switch (align) { case VerticalAlignment.Top: return sw.VerticalAlignment.Top; case VerticalAlignment.Bottom: return sw.VerticalAlignment.Bottom; case VerticalAlignment.Center: return sw.VerticalAlignment.Center; case VerticalAlignment.Stretch: return sw.VerticalAlignment.Stretch; default: throw new NotSupportedException(); } } public static Font SetEtoFont(this swc.Control control, Font font, Action<sw.TextDecorationCollection> setDecorations = null) { if (control == null) return font; if (font != null) { ((FontHandler)font.Handler).Apply(control, setDecorations); } else { control.SetValue(swc.Control.FontFamilyProperty, swc.Control.FontFamilyProperty.DefaultMetadata.DefaultValue); control.SetValue(swc.Control.FontStyleProperty, swc.Control.FontStyleProperty.DefaultMetadata.DefaultValue); control.SetValue(swc.Control.FontWeightProperty, swc.Control.FontWeightProperty.DefaultMetadata.DefaultValue); control.SetValue(swc.Control.FontSizeProperty, swc.Control.FontSizeProperty.DefaultMetadata.DefaultValue); } return font; } public static Font SetEtoFont(this swd.TextRange control, Font font) { if (control == null) return font; if (font != null) { ((FontHandler)font.Handler).Apply(control); } else { control.ApplyPropertyValue(swd.TextElement.FontFamilyProperty, swc.Control.FontFamilyProperty.DefaultMetadata.DefaultValue); control.ApplyPropertyValue(swd.TextElement.FontStyleProperty, swc.Control.FontStyleProperty.DefaultMetadata.DefaultValue); control.ApplyPropertyValue(swd.TextElement.FontWeightProperty, swc.Control.FontWeightProperty.DefaultMetadata.DefaultValue); control.ApplyPropertyValue(swd.TextElement.FontSizeProperty, swc.Control.FontSizeProperty.DefaultMetadata.DefaultValue); control.ApplyPropertyValue(swd.Inline.TextDecorationsProperty, new sw.TextDecorationCollection()); } return font; } public static FontFamily SetEtoFamily(this swd.TextRange control, FontFamily fontFamily) { if (control == null) return fontFamily; if (fontFamily != null) { ((FontFamilyHandler)fontFamily.Handler).Apply(control); } else { control.ApplyPropertyValue(swd.TextElement.FontFamilyProperty, swc.Control.FontFamilyProperty.DefaultMetadata.DefaultValue); } return fontFamily; } public static Font SetEtoFont(this swc.TextBlock control, Font font, Action<sw.TextDecorationCollection> setDecorations = null) { if (control == null) return font; if (font != null) { ((FontHandler)font.Handler).Apply(control, setDecorations); } else { control.SetValue(swc.Control.FontFamilyProperty, swc.Control.FontFamilyProperty.DefaultMetadata.DefaultValue); control.SetValue(swc.Control.FontStyleProperty, swc.Control.FontStyleProperty.DefaultMetadata.DefaultValue); control.SetValue(swc.Control.FontWeightProperty, swc.Control.FontWeightProperty.DefaultMetadata.DefaultValue); control.SetValue(swc.Control.FontSizeProperty, swc.Control.FontSizeProperty.DefaultMetadata.DefaultValue); } return font; } public static swc.Dock ToWpf(this DockPosition position) { switch (position) { case DockPosition.Top: return swc.Dock.Top; case DockPosition.Left: return swc.Dock.Left; case DockPosition.Right: return swc.Dock.Right; case DockPosition.Bottom: return swc.Dock.Bottom; default: throw new NotSupportedException(); } } public static DockPosition ToEtoTabPosition(this swc.Dock dock) { switch (dock) { case swc.Dock.Left: return DockPosition.Left; case swc.Dock.Top: return DockPosition.Top; case swc.Dock.Right: return DockPosition.Right; case swc.Dock.Bottom: return DockPosition.Bottom; default: throw new NotSupportedException(); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. namespace Microsoft.PowerShell.Commands { using System; using System.Collections; using System.Management.Automation; using System.Management.Automation.Host; using System.Management.Automation.Internal; using Microsoft.PowerShell.Commands.Internal.Format; /// <summary> /// Null sink to absorb pipeline output. /// </summary> [CmdletAttribute("Out", "Null", SupportsShouldProcess = false, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113366", RemotingCapability = RemotingCapability.None)] public class OutNullCommand : PSCmdlet { /// <summary> /// This parameter specifies the current pipeline object. /// </summary> [Parameter(ValueFromPipeline = true)] public PSObject InputObject { set; get; } = AutomationNull.Value; /// <summary> /// Do nothing. /// </summary> protected override void ProcessRecord() { // explicitely overridden: // do not do any processing } } /// <summary> /// Implementation for the out-default command /// this command it implicitly inject by the /// powershell host at the end of the pipeline as the /// default sink (display to console screen) /// </summary> [Cmdlet(VerbsData.Out, "Default", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113362", RemotingCapability = RemotingCapability.None)] public class OutDefaultCommand : FrontEndCommandBase { /// <summary> /// Determines whether objects should be sent to API consumers. /// This command is automatically added to the pipeline when PowerShell is transcribing and /// invoked via API. This ensures that the objects pass through the formatting and output /// system, but can still make it to the API consumer. /// </summary> [Parameter()] public SwitchParameter Transcript { get; set; } /// <summary> /// Set inner command. /// </summary> public OutDefaultCommand() { this.implementation = new OutputManagerInner(); } /// <summary> /// Just hook up the LineOutput interface. /// </summary> protected override void BeginProcessing() { PSHostUserInterface console = this.Host.UI; ConsoleLineOutput lineOutput = new ConsoleLineOutput(console, false, new TerminatingErrorContext(this)); ((OutputManagerInner)this.implementation).LineOutput = lineOutput; MshCommandRuntime mrt = this.CommandRuntime as MshCommandRuntime; if (mrt != null) { mrt.MergeUnclaimedPreviousErrorResults = true; } if (Transcript) { _transcribeOnlyCookie = Host.UI.SetTranscribeOnly(); } // This needs to be done directly through the command runtime, as Out-Default // doesn't actually write pipeline objects. base.BeginProcessing(); if (Context.CurrentCommandProcessor.CommandRuntime.OutVarList != null) { _outVarResults = new ArrayList(); } } /// <summary> /// Process the OutVar, if set. /// </summary> protected override void ProcessRecord() { if (Transcript) { WriteObject(InputObject); } // This needs to be done directly through the command runtime, as Out-Default // doesn't actually write pipeline objects. if (_outVarResults != null) { object inputObjectBase = PSObject.Base(InputObject); // Ignore errors and formatting records, as those can't be captured if ( (inputObjectBase != null) && (!(inputObjectBase is ErrorRecord)) && (!inputObjectBase.GetType().FullName.StartsWith( "Microsoft.PowerShell.Commands.Internal.Format", StringComparison.OrdinalIgnoreCase))) { _outVarResults.Add(InputObject); } } base.ProcessRecord(); } /// <summary> /// Swap the outVar with what we've processed, if OutVariable is set. /// </summary> protected override void EndProcessing() { // This needs to be done directly through the command runtime, as Out-Default // doesn't actually write pipeline objects. if ((_outVarResults != null) && (_outVarResults.Count > 0)) { Context.CurrentCommandProcessor.CommandRuntime.OutVarList.Clear(); foreach (Object item in _outVarResults) { Context.CurrentCommandProcessor.CommandRuntime.OutVarList.Add(item); } _outVarResults = null; } base.EndProcessing(); } /// <summary> /// Revert transcription state on Dispose. /// </summary> protected override void InternalDispose() { try { base.InternalDispose(); } finally { if (_transcribeOnlyCookie != null) { _transcribeOnlyCookie.Dispose(); _transcribeOnlyCookie = null; } } } private ArrayList _outVarResults = null; private IDisposable _transcribeOnlyCookie = null; } /// <summary> /// Implementation for the out-host command. /// </summary> [Cmdlet(VerbsData.Out, "Host", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113365", RemotingCapability = RemotingCapability.None)] public class OutHostCommand : FrontEndCommandBase { #region Command Line Parameters /// <summary> /// Non positional parameter to specify paging. /// </summary> private bool _paging; #endregion /// <summary> /// Constructor of OutHostCommand. /// </summary> public OutHostCommand() { this.implementation = new OutputManagerInner(); } /// <summary> /// Optional, non positional parameter to specify paging /// FALSE: names only /// TRUE: full info. /// </summary> [Parameter] public SwitchParameter Paging { get { return _paging; } set { _paging = value; } } /// <summary> /// Just hook up the LineOutput interface. /// </summary> protected override void BeginProcessing() { PSHostUserInterface console = this.Host.UI; ConsoleLineOutput lineOutput = new ConsoleLineOutput(console, _paging, new TerminatingErrorContext(this)); ((OutputManagerInner)this.implementation).LineOutput = lineOutput; base.BeginProcessing(); } } }
// **************************************************************** // This is free software licensed under the NUnit license. You // may obtain a copy of the license as well as information regarding // copyright ownership at http://nunit.org/?p=license&r=2.4. // **************************************************************** using System; using System.Globalization; using System.IO; using System.Text; using System.Threading; using System.Xml; using System.Xml.Schema; using NUnit.Framework; using NUnit.Util; using NUnit.TestUtilities; namespace NUnit.Core.Tests { /// <summary> /// Summary description for XmlTest. /// </summary> /// [TestFixture] public class XmlTest { public class SchemaValidator { private XmlValidatingReader myXmlValidatingReader; private bool success; public SchemaValidator(string xmlFile, string schemaFile) { XmlSchemaCollection myXmlSchemaCollection = new XmlSchemaCollection(); XmlTextReader xmlTextReader = new XmlTextReader(schemaFile); try { myXmlSchemaCollection.Add(XmlSchema.Read(xmlTextReader, null)); } finally { xmlTextReader.Close(); } // Validate the XML file with the schema XmlTextReader myXmlTextReader = new XmlTextReader (xmlFile); myXmlValidatingReader = new XmlValidatingReader(myXmlTextReader); myXmlValidatingReader.Schemas.Add(myXmlSchemaCollection); myXmlValidatingReader.ValidationType = ValidationType.Schema; } public bool Validate() { success = true; try { // Set the validation event handler myXmlValidatingReader.ValidationEventHandler += new ValidationEventHandler (this.ValidationEventHandle); // Read XML data while (myXmlValidatingReader.Read()){} } catch (Exception e) { throw new NUnitException(e.Message, e); } finally { myXmlValidatingReader.Close(); } return success; } public void ValidationEventHandle (object sender, ValidationEventArgs args) { success = false; Console.WriteLine("\tValidation error: " + args.Message); if (args.Severity == XmlSeverityType.Warning) { Console.WriteLine("No schema found to enforce validation."); } else if (args.Severity == XmlSeverityType.Error) { Console.WriteLine("validation error occurred when validating the instance document."); } if (args.Exception != null) // XSD schema validation error { Console.WriteLine(args.Exception.SourceUri + "," + args.Exception.LinePosition + "," + args.Exception.LineNumber); } } } private void runSchemaValidatorTest(string reportFileName, CultureInfo testCulture) { // Preserve current culture CultureInfo previousCulture = Thread.CurrentThread.CurrentCulture; // Enable test culture Thread.CurrentThread.CurrentCulture = testCulture; try { string testsDll = "mock-assembly.dll"; TestSuiteBuilder builder = new TestSuiteBuilder(); Test suite = builder.Build( new TestPackage( testsDll ) ); TestResult result = suite.Run(NullListener.NULL); XmlResultVisitor visitor = new XmlResultVisitor(reportFileName, result); result.Accept(visitor); visitor.Write(); SchemaValidator validator = new SchemaValidator(reportFileName, schemaFile.Path); Assert.IsTrue(validator.Validate(), "validate failed"); } finally { // Restore previous culture Thread.CurrentThread.CurrentCulture = previousCulture; } } private void runSchemaValidatorTest(TextWriter writer, CultureInfo testCulture) { // Preserve current culture CultureInfo previousCulture = Thread.CurrentThread.CurrentCulture; // Enable test culture Thread.CurrentThread.CurrentCulture = testCulture; try { string testsDll = "mock-assembly.dll"; TestSuiteBuilder builder = new TestSuiteBuilder(); Test suite = builder.Build( new TestPackage( testsDll ) ); TestResult result = suite.Run(NullListener.NULL); XmlResultVisitor visitor = new XmlResultVisitor(writer, result); result.Accept(visitor); visitor.Write(); } finally { // Restore previous culture Thread.CurrentThread.CurrentCulture = previousCulture; } } private string tempFile; private TempResourceFile schemaFile; [SetUp] public void CreateTempFileName() { tempFile = "temp" + Guid.NewGuid().ToString() + ".xml"; schemaFile = new TempResourceFile( GetType(), "Results.xsd"); } [TearDown] public void RemoveTempFiles() { schemaFile.Dispose(); FileInfo info = new FileInfo(tempFile); if(info.Exists) info.Delete(); } [Test] public void TestSchemaValidatorInvariantCulture() { runSchemaValidatorTest(tempFile, CultureInfo.InvariantCulture); } [Test] public void TestSchemaValidatorUnitedStatesCulture() { CultureInfo unitedStatesCulture = new CultureInfo("en-US", false); runSchemaValidatorTest(tempFile,unitedStatesCulture); } [Test] public void TestStream() { CultureInfo unitedStatesCulture = new CultureInfo("en-US", false); runSchemaValidatorTest(tempFile,unitedStatesCulture); StringBuilder builder = new StringBuilder(); StringWriter writer = new StringWriter(builder); runSchemaValidatorTest(writer,unitedStatesCulture); string second = builder.ToString(); StreamReader reader = new StreamReader(tempFile); string first = reader.ReadToEnd(); reader.Close(); Assert.AreEqual(removeTimeAndAssertAttributes(first), removeTimeAndAssertAttributes(second)); } [Test] public void TestSchemaValidatorFrenchCulture() { CultureInfo frenchCulture = new CultureInfo("fr-FR", false); runSchemaValidatorTest(tempFile, frenchCulture); } [Test] public void removeTime() { string input = "foo time=\"123.745774xxx\" bar asserts=\"5\" time=\"0\""; string output = removeTimeAndAssertAttributes(input); Assert.AreEqual("foo bar ", output); } private string removeTimeAndAssertAttributes(string text) { int index = 0; while ((index = text.IndexOf("time=\"")) != -1) { int endQuote = text.IndexOf("\"", index + 7); text = text.Remove(index, endQuote - index + 1); } while ((index = text.IndexOf("asserts=\"")) != -1) { int endQuote = text.IndexOf("\"", index + 10); text = text.Remove(index, endQuote - index + 1); } return text; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Diagnostics { [System.Diagnostics.SwitchLevelAttribute(typeof(bool))] public partial class BooleanSwitch : System.Diagnostics.Switch { public BooleanSwitch(string displayName, string description) : base (default(string), default(string)) { } public BooleanSwitch(string displayName, string description, string defaultSwitchValue) : base (default(string), default(string)) { } public bool Enabled { get { throw null; } set { } } protected override void OnValueChanged() { } } public partial class CorrelationManager { internal CorrelationManager() { } public System.Guid ActivityId { get { throw null; } set { } } public System.Collections.Stack LogicalOperationStack { get { throw null; } } public void StartLogicalOperation() { } public void StartLogicalOperation(object operationId) { } public void StopLogicalOperation() { } } public partial class DefaultTraceListener : System.Diagnostics.TraceListener { public DefaultTraceListener() { } public bool AssertUiEnabled { get { throw null; } set { } } public string LogFileName { get { throw null; } set { } } public override void Fail(string message) { } public override void Fail(string message, string detailMessage) { } public override void Write(string message) { } public override void WriteLine(string message) { } } public partial class EventTypeFilter : System.Diagnostics.TraceFilter { public EventTypeFilter(System.Diagnostics.SourceLevels level) { } public System.Diagnostics.SourceLevels EventType { get { throw null; } set { } } public override bool ShouldTrace(System.Diagnostics.TraceEventCache cache, string source, System.Diagnostics.TraceEventType eventType, int id, string formatOrMessage, object[] args, object data1, object[] data) { throw null; } } public partial class SourceFilter : System.Diagnostics.TraceFilter { public SourceFilter(string source) { } public string Source { get { throw null; } set { } } public override bool ShouldTrace(System.Diagnostics.TraceEventCache cache, string source, System.Diagnostics.TraceEventType eventType, int id, string formatOrMessage, object[] args, object data1, object[] data) { throw null; } } [System.FlagsAttribute] public enum SourceLevels { All = -1, Off = 0, Critical = 1, Error = 3, Warning = 7, Information = 15, Verbose = 31, [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] ActivityTracing = 65280, } public partial class SourceSwitch : System.Diagnostics.Switch { public SourceSwitch(string name) : base (default(string), default(string)) { } public SourceSwitch(string displayName, string defaultSwitchValue) : base (default(string), default(string)) { } public System.Diagnostics.SourceLevels Level { get { throw null; } set { } } protected override void OnValueChanged() { } public bool ShouldTrace(System.Diagnostics.TraceEventType eventType) { throw null; } } public abstract partial class Switch { protected Switch(string displayName, string description) { } protected Switch(string displayName, string description, string defaultSwitchValue) { } public System.Collections.Specialized.StringDictionary Attributes { get { throw null; } } public string Description { get { throw null; } } public string DisplayName { get { throw null; } } protected int SwitchSetting { get { throw null; } set { } } protected string Value { get { throw null; } set { } } protected virtual string[] GetSupportedAttributes() { throw null; } protected virtual void OnSwitchSettingChanged() { } protected virtual void OnValueChanged() { } } [System.AttributeUsageAttribute(System.AttributeTargets.Assembly | System.AttributeTargets.Class | System.AttributeTargets.Constructor | System.AttributeTargets.Event | System.AttributeTargets.Method | System.AttributeTargets.Property)] public sealed partial class SwitchAttribute : System.Attribute { public SwitchAttribute(string switchName, System.Type switchType) { } public string SwitchDescription { get { throw null; } set { } } public string SwitchName { get { throw null; } set { } } public System.Type SwitchType { get { throw null; } set { } } public static System.Diagnostics.SwitchAttribute[] GetAll(System.Reflection.Assembly assembly) { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.Class)] public sealed partial class SwitchLevelAttribute : System.Attribute { public SwitchLevelAttribute(System.Type switchLevelType) { } public System.Type SwitchLevelType { get { throw null; } set { } } } public sealed partial class Trace { internal Trace() { } public static bool AutoFlush { get { throw null; } set { } } public static System.Diagnostics.CorrelationManager CorrelationManager { get { throw null; } } public static int IndentLevel { get { throw null; } set { } } public static int IndentSize { get { throw null; } set { } } public static System.Diagnostics.TraceListenerCollection Listeners { get { throw null; } } public static bool UseGlobalLock { get { throw null; } set { } } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void Assert(bool condition) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void Assert(bool condition, string message) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void Assert(bool condition, string message, string detailMessage) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void Close() { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void Fail(string message) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void Fail(string message, string detailMessage) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void Flush() { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void Indent() { } public static void Refresh() { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void TraceError(string message) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void TraceError(string format, params object[] args) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void TraceInformation(string message) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void TraceInformation(string format, params object[] args) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void TraceWarning(string message) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void TraceWarning(string format, params object[] args) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void Unindent() { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void Write(object value) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void Write(object value, string category) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void Write(string message) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void Write(string message, string category) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void WriteIf(bool condition, object value) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void WriteIf(bool condition, object value, string category) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void WriteIf(bool condition, string message) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void WriteIf(bool condition, string message, string category) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void WriteLine(object value) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void WriteLine(object value, string category) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void WriteLine(string message) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void WriteLine(string message, string category) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void WriteLineIf(bool condition, object value) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void WriteLineIf(bool condition, object value, string category) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void WriteLineIf(bool condition, string message) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void WriteLineIf(bool condition, string message, string category) { } } public partial class TraceEventCache { public TraceEventCache() { } public string Callstack { get { throw null; } } public System.DateTime DateTime { get { throw null; } } public System.Collections.Stack LogicalOperationStack { get { throw null; } } public int ProcessId { get { throw null; } } public string ThreadId { get { throw null; } } public long Timestamp { get { throw null; } } } public enum TraceEventType { Critical = 1, Error = 2, Warning = 4, Information = 8, Verbose = 16, Start = 256, Stop = 512, Suspend = 1024, Resume = 2048, Transfer = 4096, } public abstract partial class TraceFilter { protected TraceFilter() { } public abstract bool ShouldTrace(System.Diagnostics.TraceEventCache cache, string source, System.Diagnostics.TraceEventType eventType, int id, string formatOrMessage, object[] args, object data1, object[] data); } public enum TraceLevel { Off = 0, Error = 1, Warning = 2, Info = 3, Verbose = 4, } public abstract partial class TraceListener : System.MarshalByRefObject, System.IDisposable { protected TraceListener() { } protected TraceListener(string name) { } public System.Collections.Specialized.StringDictionary Attributes { get { throw null; } } public System.Diagnostics.TraceFilter Filter { get { throw null; } set { } } public int IndentLevel { get { throw null; } set { } } public int IndentSize { get { throw null; } set { } } public virtual bool IsThreadSafe { get { throw null; } } public virtual string Name { get { throw null; } set { } } protected bool NeedIndent { get { throw null; } set { } } public System.Diagnostics.TraceOptions TraceOutputOptions { get { throw null; } set { } } public virtual void Close() { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public virtual void Fail(string message) { } public virtual void Fail(string message, string detailMessage) { } public virtual void Flush() { } protected virtual string[] GetSupportedAttributes() { throw null; } public virtual void TraceData(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType eventType, int id, object data) { } public virtual void TraceData(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType eventType, int id, params object[] data) { } public virtual void TraceEvent(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType eventType, int id) { } public virtual void TraceEvent(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType eventType, int id, string message) { } public virtual void TraceEvent(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType eventType, int id, string format, params object[] args) { } public virtual void TraceTransfer(System.Diagnostics.TraceEventCache eventCache, string source, int id, string message, System.Guid relatedActivityId) { } public virtual void Write(object o) { } public virtual void Write(object o, string category) { } public abstract void Write(string message); public virtual void Write(string message, string category) { } protected virtual void WriteIndent() { } public virtual void WriteLine(object o) { } public virtual void WriteLine(object o, string category) { } public abstract void WriteLine(string message); public virtual void WriteLine(string message, string category) { } } public partial class TraceListenerCollection : System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList { internal TraceListenerCollection() { } public int Count { get { throw null; } } public System.Diagnostics.TraceListener this[int i] { get { throw null; } set { } } public System.Diagnostics.TraceListener this[string name] { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } bool System.Collections.IList.IsFixedSize { get { throw null; } } bool System.Collections.IList.IsReadOnly { get { throw null; } } object System.Collections.IList.this[int index] { get { throw null; } set { } } public int Add(System.Diagnostics.TraceListener listener) { throw null; } public void AddRange(System.Diagnostics.TraceListenerCollection value) { } public void AddRange(System.Diagnostics.TraceListener[] value) { } public void Clear() { } public bool Contains(System.Diagnostics.TraceListener listener) { throw null; } public void CopyTo(System.Diagnostics.TraceListener[] listeners, int index) { } public System.Collections.IEnumerator GetEnumerator() { throw null; } public int IndexOf(System.Diagnostics.TraceListener listener) { throw null; } public void Insert(int index, System.Diagnostics.TraceListener listener) { } public void Remove(System.Diagnostics.TraceListener listener) { } public void Remove(string name) { } public void RemoveAt(int index) { } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } int System.Collections.IList.Add(object value) { throw null; } bool System.Collections.IList.Contains(object value) { throw null; } int System.Collections.IList.IndexOf(object value) { throw null; } void System.Collections.IList.Insert(int index, object value) { } void System.Collections.IList.Remove(object value) { } } [System.FlagsAttribute] public enum TraceOptions { None = 0, LogicalOperationStack = 1, DateTime = 2, Timestamp = 4, ProcessId = 8, ThreadId = 16, Callstack = 32, } public partial class TraceSource { public TraceSource(string name) { } public TraceSource(string name, System.Diagnostics.SourceLevels defaultLevel) { } public System.Collections.Specialized.StringDictionary Attributes { get { throw null; } } public System.Diagnostics.TraceListenerCollection Listeners { get { throw null; } } public string Name { get { throw null; } } public System.Diagnostics.SourceSwitch Switch { get { throw null; } set { } } public void Close() { } public void Flush() { } protected virtual string[] GetSupportedAttributes() { throw null; } [System.Diagnostics.ConditionalAttribute("TRACE")] public void TraceData(System.Diagnostics.TraceEventType eventType, int id, object data) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public void TraceData(System.Diagnostics.TraceEventType eventType, int id, params object[] data) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public void TraceEvent(System.Diagnostics.TraceEventType eventType, int id) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public void TraceEvent(System.Diagnostics.TraceEventType eventType, int id, string message) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public void TraceEvent(System.Diagnostics.TraceEventType eventType, int id, string format, params object[] args) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public void TraceInformation(string message) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public void TraceInformation(string format, params object[] args) { } public void TraceTransfer(int id, string message, System.Guid relatedActivityId) { } } [System.Diagnostics.SwitchLevelAttribute(typeof(System.Diagnostics.TraceLevel))] public partial class TraceSwitch : System.Diagnostics.Switch { public TraceSwitch(string displayName, string description) : base (default(string), default(string)) { } public TraceSwitch(string displayName, string description, string defaultSwitchValue) : base (default(string), default(string)) { } public System.Diagnostics.TraceLevel Level { get { throw null; } set { } } public bool TraceError { get { throw null; } } public bool TraceInfo { get { throw null; } } public bool TraceVerbose { get { throw null; } } public bool TraceWarning { get { throw null; } } protected override void OnSwitchSettingChanged() { } protected override void OnValueChanged() { } } }
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 frmGRV { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmGRV() : base() { Load += frmGRV_Load; FormClosed += frmGRV_FormClosed; KeyPress += frmGRV_KeyPress; KeyDown += frmGRV_KeyDown; //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.Timer withEventsField_tmrAutoGRV; public System.Windows.Forms.Timer tmrAutoGRV { get { return withEventsField_tmrAutoGRV; } set { if (withEventsField_tmrAutoGRV != null) { withEventsField_tmrAutoGRV.Tick -= tmrAutoGRV_Tick; } withEventsField_tmrAutoGRV = value; if (withEventsField_tmrAutoGRV != null) { withEventsField_tmrAutoGRV.Tick += tmrAutoGRV_Tick; } } } private System.Windows.Forms.Button withEventsField_cmdNext; public System.Windows.Forms.Button cmdNext { get { return withEventsField_cmdNext; } set { if (withEventsField_cmdNext != null) { withEventsField_cmdNext.Click -= cmdNext_Click; } withEventsField_cmdNext = value; if (withEventsField_cmdNext != null) { withEventsField_cmdNext.Click += cmdNext_Click; } } } private System.Windows.Forms.Button withEventsField_cmdBack; public System.Windows.Forms.Button cmdBack { get { return withEventsField_cmdBack; } set { if (withEventsField_cmdBack != null) { withEventsField_cmdBack.Click -= cmdBack_Click; } withEventsField_cmdBack = value; if (withEventsField_cmdBack != null) { withEventsField_cmdBack.Click += cmdBack_Click; } } } private System.Windows.Forms.Button withEventsField_cmdNewGT; public System.Windows.Forms.Button cmdNewGT { get { return withEventsField_cmdNewGT; } set { if (withEventsField_cmdNewGT != null) { withEventsField_cmdNewGT.Click -= cmdNewGT_Click; } withEventsField_cmdNewGT = value; if (withEventsField_cmdNewGT != null) { withEventsField_cmdNewGT.Click += cmdNewGT_Click; } } } private System.Windows.Forms.MonthCalendar withEventsField_MonthView1; public System.Windows.Forms.MonthCalendar MonthView1 { get { return withEventsField_MonthView1; } set { if (withEventsField_MonthView1 != null) { withEventsField_MonthView1.Enter -= MonthView1_Enter; withEventsField_MonthView1.Leave -= MonthView1_Leave; } withEventsField_MonthView1 = value; if (withEventsField_MonthView1 != null) { withEventsField_MonthView1.Enter += MonthView1_Enter; withEventsField_MonthView1.Leave += MonthView1_Leave; } } } private System.Windows.Forms.Button withEventsField_cmdLoad; public System.Windows.Forms.Button cmdLoad { get { return withEventsField_cmdLoad; } set { if (withEventsField_cmdLoad != null) { withEventsField_cmdLoad.Click -= cmdLoad_Click; } withEventsField_cmdLoad = value; if (withEventsField_cmdLoad != null) { withEventsField_cmdLoad.Click += cmdLoad_Click; } } } private System.Windows.Forms.TextBox withEventsField_txtInvoiceTotal; public System.Windows.Forms.TextBox txtInvoiceTotal { get { return withEventsField_txtInvoiceTotal; } set { if (withEventsField_txtInvoiceTotal != null) { withEventsField_txtInvoiceTotal.Enter -= txtInvoiceTotal_Enter; withEventsField_txtInvoiceTotal.KeyPress -= txtInvoiceTotal_KeyPress; withEventsField_txtInvoiceTotal.Leave -= txtInvoiceTotal_Leave; } withEventsField_txtInvoiceTotal = value; if (withEventsField_txtInvoiceTotal != null) { withEventsField_txtInvoiceTotal.Enter += txtInvoiceTotal_Enter; withEventsField_txtInvoiceTotal.KeyPress += txtInvoiceTotal_KeyPress; withEventsField_txtInvoiceTotal.Leave += txtInvoiceTotal_Leave; } } } private System.Windows.Forms.TextBox withEventsField_txtInvoiceNo; public System.Windows.Forms.TextBox txtInvoiceNo { get { return withEventsField_txtInvoiceNo; } set { if (withEventsField_txtInvoiceNo != null) { withEventsField_txtInvoiceNo.Enter -= txtInvoiceNo_Enter; } withEventsField_txtInvoiceNo = value; if (withEventsField_txtInvoiceNo != null) { withEventsField_txtInvoiceNo.Enter += txtInvoiceNo_Enter; } } } public myDataGridView cmbTemplate; public System.Windows.Forms.Label _lbl_4; public System.Windows.Forms.Label _lblLabels_0; public System.Windows.Forms.Label _lblData_3; public System.Windows.Forms.Label _lbl_5; public System.Windows.Forms.Label _lbl_6; public System.Windows.Forms.Label _lbl_7; public System.Windows.Forms.Label _lblData_7; public System.Windows.Forms.Label _lblLabels_36; public System.Windows.Forms.Label _lbl_2; public System.Windows.Forms.Label _lbl_1; public System.Windows.Forms.Label _lblLabels_2; public System.Windows.Forms.Label _lblLabels_8; public System.Windows.Forms.Label _lblLabels_9; public System.Windows.Forms.Label _lblData_0; public System.Windows.Forms.Label _lblData_1; public System.Windows.Forms.Label _lblData_2; public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_1; public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_2; public System.Windows.Forms.GroupBox _frmMode_1; //Public WithEvents frmMode As Microsoft.VisualBasic.Compatibility.VB6.GroupBoxArray //Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray //Public WithEvents lblData As Microsoft.VisualBasic.Compatibility.VB6.LabelArray //Public WithEvents lblLabels As Microsoft.VisualBasic.Compatibility.VB6.LabelArray public OvalShapeArray Shape1; public Microsoft.VisualBasic.PowerPacks.ShapeContainer ShapeContainer1; //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(frmGRV)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this.ShapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer(); this.tmrAutoGRV = new System.Windows.Forms.Timer(components); this.cmdNext = new System.Windows.Forms.Button(); this.cmdBack = new System.Windows.Forms.Button(); this._frmMode_1 = new System.Windows.Forms.GroupBox(); this.cmdNewGT = new System.Windows.Forms.Button(); this.MonthView1 = new System.Windows.Forms.MonthCalendar(); this.cmdLoad = new System.Windows.Forms.Button(); this.txtInvoiceTotal = new System.Windows.Forms.TextBox(); this.txtInvoiceNo = new System.Windows.Forms.TextBox(); this.cmbTemplate = new myDataGridView(); this._lbl_4 = new System.Windows.Forms.Label(); this._lblLabels_0 = new System.Windows.Forms.Label(); this._lblData_3 = new System.Windows.Forms.Label(); this._lbl_5 = new System.Windows.Forms.Label(); this._lbl_6 = new System.Windows.Forms.Label(); this._lbl_7 = new System.Windows.Forms.Label(); this._lblData_7 = new System.Windows.Forms.Label(); this._lblLabels_36 = new System.Windows.Forms.Label(); this._lbl_2 = new System.Windows.Forms.Label(); this._lbl_1 = new System.Windows.Forms.Label(); this._lblLabels_2 = new System.Windows.Forms.Label(); this._lblLabels_8 = new System.Windows.Forms.Label(); this._lblLabels_9 = new System.Windows.Forms.Label(); this._lblData_0 = new System.Windows.Forms.Label(); this._lblData_1 = new System.Windows.Forms.Label(); this._lblData_2 = new System.Windows.Forms.Label(); this._Shape1_1 = new Microsoft.VisualBasic.PowerPacks.RectangleShape(); this._Shape1_2 = new Microsoft.VisualBasic.PowerPacks.RectangleShape(); //Me.frmMode = New Microsoft.VisualBasic.Compatibility.VB6.GroupBoxArray(components) //Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) //Me.lblData = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) //Me.lblLabels = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) this.Shape1 = new OvalShapeArray(components); this._frmMode_1.SuspendLayout(); this.SuspendLayout(); this.ToolTip1.Active = true; ((System.ComponentModel.ISupportInitialize)this.MonthView1).BeginInit(); ((System.ComponentModel.ISupportInitialize)this.cmbTemplate).BeginInit(); //CType(Me.frmMode, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.lblData, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.lblLabels, System.ComponentModel.ISupportInitialize).BeginInit() ((System.ComponentModel.ISupportInitialize)this.Shape1).BeginInit(); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Text = "Process a 'Good Receiving Voucher'"; this.ClientSize = new System.Drawing.Size(360, 449); this.Location = new System.Drawing.Point(3, 22); this.ControlBox = false; this.KeyPreview = true; 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.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 = "frmGRV"; this.tmrAutoGRV.Enabled = false; this.tmrAutoGRV.Interval = 10; this.cmdNext.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdNext.Text = "&Next"; this.cmdNext.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.cmdNext.Size = new System.Drawing.Size(97, 34); this.cmdNext.Location = new System.Drawing.Point(246, 409); this.cmdNext.TabIndex = 9; this.cmdNext.TabStop = false; this.cmdNext.BackColor = System.Drawing.SystemColors.Control; this.cmdNext.CausesValidation = true; this.cmdNext.Enabled = true; this.cmdNext.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdNext.Cursor = System.Windows.Forms.Cursors.Default; this.cmdNext.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdNext.Name = "cmdNext"; this.cmdBack.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdBack.Text = "E&xit"; this.cmdBack.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.cmdBack.Size = new System.Drawing.Size(97, 34); this.cmdBack.Location = new System.Drawing.Point(15, 409); this.cmdBack.TabIndex = 8; this.cmdBack.TabStop = false; this.cmdBack.BackColor = System.Drawing.SystemColors.Control; this.cmdBack.CausesValidation = true; this.cmdBack.Enabled = true; this.cmdBack.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdBack.Cursor = System.Windows.Forms.Cursors.Default; this.cmdBack.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdBack.Name = "cmdBack"; this._frmMode_1.Text = "Select a supplier to transact with."; this._frmMode_1.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._frmMode_1.Size = new System.Drawing.Size(346, 395); this._frmMode_1.Location = new System.Drawing.Point(6, 6); this._frmMode_1.TabIndex = 10; this._frmMode_1.BackColor = System.Drawing.SystemColors.Control; this._frmMode_1.Enabled = true; this._frmMode_1.ForeColor = System.Drawing.SystemColors.ControlText; this._frmMode_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._frmMode_1.Visible = true; this._frmMode_1.Padding = new System.Windows.Forms.Padding(0); this._frmMode_1.Name = "_frmMode_1"; this.cmdNewGT.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdNewGT.Text = "Maintain GRV Templates"; this.AcceptButton = this.cmdNewGT; this.cmdNewGT.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.cmdNewGT.Size = new System.Drawing.Size(169, 23); this.cmdNewGT.Location = new System.Drawing.Point(167, 144); this.cmdNewGT.TabIndex = 24; this.cmdNewGT.BackColor = System.Drawing.SystemColors.Control; this.cmdNewGT.CausesValidation = true; this.cmdNewGT.Enabled = true; this.cmdNewGT.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdNewGT.Cursor = System.Windows.Forms.Cursors.Default; this.cmdNewGT.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdNewGT.TabStop = true; this.cmdNewGT.Name = "cmdNewGT"; //MonthView1.OcxState = CType(resources.GetObject("MonthView1.OcxState"), System.Windows.Forms.AxHost.State) this.MonthView1.Size = new System.Drawing.Size(176, 154); this.MonthView1.Location = new System.Drawing.Point(72, 223); this.MonthView1.TabIndex = 6; this.MonthView1.Name = "MonthView1"; this.cmdLoad.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdLoad.Text = "Load GRV"; this.cmdLoad.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.cmdLoad.Size = new System.Drawing.Size(73, 52); this.cmdLoad.Location = new System.Drawing.Point(255, 322); this.cmdLoad.TabIndex = 7; this.cmdLoad.BackColor = System.Drawing.SystemColors.Control; this.cmdLoad.CausesValidation = true; this.cmdLoad.Enabled = true; this.cmdLoad.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdLoad.Cursor = System.Windows.Forms.Cursors.Default; this.cmdLoad.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdLoad.TabStop = true; this.cmdLoad.Name = "cmdLoad"; this.txtInvoiceTotal.AutoSize = false; this.txtInvoiceTotal.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.txtInvoiceTotal.Size = new System.Drawing.Size(103, 19); this.txtInvoiceTotal.Location = new System.Drawing.Point(147, 199); this.txtInvoiceTotal.TabIndex = 4; this.txtInvoiceTotal.AcceptsReturn = true; this.txtInvoiceTotal.BackColor = System.Drawing.SystemColors.Window; this.txtInvoiceTotal.CausesValidation = true; this.txtInvoiceTotal.Enabled = true; this.txtInvoiceTotal.ForeColor = System.Drawing.SystemColors.WindowText; this.txtInvoiceTotal.HideSelection = true; this.txtInvoiceTotal.ReadOnly = false; this.txtInvoiceTotal.MaxLength = 0; this.txtInvoiceTotal.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtInvoiceTotal.Multiline = false; this.txtInvoiceTotal.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtInvoiceTotal.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtInvoiceTotal.TabStop = true; this.txtInvoiceTotal.Visible = true; this.txtInvoiceTotal.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtInvoiceTotal.Name = "txtInvoiceTotal"; this.txtInvoiceNo.AutoSize = false; this.txtInvoiceNo.Size = new System.Drawing.Size(178, 19); this.txtInvoiceNo.Location = new System.Drawing.Point(72, 178); this.txtInvoiceNo.TabIndex = 2; this.txtInvoiceNo.AcceptsReturn = true; this.txtInvoiceNo.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtInvoiceNo.BackColor = System.Drawing.SystemColors.Window; this.txtInvoiceNo.CausesValidation = true; this.txtInvoiceNo.Enabled = true; this.txtInvoiceNo.ForeColor = System.Drawing.SystemColors.WindowText; this.txtInvoiceNo.HideSelection = true; this.txtInvoiceNo.ReadOnly = false; this.txtInvoiceNo.MaxLength = 0; this.txtInvoiceNo.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtInvoiceNo.Multiline = false; this.txtInvoiceNo.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtInvoiceNo.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtInvoiceNo.TabStop = true; this.txtInvoiceNo.Visible = true; this.txtInvoiceNo.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtInvoiceNo.Name = "txtInvoiceNo"; //cmbTemplate.OcxState = CType(resources.GetObject("cmbTemplate.OcxState"), System.Windows.Forms.AxHost.State) this.cmbTemplate.Size = new System.Drawing.Size(228, 21); this.cmbTemplate.Location = new System.Drawing.Point(104, 117); this.cmbTemplate.TabIndex = 22; this.cmbTemplate.Name = "cmbTemplate"; this._lbl_4.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lbl_4.Text = "GRV Template :"; this._lbl_4.Size = new System.Drawing.Size(76, 13); this._lbl_4.Location = new System.Drawing.Point(22, 120); this._lbl_4.TabIndex = 23; this._lbl_4.BackColor = System.Drawing.Color.Transparent; this._lbl_4.Enabled = true; this._lbl_4.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_4.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_4.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_4.UseMnemonic = true; this._lbl_4.Visible = true; this._lbl_4.AutoSize = true; this._lbl_4.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_4.Name = "_lbl_4"; this._lblLabels_0.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblLabels_0.Text = "Order Reference:"; this._lblLabels_0.Size = new System.Drawing.Size(82, 13); this._lblLabels_0.Location = new System.Drawing.Point(16, 96); this._lblLabels_0.TabIndex = 21; this._lblLabels_0.BackColor = System.Drawing.Color.Transparent; this._lblLabels_0.Enabled = true; this._lblLabels_0.ForeColor = System.Drawing.SystemColors.ControlText; this._lblLabels_0.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_0.UseMnemonic = true; this._lblLabels_0.Visible = true; this._lblLabels_0.AutoSize = true; this._lblLabels_0.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblLabels_0.Name = "_lblLabels_0"; this._lblData_3.BackColor = System.Drawing.Color.FromArgb(224, 224, 224); this._lblData_3.Text = "PurchaseOrder_Reference"; this._lblData_3.ForeColor = System.Drawing.SystemColors.WindowText; this._lblData_3.Size = new System.Drawing.Size(226, 16); this._lblData_3.Location = new System.Drawing.Point(106, 96); this._lblData_3.TabIndex = 20; this._lblData_3.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._lblData_3.Enabled = true; this._lblData_3.Cursor = System.Windows.Forms.Cursors.Default; this._lblData_3.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblData_3.UseMnemonic = true; this._lblData_3.Visible = true; this._lblData_3.AutoSize = false; this._lblData_3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._lblData_3.Name = "_lblData_3"; this._lbl_5.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lbl_5.Text = "Number :"; this._lbl_5.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._lbl_5.Size = new System.Drawing.Size(52, 13); this._lbl_5.Location = new System.Drawing.Point(14, 181); this._lbl_5.TabIndex = 1; this._lbl_5.BackColor = System.Drawing.Color.Transparent; this._lbl_5.Enabled = true; this._lbl_5.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_5.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_5.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_5.UseMnemonic = true; this._lbl_5.Visible = true; this._lbl_5.AutoSize = true; this._lbl_5.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_5.Name = "_lbl_5"; this._lbl_6.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lbl_6.Text = "Total :"; this._lbl_6.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._lbl_6.Size = new System.Drawing.Size(38, 13); this._lbl_6.Location = new System.Drawing.Point(103, 202); this._lbl_6.TabIndex = 3; this._lbl_6.BackColor = System.Drawing.Color.Transparent; this._lbl_6.Enabled = true; this._lbl_6.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_6.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_6.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_6.UseMnemonic = true; this._lbl_6.Visible = true; this._lbl_6.AutoSize = true; this._lbl_6.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_6.Name = "_lbl_6"; this._lbl_7.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lbl_7.Text = "Date :"; this._lbl_7.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._lbl_7.Size = new System.Drawing.Size(36, 13); this._lbl_7.Location = new System.Drawing.Point(30, 220); this._lbl_7.TabIndex = 5; this._lbl_7.BackColor = System.Drawing.Color.Transparent; this._lbl_7.Enabled = true; this._lbl_7.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_7.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_7.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_7.UseMnemonic = true; this._lbl_7.Visible = true; this._lbl_7.AutoSize = true; this._lbl_7.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_7.Name = "_lbl_7"; this._lblData_7.BackColor = System.Drawing.Color.FromArgb(224, 224, 224); this._lblData_7.Text = "Supplier_ShippingCode"; this._lblData_7.ForeColor = System.Drawing.SystemColors.WindowText; this._lblData_7.Size = new System.Drawing.Size(226, 16); this._lblData_7.Location = new System.Drawing.Point(105, 75); this._lblData_7.TabIndex = 19; this._lblData_7.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._lblData_7.Enabled = true; this._lblData_7.Cursor = System.Windows.Forms.Cursors.Default; this._lblData_7.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblData_7.UseMnemonic = true; this._lblData_7.Visible = true; this._lblData_7.AutoSize = false; this._lblData_7.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._lblData_7.Name = "_lblData_7"; this._lblLabels_36.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblLabels_36.Text = "Account Number:"; this._lblLabels_36.Size = new System.Drawing.Size(83, 13); this._lblLabels_36.Location = new System.Drawing.Point(14, 75); this._lblLabels_36.TabIndex = 18; this._lblLabels_36.BackColor = System.Drawing.Color.Transparent; this._lblLabels_36.Enabled = true; this._lblLabels_36.ForeColor = System.Drawing.SystemColors.ControlText; this._lblLabels_36.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_36.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_36.UseMnemonic = true; this._lblLabels_36.Visible = true; this._lblLabels_36.AutoSize = true; this._lblLabels_36.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblLabels_36.Name = "_lblLabels_36"; this._lbl_2.BackColor = System.Drawing.Color.Transparent; this._lbl_2.Text = "&2. Invoice Details"; this._lbl_2.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._lbl_2.Size = new System.Drawing.Size(101, 13); this._lbl_2.Location = new System.Drawing.Point(9, 152); this._lbl_2.TabIndex = 0; this._lbl_2.TextAlign = System.Drawing.ContentAlignment.TopLeft; 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.BackColor = System.Drawing.Color.Transparent; this._lbl_1.Text = "&1. Supplier Details"; this._lbl_1.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._lbl_1.Size = new System.Drawing.Size(105, 13); this._lbl_1.Location = new System.Drawing.Point(9, 18); this._lbl_1.TabIndex = 17; this._lbl_1.TextAlign = System.Drawing.ContentAlignment.TopLeft; 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._lblLabels_2.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblLabels_2.Text = "Supplier Name:"; this._lblLabels_2.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._lblLabels_2.Size = new System.Drawing.Size(87, 13); this._lblLabels_2.Location = new System.Drawing.Point(13, 39); this._lblLabels_2.TabIndex = 16; this._lblLabels_2.BackColor = System.Drawing.Color.Transparent; this._lblLabels_2.Enabled = true; this._lblLabels_2.ForeColor = System.Drawing.SystemColors.ControlText; this._lblLabels_2.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_2.UseMnemonic = true; this._lblLabels_2.Visible = true; this._lblLabels_2.AutoSize = true; this._lblLabels_2.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblLabels_2.Name = "_lblLabels_2"; this._lblLabels_8.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblLabels_8.Text = "Telephone:"; this._lblLabels_8.Size = new System.Drawing.Size(55, 13); this._lblLabels_8.Location = new System.Drawing.Point(42, 57); this._lblLabels_8.TabIndex = 15; this._lblLabels_8.BackColor = System.Drawing.Color.Transparent; this._lblLabels_8.Enabled = true; this._lblLabels_8.ForeColor = System.Drawing.SystemColors.ControlText; this._lblLabels_8.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_8.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_8.UseMnemonic = true; this._lblLabels_8.Visible = true; this._lblLabels_8.AutoSize = true; this._lblLabels_8.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblLabels_8.Name = "_lblLabels_8"; this._lblLabels_9.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblLabels_9.Text = "Fax:"; this._lblLabels_9.Size = new System.Drawing.Size(22, 13); this._lblLabels_9.Location = new System.Drawing.Point(210, 57); this._lblLabels_9.TabIndex = 14; this._lblLabels_9.BackColor = System.Drawing.Color.Transparent; this._lblLabels_9.Enabled = true; this._lblLabels_9.ForeColor = System.Drawing.SystemColors.ControlText; this._lblLabels_9.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_9.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_9.UseMnemonic = true; this._lblLabels_9.Visible = true; this._lblLabels_9.AutoSize = true; this._lblLabels_9.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblLabels_9.Name = "_lblLabels_9"; this._lblData_0.BackColor = System.Drawing.Color.FromArgb(224, 224, 224); this._lblData_0.Text = "Supplier_Name"; this._lblData_0.ForeColor = System.Drawing.SystemColors.WindowText; this._lblData_0.Size = new System.Drawing.Size(226, 16); this._lblData_0.Location = new System.Drawing.Point(105, 39); this._lblData_0.TabIndex = 13; this._lblData_0.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._lblData_0.Enabled = true; this._lblData_0.Cursor = System.Windows.Forms.Cursors.Default; this._lblData_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblData_0.UseMnemonic = true; this._lblData_0.Visible = true; this._lblData_0.AutoSize = false; this._lblData_0.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._lblData_0.Name = "_lblData_0"; this._lblData_1.BackColor = System.Drawing.Color.FromArgb(224, 224, 224); this._lblData_1.Text = "Supplier_Telephone"; this._lblData_1.ForeColor = System.Drawing.SystemColors.WindowText; this._lblData_1.Size = new System.Drawing.Size(94, 16); this._lblData_1.Location = new System.Drawing.Point(105, 57); this._lblData_1.TabIndex = 12; this._lblData_1.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._lblData_1.Enabled = true; this._lblData_1.Cursor = System.Windows.Forms.Cursors.Default; this._lblData_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblData_1.UseMnemonic = true; this._lblData_1.Visible = true; this._lblData_1.AutoSize = false; this._lblData_1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._lblData_1.Name = "_lblData_1"; this._lblData_2.BackColor = System.Drawing.Color.FromArgb(224, 224, 224); this._lblData_2.Text = "Supplier_Facimile"; this._lblData_2.ForeColor = System.Drawing.SystemColors.WindowText; this._lblData_2.Size = new System.Drawing.Size(94, 16); this._lblData_2.Location = new System.Drawing.Point(237, 57); this._lblData_2.TabIndex = 11; this._lblData_2.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._lblData_2.Enabled = true; this._lblData_2.Cursor = System.Windows.Forms.Cursors.Default; this._lblData_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblData_2.UseMnemonic = true; this._lblData_2.Visible = true; this._lblData_2.AutoSize = false; this._lblData_2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._lblData_2.Name = "_lblData_2"; this._Shape1_1.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this._Shape1_1.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque; this._Shape1_1.Size = new System.Drawing.Size(328, 112); this._Shape1_1.Location = new System.Drawing.Point(9, 20); this._Shape1_1.BorderColor = System.Drawing.SystemColors.WindowText; this._Shape1_1.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid; this._Shape1_1.BorderWidth = 1; this._Shape1_1.FillColor = System.Drawing.Color.Black; this._Shape1_1.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent; this._Shape1_1.Visible = true; this._Shape1_1.Name = "_Shape1_1"; this._Shape1_2.BackColor = System.Drawing.Color.FromArgb(255, 192, 192); this._Shape1_2.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque; this._Shape1_2.Size = new System.Drawing.Size(328, 214); this._Shape1_2.Location = new System.Drawing.Point(9, 156); this._Shape1_2.BorderColor = System.Drawing.SystemColors.WindowText; this._Shape1_2.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid; this._Shape1_2.BorderWidth = 1; this._Shape1_2.FillColor = System.Drawing.Color.Black; this._Shape1_2.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent; this._Shape1_2.Visible = true; this._Shape1_2.Name = "_Shape1_2"; this.Controls.Add(cmdNext); this.Controls.Add(cmdBack); this.Controls.Add(_frmMode_1); this._frmMode_1.Controls.Add(cmdNewGT); this._frmMode_1.Controls.Add(MonthView1); this._frmMode_1.Controls.Add(cmdLoad); this._frmMode_1.Controls.Add(txtInvoiceTotal); this._frmMode_1.Controls.Add(txtInvoiceNo); this._frmMode_1.Controls.Add(cmbTemplate); this._frmMode_1.Controls.Add(_lbl_4); this._frmMode_1.Controls.Add(_lblLabels_0); this._frmMode_1.Controls.Add(_lblData_3); this._frmMode_1.Controls.Add(_lbl_5); this._frmMode_1.Controls.Add(_lbl_6); this._frmMode_1.Controls.Add(_lbl_7); this._frmMode_1.Controls.Add(_lblData_7); this._frmMode_1.Controls.Add(_lblLabels_36); this._frmMode_1.Controls.Add(_lbl_2); this._frmMode_1.Controls.Add(_lbl_1); this._frmMode_1.Controls.Add(_lblLabels_2); this._frmMode_1.Controls.Add(_lblLabels_8); this._frmMode_1.Controls.Add(_lblLabels_9); this._frmMode_1.Controls.Add(_lblData_0); this._frmMode_1.Controls.Add(_lblData_1); this._frmMode_1.Controls.Add(_lblData_2); this.ShapeContainer1.Shapes.Add(_Shape1_1); this.ShapeContainer1.Shapes.Add(_Shape1_2); this._frmMode_1.Controls.Add(ShapeContainer1); //Me.frmMode.SetIndex(_frmMode_1, CType(1, Short)) //Me.lbl.SetIndex(_lbl_4, CType(4, Short)) //Me.lbl.SetIndex(_lbl_5, CType(5, Short)) //Me.lbl.SetIndex(_lbl_6, CType(6, Short)) //Me.lbl.SetIndex(_lbl_7, CType(7, Short)) //Me.lbl.SetIndex(_lbl_2, CType(2, Short)) //Me.lbl.SetIndex(_lbl_1, CType(1, Short)) //Me.lblData.SetIndex(_lblData_3, CType(3, Short)) //Me.lblData.SetIndex(_lblData_7, CType(7, Short)) //Me.lblData.SetIndex(_lblData_0, CType(0, Short)) //Me.lblData.SetIndex(_lblData_1, CType(1, Short)) //Me.lblData.SetIndex(_lblData_2, CType(2, Short)) //Me.lblLabels.SetIndex(_lblLabels_0, CType(0, Short)) //Me.lblLabels.SetIndex(_lblLabels_36, CType(36, Short)) //Me.lblLabels.SetIndex(_lblLabels_2, CType(2, Short)) //Me.lblLabels.SetIndex(_lblLabels_8, CType(8, Short)) //Me.lblLabels.SetIndex(_lblLabels_9, CType(9, Short)) //Me.Shape1.SetIndex(_Shape1_1, CType(1, Short)) //Me.Shape1.SetIndex(_Shape1_2, CType(2, Short)) ((System.ComponentModel.ISupportInitialize)this.Shape1).EndInit(); //CType(Me.lblLabels, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.lblData, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.frmMode, System.ComponentModel.ISupportInitialize).EndInit() ((System.ComponentModel.ISupportInitialize)this.cmbTemplate).EndInit(); ((System.ComponentModel.ISupportInitialize)this.MonthView1).EndInit(); this._frmMode_1.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; namespace Microsoft.VisualStudioTools.Project.Automation { /// <summary> /// This can navigate a collection object only (partial implementation of ProjectItems interface) /// </summary> [ComVisible(true)] public class OANavigableProjectItems : EnvDTE.ProjectItems { #region fields private OAProject project; private HierarchyNode nodeWithItems; #endregion #region properties /// <summary> /// Defines a relationship to the associated project. /// </summary> internal OAProject Project { get { return this.project; } } /// <summary> /// Defines the node that contains the items /// </summary> internal HierarchyNode NodeWithItems { get { return this.nodeWithItems; } } #endregion #region ctor /// <summary> /// Constructor. /// </summary> /// <param name="project">The associated project.</param> /// <param name="nodeWithItems">The node that defines the items.</param> internal OANavigableProjectItems(OAProject project, HierarchyNode nodeWithItems) { this.project = project; this.nodeWithItems = nodeWithItems; } #endregion #region EnvDTE.ProjectItems /// <summary> /// Gets a value indicating the number of objects in the collection. /// </summary> public virtual int Count { get { int count = 0; this.project.ProjectNode.Site.GetUIThread().Invoke(() => { for (HierarchyNode child = this.NodeWithItems.FirstChild; child != null; child = child.NextSibling) { if (!child.IsNonMemberItem && child.GetAutomationObject() is EnvDTE.ProjectItem) { count += 1; } } }); return count; } } /// <summary> /// Gets the immediate parent object of a ProjectItems collection. /// </summary> public virtual object Parent { get { return this.nodeWithItems.GetAutomationObject(); } } /// <summary> /// Gets an enumeration indicating the type of object. /// </summary> public virtual string Kind { get { // TODO: Add OAProjectItems.Kind getter implementation return null; } } /// <summary> /// Gets the top-level extensibility object. /// </summary> public virtual EnvDTE.DTE DTE { get { return (EnvDTE.DTE)this.project.DTE; } } /// <summary> /// Gets the project hosting the project item or items. /// </summary> public virtual EnvDTE.Project ContainingProject { get { return this.project; } } /// <summary> /// Adds one or more ProjectItem objects from a directory to the ProjectItems collection. /// </summary> /// <param name="directory">The directory from which to add the project item.</param> /// <returns>A ProjectItem object.</returns> public virtual EnvDTE.ProjectItem AddFromDirectory(string directory) { throw new NotImplementedException(); } /// <summary> /// Creates a new project item from an existing item template file and adds it to the project. /// </summary> /// <param name="fileName">The full path and file name of the template project file.</param> /// <param name="name">The file name to use for the new project item.</param> /// <returns>A ProjectItem object. </returns> public virtual EnvDTE.ProjectItem AddFromTemplate(string fileName, string name) { throw new NotImplementedException(); } /// <summary> /// Creates a new folder in Solution Explorer. /// </summary> /// <param name="name">The name of the folder node in Solution Explorer.</param> /// <param name="kind">The type of folder to add. The available values are based on vsProjectItemsKindConstants and vsProjectItemKindConstants</param> /// <returns>A ProjectItem object.</returns> public virtual EnvDTE.ProjectItem AddFolder(string name, string kind) { throw new NotImplementedException(); } /// <summary> /// Copies a source file and adds it to the project. /// </summary> /// <param name="filePath">The path and file name of the project item to be added.</param> /// <returns>A ProjectItem object. </returns> public virtual EnvDTE.ProjectItem AddFromFileCopy(string filePath) { throw new NotImplementedException(); } /// <summary> /// Adds a project item from a file that is installed in a project directory structure. /// </summary> /// <param name="fileName">The file name of the item to add as a project item. </param> /// <returns>A ProjectItem object. </returns> public virtual EnvDTE.ProjectItem AddFromFile(string fileName) { throw new NotImplementedException(); } /// <summary> /// Get Project Item from index /// </summary> /// <param name="index">Either index by number (1-based) or by name can be used to get the item</param> /// <returns>Project Item. ArgumentException if invalid index is specified</returns> public virtual EnvDTE.ProjectItem Item(object index) { // Changed from MPFProj: throws ArgumentException instead of returning null (http://mpfproj10.codeplex.com/workitem/9158) if (index is int) { int realIndex = (int)index - 1; if (realIndex >= 0) { for (HierarchyNode child = this.NodeWithItems.FirstChild; child != null; child = child.NextSibling) { if (child.IsNonMemberItem) { continue; } var item = child.GetAutomationObject() as EnvDTE.ProjectItem; if (item != null) { if (realIndex == 0) { return item; } realIndex -= 1; } } } } else if (index is string) { string name = (string)index; for (HierarchyNode child = this.NodeWithItems.FirstChild; child != null; child = child.NextSibling) { if (child.IsNonMemberItem) { continue; } var item = child.GetAutomationObject() as EnvDTE.ProjectItem; if (item != null && String.Compare(item.Name, name, StringComparison.OrdinalIgnoreCase) == 0) { return item; } } } throw new ArgumentException("Failed to find item: " + index); } /// <summary> /// Returns an enumeration for items in a collection. /// </summary> /// <returns>An IEnumerator for this object.</returns> public virtual IEnumerator GetEnumerator() { for (HierarchyNode child = this.NodeWithItems.FirstChild; child != null; child = child.NextSibling) { if (child.IsNonMemberItem) { continue; } var item = child.GetAutomationObject() as EnvDTE.ProjectItem; if (item != null) { yield return item; } } } #endregion } }
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Windows.Forms.Design; using System.Drawing; using System.Drawing.Design; using System.ComponentModel; using AxiomCoders.PdfTemplateEditor.EditorStuff; using AxiomCoders.PdfTemplateEditor.Common; using System.Xml; namespace AxiomCoders.PdfTemplateEditor.EditorItems { [System.Reflection.Obfuscation(Exclude = true)] public class DynamicText : BaseTextItems, EditorToolBarPlugin, DynamicEditorItemInterface { private string sourceColumn; private string sourceDataStream; /// <summary> /// Constructor /// </summary> public DynamicText(): base() { sourceColumn = string.Empty; sourceDataStream = string.Empty; scaleXFactor = 1; scaleYFactor = 1; } /// <summary> /// Save Item /// </summary> /// <param name="txW"></param> public override void SaveItem(XmlDocument doc, XmlElement element) { XmlElement el = doc.CreateElement("Item"); base.SaveItem(doc, el); XmlAttribute attr = doc.CreateAttribute("Type"); attr.Value = "DynamicText"; el.SetAttributeNode(attr); attr = doc.CreateAttribute("Version"); attr.Value = "1.0"; el.SetAttributeNode(attr); XmlElement el2 = doc.CreateElement("Text"); attr = doc.CreateAttribute("DataStream"); attr.Value = this.SourceDataStream; el2.SetAttributeNode(attr); attr = doc.CreateAttribute("SourceColumn"); attr.Value = this.SourceColumn; el2.SetAttributeNode(attr); el.AppendChild(el2); element.AppendChild(el); } /// <summary> /// Load Item /// </summary> /// <param name="txR"></param> public override void Load(System.Xml.XmlNode element) { base.Load(element); // Load source data stream and column XmlNode node = element.SelectSingleNode("Text"); if (node != null) { this.SourceDataStream = node.Attributes["DataStream"].Value; this.SourceColumn = node.Attributes["SourceColumn"].Value; } } /// <summary> /// Gets or sets source column name of item. /// </summary> [Browsable(true), DisplayName("Column"), Description("Source column name of item."), Category("Standard"), EditorAttribute(typeof(ComboBoxPropertyEditor), typeof(UITypeEditor))] public string SourceColumn { get { if(SourceDataStream != "") { int tmpCount = 0; string[] tmpList = null; int i = 0; foreach(DataStream tmpStream in EditorController.Instance.EditorProject.DataStreams) { if(tmpStream.Name == SourceDataStream) { tmpCount = tmpStream.Columns.Count; tmpList = new string[tmpCount]; foreach(Column tmpCol in tmpStream.Columns) { tmpList[i] = tmpCol.Name; i++; } ComboBoxPropertyEditor.ItemList = tmpList; break; } } } return sourceColumn; } set { sourceColumn = value; // Update size of item when text is changed needToUpdateSize = true; } } /// <summary> /// Gets or sets source Data Stream of item. /// </summary> [Browsable(true), DisplayName("Data Stream"), Description("Source Data Stream name of item."), Category("Standard"), EditorAttribute(typeof(ComboBoxPropertyEditor), typeof(UITypeEditor))] public string SourceDataStream { get { ComboBoxPropertyEditor.ItemList = null; int tmpCount = EditorController.Instance.EditorProject.DataStreams.Count; if(tmpCount > 0) { string[] tmpList = new string[tmpCount]; int i = 0; foreach(DataStream tmpItem in EditorController.Instance.EditorProject.DataStreams) { tmpList[i] = tmpItem.Name; i++; } ComboBoxPropertyEditor.ItemList = tmpList; } return sourceDataStream; } set { SourceColumn = ""; sourceDataStream = value; needToUpdateSize = true; } } [Browsable(false)] public string Text { get { if (SourceColumn.Length > 0 && SourceDataStream.Length > 0) { if (EditorController.Instance.MainFormOfTheProject != null && EditorController.Instance.MainFormOfTheProject.InPreviewMode) { return string.Format("{0}:{1}:{2}", this.SourceDataStream, this.SourceColumn, this.creationId); } else { return string.Format("{0}:{1}", this.SourceDataStream, this.SourceColumn); } } else { return "DataStream:ColumnName"; } } } /// <summary> /// Relative X location comparing to ballon location. /// </summary> [Browsable(true), DisplayName("Location X In Pixels"), Category("Standard")] [Description("Relative X location comparing to ballon location.")] public override float LocationInPixelsX { get { return base.LocationInPixelsX; } } /// <summary> /// Relative Y location comparing to ballon location. /// </summary> [Browsable(true), DisplayName("Location Y In Pixels"), Category("Standard")] [Description("Relative Y location comparing to ballon location.")] public override float LocationInPixelsY { get { return base.LocationInPixelsY; } } public override string VisibleText { get { return this.Text; } } #region EditorToolBarPlugin Members void EditorToolBarPlugin.AddToToolStrip(ToolStrip toolStrip, ToolStripGroup group) { //ToolStripButton tbbNew = new ToolStripButton("Dynamic Text"); //tbbNew.Image = AxiomCoders.PdfTemplateEditor.Properties.Resources.DynamicText; //tbbNew.DisplayStyle = ToolStripItemDisplayStyle.Image; //toolStrip.Items.Add(tbbNew); //tbbNew.Click += new EventHandler(tbbNew_Click); } void tbbNew_Click(object sender, EventArgs e) { //ToolStripButton tbbButton = sender as ToolStripButton; //tbbButton.Checked = !tbbButton.Checked; //if (tbbButton.Checked) //{ // EditorController.Instance.TbbCheckedForCreate = tbbButton; // EditorController.Instance.EditorItemSelectedForCreation = this.GetType(); //} //else //{ // EditorController.Instance.EditorItemSelectedForCreation = null; //} } #endregion } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System; using UMA; /// <summary> /// Base class for serializing recipes as "packed" int/byte based data. /// </summary> public abstract class UMAPackedRecipeBase : UMARecipeBase { /// <summary> /// Load data into the specified UMA recipe. /// </summary> /// <param name="umaRecipe">UMA recipe.</param> /// <param name="context">Context.</param> public override void Load(UMA.UMAData.UMARecipe umaRecipe, UMAContext context) { var packedRecipe = PackedLoad(context); switch (packedRecipe.version) { case 2: UnpackRecipeVersion2(umaRecipe, packedRecipe, context); break; case 1: default: if (UnpackRecipeVersion1 (umaRecipe, packedRecipe, context)) { umaRecipe.MergeMatchingOverlays (); } break; } } /// <summary> /// Save data from the specified UMA recipe. /// </summary> /// <param name="umaRecipe">UMA recipe.</param> /// <param name="context">Context.</param> public override void Save(UMA.UMAData.UMARecipe umaRecipe, UMAContext context) { umaRecipe.MergeMatchingOverlays(); var packedRecipe = PackRecipeV2(umaRecipe); PackedSave(packedRecipe, context); } /// <summary> /// Load serialized data into the packed recipe. /// </summary> /// <returns>The UMAPackRecipe.</returns> /// <param name="context">Context.</param> public abstract UMAPackRecipe PackedLoad(UMAContext context); /// <summary> /// Serialize the packed recipe. /// </summary> /// <param name="packedRecipe">Packed recipe.</param> /// <param name="context">Context.</param> public abstract void PackedSave(UMAPackRecipe packedRecipe, UMAContext context); #region Packing Related [System.Serializable] public class packedSlotData { public string slotID; public int overlayScale = 1; public int copyOverlayIndex = -1; public packedOverlayData[] OverlayDataList; } [System.Serializable] public class packedOverlayData { public string overlayID; public int[] colorList; public int[][] channelMaskList; public int[][] channelAdditiveMaskList; public int[] rectList; } [System.Serializable] public class PackedSlotDataV2 { public string id; public int scale = 1; public int copyIdx = -1; public PackedOverlayDataV2[] overlays; } [System.Serializable] public class PackedOverlayDataV2 { public string id; public int colorIdx; public int[] rect; } [System.Serializable] public class PackedOverlayColorDataV2 { public string name; public byte[] color; public byte[][] masks; public byte[][] addMasks; public PackedOverlayColorDataV2() { name = ""; color = new byte[4]; } public PackedOverlayColorDataV2(OverlayColorData colorData) { name = colorData.name; color = new byte[4]; color[0] = (byte)Mathf.FloorToInt(colorData.color.r * 255f); color[1] = (byte)Mathf.FloorToInt(colorData.color.g * 255f); color[2] = (byte)Mathf.FloorToInt(colorData.color.b * 255f); color[3] = (byte)Mathf.FloorToInt(colorData.color.a * 255f); if (colorData.channelMask != null && colorData.channelMask.Length > 0) { int channelCount = colorData.channelMask.Length; masks = new byte[channelCount][]; addMasks = new byte[channelCount][]; for (int channel = 0; channel < channelCount; channel++) { masks[channel] = new byte[4]; addMasks[channel] = new byte[4]; Color32 maskColor = colorData.channelMask[channel]; masks[channel][0] = maskColor.r; masks[channel][1] = maskColor.g; masks[channel][2] = maskColor.b; masks[channel][3] = maskColor.a; Color32 additiveMaskColor = colorData.channelAdditiveMask[channel]; addMasks[channel][0] = additiveMaskColor.r; addMasks[channel][1] = additiveMaskColor.g; addMasks[channel][2] = additiveMaskColor.b; addMasks[channel][3] = additiveMaskColor.a; } } } public void SetOverlayColorData(OverlayColorData overlayColorData) { overlayColorData.name = name; if (masks != null && masks.Length > 0) { int channelCount = masks.Length; overlayColorData.channelMask = new Color[channelCount]; overlayColorData.channelAdditiveMask = new Color[channelCount]; for (int channel = 0; channel < channelCount; channel++) { overlayColorData.channelMask[channel].r = masks[channel][0] / 255f; overlayColorData.channelMask[channel].g = masks[channel][1] / 255f; overlayColorData.channelMask[channel].b = masks[channel][2] / 255f; overlayColorData.channelMask[channel].a = masks[channel][3] / 255f; overlayColorData.channelAdditiveMask[channel].r = addMasks[channel][0]; overlayColorData.channelAdditiveMask[channel].g = addMasks[channel][1]; overlayColorData.channelAdditiveMask[channel].b = addMasks[channel][2]; overlayColorData.channelAdditiveMask[channel].a = addMasks[channel][3]; } } else { overlayColorData.channelMask = new Color[1]; overlayColorData.channelAdditiveMask = new Color[1]; overlayColorData.channelMask[0] = new Color(color[0] / 255f, color[1] / 255f, color[2] / 255f, color[3] / 255f); } } } [System.Serializable] public class PackedOverlayColorDataV3 { public string name; // Put everything in one array public short[] colors; public PackedOverlayColorDataV3() { name = ""; colors = new short[0]; } public PackedOverlayColorDataV3(OverlayColorData colorData) { name = colorData.name; if (colorData.channelMask != null) { int channelCount = colorData.channelMask.Length; colors = new short[channelCount * 8]; int colorIndex = 0; for (int channel = 0; channel < channelCount; channel++) { Color maskColor = colorData.channelMask[channel]; colors[colorIndex++] = (short)Mathf.FloorToInt(maskColor.r * 255f); colors[colorIndex++] = (short)Mathf.FloorToInt(maskColor.g * 255f); colors[colorIndex++] = (short)Mathf.FloorToInt(maskColor.b * 255f); colors[colorIndex++] = (short)Mathf.FloorToInt(maskColor.a * 255f); Color additiveMaskColor = colorData.channelAdditiveMask[channel]; colors[colorIndex++] = (short)Mathf.FloorToInt(additiveMaskColor.r * 255f); colors[colorIndex++] = (short)Mathf.FloorToInt(additiveMaskColor.g * 255f); colors[colorIndex++] = (short)Mathf.FloorToInt(additiveMaskColor.b * 255f); colors[colorIndex++] = (short)Mathf.FloorToInt(additiveMaskColor.a * 255f); } } } public void SetOverlayColorData(OverlayColorData overlayColorData) { overlayColorData.name = name; if (colors != null) { int channelCount = colors.Length / 8; overlayColorData.channelMask = new Color[channelCount]; overlayColorData.channelAdditiveMask = new Color[channelCount]; int colorIndex = 0; for (int channel = 0; channel < channelCount; channel++) { overlayColorData.channelMask[channel].r = colors[colorIndex++] / 255f; overlayColorData.channelMask[channel].g = colors[colorIndex++] / 255f; overlayColorData.channelMask[channel].b = colors[colorIndex++] / 255f; overlayColorData.channelMask[channel].a = colors[colorIndex++] / 255f; overlayColorData.channelAdditiveMask[channel].r = colors[colorIndex++] / 255f; overlayColorData.channelAdditiveMask[channel].g = colors[colorIndex++] / 255f; overlayColorData.channelAdditiveMask[channel].b = colors[colorIndex++] / 255f; overlayColorData.channelAdditiveMask[channel].a = colors[colorIndex++] / 255f; } } } } [System.Serializable] public class UMAPackedDna { public string dnaType; public string packedDna; } [System.Serializable] public class UMAPackRecipe { public int version = 1; public packedSlotData[] packedSlotDataList; public PackedSlotDataV2[] slotsV2; public PackedOverlayColorDataV2[] colors; public PackedOverlayColorDataV3[] fColors; public int sharedColorCount; public string race; public Dictionary<Type, UMADna> umaDna = new Dictionary<Type, UMADna>(); public List<UMAPackedDna> packedDna = new List<UMAPackedDna>(); } /* public static UMAPackRecipe PackRecipeV1(UMA.UMAData.UMARecipe umaRecipe) { UMAPackRecipe umaPackRecipe = new UMAPackRecipe(); //var umaPackRecipe = new Packed int slotCount = umaRecipe.slotDataList.Length - umaRecipe.AdditionalSlots; umaPackRecipe.packedSlotDataList = new packedSlotData[slotCount]; umaPackRecipe.race = umaRecipe.raceData.raceName; foreach (var dna in umaRecipe.GetAllDna()) { UMAPackedDna packedDna = new UMAPackedDna(); packedDna.dnaType = dna.GetType().Name; packedDna.packedDna = UMA.UMADna.SaveInstance(dna); umaPackRecipe.packedDna.Add(packedDna); } for (int i = 0; i < slotCount; i++) { if (umaRecipe.slotDataList[i] != null) { packedSlotData tempPackedSlotData = new packedSlotData(); umaPackRecipe.packedSlotDataList[i] = tempPackedSlotData; tempPackedSlotData.slotID = umaRecipe.slotDataList[i].asset.slotName; tempPackedSlotData.overlayScale = Mathf.FloorToInt(umaRecipe.slotDataList[i].overlayScale * 100); bool copiedOverlays = false; for (int i2 = 0; i2 < i; i2++) { if (umaRecipe.slotDataList[i2] != null && umaPackRecipe.packedSlotDataList[i2] != null) { if (umaRecipe.slotDataList[i].GetOverlayList() == umaRecipe.slotDataList[i2].GetOverlayList()) { tempPackedSlotData.copyOverlayIndex = i2; copiedOverlays = true; break; } } } if( copiedOverlays ) continue; tempPackedSlotData.OverlayDataList = new packedOverlayData[umaRecipe.slotDataList[i].OverlayCount]; for (int overlayID = 0; overlayID < tempPackedSlotData.OverlayDataList.Length; overlayID++) { tempPackedSlotData.OverlayDataList[overlayID] = new packedOverlayData(); tempPackedSlotData.OverlayDataList[overlayID].overlayID = umaRecipe.slotDataList[i].GetOverlay(overlayID).asset.overlayName; OverlayColorData colorData = umaRecipe.slotDataList[i].GetOverlay(overlayID).colorData; if (colorData.color != Color.white) { Color32 color = umaRecipe.slotDataList[i].GetOverlay(overlayID).colorData.color; tempPackedSlotData.OverlayDataList[overlayID].colorList = new int[4]; tempPackedSlotData.OverlayDataList[overlayID].colorList[0] = color.r; tempPackedSlotData.OverlayDataList[overlayID].colorList[1] = color.g; tempPackedSlotData.OverlayDataList[overlayID].colorList[2] = color.b; tempPackedSlotData.OverlayDataList[overlayID].colorList[3] = color.a; } if (umaRecipe.slotDataList[i].GetOverlay(overlayID).rect != new Rect(0, 0, 0, 0)) { //Might need float in next version tempPackedSlotData.OverlayDataList[overlayID].rectList = new int[4]; tempPackedSlotData.OverlayDataList[overlayID].rectList[0] = (int)umaRecipe.slotDataList[i].GetOverlay(overlayID).rect.x; tempPackedSlotData.OverlayDataList[overlayID].rectList[1] = (int)umaRecipe.slotDataList[i].GetOverlay(overlayID).rect.y; tempPackedSlotData.OverlayDataList[overlayID].rectList[2] = (int)umaRecipe.slotDataList[i].GetOverlay(overlayID).rect.width; tempPackedSlotData.OverlayDataList[overlayID].rectList[3] = (int)umaRecipe.slotDataList[i].GetOverlay(overlayID).rect.height; } if (colorData.channelMask != null && colorData.channelMask.Length > 0) { tempPackedSlotData.OverlayDataList[overlayID].channelMaskList = new int[colorData.channelMask.Length][]; for (int channelAdjust = 0; channelAdjust < colorData.channelMask.Length; channelAdjust++) { tempPackedSlotData.OverlayDataList[overlayID].channelMaskList[channelAdjust] = new int[4]; tempPackedSlotData.OverlayDataList[overlayID].channelMaskList[channelAdjust][0] = colorData.channelMask[channelAdjust].r; tempPackedSlotData.OverlayDataList[overlayID].channelMaskList[channelAdjust][1] = colorData.channelMask[channelAdjust].g; tempPackedSlotData.OverlayDataList[overlayID].channelMaskList[channelAdjust][2] = colorData.channelMask[channelAdjust].b; tempPackedSlotData.OverlayDataList[overlayID].channelMaskList[channelAdjust][3] = colorData.channelMask[channelAdjust].a; } } if (colorData.channelAdditiveMask != null) { tempPackedSlotData.OverlayDataList[overlayID].channelAdditiveMaskList = new int[colorData.channelAdditiveMask.Length][]; for (int channelAdjust = 0; channelAdjust < colorData.channelAdditiveMask.Length; channelAdjust++) { tempPackedSlotData.OverlayDataList[overlayID].channelAdditiveMaskList[channelAdjust] = new int[4]; tempPackedSlotData.OverlayDataList[overlayID].channelAdditiveMaskList[channelAdjust][0] = colorData.channelAdditiveMask[channelAdjust].r; tempPackedSlotData.OverlayDataList[overlayID].channelAdditiveMaskList[channelAdjust][1] = colorData.channelAdditiveMask[channelAdjust].g; tempPackedSlotData.OverlayDataList[overlayID].channelAdditiveMaskList[channelAdjust][2] = colorData.channelAdditiveMask[channelAdjust].b; tempPackedSlotData.OverlayDataList[overlayID].channelAdditiveMaskList[channelAdjust][3] = colorData.channelAdditiveMask[channelAdjust].a; } } } } } return umaPackRecipe; } */ public static UMAPackRecipe PackRecipeV2(UMA.UMAData.UMARecipe umaRecipe) { UMAPackRecipe umaPackRecipe = new UMAPackRecipe(); umaPackRecipe.version = 2; int slotCount = umaRecipe.slotDataList.Length - umaRecipe.additionalSlotCount; umaPackRecipe.slotsV2 = new PackedSlotDataV2[slotCount]; if (umaRecipe.raceData != null) { umaPackRecipe.race = umaRecipe.raceData.raceName; } foreach (var dna in umaRecipe.GetAllDna()) { UMAPackedDna packedDna = new UMAPackedDna(); packedDna.dnaType = dna.GetType().Name; packedDna.packedDna = UMA.UMADna.SaveInstance(dna); umaPackRecipe.packedDna.Add(packedDna); } umaPackRecipe.sharedColorCount = 0; if (umaRecipe.sharedColors != null) umaPackRecipe.sharedColorCount = umaRecipe.sharedColors.Length; List<OverlayColorData> colorEntries = new List<OverlayColorData>(umaPackRecipe.sharedColorCount); List<PackedOverlayColorDataV3> packedColorEntries = new List<PackedOverlayColorDataV3>(umaPackRecipe.sharedColorCount); for (int i = 0; i < umaPackRecipe.sharedColorCount; i++) { colorEntries.Add(umaRecipe.sharedColors[i]); packedColorEntries.Add(new PackedOverlayColorDataV3(umaRecipe.sharedColors[i])); } for (int i = 0; i < slotCount; i++) { if (umaRecipe.slotDataList[i] != null) { PackedSlotDataV2 tempPackedSlotData = new PackedSlotDataV2(); umaPackRecipe.slotsV2[i] = tempPackedSlotData; tempPackedSlotData.id = umaRecipe.slotDataList[i].asset.slotName; tempPackedSlotData.scale = Mathf.FloorToInt(umaRecipe.slotDataList[i].overlayScale * 100); bool copiedOverlays = false; for (int i2 = 0; i2 < i; i2++) { if (umaRecipe.slotDataList[i2] != null && umaPackRecipe.slotsV2[i2] != null) { if (umaRecipe.slotDataList[i].GetOverlayList() == umaRecipe.slotDataList[i2].GetOverlayList()) { tempPackedSlotData.copyIdx = i2; copiedOverlays = true; break; } } } if( copiedOverlays ) continue; tempPackedSlotData.overlays = new PackedOverlayDataV2[umaRecipe.slotDataList[i].OverlayCount]; for (int overlayIdx = 0; overlayIdx < tempPackedSlotData.overlays.Length; overlayIdx++) { PackedOverlayDataV2 tempPackedOverlay = new PackedOverlayDataV2(); OverlayData overlayData = umaRecipe.slotDataList[i].GetOverlay(overlayIdx); tempPackedOverlay.id = overlayData.asset.overlayName; tempPackedOverlay.rect = new int[4]; tempPackedOverlay.rect[0] = Mathf.FloorToInt(overlayData.rect.x); tempPackedOverlay.rect[1] = Mathf.FloorToInt(overlayData.rect.y); tempPackedOverlay.rect[2] = Mathf.FloorToInt(overlayData.rect.width); tempPackedOverlay.rect[3] = Mathf.FloorToInt(overlayData.rect.height); OverlayColorData colorData = overlayData.colorData; int colorIndex = -1; int cIndex = 0; foreach(OverlayColorData cData in colorEntries) { if (cData.name != null && cData.name.Equals(colorData.name)) { colorIndex = cIndex; break; } cIndex++; } if (colorIndex < 0) { PackedOverlayColorDataV3 newColorEntry = new PackedOverlayColorDataV3(colorData); packedColorEntries.Add(newColorEntry); colorIndex = colorEntries.Count; colorEntries.Add(colorData); } tempPackedOverlay.colorIdx = colorIndex; tempPackedSlotData.overlays[overlayIdx] = tempPackedOverlay; } } } umaPackRecipe.fColors = packedColorEntries.ToArray(); return umaPackRecipe; } public static bool UnpackRecipeVersion1(UMA.UMAData.UMARecipe umaRecipe, UMAPackRecipe umaPackRecipe, UMAContext context) { if (umaPackRecipe.packedSlotDataList == null) return false; umaRecipe.slotDataList = new SlotData[umaPackRecipe.packedSlotDataList.Length]; umaRecipe.additionalSlotCount = 0; umaRecipe.SetRace(context.GetRace(umaPackRecipe.race)); umaRecipe.ClearDna(); for (int dna = 0; dna < umaPackRecipe.packedDna.Count; dna++) { Type dnaType = UMADna.GetType(umaPackRecipe.packedDna[dna].dnaType); umaRecipe.AddDna(UMADna.LoadInstance(dnaType, umaPackRecipe.packedDna[dna].packedDna)); } for (int i = 0; i < umaPackRecipe.packedSlotDataList.Length; i++) { if (umaPackRecipe.packedSlotDataList[i] != null && umaPackRecipe.packedSlotDataList[i].slotID != null) { var tempSlotData = context.InstantiateSlot(umaPackRecipe.packedSlotDataList[i].slotID); tempSlotData.overlayScale = umaPackRecipe.packedSlotDataList[i].overlayScale * 0.01f; umaRecipe.slotDataList[i] = tempSlotData; if (umaPackRecipe.packedSlotDataList[i].copyOverlayIndex == -1) { for (int overlay = 0; overlay < umaPackRecipe.packedSlotDataList[i].OverlayDataList.Length; overlay++) { Color tempColor; Rect tempRect; if (umaPackRecipe.packedSlotDataList[i].OverlayDataList[overlay].colorList != null) { tempColor = new Color(umaPackRecipe.packedSlotDataList[i].OverlayDataList[overlay].colorList[0] / 255.0f, umaPackRecipe.packedSlotDataList[i].OverlayDataList[overlay].colorList[1] / 255.0f, umaPackRecipe.packedSlotDataList[i].OverlayDataList[overlay].colorList[2] / 255.0f, umaPackRecipe.packedSlotDataList[i].OverlayDataList[overlay].colorList[3] / 255.0f); } else { tempColor = new Color(1.0f, 1.0f, 1.0f, 1.0f); } if (umaPackRecipe.packedSlotDataList[i].OverlayDataList[overlay].rectList != null) { Rect originalRect = context.InstantiateOverlay(umaPackRecipe.packedSlotDataList[i].OverlayDataList[overlay].overlayID).rect; tempRect = new Rect(umaPackRecipe.packedSlotDataList[i].OverlayDataList[overlay].rectList[0], umaPackRecipe.packedSlotDataList[i].OverlayDataList[overlay].rectList[1], umaPackRecipe.packedSlotDataList[i].OverlayDataList[overlay].rectList[2], umaPackRecipe.packedSlotDataList[i].OverlayDataList[overlay].rectList[3]); Vector2 aspectRatio = new Vector2(tempRect.width/originalRect.width,tempRect.height/originalRect.height); tempRect = new Rect(tempRect.x/aspectRatio.x,tempRect.y/aspectRatio.y,tempRect.width/aspectRatio.x,tempRect.height/aspectRatio.y); } else { tempRect = new Rect(0, 0, 0, 0); } tempSlotData.AddOverlay(context.InstantiateOverlay(umaPackRecipe.packedSlotDataList[i].OverlayDataList[overlay].overlayID)); tempSlotData.GetOverlay(tempSlotData.OverlayCount - 1).colorData.color = tempColor; tempSlotData.GetOverlay(tempSlotData.OverlayCount - 1).rect = tempRect; if (umaPackRecipe.packedSlotDataList[i].OverlayDataList[overlay].channelMaskList != null) { for (int channelAdjust = 0; channelAdjust < umaPackRecipe.packedSlotDataList[i].OverlayDataList[overlay].channelMaskList.Length; channelAdjust++) { packedOverlayData tempData = umaPackRecipe.packedSlotDataList[i].OverlayDataList[overlay]; tempSlotData.GetOverlay(tempSlotData.OverlayCount - 1).SetColor(channelAdjust, new Color32((byte)tempData.channelMaskList[channelAdjust][0], (byte)tempData.channelMaskList[channelAdjust][1], (byte)tempData.channelMaskList[channelAdjust][2], (byte)tempData.channelMaskList[channelAdjust][3])); } } if (umaPackRecipe.packedSlotDataList[i].OverlayDataList[overlay].channelAdditiveMaskList != null) { for (int channelAdjust = 0; channelAdjust < umaPackRecipe.packedSlotDataList[i].OverlayDataList[overlay].channelAdditiveMaskList.Length; channelAdjust++) { packedOverlayData tempData = umaPackRecipe.packedSlotDataList[i].OverlayDataList[overlay]; tempSlotData.GetOverlay(tempSlotData.OverlayCount - 1).SetAdditive(channelAdjust, new Color32((byte)tempData.channelAdditiveMaskList[channelAdjust][0], (byte)tempData.channelAdditiveMaskList[channelAdjust][1], (byte)tempData.channelAdditiveMaskList[channelAdjust][2], (byte)tempData.channelAdditiveMaskList[channelAdjust][3])); } } } } else { tempSlotData.SetOverlayList(umaRecipe.slotDataList[umaPackRecipe.packedSlotDataList[i].copyOverlayIndex].GetOverlayList()); } } } return true; } public static void UnpackRecipeVersion2(UMA.UMAData.UMARecipe umaRecipe, UMAPackRecipe umaPackRecipe, UMAContext context) { umaRecipe.slotDataList = new SlotData[umaPackRecipe.slotsV2.Length]; umaRecipe.additionalSlotCount = 0; umaRecipe.SetRace(context.GetRace(umaPackRecipe.race)); umaRecipe.ClearDna(); for (int dna = 0; dna < umaPackRecipe.packedDna.Count; dna++) { Type dnaType = UMADna.GetType(umaPackRecipe.packedDna[dna].dnaType); umaRecipe.AddDna(UMADna.LoadInstance(dnaType, umaPackRecipe.packedDna[dna].packedDna)); } OverlayColorData[] colorData; if ((umaPackRecipe.fColors != null) && (umaPackRecipe.fColors.Length > 0)) { colorData = new OverlayColorData[umaPackRecipe.fColors.Length]; for (int i = 0; i < colorData.Length; i++) { colorData[i] = new OverlayColorData(); umaPackRecipe.fColors[i].SetOverlayColorData(colorData[i]); } } else if ((umaPackRecipe.colors != null) && (umaPackRecipe.colors.Length > 0)) { colorData = new OverlayColorData[umaPackRecipe.colors.Length]; for (int i = 0; i < colorData.Length; i++) { colorData[i] = new OverlayColorData(); umaPackRecipe.colors[i].SetOverlayColorData(colorData[i]); } } else { colorData = new OverlayColorData[0]; } umaRecipe.sharedColors = new OverlayColorData[umaPackRecipe.sharedColorCount]; for (int i = 0; i < umaRecipe.sharedColors.Length; i++) { umaRecipe.sharedColors[i] = colorData[i]; } for (int i = 0; i < umaPackRecipe.slotsV2.Length; i++) { PackedSlotDataV2 packedSlot = umaPackRecipe.slotsV2[i]; if (packedSlot != null && packedSlot.id != null) { var tempSlotData = context.InstantiateSlot(packedSlot.id); tempSlotData.overlayScale = packedSlot.scale * 0.01f; umaRecipe.slotDataList[i] = tempSlotData; if (packedSlot.copyIdx == -1) { for (int i2 = 0; i2 < packedSlot.overlays.Length; i2++) { PackedOverlayDataV2 packedOverlay = packedSlot.overlays[i2]; OverlayData overlayData = context.InstantiateOverlay(packedOverlay.id); overlayData.rect = new Rect(packedOverlay.rect[0], packedOverlay.rect[1], packedOverlay.rect[2], packedOverlay.rect[3]); if (packedOverlay.colorIdx < umaPackRecipe.sharedColorCount) { overlayData.colorData = umaRecipe.sharedColors[packedOverlay.colorIdx]; } else { overlayData.colorData = colorData[packedOverlay.colorIdx]; } if (overlayData.asset.material != null) overlayData.EnsureChannels(overlayData.asset.material.channels.Length); tempSlotData.AddOverlay(overlayData); } } else { tempSlotData.SetOverlayList(umaRecipe.slotDataList[packedSlot.copyIdx].GetOverlayList()); } } } } #endregion }